Run php-cs-fixer on the code base

This commit is contained in:
Frederic Guillot 2016-04-17 19:44:45 -04:00
parent 427b41f892
commit aaaafb263b
36 changed files with 511 additions and 603 deletions

View File

@ -4,7 +4,7 @@ use PicoFeed\Syndication\AtomFeedBuilder;
use PicoFeed\Syndication\AtomItemBuilder; use PicoFeed\Syndication\AtomItemBuilder;
// Ajax call to add or remove a bookmark // Ajax call to add or remove a bookmark
Router\post_action('bookmark', function() { Router\post_action('bookmark', function () {
$id = Request\param('id'); $id = Request\param('id');
$value = Request\int_param('value'); $value = Request\int_param('value');
@ -16,7 +16,7 @@ Router\post_action('bookmark', function() {
}); });
// Add new bookmark // Add new bookmark
Router\get_action('bookmark', function() { Router\get_action('bookmark', function () {
$id = Request\param('id'); $id = Request\param('id');
$menu = Request\param('menu', 'unread'); $menu = Request\param('menu', 'unread');
$source = Request\param('source', 'unread'); $source = Request\param('source', 'unread');
@ -33,7 +33,7 @@ Router\get_action('bookmark', function() {
}); });
// Display bookmarks page // Display bookmarks page
Router\get_action('bookmarks', function() { Router\get_action('bookmarks', function () {
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
$group_id = Request\int_param('group_id', null); $group_id = Request\int_param('group_id', null);
$feed_ids = array(); $feed_ids = array();
@ -70,7 +70,7 @@ Router\get_action('bookmarks', function() {
}); });
// Display bookmark feeds // Display bookmark feeds
Router\get_action('bookmark-feed', function() { Router\get_action('bookmark-feed', function () {
// Select database if the parameter is set // Select database if the parameter is set
$database = Request\param('database'); $database = Request\param('database');

View File

@ -1,7 +1,7 @@
<?php <?php
// Called before each action // Called before each action
Router\before(function($action) { Router\before(function ($action) {
Session\open(BASE_URL_DIRECTORY, SESSION_SAVE_PATH, 0); Session\open(BASE_URL_DIRECTORY, SESSION_SAVE_PATH, 0);
// Select the requested database either from post param database or from the // Select the requested database either from post param database or from the
@ -10,8 +10,7 @@ Router\before(function($action) {
if (! is_null(Request\value('database')) && ! Model\Database\select(Request\value('database'))) { if (! is_null(Request\value('database')) && ! Model\Database\select(Request\value('database'))) {
Model\User\logout(); Model\User\logout();
Response\redirect('?action=login'); Response\redirect('?action=login');
} } elseif (! empty($_SESSION['database'])) {
elseif (! empty($_SESSION['database'])) {
if (! Model\Database\select($_SESSION['database'])) { if (! Model\Database\select($_SESSION['database'])) {
Model\User\logout(); Model\User\logout();
Response\redirect('?action=login'); Response\redirect('?action=login');
@ -26,8 +25,7 @@ Router\before(function($action) {
Model\User\logout(); Model\User\logout();
Response\redirect('?action=login'); Response\redirect('?action=login');
} }
} } elseif (Model\RememberMe\has_cookie()) {
elseif (Model\RememberMe\has_cookie()) {
Model\RememberMe\refresh(); Model\RememberMe\refresh();
} }
@ -56,17 +54,17 @@ Router\before(function($action) {
}); });
// Show help // Show help
Router\get_action('show-help', function() { Router\get_action('show-help', function () {
Response\html(Template\load('show_help')); Response\html(Template\load('show_help'));
}); });
// Show the menu for the mobile view // Show the menu for the mobile view
Router\get_action('more', function() { Router\get_action('more', function () {
Response\html(Template\layout('show_more', array('menu' => 'more'))); Response\html(Template\layout('show_more', array('menu' => 'more')));
}); });
// Image proxy (avoid SSL mixed content warnings) // Image proxy (avoid SSL mixed content warnings)
Router\get_action('proxy', function() { Router\get_action('proxy', function () {
Model\Proxy\download(rawurldecode(Request\param('url'))); Model\Proxy\download(rawurldecode(Request\param('url')));
exit; exit;
}); });

View File

@ -3,7 +3,7 @@
use PicoDb\Database; use PicoDb\Database;
// Display a form to add a new database // Display a form to add a new database
Router\get_action('new-db', function() { Router\get_action('new-db', function () {
if (ENABLE_MULTIPLE_DB) { if (ENABLE_MULTIPLE_DB) {
Response\html(Template\layout('new_db', array( Response\html(Template\layout('new_db', array(
'errors' => array(), 'errors' => array(),
@ -20,18 +20,16 @@ Router\get_action('new-db', function() {
}); });
// Create a new database // Create a new database
Router\post_action('new-db', function() { Router\post_action('new-db', function () {
if (ENABLE_MULTIPLE_DB) { if (ENABLE_MULTIPLE_DB) {
$values = Request\values(); $values = Request\values();
Model\Config\check_csrf_values($values); Model\Config\check_csrf_values($values);
list($valid, $errors) = Model\Database\validate($values); list($valid, $errors) = Model\Database\validate($values);
if ($valid) { if ($valid) {
if (Model\Database\create(strtolower($values['name']).'.sqlite', $values['username'], $values['password'])) { if (Model\Database\create(strtolower($values['name']).'.sqlite', $values['username'], $values['password'])) {
Session\flash(t('Database created successfully.')); Session\flash(t('Database created successfully.'));
} } else {
else {
Session\flash_error(t('Unable to create the new database.')); Session\flash_error(t('Unable to create the new database.'));
} }
@ -51,7 +49,7 @@ Router\post_action('new-db', function() {
}); });
// Confirmation box before auto-update // Confirmation box before auto-update
Router\get_action('confirm-auto-update', function() { Router\get_action('confirm-auto-update', function () {
Response\html(Template\layout('confirm_auto_update', array( Response\html(Template\layout('confirm_auto_update', array(
'nb_unread_items' => Model\Item\count_by_status('unread'), 'nb_unread_items' => Model\Item\count_by_status('unread'),
'menu' => 'config', 'menu' => 'config',
@ -60,7 +58,7 @@ Router\get_action('confirm-auto-update', function() {
}); });
// Auto-update // Auto-update
Router\get_action('auto-update', function() { Router\get_action('auto-update', function () {
if (ENABLE_AUTO_UPDATE) { if (ENABLE_AUTO_UPDATE) {
if (Model\AutoUpdate\execute(Model\Config\get('auto_update_url'))) { if (Model\AutoUpdate\execute(Model\Config\get('auto_update_url'))) {
Session\flash(t('Miniflux is updated!')); Session\flash(t('Miniflux is updated!'));
@ -73,7 +71,7 @@ Router\get_action('auto-update', function() {
}); });
// Re-generate tokens // Re-generate tokens
Router\get_action('generate-tokens', function() { Router\get_action('generate-tokens', function () {
if (Model\Config\check_csrf(Request\param('csrf'))) { if (Model\Config\check_csrf(Request\param('csrf'))) {
Model\Config\new_tokens(); Model\Config\new_tokens();
} }
@ -82,7 +80,7 @@ Router\get_action('generate-tokens', function() {
}); });
// Optimize the database manually // Optimize the database manually
Router\get_action('optimize-db', function() { Router\get_action('optimize-db', function () {
if (Model\Config\check_csrf(Request\param('csrf'))) { if (Model\Config\check_csrf(Request\param('csrf'))) {
Database::getInstance('db')->getConnection()->exec('VACUUM'); Database::getInstance('db')->getConnection()->exec('VACUUM');
} }
@ -91,7 +89,7 @@ Router\get_action('optimize-db', function() {
}); });
// Download the compressed database // Download the compressed database
Router\get_action('download-db', function() { Router\get_action('download-db', function () {
if (Model\Config\check_csrf(Request\param('csrf'))) { if (Model\Config\check_csrf(Request\param('csrf'))) {
Response\force_download('db.sqlite.gz'); Response\force_download('db.sqlite.gz');
Response\binary(gzencode(file_get_contents(Model\Database\get_path()))); Response\binary(gzencode(file_get_contents(Model\Database\get_path())));
@ -99,7 +97,7 @@ Router\get_action('download-db', function() {
}); });
// Display preferences page // Display preferences page
Router\get_action('config', function() { Router\get_action('config', function () {
Response\html(Template\layout('config', array( Response\html(Template\layout('config', array(
'errors' => array(), 'errors' => array(),
'values' => Model\Config\get_all() + array('csrf' => Model\Config\generate_csrf()), 'values' => Model\Config\get_all() + array('csrf' => Model\Config\generate_csrf()),
@ -120,17 +118,15 @@ Router\get_action('config', function() {
}); });
// Update preferences // Update preferences
Router\post_action('config', function() { Router\post_action('config', function () {
$values = Request\values() + array('nocontent' => 0, 'image_proxy' => 0, 'favicons' => 0, 'debug_mode' => 0, 'original_marks_read' => 0); $values = Request\values() + array('nocontent' => 0, 'image_proxy' => 0, 'favicons' => 0, 'debug_mode' => 0, 'original_marks_read' => 0);
Model\Config\check_csrf_values($values); Model\Config\check_csrf_values($values);
list($valid, $errors) = Model\Config\validate_modification($values); list($valid, $errors) = Model\Config\validate_modification($values);
if ($valid) { if ($valid) {
if (Model\Config\save($values)) { if (Model\Config\save($values)) {
Session\flash(t('Your preferences are updated.')); Session\flash(t('Your preferences are updated.'));
} } else {
else {
Session\flash_error(t('Unable to update your preferences.')); Session\flash_error(t('Unable to update your preferences.'));
} }
@ -157,14 +153,13 @@ Router\post_action('config', function() {
}); });
// Get configuration parameters (AJAX request) // Get configuration parameters (AJAX request)
Router\post_action('get-config', function() { Router\post_action('get-config', function () {
$return = array(); $return = array();
$options = Request\values(); $options = Request\values();
if (empty($options)) { if (empty($options)) {
$return = Model\Config\get_all(); $return = Model\Config\get_all();
} } else {
else {
foreach ($options as $name) { foreach ($options as $name) {
$return[$name] = Model\Config\get($name); $return[$name] = Model\Config\get($name);
} }
@ -174,7 +169,7 @@ Router\post_action('get-config', function() {
}); });
// Display help page // Display help page
Router\get_action('help', function() { Router\get_action('help', function () {
Response\html(Template\layout('help', array( Response\html(Template\layout('help', array(
'config' => Model\Config\get_all(), 'config' => Model\Config\get_all(),
'nb_unread_items' => Model\Item\count_by_status('unread'), 'nb_unread_items' => Model\Item\count_by_status('unread'),
@ -184,7 +179,7 @@ Router\get_action('help', function() {
}); });
// Display about page // Display about page
Router\get_action('about', function() { Router\get_action('about', function () {
Response\html(Template\layout('about', array( Response\html(Template\layout('about', array(
'csrf' => Model\Config\generate_csrf(), 'csrf' => Model\Config\generate_csrf(),
'config' => Model\Config\get_all(), 'config' => Model\Config\get_all(),
@ -196,7 +191,7 @@ Router\get_action('about', function() {
}); });
// Display database page // Display database page
Router\get_action('database', function() { Router\get_action('database', function () {
Response\html(Template\layout('database', array( Response\html(Template\layout('database', array(
'csrf' => Model\Config\generate_csrf(), 'csrf' => Model\Config\generate_csrf(),
'config' => Model\Config\get_all(), 'config' => Model\Config\get_all(),
@ -208,7 +203,7 @@ Router\get_action('database', function() {
}); });
// Display API page // Display API page
Router\get_action('api', function() { Router\get_action('api', function () {
Response\html(Template\layout('api', array( Response\html(Template\layout('api', array(
'config' => Model\Config\get_all(), 'config' => Model\Config\get_all(),
'nb_unread_items' => Model\Item\count_by_status('unread'), 'nb_unread_items' => Model\Item\count_by_status('unread'),
@ -218,7 +213,7 @@ Router\get_action('api', function() {
}); });
// Display bookmark services page // Display bookmark services page
Router\get_action('services', function() { Router\get_action('services', function () {
Response\html(Template\layout('services', array( Response\html(Template\layout('services', array(
'errors' => array(), 'errors' => array(),
'values' => Model\Config\get_all() + array('csrf' => Model\Config\generate_csrf()), 'values' => Model\Config\get_all() + array('csrf' => Model\Config\generate_csrf()),
@ -228,14 +223,13 @@ Router\get_action('services', function() {
}); });
// Update bookmark services // Update bookmark services
Router\post_action('services', function() { Router\post_action('services', function () {
$values = Request\values() + array('pinboard_enabled' => 0, 'instapaper_enabled' => 0); $values = Request\values() + array('pinboard_enabled' => 0, 'instapaper_enabled' => 0);
Model\Config\check_csrf_values($values); Model\Config\check_csrf_values($values);
if (Model\Config\save($values)) { if (Model\Config\save($values)) {
Session\flash(t('Your preferences are updated.')); Session\flash(t('Your preferences are updated.'));
} } else {
else {
Session\flash_error(t('Unable to update your preferences.')); Session\flash_error(t('Unable to update your preferences.'));
} }

View File

@ -1,13 +1,13 @@
<?php <?php
// Flush console messages // Flush console messages
Router\get_action('flush-console', function() { Router\get_action('flush-console', function () {
@unlink(DEBUG_FILENAME); @unlink(DEBUG_FILENAME);
Response\redirect('?action=console'); Response\redirect('?action=console');
}); });
// Display console // Display console
Router\get_action('console', function() { Router\get_action('console', function () {
Response\html(Template\layout('console', array( Response\html(Template\layout('console', array(
'content' => @file_get_contents(DEBUG_FILENAME), 'content' => @file_get_contents(DEBUG_FILENAME),
'nb_unread_items' => Model\Item\count_by_status('unread'), 'nb_unread_items' => Model\Item\count_by_status('unread'),

View File

@ -3,14 +3,14 @@
use PicoFeed\Parser\MalformedXmlException; use PicoFeed\Parser\MalformedXmlException;
// Refresh all feeds, used when Javascript is disabled // Refresh all feeds, used when Javascript is disabled
Router\get_action('refresh-all', function() { Router\get_action('refresh-all', function () {
Model\Feed\refresh_all(); Model\Feed\refresh_all();
Session\flash(t('Your subscriptions are updated')); Session\flash(t('Your subscriptions are updated'));
Response\redirect('?action=unread'); Response\redirect('?action=unread');
}); });
// Edit feed form // Edit feed form
Router\get_action('edit-feed', function() { Router\get_action('edit-feed', function () {
$id = Request\int_param('feed_id'); $id = Request\int_param('feed_id');
$values = Model\Feed\get($id); $values = Model\Feed\get($id);
@ -29,7 +29,7 @@ Router\get_action('edit-feed', function() {
}); });
// Submit edit feed form // Submit edit feed form
Router\post_action('edit-feed', function() { Router\post_action('edit-feed', function () {
$values = Request\values(); $values = Request\values();
$values += array( $values += array(
'enabled' => 0, 'enabled' => 0,
@ -46,8 +46,7 @@ Router\post_action('edit-feed', function() {
if (Model\Feed\update($values)) { if (Model\Feed\update($values)) {
Session\flash(t('Your subscription has been updated.')); Session\flash(t('Your subscription has been updated.'));
Response\redirect('?action=feeds'); Response\redirect('?action=feeds');
} } else {
else {
Session\flash_error(t('Unable to edit your subscription.')); Session\flash_error(t('Unable to edit your subscription.'));
} }
} }
@ -63,7 +62,7 @@ Router\post_action('edit-feed', function() {
}); });
// Confirmation box to remove a feed // Confirmation box to remove a feed
Router\get_action('confirm-remove-feed', function() { Router\get_action('confirm-remove-feed', function () {
$id = Request\int_param('feed_id'); $id = Request\int_param('feed_id');
Response\html(Template\layout('confirm_remove_feed', array( Response\html(Template\layout('confirm_remove_feed', array(
@ -75,13 +74,12 @@ Router\get_action('confirm-remove-feed', function() {
}); });
// Remove a feed // Remove a feed
Router\get_action('remove-feed', function() { Router\get_action('remove-feed', function () {
$id = Request\int_param('feed_id'); $id = Request\int_param('feed_id');
if ($id && Model\Feed\remove($id)) { if ($id && Model\Feed\remove($id)) {
Session\flash(t('This subscription has been removed successfully.')); Session\flash(t('This subscription has been removed successfully.'));
} } else {
else {
Session\flash_error(t('Unable to remove this subscription.')); Session\flash_error(t('Unable to remove this subscription.'));
} }
@ -89,7 +87,7 @@ Router\get_action('remove-feed', function() {
}); });
// Refresh one feed and redirect to unread items // Refresh one feed and redirect to unread items
Router\get_action('refresh-feed', function() { Router\get_action('refresh-feed', function () {
$feed_id = Request\int_param('feed_id'); $feed_id = Request\int_param('feed_id');
$redirect = Request\param('redirect', 'unread'); $redirect = Request\param('redirect', 'unread');
@ -98,7 +96,7 @@ Router\get_action('refresh-feed', function() {
}); });
// Ajax call to refresh one feed // Ajax call to refresh one feed
Router\post_action('refresh-feed', function() { Router\post_action('refresh-feed', function () {
$feed_id = Request\int_param('feed_id', 0); $feed_id = Request\int_param('feed_id', 0);
Response\json(array( Response\json(array(
@ -109,7 +107,7 @@ Router\post_action('refresh-feed', function() {
}); });
// Display all feeds // Display all feeds
Router\get_action('feeds', function() { Router\get_action('feeds', function () {
$nothing_to_read = Request\int_param('nothing_to_read'); $nothing_to_read = Request\int_param('nothing_to_read');
$nb_unread_items = Model\Item\count_by_status('unread'); $nb_unread_items = Model\Item\count_by_status('unread');
@ -130,7 +128,7 @@ Router\get_action('feeds', function() {
}); });
// Display form to add one feed // Display form to add one feed
Router\get_action('add', function() { Router\get_action('add', function () {
$values = array( $values = array(
'download_content' => 0, 'download_content' => 0,
'rtl' => 0, 'rtl' => 0,
@ -150,7 +148,7 @@ Router\get_action('add', function() {
}); });
// Add a feed with the form or directly from the url, it can be used by a bookmarklet by example // Add a feed with the form or directly from the url, it can be used by a bookmarklet by example
Router\action('subscribe', function() { Router\action('subscribe', function () {
if (Request\is_post()) { if (Request\is_post()) {
$values = Request\values(); $values = Request\values();
Model\Config\check_csrf_values($values); Model\Config\check_csrf_values($values);
@ -183,34 +181,25 @@ Router\action('subscribe', function() {
$values['feed_group_ids'], $values['feed_group_ids'],
$values['create_group'] $values['create_group']
); );
} } catch (UnexpectedValueException $e) {
catch (UnexpectedValueException $e) {
$error_message = t('This subscription already exists.'); $error_message = t('This subscription already exists.');
} } catch (PicoFeed\Client\InvalidCertificateException $e) {
catch (PicoFeed\Client\InvalidCertificateException $e) {
$error_message = t('Invalid SSL certificate.'); $error_message = t('Invalid SSL certificate.');
} } catch (PicoFeed\Client\InvalidUrlException $e) {
catch (PicoFeed\Client\InvalidUrlException $e) {
// picoFeed uses this exception for multiple reasons, but doesn't // picoFeed uses this exception for multiple reasons, but doesn't
// provide an exception code to distinguish what exactly happend here // provide an exception code to distinguish what exactly happend here
$error_message = $e->getMessage(); $error_message = $e->getMessage();
} } catch (PicoFeed\Client\MaxRedirectException $e) {
catch (PicoFeed\Client\MaxRedirectException $e) {
$error_message = t('Maximum number of HTTP redirections exceeded.'); $error_message = t('Maximum number of HTTP redirections exceeded.');
} } catch (PicoFeed\Client\MaxSizeException $e) {
catch (PicoFeed\Client\MaxSizeException $e) {
$error_message = t('The content size exceeds to maximum allowed size.'); $error_message = t('The content size exceeds to maximum allowed size.');
} } catch (PicoFeed\Client\TimeoutException $e) {
catch (PicoFeed\Client\TimeoutException $e) {
$error_message = t('Connection timeout.'); $error_message = t('Connection timeout.');
} } catch (PicoFeed\Parser\MalformedXmlException $e) {
catch (PicoFeed\Parser\MalformedXmlException $e) {
$error_message = t('Feed is malformed.'); $error_message = t('Feed is malformed.');
} } catch (PicoFeed\Reader\SubscriptionNotFoundException $e) {
catch (PicoFeed\Reader\SubscriptionNotFoundException $e) {
$error_message = t('Unable to find a subscription.'); $error_message = t('Unable to find a subscription.');
} } catch (PicoFeed\Reader\UnsupportedFeedFormatException $e) {
catch (PicoFeed\Reader\UnsupportedFeedFormatException $e) {
$error_message = t('Unable to detect the feed format.'); $error_message = t('Unable to detect the feed format.');
} }
@ -219,8 +208,7 @@ Router\action('subscribe', function() {
if (isset($feed_id) && $feed_id !== false) { if (isset($feed_id) && $feed_id !== false) {
Session\flash(t('Subscription added successfully.')); Session\flash(t('Subscription added successfully.'));
Response\redirect('?action=feed-items&feed_id='.$feed_id); Response\redirect('?action=feed-items&feed_id='.$feed_id);
} } else {
else {
if (! isset($error_message)) { if (! isset($error_message)) {
$error_message = t('Error occured.'); $error_message = t('Error occured.');
} }
@ -238,13 +226,13 @@ Router\action('subscribe', function() {
}); });
// OPML export // OPML export
Router\get_action('export', function() { Router\get_action('export', function () {
Response\force_download('feeds.opml'); Response\force_download('feeds.opml');
Response\xml(Model\Feed\export_opml()); Response\xml(Model\Feed\export_opml());
}); });
// OPML import form // OPML import form
Router\get_action('import', function() { Router\get_action('import', function () {
Response\html(Template\layout('import', array( Response\html(Template\layout('import', array(
'errors' => array(), 'errors' => array(),
'nb_unread_items' => Model\Item\count_by_status('unread'), 'nb_unread_items' => Model\Item\count_by_status('unread'),
@ -254,7 +242,7 @@ Router\get_action('import', function() {
}); });
// OPML importation // OPML importation
Router\post_action('import', function() { Router\post_action('import', function () {
try { try {
Model\Feed\import_opml(Request\file_content('file')); Model\Feed\import_opml(Request\file_content('file'));
Session\flash(t('Your feeds have been imported.')); Session\flash(t('Your feeds have been imported.'));

View File

@ -1,7 +1,7 @@
<?php <?php
// Display history page // Display history page
Router\get_action('history', function() { Router\get_action('history', function () {
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
$group_id = Request\int_param('group_id', null); $group_id = Request\int_param('group_id', null);
$feed_ids = array(); $feed_ids = array();
@ -42,7 +42,7 @@ Router\get_action('history', function() {
}); });
// Confirmation box to flush history // Confirmation box to flush history
Router\get_action('confirm-flush-history', function() { Router\get_action('confirm-flush-history', function () {
$group_id = Request\int_param('group_id', null); $group_id = Request\int_param('group_id', null);
Response\html(Template\layout('confirm_flush_items', array( Response\html(Template\layout('confirm_flush_items', array(
@ -54,7 +54,7 @@ Router\get_action('confirm-flush-history', function() {
}); });
// Flush history // Flush history
Router\get_action('flush-history', function() { Router\get_action('flush-history', function () {
$group_id = Request\int_param('group_id', null); $group_id = Request\int_param('group_id', null);
if (!is_null($group_id)) { if (!is_null($group_id)) {

View File

@ -1,7 +1,7 @@
<?php <?php
// Display unread items // Display unread items
Router\get_action('unread', function() { Router\get_action('unread', function () {
Model\Item\autoflush_read(); Model\Item\autoflush_read();
Model\Item\autoflush_unread(); Model\Item\autoflush_unread();
@ -52,7 +52,7 @@ Router\get_action('unread', function() {
}); });
// Show item // Show item
Router\get_action('show', function() { Router\get_action('show', function () {
$id = Request\param('id'); $id = Request\param('id');
$menu = Request\param('menu'); $menu = Request\param('menu');
$item = Model\Item\get($id); $item = Model\Item\get($id);
@ -98,7 +98,7 @@ Router\get_action('show', function() {
}); });
// Display feed items page // Display feed items page
Router\get_action('feed-items', function() { Router\get_action('feed-items', function () {
$feed_id = Request\int_param('feed_id', 0); $feed_id = Request\int_param('feed_id', 0);
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
$nb_items = Model\Item\count_by_feed($feed_id); $nb_items = Model\Item\count_by_feed($feed_id);
@ -126,7 +126,7 @@ Router\get_action('feed-items', function() {
}); });
// Ajax call to download an item (fetch the full content from the original website) // Ajax call to download an item (fetch the full content from the original website)
Router\post_action('download-item', function() { Router\post_action('download-item', function () {
$id = Request\param('id'); $id = Request\param('id');
$item = Model\Item\get($id); $item = Model\Item\get($id);
@ -139,31 +139,30 @@ Router\post_action('download-item', function() {
}); });
// Ajax call to mark item read // Ajax call to mark item read
Router\post_action('mark-item-read', function() { Router\post_action('mark-item-read', function () {
Model\Item\set_read(Request\param('id')); Model\Item\set_read(Request\param('id'));
Response\json(array('Ok')); Response\json(array('Ok'));
}); });
// Ajax call to mark item as removed // Ajax call to mark item as removed
Router\post_action('mark-item-removed', function() { Router\post_action('mark-item-removed', function () {
Model\Item\set_removed(Request\param('id')); Model\Item\set_removed(Request\param('id'));
Response\json(array('Ok')); Response\json(array('Ok'));
}); });
// Ajax call to mark item unread // Ajax call to mark item unread
Router\post_action('mark-item-unread', function() { Router\post_action('mark-item-unread', function () {
Model\Item\set_unread(Request\param('id')); Model\Item\set_unread(Request\param('id'));
Response\json(array('Ok')); Response\json(array('Ok'));
}); });
// Mark unread items as read // Mark unread items as read
Router\get_action('mark-all-read', function() { Router\get_action('mark-all-read', function () {
$group_id = Request\int_param('group_id', null); $group_id = Request\int_param('group_id', null);
if (!is_null($group_id)) { if (!is_null($group_id)) {
Model\Item\mark_group_as_read($group_id); Model\Item\mark_group_as_read($group_id);
} } else {
else {
Model\Item\mark_all_as_read(); Model\Item\mark_all_as_read();
} }
@ -171,7 +170,7 @@ Router\get_action('mark-all-read', function() {
}); });
// Mark all unread items as read for a specific feed // Mark all unread items as read for a specific feed
Router\get_action('mark-feed-as-read', function() { Router\get_action('mark-feed-as-read', function () {
$feed_id = Request\int_param('feed_id'); $feed_id = Request\int_param('feed_id');
Model\Item\mark_feed_as_read($feed_id); Model\Item\mark_feed_as_read($feed_id);
@ -182,7 +181,7 @@ Router\get_action('mark-feed-as-read', function() {
// the number of unread items. It's not possible to get the number of items // the number of unread items. It's not possible to get the number of items
// that where marked read from the frontend, since the number of unread items // that where marked read from the frontend, since the number of unread items
// on page 2+ is unknown. // on page 2+ is unknown.
Router\post_action('mark-feed-as-read', function() { Router\post_action('mark-feed-as-read', function () {
Model\Item\mark_feed_as_read(Request\int_param('feed_id')); Model\Item\mark_feed_as_read(Request\int_param('feed_id'));
$nb_items = Model\Item\count_by_status('unread'); $nb_items = Model\Item\count_by_status('unread');
@ -190,7 +189,7 @@ Router\post_action('mark-feed-as-read', function() {
}); });
// Mark item as read and redirect to the listing page // Mark item as read and redirect to the listing page
Router\get_action('mark-item-read', function() { Router\get_action('mark-item-read', function () {
$id = Request\param('id'); $id = Request\param('id');
$redirect = Request\param('redirect', 'unread'); $redirect = Request\param('redirect', 'unread');
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
@ -201,7 +200,7 @@ Router\get_action('mark-item-read', function() {
}); });
// Mark item as unread and redirect to the listing page // Mark item as unread and redirect to the listing page
Router\get_action('mark-item-unread', function() { Router\get_action('mark-item-unread', function () {
$id = Request\param('id'); $id = Request\param('id');
$redirect = Request\param('redirect', 'history'); $redirect = Request\param('redirect', 'history');
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
@ -212,7 +211,7 @@ Router\get_action('mark-item-unread', function() {
}); });
// Mark item as removed and redirect to the listing page // Mark item as removed and redirect to the listing page
Router\get_action('mark-item-removed', function() { Router\get_action('mark-item-removed', function () {
$id = Request\param('id'); $id = Request\param('id');
$redirect = Request\param('redirect', 'history'); $redirect = Request\param('redirect', 'history');
$offset = Request\int_param('offset', 0); $offset = Request\int_param('offset', 0);
@ -222,7 +221,7 @@ Router\get_action('mark-item-removed', function() {
Response\redirect('?action='.$redirect.'&offset='.$offset.'&feed_id='.$feed_id); Response\redirect('?action='.$redirect.'&offset='.$offset.'&feed_id='.$feed_id);
}); });
Router\post_action('latest-feeds-items', function() { Router\post_action('latest-feeds-items', function () {
$items = Model\Item\get_latest_feeds_items(); $items = Model\Item\get_latest_feeds_items();
$nb_unread_items = Model\Item\count_by_status('unread'); $nb_unread_items = Model\Item\count_by_status('unread');

View File

@ -1,13 +1,13 @@
<?php <?php
// Logout and destroy session // Logout and destroy session
Router\get_action('logout', function() { Router\get_action('logout', function () {
Model\User\logout(); Model\User\logout();
Response\redirect('?action=login'); Response\redirect('?action=login');
}); });
// Display form login // Display form login
Router\get_action('login', function() { Router\get_action('login', function () {
if (Model\User\is_loggedin()) { if (Model\User\is_loggedin()) {
Response\redirect('?action=unread'); Response\redirect('?action=unread');
} }
@ -23,7 +23,7 @@ Router\get_action('login', function() {
}); });
// Check credentials and redirect to unread items // Check credentials and redirect to unread items
Router\post_action('login', function() { Router\post_action('login', function () {
$values = Request\values(); $values = Request\values();
Model\Config\check_csrf_values($values); Model\Config\check_csrf_values($values);
list($valid, $errors) = Model\User\validate_login($values); list($valid, $errors) = Model\User\validate_login($values);

View File

@ -14,8 +14,7 @@ function route($name, Closure $callback = null)
if ($callback !== null) { if ($callback !== null) {
$routes[$name] = $callback; $routes[$name] = $callback;
} } elseif (isset($routes[$name])) {
else if (isset($routes[$name])) {
$routes[$name](); $routes[$name]();
} }
} }
@ -46,7 +45,7 @@ function auth()
$response = array( $response = array(
'api_version' => 3, 'api_version' => 3,
'auth' => (int) (isset($_POST['api_key']) && (strcasecmp($_POST['api_key'], $api_key) === 0 )), 'auth' => (int) (isset($_POST['api_key']) && (strcasecmp($_POST['api_key'], $api_key) === 0)),
'last_refreshed_on_time' => time(), 'last_refreshed_on_time' => time(),
); );
@ -54,12 +53,11 @@ function auth()
} }
// Call: ?api&groups // Call: ?api&groups
route('groups', function() { route('groups', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$response['groups'] = Group\get_all(); $response['groups'] = Group\get_all();
$response['feeds_groups'] = array(); $response['feeds_groups'] = array();
$group_map = Group\get_map(); $group_map = Group\get_map();
@ -76,12 +74,11 @@ route('groups', function() {
}); });
// Call: ?api&feeds // Call: ?api&feeds
route('feeds', function() { route('feeds', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$response['feeds'] = array(); $response['feeds'] = array();
$response['feeds_groups'] = array(); $response['feeds_groups'] = array();
@ -112,12 +109,11 @@ route('feeds', function() {
}); });
// Call: ?api&favicons // Call: ?api&favicons
route('favicons', function() { route('favicons', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$favicons = Database::getInstance('db') $favicons = Database::getInstance('db')
->table('favicons') ->table('favicons')
->columns( ->columns(
@ -140,12 +136,11 @@ route('favicons', function() {
}); });
// Call: ?api&items // Call: ?api&items
route('items', function() { route('items', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$query = Database::getInstance('db') $query = Database::getInstance('db')
->table('items') ->table('items')
->columns( ->columns(
@ -163,11 +158,9 @@ route('items', function() {
->neq('status', 'removed'); ->neq('status', 'removed');
if (isset($_GET['since_id']) && is_numeric($_GET['since_id'])) { if (isset($_GET['since_id']) && is_numeric($_GET['since_id'])) {
$items = $query->gt('rowid', $_GET['since_id']) $items = $query->gt('rowid', $_GET['since_id'])
->asc('rowid'); ->asc('rowid');
} } elseif (! empty($_GET['with_ids'])) {
else if (! empty($_GET['with_ids'])) {
$query->in('rowid', explode(',', $_GET['with_ids'])); $query->in('rowid', explode(',', $_GET['with_ids']));
} }
@ -198,7 +191,7 @@ route('items', function() {
}); });
// Call: ?api&links // Call: ?api&links
route('links', function() { route('links', function () {
$response = auth(); $response = auth();
@ -210,12 +203,11 @@ route('links', function() {
}); });
// Call: ?api&unread_item_ids // Call: ?api&unread_item_ids
route('unread_item_ids', function() { route('unread_item_ids', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$item_ids = Database::getInstance('db') $item_ids = Database::getInstance('db')
->table('items') ->table('items')
->eq('status', 'unread') ->eq('status', 'unread')
@ -228,12 +220,11 @@ route('unread_item_ids', function() {
}); });
// Call: ?api&saved_item_ids // Call: ?api&saved_item_ids
route('saved_item_ids', function() { route('saved_item_ids', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$item_ids = Database::getInstance('db') $item_ids = Database::getInstance('db')
->table('items') ->table('items')
->eq('bookmark', 1) ->eq('bookmark', 1)
@ -246,12 +237,11 @@ route('saved_item_ids', function() {
}); });
// handle write items // handle write items
route('write_items', function() { route('write_items', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
$query = Database::getInstance('db') $query = Database::getInstance('db')
->table('items') ->table('items')
->eq('rowid', $_POST['id']); ->eq('rowid', $_POST['id']);
@ -266,14 +256,11 @@ route('write_items', function() {
->findOneColumn('id'); ->findOneColumn('id');
Service\push($item_id); Service\push($item_id);
} } elseif ($_POST['as'] === 'unsaved') {
else if ($_POST['as'] === 'unsaved') {
$query->update(array('bookmark' => 0)); $query->update(array('bookmark' => 0));
} } elseif ($_POST['as'] === 'read') {
else if ($_POST['as'] === 'read') {
$query->update(array('status' => 'read')); $query->update(array('status' => 'read'));
} } elseif ($_POST['as'] === 'unread') {
else if ($_POST['as'] === 'unread') {
$query->update(array('status' => 'unread')); $query->update(array('status' => 'unread'));
} }
} }
@ -282,12 +269,11 @@ route('write_items', function() {
}); });
// handle write feeds // handle write feeds
route('write_feeds', function() { route('write_feeds', function () {
$response = auth(); $response = auth();
if ($response['auth']) { if ($response['auth']) {
Database::getInstance('db') Database::getInstance('db')
->table('items') ->table('items')
->eq('feed_id', $_POST['id']) ->eq('feed_id', $_POST['id'])
@ -299,7 +285,7 @@ route('write_feeds', function() {
}); });
// handle write groups // handle write groups
route('write_groups', function() { route('write_groups', function () {
$response = auth(); $response = auth();
@ -323,15 +309,12 @@ foreach (array_keys($_GET) as $action) {
} }
if (! empty($_POST['mark']) && ! empty($_POST['as']) if (! empty($_POST['mark']) && ! empty($_POST['as'])
&& ! is_null(filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, array('options' => array('default' => NULL,'min_range' => -1)))) ){ && ! is_null(filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, array('options' => array('default' => null, 'min_range' => -1))))) {
if ($_POST['mark'] === 'item') { if ($_POST['mark'] === 'item') {
route('write_items'); route('write_items');
} } elseif ($_POST['mark'] === 'feed' && ! empty($_POST['before'])) {
else if ($_POST['mark'] === 'feed' && ! empty($_POST['before'])) {
route('write_feeds'); route('write_feeds');
} } elseif ($_POST['mark'] === 'group' && ! empty($_POST['before'])) {
else if ($_POST['mark'] === 'group' && ! empty($_POST['before'])) {
route('write_groups'); route('write_groups');
} }
} }

View File

@ -2,7 +2,6 @@
namespace Request; namespace Request;
function param($name, $default_value = null) function param($name, $default_value = null)
{ {
return isset($_GET[$name]) ? $_GET[$name] : $default_value; return isset($_GET[$name]) ? $_GET[$name] : $default_value;
@ -25,7 +24,6 @@ function value($name)
function values() function values()
{ {
if (! empty($_POST)) { if (! empty($_POST)) {
return $_POST; return $_POST;
} }

View File

@ -2,7 +2,6 @@
namespace Response; namespace Response;
function force_download($filename) function force_download($filename)
{ {
header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"');
@ -21,8 +20,7 @@ function status($status_code)
if (strpos($sapi_name, 'apache') !== false || $sapi_name === 'cli-server') { if (strpos($sapi_name, 'apache') !== false || $sapi_name === 'cli-server') {
header('HTTP/1.0 '.$status_code); header('HTTP/1.0 '.$status_code);
} } else {
else {
header('Status: '.$status_code); header('Status: '.$status_code);
} }
} }
@ -116,20 +114,15 @@ function csp(array $policies = array())
$values = ''; $values = '';
foreach ($policies as $policy => $hosts) { foreach ($policies as $policy => $hosts) {
if (is_array($hosts)) { if (is_array($hosts)) {
$acl = ''; $acl = '';
foreach ($hosts as &$host) { foreach ($hosts as &$host) {
if ($host === '*' || $host === "'self'" || strpos($host, 'http') === 0) { if ($host === '*' || $host === "'self'" || strpos($host, 'http') === 0) {
$acl .= $host.' '; $acl .= $host.' ';
} }
} }
} } else {
else {
$acl = $hosts; $acl = $hosts;
} }

View File

@ -20,8 +20,7 @@ function before($value = null)
if (is_callable($value)) { if (is_callable($value)) {
$before_callback = $value; $before_callback = $value;
} } elseif (is_callable($before_callback)) {
else if (is_callable($before_callback)) {
$before_callback($value); $before_callback($value);
} }
} }
@ -33,8 +32,7 @@ function before_action($name, $value = null)
if (is_callable($value)) { if (is_callable($value)) {
$callbacks[$name] = $value; $callbacks[$name] = $value;
} } elseif (isset($callbacks[$name]) && is_callable($callbacks[$name])) {
else if (isset($callbacks[$name]) && is_callable($callbacks[$name])) {
$callbacks[$name]($value); $callbacks[$name]($value);
} }
} }
@ -103,18 +101,15 @@ function delete($url, \Closure $callback)
function find_route($method, $route, \Closure $callback) function find_route($method, $route, \Closure $callback)
{ {
if ($_SERVER['REQUEST_METHOD'] === $method) { if ($_SERVER['REQUEST_METHOD'] === $method) {
if (! empty($_SERVER['QUERY_STRING'])) { if (! empty($_SERVER['QUERY_STRING'])) {
$url = substr($_SERVER['REQUEST_URI'], 0, -(strlen($_SERVER['QUERY_STRING']) + 1)); $url = substr($_SERVER['REQUEST_URI'], 0, -(strlen($_SERVER['QUERY_STRING']) + 1));
} } else {
else {
$url = $_SERVER['REQUEST_URI']; $url = $_SERVER['REQUEST_URI'];
} }
$params = array(); $params = array();
if (url_match($route, $url, $params)) { if (url_match($route, $url, $params)) {
before($route); before($route);
\call_user_func_array($callback, $params); \call_user_func_array($callback, $params);
exit; exit;
@ -125,8 +120,12 @@ function find_route($method, $route, \Closure $callback)
// Parse url and find matches // Parse url and find matches
function url_match($route_uri, $request_uri, array &$params) function url_match($route_uri, $request_uri, array &$params)
{ {
if ($request_uri === $route_uri) return true; if ($request_uri === $route_uri) {
if ($route_uri === '/' || $request_uri === '/') return false; return true;
}
if ($route_uri === '/' || $request_uri === '/') {
return false;
}
$route_uri = trim($route_uri, '/'); $route_uri = trim($route_uri, '/');
$request_uri = trim($request_uri, '/'); $request_uri = trim($request_uri, '/');
@ -136,15 +135,10 @@ function url_match($route_uri, $request_uri, array &$params)
$nb_route_items = count($route_items); $nb_route_items = count($route_items);
if ($nb_route_items === count($request_items)) { if ($nb_route_items === count($request_items)) {
for ($i = 0; $i < $nb_route_items; ++$i) { for ($i = 0; $i < $nb_route_items; ++$i) {
if ($route_items[$i][0] === ':') { if ($route_items[$i][0] === ':') {
$params[substr($route_items[$i], 1)] = $request_items[$i]; $params[substr($route_items[$i], 1)] = $request_items[$i];
} } elseif ($route_items[$i] !== $request_items[$i]) {
else if ($route_items[$i] !== $request_items[$i]) {
$params = array(); $params = array();
return false; return false;
} }

View File

@ -7,7 +7,9 @@ const SESSION_LIFETIME = 2678400;
function open($base_path = '/', $save_path = '', $session_lifetime = SESSION_LIFETIME) function open($base_path = '/', $save_path = '', $session_lifetime = SESSION_LIFETIME)
{ {
if ($save_path !== '') session_save_path($save_path); if ($save_path !== '') {
session_save_path($save_path);
}
// HttpOnly and secure flags for session cookie // HttpOnly and secure flags for session cookie
session_set_cookie_params( session_set_cookie_params(

View File

@ -16,7 +16,6 @@ function load()
} }
if (func_num_args() === 2) { if (func_num_args() === 2) {
if (! is_array(func_get_arg(1))) { if (! is_array(func_get_arg(1))) {
die('Template variables must be an array'); die('Template variables must be an array');
} }

View File

@ -55,14 +55,12 @@ namespace Translator {
$str = ''; $str = '';
if ($position === 'before') { if ($position === 'before') {
$str .= $symbol; $str .= $symbol;
} }
$str .= number($amount); $str .= number($amount);
if ($position === 'after') { if ($position === 'after') {
$str .= ' '.$symbol; $str .= ' '.$symbol;
} }
@ -89,8 +87,7 @@ namespace Translator {
if (isset($locales[$identifier])) { if (isset($locales[$identifier])) {
if (is_array($locales[$identifier])) { if (is_array($locales[$identifier])) {
$translation = plural($identifier, $default, $values); $translation = plural($identifier, $default, $values);
} } else {
else {
$translation = $locales[$identifier]; $translation = $locales[$identifier];
} }
} }
@ -129,7 +126,6 @@ namespace Translator {
$locales = array(); $locales = array();
if (is_dir($path)) { if (is_dir($path)) {
$dir = new \DirectoryIterator($path); $dir = new \DirectoryIterator($path);
foreach ($dir as $fileinfo) { foreach ($dir as $fileinfo) {
@ -157,23 +153,28 @@ namespace Translator {
namespace { namespace {
function tne() { function tne()
{
return call_user_func_array('\Translator\translate_no_escaping', func_get_args()); return call_user_func_array('\Translator\translate_no_escaping', func_get_args());
} }
function t() { function t()
{
return call_user_func_array('\Translator\translate', func_get_args()); return call_user_func_array('\Translator\translate', func_get_args());
} }
function c() { function c()
{
return call_user_func_array('\Translator\currency', func_get_args()); return call_user_func_array('\Translator\currency', func_get_args());
} }
function n() { function n()
{
return call_user_func_array('\Translator\number', func_get_args()); return call_user_func_array('\Translator\number', func_get_args());
} }
function dt() { function dt()
{
return call_user_func_array('\Translator\datetime', func_get_args()); return call_user_func_array('\Translator\datetime', func_get_args());
} }
} }

View File

@ -68,7 +68,6 @@ function css()
$theme = \Model\Config\get('theme'); $theme = \Model\Config\get('theme');
if ($theme !== 'original') { if ($theme !== 'original') {
$css_file = THEME_DIRECTORY.'/'.$theme.'/css/app.css'; $css_file = THEME_DIRECTORY.'/'.$theme.'/css/app.css';
if (file_exists($css_file)) { if (file_exists($css_file)) {
@ -129,8 +128,7 @@ function summary($value, $min_length = 5, $max_length = 120, $end = '[...]')
$max = $max_length; $max = $max_length;
} }
return substr($value, 0, $max).' '.$end; return substr($value, 0, $max).' '.$end;
} } elseif ($length < $min_length) {
else if ($length < $min_length) {
return ''; return '';
} }
@ -150,24 +148,38 @@ function relative_time($timestamp, $fallback_date_format = '%e %B %Y %k:%M')
{ {
$diff = time() - $timestamp; $diff = time() - $timestamp;
if ($diff < 0) return \dt($fallback_date_format, $timestamp); if ($diff < 0) {
return \dt($fallback_date_format, $timestamp);
}
if ($diff < 60) return \t('%d second ago', $diff); if ($diff < 60) {
return \t('%d second ago', $diff);
}
$diff = floor($diff / 60); $diff = floor($diff / 60);
if ($diff < 60) return \t('%d minute ago', $diff); if ($diff < 60) {
return \t('%d minute ago', $diff);
}
$diff = floor($diff / 60); $diff = floor($diff / 60);
if ($diff < 24) return \t('%d hour ago', $diff); if ($diff < 24) {
return \t('%d hour ago', $diff);
}
$diff = floor($diff / 24); $diff = floor($diff / 24);
if ($diff < 7) return \t('%d day ago', $diff); if ($diff < 7) {
return \t('%d day ago', $diff);
}
$diff = floor($diff / 7); $diff = floor($diff / 7);
if ($diff < 4) return \t('%d week ago', $diff); if ($diff < 4) {
return \t('%d week ago', $diff);
}
$diff = floor($diff / 4); $diff = floor($diff / 4);
if ($diff < 12) return \t('%d month ago', $diff); if ($diff < 12) {
return \t('%d month ago', $diff);
}
return \dt($fallback_date_format, $timestamp); return \dt($fallback_date_format, $timestamp);
} }
@ -182,7 +194,6 @@ function error_list(array $errors, $name)
$html = ''; $html = '';
if (isset($errors[$name])) { if (isset($errors[$name])) {
$html .= '<ul class="form-errors">'; $html .= '<ul class="form-errors">';
foreach ($errors[$name] as $error) { foreach ($errors[$name] as $error) {
@ -220,11 +231,14 @@ function form_select($name, array $options, $values = array(), array $errors = a
$html = '<select name="'.$name.'" id="form-'.$name.'" class="'.$class.'">'; $html = '<select name="'.$name.'" id="form-'.$name.'" class="'.$class.'">';
foreach ($options as $id => $value) { foreach ($options as $id => $value) {
$html .= '<option value="'.escape($id).'"'; $html .= '<option value="'.escape($id).'"';
if (isset($values->$name) && $id == $values->$name) $html .= ' selected="selected"'; if (isset($values->$name) && $id == $values->$name) {
if (isset($values[$name]) && $id == $values[$name]) $html .= ' selected="selected"'; $html .= ' selected="selected"';
}
if (isset($values[$name]) && $id == $values[$name]) {
$html .= ' selected="selected"';
}
$html .= '>'.escape($value).'</option>'; $html .= '>'.escape($value).'</option>';
} }

View File

@ -8,220 +8,219 @@
*/ */
if (!defined('PASSWORD_BCRYPT')) { if (!defined('PASSWORD_BCRYPT')) {
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
define('PASSWORD_BCRYPT', 1); if (version_compare(PHP_VERSION, '5.3.7', '<')) {
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); define('PASSWORD_PREFIX', '$2a$');
} else {
define('PASSWORD_PREFIX', '$2y$');
}
if (version_compare(PHP_VERSION, '5.3.7', '<')) { /**
* Hash the password using the specified algorithm
*
* @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array())
{
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
switch ($algo) {
case PASSWORD_BCRYPT:
// Note that this is a C constant, but not exposed to PHP, so we don't define it here.
$cost = 10;
if (isset($options['cost'])) {
$cost = $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
$required_salt_len = 22;
$hash_format = sprintf("%s%02d$", PASSWORD_PREFIX, $cost);
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL':
case 'boolean':
case 'integer':
case 'double':
case 'string':
$salt = (string) $options['salt'];
break;
case 'object':
if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt'];
break;
}
case 'array':
case 'resource':
default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt = str_replace('+', '.', base64_encode($salt));
}
} else {
$buffer = '';
$raw_length = (int) ($required_salt_len * 3 / 4 + 1);
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_length, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_length);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r');
$read = strlen($buffer);
while ($read < $raw_length) {
$buffer .= fread($f, $raw_length - $read);
$read = strlen($buffer);
}
fclose($f);
if ($read >= $raw_length) {
$buffer_valid = true;
}
}
if (!$buffer_valid || strlen($buffer) < $raw_length) {
$bl = strlen($buffer);
for ($i = 0; $i < $raw_length; $i++) {
if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = str_replace('+', '.', base64_encode($buffer));
}
$salt = substr($salt, 0, $required_salt_len);
define('PASSWORD_PREFIX', '$2a$'); $hash = $hash_format . $salt;
}
else {
define('PASSWORD_PREFIX', '$2y$'); $ret = crypt($password, $hash);
}
/** if (!is_string($ret) || strlen($ret) <= 13) {
* Hash the password using the specified algorithm return false;
* }
* @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
switch ($algo) {
case PASSWORD_BCRYPT:
// Note that this is a C constant, but not exposed to PHP, so we don't define it here.
$cost = 10;
if (isset($options['cost'])) {
$cost = $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
$required_salt_len = 22;
$hash_format = sprintf("%s%02d$", PASSWORD_PREFIX, $cost);
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL':
case 'boolean':
case 'integer':
case 'double':
case 'string':
$salt = (string) $options['salt'];
break;
case 'object':
if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt'];
break;
}
case 'array':
case 'resource':
default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt = str_replace('+', '.', base64_encode($salt));
}
} else {
$buffer = '';
$raw_length = (int) ($required_salt_len * 3 / 4 + 1);
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_length, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_length);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r');
$read = strlen($buffer);
while ($read < $raw_length) {
$buffer .= fread($f, $raw_length - $read);
$read = strlen($buffer);
}
fclose($f);
if ($read >= $raw_length) {
$buffer_valid = true;
}
}
if (!$buffer_valid || strlen($buffer) < $raw_length) {
$bl = strlen($buffer);
for ($i = 0; $i < $raw_length; $i++) {
if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = str_replace('+', '.', base64_encode($buffer));
} return $ret;
$salt = substr($salt, 0, $required_salt_len); }
$hash = $hash_format . $salt; /**
* Get information about the password hash. Returns an array of the information
* that was used to generate the password hash.
*
* array(
* 'algo' => 1,
* 'algoName' => 'bcrypt',
* 'options' => array(
* 'cost' => 10,
* ),
* )
*
* @param string $hash The password hash to extract info from
*
* @return array The array of information about the hash.
*/
function password_get_info($hash)
{
$return = array(
'algo' => 0,
'algoName' => 'unknown',
'options' => array(),
);
if (substr($hash, 0, 4) == PASSWORD_PREFIX && strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, PASSWORD_PREFIX."%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
$ret = crypt($password, $hash); /**
* Determine if the password hash needs to be rehashed according to the options provided
*
* If the answer is true, after validating the password using password_verify, rehash it.
*
* @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array())
{
$info = password_get_info($hash);
if ($info['algo'] != $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? $options['cost'] : 10;
if ($cost != $info['options']['cost']) {
return true;
}
break;
}
return false;
}
if (!is_string($ret) || strlen($ret) <= 13) { /**
return false; * Verify a password against a hash using a timing attack resistant approach
} *
* @param string $password The password to verify
* @param string $hash The hash to verify against
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash)
{
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) {
return false;
}
return $ret; $status = 0;
} for ($i = 0; $i < strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
/** return $status === 0;
* Get information about the password hash. Returns an array of the information }
* that was used to generate the password hash.
*
* array(
* 'algo' => 1,
* 'algoName' => 'bcrypt',
* 'options' => array(
* 'cost' => 10,
* ),
* )
*
* @param string $hash The password hash to extract info from
*
* @return array The array of information about the hash.
*/
function password_get_info($hash) {
$return = array(
'algo' => 0,
'algoName' => 'unknown',
'options' => array(),
);
if (substr($hash, 0, 4) == PASSWORD_PREFIX && strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, PASSWORD_PREFIX."%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
/**
* Determine if the password hash needs to be rehashed according to the options provided
*
* If the answer is true, after validating the password using password_verify, rehash it.
*
* @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash);
if ($info['algo'] != $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? $options['cost'] : 10;
if ($cost != $info['options']['cost']) {
return true;
}
break;
}
return false;
}
/**
* Verify a password against a hash using a timing attack resistant approach
*
* @param string $password The password to verify
* @param string $hash The hash to verify against
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) {
return false;
}
$status = 0;
for ($i = 0; $i < strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
return $status === 0;
}
} }

View File

@ -23,7 +23,6 @@ function get_files_list($directory)
$files = array(); $files = array();
while ($it->valid()) { while ($it->valid()) {
if ($it->isFile() && ! is_excluded_path($it->getSubPathname(), $exclude_list)) { if ($it->isFile() && ! is_excluded_path($it->getSubPathname(), $exclude_list)) {
$files[] = $it->getSubPathname(); $files[] = $it->getSubPathname();
} }
@ -38,7 +37,6 @@ function get_files_list($directory)
function is_excluded_path($path, array $exclude_list) function is_excluded_path($path, array $exclude_list)
{ {
foreach ($exclude_list as $excluded_path) { foreach ($exclude_list as $excluded_path) {
if (strpos($path, $excluded_path) === 0) { if (strpos($path, $excluded_path) === 0) {
return true; return true;
} }
@ -59,9 +57,7 @@ function synchronize($source_directory, $destination_directory)
$remove_files = array_diff($dst_files, $src_files); $remove_files = array_diff($dst_files, $src_files);
foreach ($remove_files as $file) { foreach ($remove_files as $file) {
if ($file !== '.htaccess') { if ($file !== '.htaccess') {
$destination_file = $destination_directory.DIRECTORY_SEPARATOR.$file; $destination_file = $destination_directory.DIRECTORY_SEPARATOR.$file;
Config\debug('[REMOVE] '.$destination_file); Config\debug('[REMOVE] '.$destination_file);
@ -73,11 +69,9 @@ function synchronize($source_directory, $destination_directory)
// Overwrite all files // Overwrite all files
foreach ($src_files as $file) { foreach ($src_files as $file) {
$directory = $destination_directory.DIRECTORY_SEPARATOR.dirname($file); $directory = $destination_directory.DIRECTORY_SEPARATOR.dirname($file);
if (! is_dir($directory)) { if (! is_dir($directory)) {
Config\debug('[MKDIR] '.$directory); Config\debug('[MKDIR] '.$directory);
if (! @mkdir($directory, 0755, true)) { if (! @mkdir($directory, 0755, true)) {
@ -135,16 +129,13 @@ function cleanup_directory($directory)
$dir = new DirectoryIterator($directory); $dir = new DirectoryIterator($directory);
foreach ($dir as $fileinfo) { foreach ($dir as $fileinfo) {
if (! $fileinfo->isDot()) { if (! $fileinfo->isDot()) {
$filename = $fileinfo->getRealPath(); $filename = $fileinfo->getRealPath();
if ($fileinfo->isFile()) { if ($fileinfo->isFile()) {
\Model\Config\debug('[REMOVE] '.$filename); \Model\Config\debug('[REMOVE] '.$filename);
@unlink($filename); @unlink($filename);
} } else {
else {
cleanup_directory($filename); cleanup_directory($filename);
@rmdir($filename); @rmdir($filename);
} }
@ -187,18 +178,36 @@ function find_archive_root($base_directory = AUTO_UPDATE_ARCHIVE_DIRECTORY)
// Check if everything is setup correctly // Check if everything is setup correctly
function check_setup() function check_setup()
{ {
if (! class_exists('ZipArchive')) die('To use this feature, your PHP installation must be able to uncompress zip files!'); if (! class_exists('ZipArchive')) {
die('To use this feature, your PHP installation must be able to uncompress zip files!');
}
if (AUTO_UPDATE_DOWNLOAD_DIRECTORY === '') die('The constant AUTO_UPDATE_DOWNLOAD_DIRECTORY is not set!'); if (AUTO_UPDATE_DOWNLOAD_DIRECTORY === '') {
if (AUTO_UPDATE_ARCHIVE_DIRECTORY === '') die('The constant AUTO_UPDATE_ARCHIVE_DIRECTORY is not set!'); die('The constant AUTO_UPDATE_DOWNLOAD_DIRECTORY is not set!');
if (AUTO_UPDATE_DOWNLOAD_DIRECTORY === '') die('The constant AUTO_UPDATE_DOWNLOAD_DIRECTORY is not set!'); }
if (AUTO_UPDATE_ARCHIVE_DIRECTORY === '') {
die('The constant AUTO_UPDATE_ARCHIVE_DIRECTORY is not set!');
}
if (AUTO_UPDATE_DOWNLOAD_DIRECTORY === '') {
die('The constant AUTO_UPDATE_DOWNLOAD_DIRECTORY is not set!');
}
if (! is_dir(AUTO_UPDATE_DOWNLOAD_DIRECTORY)) @mkdir(AUTO_UPDATE_DOWNLOAD_DIRECTORY, 0755); if (! is_dir(AUTO_UPDATE_DOWNLOAD_DIRECTORY)) {
if (! is_dir(AUTO_UPDATE_ARCHIVE_DIRECTORY)) @mkdir(AUTO_UPDATE_ARCHIVE_DIRECTORY, 0755); @mkdir(AUTO_UPDATE_DOWNLOAD_DIRECTORY, 0755);
if (! is_dir(AUTO_UPDATE_BACKUP_DIRECTORY)) @mkdir(AUTO_UPDATE_BACKUP_DIRECTORY, 0755); }
if (! is_dir(AUTO_UPDATE_ARCHIVE_DIRECTORY)) {
@mkdir(AUTO_UPDATE_ARCHIVE_DIRECTORY, 0755);
}
if (! is_dir(AUTO_UPDATE_BACKUP_DIRECTORY)) {
@mkdir(AUTO_UPDATE_BACKUP_DIRECTORY, 0755);
}
if (! is_writable(AUTO_UPDATE_DOWNLOAD_DIRECTORY)) die('Update directories must be writable by your web server user!'); if (! is_writable(AUTO_UPDATE_DOWNLOAD_DIRECTORY)) {
if (! is_writable(__DIR__)) die('Source files must be writable by your web server user!'); die('Update directories must be writable by your web server user!');
}
if (! is_writable(__DIR__)) {
die('Source files must be writable by your web server user!');
}
} }
// Update the source code // Update the source code
@ -208,7 +217,6 @@ function execute($url)
cleanup_directories(); cleanup_directories();
if (uncompress_archive($url)) { if (uncompress_archive($url)) {
$update_directory = find_archive_root(); $update_directory = find_archive_root();
if ($update_directory) { if ($update_directory) {
@ -220,8 +228,7 @@ function execute($url)
if (synchronize($update_directory, ROOT_DIRECTORY)) { if (synchronize($update_directory, ROOT_DIRECTORY)) {
cleanup_directories(); cleanup_directories();
return true; return true;
} } else {
else {
// If update failed, rollback // If update failed, rollback
synchronize(AUTO_UPDATE_BACKUP_DIRECTORY, ROOT_DIRECTORY); synchronize(AUTO_UPDATE_BACKUP_DIRECTORY, ROOT_DIRECTORY);
} }

View File

@ -118,11 +118,9 @@ function get_themes()
); );
if (file_exists(THEME_DIRECTORY)) { if (file_exists(THEME_DIRECTORY)) {
$dir = new DirectoryIterator(THEME_DIRECTORY); $dir = new DirectoryIterator(THEME_DIRECTORY);
foreach ($dir as $fileinfo) { foreach ($dir as $fileinfo) {
if (! $fileinfo->isDot() && $fileinfo->isDir()) { if (! $fileinfo->isDot() && $fileinfo->isDir()) {
$themes[$dir->getFilename()] = ucfirst($dir->getFilename()); $themes[$dir->getFilename()] = ucfirst($dir->getFilename());
} }
@ -144,19 +142,19 @@ function get_sorting_directions()
// Display summaries or full contents on lists // Display summaries or full contents on lists
function get_display_mode() function get_display_mode()
{ {
return array( return array(
'summaries' => t('Summaries'), 'summaries' => t('Summaries'),
'full' => t('Full contents') 'full' => t('Full contents')
); );
} }
// Item title links to original or full contents // Item title links to original or full contents
function get_item_title_link() function get_item_title_link()
{ {
return array( return array(
'original' => t('Original'), 'original' => t('Original'),
'full' => t('Full contents') 'full' => t('Full contents')
); );
} }
// Autoflush choices for read items // Autoflush choices for read items
@ -227,9 +225,7 @@ function check_csrf_values(array &$values)
{ {
if (empty($values['csrf']) || ! isset($_SESSION['csrf'][$values['csrf']])) { if (empty($values['csrf']) || ! isset($_SESSION['csrf'][$values['csrf']])) {
$values = array(); $values = array();
} } else {
else {
unset($_SESSION['csrf'][$values['csrf']]); unset($_SESSION['csrf'][$values['csrf']]);
unset($values['csrf']); unset($values['csrf']);
} }
@ -251,11 +247,9 @@ function generate_token()
{ {
if (function_exists('random_bytes')) { if (function_exists('random_bytes')) {
return bin2hex(random_bytes(30)); return bin2hex(random_bytes(30));
} } elseif (function_exists('openssl_random_pseudo_bytes')) {
else if (function_exists('openssl_random_pseudo_bytes')) {
return bin2hex(openssl_random_pseudo_bytes(30)); return bin2hex(openssl_random_pseudo_bytes(30));
} } elseif (ini_get('open_basedir') === '' && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
else if (ini_get('open_basedir') === '' && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
return hash('sha256', file_get_contents('/dev/urandom', false, null, 0, 30)); return hash('sha256', file_get_contents('/dev/urandom', false, null, 0, 30));
} }
@ -280,9 +274,7 @@ function get($name)
{ {
if (! isset($_SESSION)) { if (! isset($_SESSION)) {
return current(Database::getInstance('db')->hashtable('settings')->get($name)); return current(Database::getInstance('db')->hashtable('settings')->get($name));
} } else {
else {
if (! isset($_SESSION['config'][$name])) { if (! isset($_SESSION['config'][$name])) {
$_SESSION['config'] = get_all(); $_SESSION['config'] = get_all();
} }
@ -392,11 +384,8 @@ function get_ip_address($only_public = false)
); );
foreach ($keys as $key) { foreach ($keys as $key) {
if (isset($_SERVER[$key])) { if (isset($_SERVER[$key])) {
foreach (explode(',', $_SERVER[$key]) as $ip_address) { foreach (explode(',', $_SERVER[$key]) as $ip_address) {
$ip_address = trim($ip_address); $ip_address = trim($ip_address);
if ($only_public) { if ($only_public) {
@ -405,9 +394,7 @@ function get_ip_address($only_public = false)
if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) { if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
return $ip_address; return $ip_address;
} }
} } else {
else {
return $ip_address; return $ip_address;
} }
} }

View File

@ -14,7 +14,6 @@ function create($filename, $username, $password)
$filename = DATA_DIRECTORY.DIRECTORY_SEPARATOR.$filename; $filename = DATA_DIRECTORY.DIRECTORY_SEPARATOR.$filename;
if (ENABLE_MULTIPLE_DB && ! file_exists($filename)) { if (ENABLE_MULTIPLE_DB && ! file_exists($filename)) {
$db = new \PicoDb\Database(array( $db = new \PicoDb\Database(array(
'driver' => 'sqlite', 'driver' => 'sqlite',
'filename' => $filename, 'filename' => $filename,
@ -55,8 +54,7 @@ function select($filename = '')
$_SESSION['database'] = $filename; $_SESSION['database'] = $filename;
$_SESSION['config'] = Config\get_all(); $_SESSION['config'] = Config\get_all();
} }
} } else {
else {
return false; return false;
} }
} }
@ -92,11 +90,9 @@ function get_list()
$listing = array(); $listing = array();
foreach (get_all() as $filename) { foreach (get_all() as $filename) {
if ($filename === DB_FILENAME) { if ($filename === DB_FILENAME) {
$label = t('Default database'); $label = t('Default database');
} } else {
else {
$label = ucfirst(substr($filename, 0, -7)); $label = ucfirst(substr($filename, 0, -7));
} }

View File

@ -9,7 +9,8 @@ use PicoDb\Database;
use PicoFeed\Reader\Favicon; use PicoFeed\Reader\Favicon;
// Create a favicons // Create a favicons
function create_feed_favicon($feed_id, $site_url, $icon_link) { function create_feed_favicon($feed_id, $site_url, $icon_link)
{
if (has_favicon($feed_id)) { if (has_favicon($feed_id)) {
return true; return true;
} }
@ -81,7 +82,8 @@ function store($type, $icon)
return get_favicon_id($hash); return get_favicon_id($hash);
} }
function get_favicon_id($hash) { function get_favicon_id($hash)
{
return Database::getInstance('db') return Database::getInstance('db')
->table('favicons') ->table('favicons')
->eq('hash', $hash) ->eq('hash', $hash)
@ -112,9 +114,9 @@ function purge_favicons()
->isNull('favicons_feeds.feed_id') ->isNull('favicons_feeds.feed_id')
->findAll(); ->findAll();
foreach ($favicons as $favicon) { foreach ($favicons as $favicon) {
delete_favicon($favicon); delete_favicon($favicon);
} }
} }
// Return true if the feed has a favicon // Return true if the feed has a favicon
@ -179,7 +181,7 @@ function get_all_favicons()
$map = array(); $map = array();
foreach ($result as $row) { foreach ($result as $row) {
$map[$row['feed_id']] = array( $map[$row['feed_id']] = array(
"type" => $row['type'], "type" => $row['type'],
"hash" => $row['hash'] "hash" => $row['hash']
); );

View File

@ -181,7 +181,6 @@ function refresh_all($limit = LIMIT_ALL)
function refresh($feed_id) function refresh($feed_id)
{ {
try { try {
$feed = get($feed_id); $feed = get($feed_id);
if (empty($feed)) { if (empty($feed)) {
@ -201,7 +200,6 @@ function refresh($feed_id)
// Feed modified // Feed modified
if ($resource->isModified()) { if ($resource->isModified()) {
$parser = $reader->getParser( $parser = $reader->getParser(
$resource->getUrl(), $resource->getUrl(),
$resource->getContent(), $resource->getContent(),
@ -209,7 +207,6 @@ function refresh($feed_id)
); );
if ($feed['download_content']) { if ($feed['download_content']) {
$parser->enableContentGrabber(); $parser->enableContentGrabber();
// Don't fetch previous items, only new one // Don't fetch previous items, only new one
@ -230,8 +227,7 @@ function refresh($feed_id)
Config\write_debug(); Config\write_debug();
return true; return true;
} } catch (PicoFeedException $e) {
catch (PicoFeedException $e) {
} }
update_parsing_error($feed_id, 1); update_parsing_error($feed_id, 1);
@ -305,7 +301,6 @@ function count_items($feed_id)
); );
foreach ($counts as &$count) { foreach ($counts as &$count) {
if ($count['status'] === 'unread') { if ($count['status'] === 'unread') {
$result['items_unread'] = (int) $count['item_count']; $result['items_unread'] = (int) $count['item_count'];
} }

View File

@ -38,8 +38,7 @@ function get_map()
if (isset($map[$group_id])) { if (isset($map[$group_id])) {
$map[$group_id][] = $feed_id; $map[$group_id][] = $feed_id;
} } else {
else {
$map[$group_id] = array($feed_id); $map[$group_id] = array($feed_id);
} }
} }
@ -136,7 +135,7 @@ function create($title)
// create group if missing // create group if missing
if ($group_id === false) { if ($group_id === false) {
Database::getInstance('db') Database::getInstance('db')
->table('groups') ->table('groups')
->insert($data); ->insert($data);
@ -155,7 +154,7 @@ function create($title)
*/ */
function add($feed_id, array $group_ids) function add($feed_id, array $group_ids)
{ {
foreach ($group_ids as $group_id){ foreach ($group_ids as $group_id) {
$data = array('feed_id' => $feed_id, 'group_id' => $group_id); $data = array('feed_id' => $feed_id, 'group_id' => $group_id);
$result = Database::getInstance('db') $result = Database::getInstance('db')

View File

@ -231,9 +231,13 @@ function get_nav($item, $status = array('unread'), $bookmark = array(1, 0), $fee
->neq('status', 'removed') ->neq('status', 'removed')
->orderBy('updated', Config\get('items_sorting_direction')); ->orderBy('updated', Config\get('items_sorting_direction'));
if ($feed_id) $query->eq('feed_id', $feed_id); if ($feed_id) {
$query->eq('feed_id', $feed_id);
}
if ($group_id) $query->in('feed_id', Group\get_feeds_by_group($group_id)); if ($group_id) {
$query->in('feed_id', Group\get_feeds_by_group($group_id));
}
$items = $query->findAll(); $items = $query->findAll();
@ -241,15 +245,11 @@ function get_nav($item, $status = array('unread'), $bookmark = array(1, 0), $fee
$previous_item = null; $previous_item = null;
for ($i = 0, $ilen = count($items); $i < $ilen; $i++) { for ($i = 0, $ilen = count($items); $i < $ilen; $i++) {
if ($items[$i]['id'] == $item['id']) { if ($items[$i]['id'] == $item['id']) {
if ($i > 0) { if ($i > 0) {
$j = $i - 1; $j = $i - 1;
while ($j >= 0) { while ($j >= 0) {
if (in_array($items[$j]['status'], $status) && in_array($items[$j]['bookmark'], $bookmark)) { if (in_array($items[$j]['status'], $status) && in_array($items[$j]['bookmark'], $bookmark)) {
$previous_item = $items[$j]; $previous_item = $items[$j];
break; break;
@ -260,11 +260,9 @@ function get_nav($item, $status = array('unread'), $bookmark = array(1, 0), $fee
} }
if ($i < ($ilen - 1)) { if ($i < ($ilen - 1)) {
$j = $i + 1; $j = $i + 1;
while ($j < $ilen) { while ($j < $ilen) {
if (in_array($items[$j]['status'], $status) && in_array($items[$j]['bookmark'], $bookmark)) { if (in_array($items[$j]['status'], $status) && in_array($items[$j]['bookmark'], $bookmark)) {
$next_item = $items[$j]; $next_item = $items[$j];
break; break;
@ -314,7 +312,9 @@ function set_unread($id)
// Change item status to "read", "unread" or "removed" // Change item status to "read", "unread" or "removed"
function set_status($status, array $items) function set_status($status, array $items)
{ {
if (! in_array($status, array('read', 'unread', 'removed'))) return false; if (! in_array($status, array('read', 'unread', 'removed'))) {
return false;
}
return Database::getInstance('db') return Database::getInstance('db')
->table('items') ->table('items')
@ -405,8 +405,7 @@ function autoflush_read()
->eq('status', 'read') ->eq('status', 'read')
->lt('updated', strtotime('-'.$autoflush.'day')) ->lt('updated', strtotime('-'.$autoflush.'day'))
->save(array('status' => 'removed', 'content' => '')); ->save(array('status' => 'removed', 'content' => ''));
} } elseif ($autoflush === -1) {
else if ($autoflush === -1) {
// Mark read items removed immediately // Mark read items removed immediately
Database::getInstance('db') Database::getInstance('db')
@ -445,12 +444,10 @@ function update_all($feed_id, array $items)
$db->startTransaction(); $db->startTransaction();
foreach ($items as $item) { foreach ($items as $item) {
Logger::setMessage('Item => '.$item->getId().' '.$item->getUrl()); Logger::setMessage('Item => '.$item->getId().' '.$item->getUrl());
// Item parsed correctly? // Item parsed correctly?
if ($item->getId() && $item->getUrl()) { if ($item->getId() && $item->getUrl()) {
Logger::setMessage('Item parsed correctly'); Logger::setMessage('Item parsed correctly');
// Get item record in database, if any // Get item record in database, if any
@ -462,7 +459,6 @@ function update_all($feed_id, array $items)
// Insert a new item // Insert a new item
if ($itemrec === null) { if ($itemrec === null) {
Logger::setMessage('Item added to the database'); Logger::setMessage('Item added to the database');
$db->table('items')->save(array( $db->table('items')->save(array(
@ -478,9 +474,7 @@ function update_all($feed_id, array $items)
'enclosure_type' => $item->getEnclosureType(), 'enclosure_type' => $item->getEnclosureType(),
'language' => $item->getLanguage(), 'language' => $item->getLanguage(),
)); ));
} } elseif (! $itemrec['enclosure'] && $item->getEnclosureUrl()) {
else if (! $itemrec['enclosure'] && $item->getEnclosureUrl()) {
Logger::setMessage('Update item enclosure'); Logger::setMessage('Update item enclosure');
$db->table('items')->eq('id', $item->getId())->save(array( $db->table('items')->eq('id', $item->getId())->save(array(
@ -488,8 +482,7 @@ function update_all($feed_id, array $items)
'enclosure' => $item->getEnclosureUrl(), 'enclosure' => $item->getEnclosureUrl(),
'enclosure_type' => $item->getEnclosureType(), 'enclosure_type' => $item->getEnclosureType(),
)); ));
} } else {
else {
Logger::setMessage('Item already in the database'); Logger::setMessage('Item already in the database');
} }
@ -509,7 +502,6 @@ function update_all($feed_id, array $items)
function cleanup($feed_id, array $items_in_feed) function cleanup($feed_id, array $items_in_feed)
{ {
if (! empty($items_in_feed)) { if (! empty($items_in_feed)) {
$db = Database::getInstance('db'); $db = Database::getInstance('db');
$removed_items = $db $removed_items = $db
@ -524,11 +516,9 @@ function cleanup($feed_id, array $items_in_feed)
// Keep a buffer of 2 items // Keep a buffer of 2 items
// It's workaround for buggy feeds (cache issue with some Wordpress plugins) // It's workaround for buggy feeds (cache issue with some Wordpress plugins)
if (is_array($removed_items)) { if (is_array($removed_items)) {
$items_to_remove = array_slice($removed_items, 2); $items_to_remove = array_slice($removed_items, 2);
if (! empty($items_to_remove)) { if (! empty($items_to_remove)) {
$nb_items = count($items_to_remove); $nb_items = count($items_to_remove);
Logger::setMessage('There is '.$nb_items.' items to remove'); Logger::setMessage('There is '.$nb_items.' items to remove');
@ -539,7 +529,6 @@ function cleanup($feed_id, array $items_in_feed)
$chunks = array_chunk($items_to_remove, 500); $chunks = array_chunk($items_to_remove, 500);
foreach ($chunks as $chunk) { foreach ($chunks as $chunk) {
$db->table('items') $db->table('items')
->in('id', $chunk) ->in('id', $chunk)
->eq('status', 'removed') ->eq('status', 'removed')
@ -574,7 +563,6 @@ function download_content_id($item_id)
$content = download_content_url($item['url']); $content = download_content_url($item['url']);
if (! empty($content)) { if (! empty($content)) {
if (! Config\get('nocontent')) { if (! Config\get('nocontent')) {
// Save content // Save content

View File

@ -35,8 +35,7 @@ function rewrite_html($html, $website, $proxy_images, $cloak_referrer)
// image proxy mode only: https links do not need to be proxied, since // image proxy mode only: https links do not need to be proxied, since
// they do not trigger mixed content warnings. // they do not trigger mixed content warnings.
$config->setFilterImageProxyProtocol('http'); $config->setFilterImageProxyProtocol('http');
} } elseif (! $proxy_images && $cloak_referrer && Helper\is_secure_connection()) {
elseif (! $proxy_images && $cloak_referrer && Helper\is_secure_connection()) {
// cloaking mode only: if a request from a HTTPS connection to a HTTP // cloaking mode only: if a request from a HTTPS connection to a HTTP
// connection is made, the referrer will be omitted by the browser. // connection is made, the referrer will be omitted by the browser.
// Only the referrer for HTTPS to HTTPs requests needs to be cloaked. // Only the referrer for HTTPS to HTTPs requests needs to be cloaked.
@ -60,8 +59,8 @@ function download($url)
$client->setUserAgent(Config\HTTP_USER_AGENT); $client->setUserAgent(Config\HTTP_USER_AGENT);
$client->enablePassthroughMode(); $client->enablePassthroughMode();
$client->execute($url); $client->execute($url);
} catch (ClientException $e) {
} }
catch (ClientException $e) {}
Config\write_debug(); Config\write_debug();
} }

View File

@ -52,7 +52,6 @@ function authenticate()
$credentials = read_cookie(); $credentials = read_cookie();
if ($credentials !== false) { if ($credentials !== false) {
$record = find($credentials['token'], $credentials['sequence']); $record = find($credentials['token'], $credentials['sequence']);
if ($record) { if ($record) {
@ -84,7 +83,6 @@ function refresh()
$credentials = read_cookie(); $credentials = read_cookie();
if ($credentials !== false) { if ($credentials !== false) {
$record = find($credentials['token'], $credentials['sequence']); $record = find($credentials['token'], $credentials['sequence']);
if ($record) { if ($record) {
@ -109,7 +107,6 @@ function destroy()
$credentials = read_cookie(); $credentials = read_cookie();
if ($credentials !== false) { if ($credentials !== false) {
Database::getInstance('db') Database::getInstance('db')
->table(TABLE) ->table(TABLE)
->eq('token', $credentials['token']) ->eq('token', $credentials['token'])

View File

@ -303,13 +303,9 @@ function version_11(PDO $pdo)
$items = $rq->fetchAll(PDO::FETCH_ASSOC); $items = $rq->fetchAll(PDO::FETCH_ASSOC);
foreach ($items as $item) { foreach ($items as $item) {
if ($item['id'] !== $item['item_url']) { if ($item['id'] !== $item['item_url']) {
$id = hash('crc32b', $item['id'].$item['site_url']); $id = hash('crc32b', $item['id'].$item['site_url']);
} } else {
else {
$id = hash('crc32b', $item['item_url'].$item['site_url']); $id = hash('crc32b', $item['item_url'].$item['site_url']);
} }

View File

@ -73,8 +73,7 @@ function api_call($url)
$client->setUserAgent(Config\HTTP_USER_AGENT); $client->setUserAgent(Config\HTTP_USER_AGENT);
$client->execute($url); $client->execute($url);
return $client; return $client;
} } catch (ClientException $e) {
catch (ClientException $e) {
return false; return false;
} }
} }

View File

@ -52,7 +52,6 @@ function validate_login(array $values)
$errors = $v->getErrors(); $errors = $v->getErrors();
if ($result) { if ($result) {
$credentials = get_credentials(); $credentials = get_credentials();
if ($credentials && $credentials['username'] === $values['username'] && password_verify($values['password'], $credentials['password'])) { if ($credentials && $credentials['username'] === $values['username'] && password_verify($values['password'], $credentials['password'])) {
@ -65,9 +64,7 @@ function validate_login(array $values)
$cookie = RememberMe\create(DatabaseModel\select(), $values['username'], Config\get_ip_address(), Config\get_user_agent()); $cookie = RememberMe\create(DatabaseModel\select(), $values['username'], Config\get_ip_address(), Config\get_user_agent());
RememberMe\write_cookie($cookie['token'], $cookie['sequence'], $cookie['expiration']); RememberMe\write_cookie($cookie['token'], $cookie['sequence'], $cookie['expiration']);
} }
} } else {
else {
$result = false; $result = false;
$errors['login'] = t('Bad username or password'); $errors['login'] = t('Bad username or password');
} }

View File

@ -283,7 +283,7 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = $url; $this->expectedPageUrl = $url;
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
/** /**
@ -298,7 +298,7 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = $this->getURLPageBookmarks(); $this->expectedPageUrl = $this->getURLPageBookmarks();
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
/** /**
@ -313,7 +313,7 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = $this->getURLPageHistory(); $this->expectedPageUrl = $this->getURLPageHistory();
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
/** /**
@ -328,7 +328,7 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = $this->getURLPageUnread(); $this->expectedPageUrl = $this->getURLPageUnread();
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
/** /**
@ -342,7 +342,7 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds'; $this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds';
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
/** /**
@ -356,7 +356,6 @@ class keyboardShortcutTest extends minifluxTestCase
$this->expectedPageUrl = $this->getURLPagePreferences(); $this->expectedPageUrl = $this->getURLPagePreferences();
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
} }
?>

View File

@ -4,16 +4,16 @@ use PHPUnit_Extensions_Selenium2TestCase_Keys as Keys;
abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
{ {
protected $basePageHeading = NULL; protected $basePageHeading = null;
protected $expectedPageUrl = NULL; protected $expectedPageUrl = null;
protected $expectedDataSet = NULL; protected $expectedDataSet = null;
protected $expectedCounterPage = NULL; protected $expectedCounterPage = null;
protected $expectedCounterUnread = ''; protected $expectedCounterUnread = '';
protected $ignorePageTitle = FALSE; protected $ignorePageTitle = false;
protected static $databaseConnection = NULL; protected static $databaseConnection = null;
protected static $databaseTester = NULL; protected static $databaseTester = null;
private $waitTimeout = 5000; private $waitTimeout = 5000;
@ -57,8 +57,8 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
public static function tearDownAfterClass() public static function tearDownAfterClass()
{ {
static::$databaseConnection = NULL; static::$databaseConnection = null;
static::$databaseTester = NULL; static::$databaseTester = null;
} }
protected function assertPostConditions() protected function assertPostConditions()
@ -72,7 +72,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// some tests switch to a page where no counter exists and the expected // some tests switch to a page where no counter exists and the expected
// pagetitle doesn't match to definition. // pagetitle doesn't match to definition.
if ($this->ignorePageTitle === FALSE) { if ($this->ignorePageTitle === false) {
//remove LEFT-TO-RIGHT MARK char from string as the webdriver does it when using text() on the page <h[1|2|3]> //remove LEFT-TO-RIGHT MARK char from string as the webdriver does it when using text() on the page <h[1|2|3]>
$pagetitle = preg_replace('/\x{200E}/u', '', $this->title()); $pagetitle = preg_replace('/\x{200E}/u', '', $this->title());
$this->assertEquals($this->getExpectedPageTitle(), $pagetitle, 'page title differ from expectation'); $this->assertEquals($this->getExpectedPageTitle(), $pagetitle, 'page title differ from expectation');
@ -170,7 +170,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
{ {
$displaySize = $element->size(); $displaySize = $element->size();
return ($element->displayed() === FALSE || $displaySize['height']=0 || $displaySize['width']=0); return ($element->displayed() === false || $displaySize['height']=0 || $displaySize['width']=0);
} }
private function waitForElementVisibility($element, $visible) private function waitForElementVisibility($element, $visible)
@ -180,31 +180,28 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// Workaround for PHP < 5.4 // Workaround for PHP < 5.4
$CI = $this; $CI = $this;
$value = $this->waitUntil(function() use($CI, $element, $visible) { $value = $this->waitUntil(function () use ($CI, $element,$visible) {
// a "No such Element" or "Stale Element Reference" exception is // a "No such Element" or "Stale Element Reference" exception is
// valid if an object should disappear // valid if an object should disappear
try { try {
if (($visible && $CI->isElementVisible($element)) if (($visible && $CI->isElementVisible($element))
|| (! $visible && $CI->isElementInvisible($element))) { || (! $visible && $CI->isElementInvisible($element))) {
return TRUE; return true;
} }
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
$noSuchElement = ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement $noSuchElement = ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement
|| $e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::StaleElementReference); || $e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::StaleElementReference);
if (($visible === FALSE) && ($noSuchElement)) { if (($visible === false) && ($noSuchElement)) {
return TRUE; return true;
} else { } else {
throw $e; throw $e;
} }
} }
}, $this->waitTimeout); }, $this->waitTimeout);
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) { if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) {
return FALSE; return false;
} else { } else {
throw $e; throw $e;
} }
@ -220,17 +217,16 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// Workaround for PHP < 5.4 // Workaround for PHP < 5.4
$CI = $this; $CI = $this;
$value = $this->waitUntil(function() use($cssSelector, $elementCount, $CI) { $value = $this->waitUntil(function () use ($cssSelector, $elementCount,$CI) {
$elements = $CI->elements($CI->using('css selector')->value($cssSelector)); $elements = $CI->elements($CI->using('css selector')->value($cssSelector));
if (count($elements) === $elementCount) { if (count($elements) === $elementCount) {
return TRUE; return true;
} }
}, $this->waitTimeout); }, $this->waitTimeout);
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) { if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) {
return FALSE; return false;
} else { } else {
throw $e; throw $e;
} }
@ -239,23 +235,22 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
return $value; return $value;
} }
private function waitForElementByIdText($id, $text) private function waitForElementByIdText($id, $text)
{ {
// return false in case of timeout // return false in case of timeout
try { try {
// Workaround for PHP < 5.4 // Workaround for PHP < 5.4
$CI = $this; $CI = $this;
$value = $this->waitUntil(function() use($CI, $id, $text) { $value = $this->waitUntil(function () use ($CI, $id,$text) {
try { try {
$elements = $this->elements($this->using('id')->value($id)); $elements = $this->elements($this->using('id')->value($id));
if (count($elements) === 1 && $elements[0]->text() == $text if (count($elements) === 1 && $elements[0]->text() == $text
|| count($elements) === 0 && is_null($text)) { || count($elements) === 0 && is_null($text)) {
return TRUE; return true;
} }
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
$noSuchElement = ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement $noSuchElement = ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement
|| $e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::StaleElementReference); || $e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::StaleElementReference);
@ -266,10 +261,9 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
} }
} }
}, $this->waitTimeout); }, $this->waitTimeout);
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) { if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) {
return FALSE; return false;
} else { } else {
throw $e; throw $e;
} }
@ -278,21 +272,20 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
return $value; return $value;
} }
private function waitForElementAttributeHasValue($element, $attribute, $attributeValue, $invertMatch = FALSE) private function waitForElementAttributeHasValue($element, $attribute, $attributeValue, $invertMatch = false)
{ {
// return false in case of timeout // return false in case of timeout
try { try {
$value = $this->waitUntil(function() use($element, $attribute, $attributeValue, $invertMatch) { $value = $this->waitUntil(function () use ($element, $attribute, $attributeValue,$invertMatch) {
$attributeHasValue = ($element->attribute($attribute) === $attributeValue); $attributeHasValue = ($element->attribute($attribute) === $attributeValue);
if (($attributeHasValue && !$invertMatch) || (!$attributeHasValue && $invertMatch)) { if (($attributeHasValue && !$invertMatch) || (!$attributeHasValue && $invertMatch)) {
return TRUE; return true;
} }
}, $this->waitTimeout); }, $this->waitTimeout);
} } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) { if ($e->getCode() === PHPUnit_Extensions_Selenium2TestCase_WebDriverException::Timeout) {
return FALSE; return false;
} else { } else {
throw $e; throw $e;
} }
@ -331,8 +324,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// Some PageHeadings have a counter included // Some PageHeadings have a counter included
$innerHeadingElements = $this->elements($this->using('css selector')->value('div.page-header > h2:first-child *')); $innerHeadingElements = $this->elements($this->using('css selector')->value('div.page-header > h2:first-child *'));
if (count($innerHeadingElements) > 0) if (count($innerHeadingElements) > 0) {
{
$innerHeading = $innerHeadingElements[0]->text(); $innerHeading = $innerHeadingElements[0]->text();
$pageHeading = substr($pageHeading, 0, (strlen($innerHeading) * -1)); $pageHeading = substr($pageHeading, 0, (strlen($innerHeading) * -1));
} }
@ -477,8 +469,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
if (func_num_args() === 0) { if (func_num_args() === 0) {
$feed = $this; $feed = $this;
} } else {
else {
$feed = func_get_arg(0); $feed = func_get_arg(0);
} }
@ -487,7 +478,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// Workaround for PHP < 5.4 // Workaround for PHP < 5.4
$CI = $this; $CI = $this;
return array_filter($feeds, function($feed) use($CI) { return array_filter($feeds, function ($feed) use ($CI) {
return $CI->isElementVisible($feed); return $CI->isElementVisible($feed);
}); });
} }
@ -514,7 +505,7 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
$article = $this->element($this->using('css selector')->value($cssSelector)); $article = $this->element($this->using('css selector')->value($cssSelector));
return $article; return $article;
} }
public function getArticleReadBookmarked() public function getArticleReadBookmarked()
{ {
@ -594,37 +585,37 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
public function waitForArticleIsNotCurrentArticle($article) public function waitForArticleIsNotCurrentArticle($article)
{ {
$isCurrent = $this->waitForElementAttributeHasValue($article, 'id', 'current-item', TRUE); $isCurrent = $this->waitForElementAttributeHasValue($article, 'id', 'current-item', true);
return $isCurrent; return $isCurrent;
} }
public function waitForIconMarkReadVisible($article) public function waitForIconMarkReadVisible($article)
{ {
$visible = $this->waitForIconMarkRead($article, TRUE); $visible = $this->waitForIconMarkRead($article, true);
return $visible; return $visible;
} }
public function waitForIconMarkReadInvisible($article) public function waitForIconMarkReadInvisible($article)
{ {
$invisible = $this->waitForIconMarkRead($article, FALSE); $invisible = $this->waitForIconMarkRead($article, false);
return $invisible; return $invisible;
} }
public function waitForIconBookmarkVisible($article) public function waitForIconBookmarkVisible($article)
{ {
$visible = $this->waitForIconBookmark($article, TRUE); $visible = $this->waitForIconBookmark($article, true);
return $visible; return $visible;
} }
public function waitForIconBookmarkInvisible($article) public function waitForIconBookmarkInvisible($article)
{ {
$invisible = $this->waitForIconBookmark($article, FALSE); $invisible = $this->waitForIconBookmark($article, false);
return $invisible; return $invisible;
} }
public function waitForArticleInvisible($article) public function waitForArticleInvisible($article)
{ {
$invisible = $this->waitForElementVisibility($article, FALSE); $invisible = $this->waitForElementVisibility($article, false);
return $invisible; return $invisible;
} }
@ -651,14 +642,14 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
// Workaround for PHP < 5.4 // Workaround for PHP < 5.4
$CI = $this; $CI = $this;
$this->waitUntil(function() use($CI) { $this->waitUntil(function () use ($CI) {
$readyState = $CI->execute(array( $readyState = $CI->execute(array(
'script' => 'return document.readyState;', 'script' => 'return document.readyState;',
'args' => array() 'args' => array()
)); ));
if ($readyState === 'complete') { if ($readyState === 'complete') {
return TRUE; return true;
} }
}, $this->waitTimeout); }, $this->waitTimeout);
} }
@ -674,9 +665,8 @@ abstract class minifluxTestCase extends PHPUnit_Extensions_Selenium2TestCase
)); ));
$result = $this->waitForArticleIsCurrentArticle($article); $result = $this->waitForArticleIsCurrentArticle($article);
if ($result === FALSE) { if ($result === false) {
throw new Exception('the article could not be set as current article.'); throw new Exception('the article could not be set as current article.');
} }
} }
} }
?>

View File

@ -128,7 +128,6 @@ class pageBookmarksTest extends minifluxTestCase
$this->expectedCounterPage = static::DEFAULT_COUNTER_PAGE - 1; $this->expectedCounterPage = static::DEFAULT_COUNTER_PAGE - 1;
$this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD; $this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD;
$this->expectedDataSet = $this->getDataSet('expected_UnbookmarkReadArticle', 'fixture_feed2'); $this->expectedDataSet = $this->getDataSet('expected_UnbookmarkReadArticle', 'fixture_feed2');
} }
/** /**
@ -217,7 +216,7 @@ class pageBookmarksTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_OnlyReadArticles'); $dataset = $this->getDataSet('fixture_OnlyReadArticles');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -244,7 +243,7 @@ class pageBookmarksTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_OneUnreadArticle'); $dataset = $this->getDataSet('fixture_OneUnreadArticle');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -269,7 +268,7 @@ class pageBookmarksTest extends minifluxTestCase
{ {
$articles = $this->getArticles(); $articles = $this->getArticles();
foreach($articles as $article) { foreach ($articles as $article) {
$link = $this->getLinkBookmarkStatusToogle($article); $link = $this->getLinkBookmarkStatusToogle($article);
$link->click(); $link->click();
@ -279,11 +278,10 @@ class pageBookmarksTest extends minifluxTestCase
$visible = $this->waitForAlert(); $visible = $this->waitForAlert();
$this->assertTrue($visible, 'alert box did not appear'); $this->assertTrue($visible, 'alert box did not appear');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD; $this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD;
$this->expectedDataSet = $this->getDataSet('expected_NoBookmarkedArticles'); $this->expectedDataSet = $this->getDataSet('expected_NoBookmarkedArticles');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
} }
?>

View File

@ -34,7 +34,7 @@ class pageFirstFeedTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1_parsing_error', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1_parsing_error', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -389,7 +389,7 @@ class pageFirstFeedTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -414,7 +414,7 @@ class pageFirstFeedTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -439,7 +439,7 @@ class pageFirstFeedTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_OnlyReadArticles'); $dataset = $this->getDataSet('fixture_OnlyReadArticles');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -466,7 +466,7 @@ class pageFirstFeedTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_OneUnreadArticle'); $dataset = $this->getDataSet('fixture_OneUnreadArticle');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -492,7 +492,7 @@ class pageFirstFeedTest extends minifluxTestCase
$articles = $this->getArticles(); $articles = $this->getArticles();
$this->assertGreaterThanOrEqual(1, count($articles), 'no articles found'); $this->assertGreaterThanOrEqual(1, count($articles), 'no articles found');
foreach($articles as $article) { foreach ($articles as $article) {
$link = $this->getLinkRemove($article); $link = $this->getLinkRemove($article);
$link->click(); $link->click();
@ -502,11 +502,10 @@ class pageFirstFeedTest extends minifluxTestCase
$visible = $this->waitForAlert(); $visible = $this->waitForAlert();
$this->assertTrue($visible, 'alert box did not appear'); $this->assertTrue($visible, 'alert box did not appear');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = 2; $this->expectedCounterUnread = 2;
$this->expectedDataSet = $this->getDataSet('expected_FirstFeedAllRemoved', 'fixture_feed2'); $this->expectedDataSet = $this->getDataSet('expected_FirstFeedAllRemoved', 'fixture_feed2');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
} }
?>

View File

@ -8,7 +8,8 @@ class pageHistoryTest extends minifluxTestCase
public function setUpPage() public function setUpPage()
{ {
$url = $this->getURLPageHistory(); $url = $this->getURLPageHistory();
$this->doLoginIfRequired($url);; $this->doLoginIfRequired($url);
;
$this->basePageHeading = $this->getBasePageHeading(); $this->basePageHeading = $this->getBasePageHeading();
$this->expectedPageUrl = $url; $this->expectedPageUrl = $url;
@ -223,7 +224,7 @@ class pageHistoryTest extends minifluxTestCase
$this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD; $this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD;
$this->expectedDataSet = $this->getDataSet('expected_NoReadNotBookmarkedArticles'); $this->expectedDataSet = $this->getDataSet('expected_NoReadNotBookmarkedArticles');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
public function testUnreadCounterFromNothingToValue() public function testUnreadCounterFromNothingToValue()
@ -231,7 +232,7 @@ class pageHistoryTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_OnlyReadArticles'); $dataset = $this->getDataSet('fixture_OnlyReadArticles');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -256,7 +257,7 @@ class pageHistoryTest extends minifluxTestCase
$articles = $this->getArticles(); $articles = $this->getArticles();
$this->assertGreaterThanOrEqual(1, count($articles), 'no articles found'); $this->assertGreaterThanOrEqual(1, count($articles), 'no articles found');
foreach($articles as $article) { foreach ($articles as $article) {
$link = $this->getLinkReadStatusToogle($article); $link = $this->getLinkReadStatusToogle($article);
$link->click(); $link->click();
@ -266,11 +267,10 @@ class pageHistoryTest extends minifluxTestCase
$visible = $this->waitForAlert(); $visible = $this->waitForAlert();
$this->assertTrue($visible, 'alert box did not appear'); $this->assertTrue($visible, 'alert box did not appear');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD + static::DEFAULT_COUNTER_PAGE; $this->expectedCounterUnread = static::DEFAULT_COUNTER_UNREAD + static::DEFAULT_COUNTER_PAGE;
$this->expectedDataSet = $this->getDataSet('expected_NoReadArticles'); $this->expectedDataSet = $this->getDataSet('expected_NoReadArticles');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
} }
?>

View File

@ -34,7 +34,7 @@ class pageSubscriptionTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -55,7 +55,7 @@ class pageSubscriptionTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -127,4 +127,3 @@ class pageSubscriptionTest extends minifluxTestCase
$this->expectedDataSet = static::$databaseTester->getDataSet(); $this->expectedDataSet = static::$databaseTester->getDataSet();
} }
} }
?>

View File

@ -216,7 +216,7 @@ class pageUnreadTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -231,12 +231,12 @@ class pageUnreadTest extends minifluxTestCase
$read = $this->waitForArticlesMarkRead(); $read = $this->waitForArticlesMarkRead();
$this->assertTrue($read, 'there are still unread articles'); $this->assertTrue($read, 'there are still unread articles');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = ''; $this->expectedCounterUnread = '';
$this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1'; $this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1';
$this->expectedDataSet = $this->getDataSet('expected_MarkAllRead'); $this->expectedDataSet = $this->getDataSet('expected_MarkAllRead');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
public function testMarkAllReadBottomLink() public function testMarkAllReadBottomLink()
@ -244,7 +244,7 @@ class pageUnreadTest extends minifluxTestCase
// load different fixture and reload the page // load different fixture and reload the page
$backupDataTester = static::$databaseTester; $backupDataTester = static::$databaseTester;
static::$databaseTester = NULL; static::$databaseTester = null;
$dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2'); $dataset = $this->getDataSet('fixture_feed1_extra_long', 'fixture_feed2');
$this->getDatabaseTester($dataset)->onSetUp(); $this->getDatabaseTester($dataset)->onSetUp();
@ -259,12 +259,12 @@ class pageUnreadTest extends minifluxTestCase
$read = $this->waitForArticlesMarkRead(); $read = $this->waitForArticlesMarkRead();
$this->assertTrue($read, 'there are still unread articles'); $this->assertTrue($read, 'there are still unread articles');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = ''; $this->expectedCounterUnread = '';
$this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1'; $this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1';
$this->expectedDataSet = $this->getDataSet('expected_MarkAllRead'); $this->expectedDataSet = $this->getDataSet('expected_MarkAllRead');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
public function testRedirectWithZeroArticles() public function testRedirectWithZeroArticles()
@ -272,7 +272,7 @@ class pageUnreadTest extends minifluxTestCase
$articles = $this->getArticles(); $articles = $this->getArticles();
$this->assertGreaterThanOrEqual(1, count($articles), 'no articles found'); $this->assertGreaterThanOrEqual(1, count($articles), 'no articles found');
foreach($articles as $article) { foreach ($articles as $article) {
$link = $this->getLinkReadStatusToogle($article); $link = $this->getLinkReadStatusToogle($article);
$link->click(); $link->click();
@ -282,12 +282,11 @@ class pageUnreadTest extends minifluxTestCase
$visible = $this->waitForAlert(); $visible = $this->waitForAlert();
$this->assertTrue($visible, 'alert box did not appear'); $this->assertTrue($visible, 'alert box did not appear');
$this->expectedCounterPage = NULL; $this->expectedCounterPage = null;
$this->expectedCounterUnread = ''; $this->expectedCounterUnread = '';
$this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1'; $this->expectedPageUrl = PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BASEURL.'?action=feeds&nothing_to_read=1';
$this->expectedDataSet = $this->getDataSet('fixture_OnlyReadArticles'); $this->expectedDataSet = $this->getDataSet('fixture_OnlyReadArticles');
$this->ignorePageTitle = TRUE; $this->ignorePageTitle = true;
} }
} }
?>