- 327 ArthurHoaro <arthur@hoa.ro>
- 188 VirtualTam <virtualtam@flibidi.net>
+ 472 ArthurHoaro <arthur@hoa.ro>
+ 201 VirtualTam <virtualtam@flibidi.net>
132 nodiscc <nodiscc@gmail.com>
56 Sébastien Sauvage <sebsauvage@sebsauvage.net>
15 Florian Eula <eula.florian@gmail.com>
13 Emilien Klein <emilien@klein.st>
12 Nicolas Danelon <hi@nicolasmd.com.ar>
- 7 Christophe HENRY <christophe.henry@sbgodin.fr>
+ 8 Christophe HENRY <christophe.henry@sbgodin.fr>
4 Alexandre Alapetite <alexandre@alapetite.fr>
4 David Sferruzza <david.sferruzza@gmail.com>
3 Teromene <teromene@teromene.fr>
1 Sbgodin <Sbgodin@users.noreply.github.com>
1 TsT <tst2005@gmail.com>
1 dimtion <zizou.xena@gmail.com>
+ 1 philipp-r <philipp-r@users.noreply.github.com>
and this project adheres to [Semantic Versioning](http://semver.org/).
-## [v0.9.0](https://github.com/shaarli/Shaarli/releases/tag/v0.9.0) - UNPUBLISHED
+## [v0.9.0](https://github.com/shaarli/Shaarli/releases/tag/v0.9.0) - 2017-05-07
This release introduces the REST API, and requires updating HTTP server
configuration to enable URL rewriting, see:
- versioned API endpoints:
- `/api/v1/info`: get general information on the Shaarli instance
- `/api/v1/links`: get a list of shaared links
+ - `/api/v1/history`: get a list of latest actions
Theming:
- Introduce a new theme
- Allow selecting themes/templates from the configuration page
- Add `campaign_` to the URL cleanup pattern list
- Add an AUTHORS file and Makefile target to list authors from Git commit data
- Link imports are now logged in `data/` folder, and can be debug using `dev.debug=true` setting.
+- `composer.lock` is now included in git file to allow proper `composer install`
+- History mechanism which logs link addition/modification/deletion
### Changed
- Docker: enable nginx URL rewriting for the REST API
- Rename the legacy theme to `vintage`
- Private only filter is now displayed as a search parameter
- Autocomplete: pre-select the first element
+ - Display daily date in the page title (browser title)
+ - Timezone lists are now passed as an array instead of raw HTML
- Move PubSubHub to a dedicated plugin
- Coding style:
- explicit method visibility
- Improved client locale detection
- Improved date time display depending on the locale
- Partial namespace support for Shaarli classes
+- Shaarli version is now only present in `shaarli_version.php`
+- Human readable maximum file size upload
+
### Removed
- PHP < 5.5 compatibility
+- ReadItYourself plugin
### Fixed
- Ignore generated release tarballs
- Remove extra spaces in the bookmarklet's name
- Piwik plugin: Piwik URL protocol can now be set (http or https)
- All inline JS has been moved to dedicated JS files
+- Keep tags after login redirection
### Security
- Markdown plugin: escape HTML entities by default
_Shaarli is a minimalist delicious clone that you can install on your own server._
_It is designed to be personal (single-user), fast and handy._
-[![](https://img.shields.io/badge/stable-v0.7.1-blue.svg)](https://github.com/shaarli/Shaarli/releases/tag/v0.7.1)
+[![](https://img.shields.io/badge/stable-v0.8.4-blue.svg)](https://github.com/shaarli/Shaarli/releases/tag/v0.8.4)
[![](https://img.shields.io/travis/shaarli/Shaarli/stable.svg?label=stable)](https://travis-ci.org/shaarli/Shaarli)
•
-[![](https://img.shields.io/badge/latest-v0.8.4-blue.svg)](https://github.com/shaarli/Shaarli/releases/tag/v0.8.4)
+[![](https://img.shields.io/badge/latest-v0.9.0-blue.svg)](https://github.com/shaarli/Shaarli/releases/tag/v0.9.0)
[![](https://img.shields.io/travis/shaarli/Shaarli/latest.svg?label=latest)](https://travis-ci.org/shaarli/Shaarli)
•
[![](https://img.shields.io/badge/master-v0.9.x-blue.svg)](https://github.com/shaarli/Shaarli)
- URL cleanup: automatic removal of `?utm_source=...`, `fb=...`
- discreet pop-up notification when a new release is available
+### REST API
+
+Easily extensible by any client using the REST API exposed by Shaarli.
+
+See the [API documentation](http://shaarli.github.io/api-documentation/).
+
### Other usages
Though Shaarli is primarily a bookmarking application, it can serve other purposes
(see [usage examples](https://github.com/shaarli/Shaarli/wiki#usage-examples)):
<?php
+
+require_once 'exceptions/IOException.php';
+
/**
- * Exception class thrown when a filesystem access failure happens
+ * Class FileUtils
+ *
+ * Utility class for file manipulation.
*/
-class IOException extends Exception
+class FileUtils
{
- private $path;
+ /**
+ * @var string
+ */
+ protected static $phpPrefix = '<?php /* ';
+
+ /**
+ * @var string
+ */
+ protected static $phpSuffix = ' */ ?>';
/**
- * Construct a new IOException
+ * Write data into a file (Shaarli database format).
+ * The data is stored in a PHP file, as a comment, in compressed base64 format.
+ *
+ * The file will be created if it doesn't exist.
+ *
+ * @param string $file File path.
+ * @param mixed $content Content to write.
+ *
+ * @return int|bool Number of bytes written or false if it fails.
*
- * @param string $path path to the resource that cannot be accessed
- * @param string $message Custom exception message.
+ * @throws IOException The destination file can't be written.
*/
- public function __construct($path, $message = '')
+ public static function writeFlatDB($file, $content)
{
- $this->path = $path;
- $this->message = empty($message) ? 'Error accessing' : $message;
- $this->message .= PHP_EOL . $this->path;
+ if (is_file($file) && !is_writeable($file)) {
+ // The datastore exists but is not writeable
+ throw new IOException($file);
+ } else if (!is_file($file) && !is_writeable(dirname($file))) {
+ // The datastore does not exist and its parent directory is not writeable
+ throw new IOException(dirname($file));
+ }
+
+ return file_put_contents(
+ $file,
+ self::$phpPrefix.base64_encode(gzdeflate(serialize($content))).self::$phpSuffix
+ );
+ }
+
+ /**
+ * Read data from a file containing Shaarli database format content.
+ * If the file isn't readable or doesn't exists, default data will be returned.
+ *
+ * @param string $file File path.
+ * @param mixed $default The default value to return if the file isn't readable.
+ *
+ * @return mixed The content unserialized, or default if the file isn't readable, or false if it fails.
+ */
+ public static function readFlatDB($file, $default = null)
+ {
+ // Note that gzinflate is faster than gzuncompress.
+ // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
+ if (is_readable($file)) {
+ return unserialize(
+ gzinflate(
+ base64_decode(
+ substr(file_get_contents($file), strlen(self::$phpPrefix), -strlen(self::$phpSuffix))
+ )
+ )
+ );
+ }
+
+ return $default;
}
}
--- /dev/null
+<?php
+
+/**
+ * Class History
+ *
+ * Handle the history file tracing events in Shaarli.
+ * The history is stored as JSON in a file set by 'resource.history' setting.
+ *
+ * Available data:
+ * - event: event key
+ * - datetime: event date, in ISO8601 format.
+ * - id: event item identifier (currently only link IDs).
+ *
+ * Available event keys:
+ * - CREATED: new link
+ * - UPDATED: link updated
+ * - DELETED: link deleted
+ * - SETTINGS: the settings have been updated through the UI.
+ *
+ * Note: new events are put at the beginning of the file and history array.
+ */
+class History
+{
+ /**
+ * @var string Action key: a new link has been created.
+ */
+ const CREATED = 'CREATED';
+
+ /**
+ * @var string Action key: a link has been updated.
+ */
+ const UPDATED = 'UPDATED';
+
+ /**
+ * @var string Action key: a link has been deleted.
+ */
+ const DELETED = 'DELETED';
+
+ /**
+ * @var string Action key: settings have been updated.
+ */
+ const SETTINGS = 'SETTINGS';
+
+ /**
+ * @var string History file path.
+ */
+ protected $historyFilePath;
+
+ /**
+ * @var array History data.
+ */
+ protected $history;
+
+ /**
+ * @var int History retention time in seconds (1 month).
+ */
+ protected $retentionTime = 2678400;
+
+ /**
+ * History constructor.
+ *
+ * @param string $historyFilePath History file path.
+ * @param int $retentionTime History content rentention time in seconds.
+ *
+ * @throws Exception if something goes wrong.
+ */
+ public function __construct($historyFilePath, $retentionTime = null)
+ {
+ $this->historyFilePath = $historyFilePath;
+ if ($retentionTime !== null) {
+ $this->retentionTime = $retentionTime;
+ }
+ }
+
+ /**
+ * Initialize: read history file.
+ *
+ * Allow lazy loading (don't read the file if it isn't necessary).
+ */
+ protected function initialize()
+ {
+ $this->check();
+ $this->read();
+ }
+
+ /**
+ * Add Event: new link.
+ *
+ * @param array $link Link data.
+ */
+ public function addLink($link)
+ {
+ $this->addEvent(self::CREATED, $link['id']);
+ }
+
+ /**
+ * Add Event: update existing link.
+ *
+ * @param array $link Link data.
+ */
+ public function updateLink($link)
+ {
+ $this->addEvent(self::UPDATED, $link['id']);
+ }
+
+ /**
+ * Add Event: delete existing link.
+ *
+ * @param array $link Link data.
+ */
+ public function deleteLink($link)
+ {
+ $this->addEvent(self::DELETED, $link['id']);
+ }
+
+ /**
+ * Add Event: settings updated.
+ */
+ public function updateSettings()
+ {
+ $this->addEvent(self::SETTINGS);
+ }
+
+ /**
+ * Save a new event and write it in the history file.
+ *
+ * @param string $status Event key, should be defined as constant.
+ * @param mixed $id Event item identifier (e.g. link ID).
+ */
+ protected function addEvent($status, $id = null)
+ {
+ if ($this->history === null) {
+ $this->initialize();
+ }
+
+ $item = [
+ 'event' => $status,
+ 'datetime' => new DateTime(),
+ 'id' => $id !== null ? $id : '',
+ ];
+ $this->history = array_merge([$item], $this->history);
+ $this->write();
+ }
+
+ /**
+ * Check that the history file is writable.
+ * Create the file if it doesn't exist.
+ *
+ * @throws Exception if it isn't writable.
+ */
+ protected function check()
+ {
+ if (! is_file($this->historyFilePath)) {
+ FileUtils::writeFlatDB($this->historyFilePath, []);
+ }
+
+ if (! is_writable($this->historyFilePath)) {
+ throw new Exception('History file isn\'t readable or writable');
+ }
+ }
+
+ /**
+ * Read JSON history file.
+ */
+ protected function read()
+ {
+ $this->history = FileUtils::readFlatDB($this->historyFilePath, []);
+ if ($this->history === false) {
+ throw new Exception('Could not parse history file');
+ }
+ }
+
+ /**
+ * Write JSON history file and delete old entries.
+ */
+ protected function write()
+ {
+ $comparaison = new DateTime('-'. $this->retentionTime . ' seconds');
+ foreach ($this->history as $key => $value) {
+ if ($value['datetime'] < $comparaison) {
+ unset($this->history[$key]);
+ }
+ }
+ FileUtils::writeFlatDB($this->historyFilePath, array_values($this->history));
+ }
+
+ /**
+ * Get the History.
+ *
+ * @return array
+ */
+ public function getHistory()
+ {
+ if ($this->history === null) {
+ $this->initialize();
+ }
+
+ return $this->history;
+ }
+}
// Link date storage format
const LINK_DATE_FORMAT = 'Ymd_His';
- // Datastore PHP prefix
- protected static $phpPrefix = '<?php /* ';
-
- // Datastore PHP suffix
- protected static $phpSuffix = ' */ ?>';
-
// List of links (associative array)
// - key: link date (e.g. "20110823_124546"),
// - value: associative array (keys: title, description...)
if (!isset($value['id']) || empty($value['url'])) {
die('Internal Error: A link should always have an id and URL.');
}
- if ((! empty($offset) && ! is_int($offset)) || ! is_int($value['id'])) {
+ if (($offset !== null && ! is_int($offset)) || ! is_int($value['id'])) {
die('You must specify an integer as a key.');
}
- if (! empty($offset) && $offset !== $value['id']) {
+ if ($offset !== null && $offset !== $value['id']) {
die('Array offset and link ID must be equal.');
}
return;
}
- // Read data
- // Note that gzinflate is faster than gzuncompress.
- // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
- $this->links = array();
-
- if (file_exists($this->datastore)) {
- $this->links = unserialize(gzinflate(base64_decode(
- substr(file_get_contents($this->datastore),
- strlen(self::$phpPrefix), -strlen(self::$phpSuffix)))));
- }
+ $this->links = FileUtils::readFlatDB($this->datastore, []);
$toremove = array();
foreach ($this->links as $key => &$link) {
*/
private function write()
{
- if (is_file($this->datastore) && !is_writeable($this->datastore)) {
- // The datastore exists but is not writeable
- throw new IOException($this->datastore);
- } else if (!is_file($this->datastore) && !is_writeable(dirname($this->datastore))) {
- // The datastore does not exist and its parent directory is not writeable
- throw new IOException(dirname($this->datastore));
- }
-
- file_put_contents(
- $this->datastore,
- self::$phpPrefix.base64_encode(gzdeflate(serialize($this->links))).self::$phpSuffix
- );
-
+ FileUtils::writeFlatDB($this->datastore, $this->links);
}
/**
}
/**
- * Returns the list of all tags
- * Output: associative array key=tags, value=0
+ * Returns the list tags appearing in the links with the given tags
+ * @param $filteringTags: tags selecting the links to consider
+ * @param $visibility: process only all/private/public links
+ * @return: a tag=>linksCount array
*/
- public function allTags()
+ public function linksCountPerTag($filteringTags = [], $visibility = 'all')
{
+ $links = empty($filteringTags) ? $this->links : $this->filterSearch(['searchtags' => $filteringTags], false, $visibility);
$tags = array();
$caseMapping = array();
- foreach ($this->links as $link) {
+ foreach ($links as $link) {
foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY) as $tag) {
if (empty($tag)) {
continue;
* @param array $files Server $_FILES parameters
* @param LinkDB $linkDb Loaded LinkDB instance
* @param ConfigManager $conf instance
+ * @param History $history History instance
*
* @return string Summary of the bookmark import status
*/
- public static function import($post, $files, $linkDb, $conf)
+ public static function import($post, $files, $linkDb, $conf, $history)
{
$filename = $files['filetoupload']['name'];
$filesize = $files['filetoupload']['size'];
$newLink['id'] = $existingLink['id'];
$newLink['created'] = $existingLink['created'];
$newLink['updated'] = new DateTime();
+ $newLink['shorturl'] = $existingLink['shorturl'];
$linkDb[$existingLink['id']] = $newLink;
$importCount++;
$overwriteCount++;
+ $history->updateLink($newLink);
continue;
}
$newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
$linkDb[$newLink['id']] = $newLink;
$importCount++;
+ $history->addLink($newLink);
}
$linkDb->save($conf->get('resource.page_cache'));
<?php
+use Shaarli\Config\ConfigManager;
+
/**
* This class is in charge of building the final page.
* (This is basically a wrapper around RainTPL which pre-fills some fields.)
*/
protected $conf;
+ /**
+ * @var LinkDB $linkDB instance.
+ */
+ protected $linkDB;
+
/**
* PageBuilder constructor.
* $tpl is initialized at false for lazy loading.
*
- * @param ConfigManager $conf Configuration Manager instance (reference).
+ * @param ConfigManager $conf Configuration Manager instance (reference).
+ * @param LinkDB $linkDB instance.
*/
- public function __construct(&$conf)
+ public function __construct(&$conf, $linkDB = null)
{
$this->tpl = false;
$this->conf = $conf;
+ $this->linkDB = $linkDB;
}
/**
$this->tpl->assign('feed_type', $this->conf->get('feed.show_atom', true) !== false ? 'atom' : 'rss');
$this->tpl->assign('hide_timestamps', $this->conf->get('privacy.hide_timestamps', false));
$this->tpl->assign('token', getToken($this->conf));
+ if ($this->linkDB !== null) {
+ $this->tpl->assign('tags', $this->linkDB->linksCountPerTag());
+ }
// To be removed with a proper theme configuration.
$this->tpl->assign('conf', $this->conf);
}
public static $PAGE_TAGCLOUD = 'tagcloud';
+ public static $PAGE_TAGLIST = 'taglist';
+
public static $PAGE_DAILY = 'daily';
public static $PAGE_FEED_ATOM = 'atom';
public static $PAGE_SAVE_PLUGINSADMIN = 'save_pluginadmin';
+ public static $GET_TOKEN = 'token';
+
/**
* Reproducing renderPage() if hell, to avoid regression.
*
return self::$PAGE_TAGCLOUD;
}
+ if (startsWith($query, 'do='. self::$PAGE_TAGLIST)) {
+ return self::$PAGE_TAGLIST;
+ }
+
if (startsWith($query, 'do='. self::$PAGE_OPENSEARCH)) {
return self::$PAGE_OPENSEARCH;
}
return self::$PAGE_SAVE_PLUGINSADMIN;
}
+ if (startsWith($query, 'do='. self::$GET_TOKEN)) {
+ return self::$GET_TOKEN;
+ }
+
return self::$PAGE_LINKLIST;
}
}
<?php
/**
- * Generates the timezone selection form and JavaScript.
+ * Generates a list of available timezone continents and cities.
*
- * Note: 'UTC/UTC' is mapped to 'UTC' to form a valid option
+ * Two distinct array based on available timezones
+ * and the one selected in the settings:
+ * - (0) continents:
+ * + list of available continents
+ * + special key 'selected' containing the value of the selected timezone's continent
+ * - (1) cities:
+ * + list of available cities associated with their continent
+ * + special key 'selected' containing the value of the selected timezone's city (without the continent)
*
- * Example: preselect Europe/Paris
- * list($htmlform, $js) = generateTimeZoneForm('Europe/Paris');
+ * Example:
+ * [
+ * [
+ * 'America',
+ * 'Europe',
+ * 'selected' => 'Europe',
+ * ],
+ * [
+ * ['continent' => 'America', 'city' => 'Toronto'],
+ * ['continent' => 'Europe', 'city' => 'Paris'],
+ * 'selected' => 'Paris',
+ * ],
+ * ];
*
+ * Notes:
+ * - 'UTC/UTC' is mapped to 'UTC' to form a valid option
+ * - a few timezone cities includes the country/state, such as Argentina/Buenos_Aires
+ * - these arrays are designed to build timezone selects in template files with any HTML structure
+ *
+ * @param array $installedTimeZones List of installed timezones as string
* @param string $preselectedTimezone preselected timezone (optional)
*
- * @return array containing the generated HTML form and Javascript code
+ * @return array[] continents and cities
**/
-function generateTimeZoneForm($preselectedTimezone='')
+function generateTimeZoneData($installedTimeZones, $preselectedTimezone = '')
{
- // Select the server timezone
- if ($preselectedTimezone == '') {
- $preselectedTimezone = date_default_timezone_get();
- }
-
if ($preselectedTimezone == 'UTC') {
$pcity = $pcontinent = 'UTC';
} else {
$pcity = substr($preselectedTimezone, $spos+1);
}
- // The list is in the form 'Europe/Paris', 'America/Argentina/Buenos_Aires'
- // We split the list in continents/cities.
- $continents = array();
- $cities = array();
-
- // TODO: use a template to generate the HTML/Javascript form
-
- foreach (timezone_identifiers_list() as $tz) {
+ $continents = [];
+ $cities = [];
+ foreach ($installedTimeZones as $tz) {
if ($tz == 'UTC') {
$tz = 'UTC/UTC';
}
$spos = strpos($tz, '/');
- if ($spos !== false) {
- $continent = substr($tz, 0, $spos);
- $city = substr($tz, $spos+1);
- $continents[$continent] = 1;
-
- if (!isset($cities[$continent])) {
- $cities[$continent] = '';
- }
- $cities[$continent] .= '<option value="'.$city.'"';
- if ($pcity == $city) {
- $cities[$continent] .= ' selected="selected"';
- }
- $cities[$continent] .= '>'.$city.'</option>';
+ // Ignore invalid timezones
+ if ($spos === false) {
+ continue;
}
- }
-
- $continentsHtml = '';
- $continents = array_keys($continents);
- foreach ($continents as $continent) {
- $continentsHtml .= '<option value="'.$continent.'"';
- if ($pcontinent == $continent) {
- $continentsHtml .= ' selected="selected"';
- }
- $continentsHtml .= '>'.$continent.'</option>';
+ $continent = substr($tz, 0, $spos);
+ $city = substr($tz, $spos+1);
+ $cities[] = ['continent' => $continent, 'city' => $city];
+ $continents[$continent] = true;
}
- // Timezone selection form
- $timezoneForm = 'Continent:';
- $timezoneForm .= '<select name="continent" id="continent" onChange="onChangecontinent();">';
- $timezoneForm .= $continentsHtml.'</select>';
- $timezoneForm .= ' City:';
- $timezoneForm .= '<select name="city" id="city">'.$cities[$pcontinent].'</select><br />';
-
- // Javascript handler - updates the city list when the user selects a continent
- $timezoneJs = '<script>';
- $timezoneJs .= 'function onChangecontinent() {';
- $timezoneJs .= 'document.getElementById("city").innerHTML =';
- $timezoneJs .= ' citiescontinent[document.getElementById("continent").value]; }';
- $timezoneJs .= 'var citiescontinent = '.json_encode($cities).';';
- $timezoneJs .= '</script>';
+ $continents = array_keys($continents);
+ $continents['selected'] = $pcontinent;
+ $cities['selected'] = $pcity;
- return array($timezoneForm, $timezoneJs);
+ return [$continents, $cities];
}
/**
return rename('inc/user.css', 'data/user.css');
}
- /**
- * While the new default theme is in an unstable state
- * continue to use the vintage theme
- */
- public function updateMethodDefaultThemeVintage()
- {
- if ($this->conf->get('resource.theme') !== 'default') {
- return true;
- }
- $this->conf->set('resource.theme', 'vintage');
- $this->conf->write($this->isLoggedIn);
-
- return true;
- }
-
/**
* * `markdown_escape` is a new setting, set to true as default.
*
$this->conf->write($this->isLoggedIn);
return true;
}
+
+ /**
+ * Reset history store file due to date format change.
+ */
+ public function updateMethodResetHistoryFile()
+ {
+ if (is_file($this->conf->get('resource.history'))) {
+ unlink($this->conf->get('resource.history'));
+ }
+ return true;
+ }
}
/**
* otherwise default format '%c' will be returned.
*
* @param DateTime $date to format.
+ * @param bool $time Displays time if true.
* @param bool $intl Use international format if true.
*
* @return bool|string Formatted date, or false if the input is invalid.
*/
-function format_date($date, $intl = true)
+function format_date($date, $time = true, $intl = true)
{
if (! $date instanceof DateTime) {
return false;
}
if (! $intl || ! class_exists('IntlDateFormatter')) {
- return strftime('%c', $date->getTimestamp());
+ $format = $time ? '%c' : '%x';
+ return strftime($format, $date->getTimestamp());
}
$formatter = new IntlDateFormatter(
setlocale(LC_TIME, 0),
IntlDateFormatter::LONG,
- IntlDateFormatter::LONG
+ $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE
);
return $formatter->format($date);
}
+
+/**
+ * Check if the input is an integer, no matter its real type.
+ *
+ * PHP is a bit messy regarding this:
+ * - is_int returns false if the input is a string
+ * - ctype_digit returns false if the input is an integer or negative
+ *
+ * @param mixed $input value
+ *
+ * @return bool true if the input is an integer, false otherwise
+ */
+function is_integer_mixed($input)
+{
+ if (is_array($input) || is_bool($input) || is_object($input)) {
+ return false;
+ }
+ $input = strval($input);
+ return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
+}
+
+/**
+ * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
+ *
+ * @param string $val Size expressed in string.
+ *
+ * @return int Size expressed in bytes.
+ */
+function return_bytes($val)
+{
+ if (is_integer_mixed($val) || $val === '0' || empty($val)) {
+ return $val;
+ }
+ $val = trim($val);
+ $last = strtolower($val[strlen($val)-1]);
+ $val = intval(substr($val, 0, -1));
+ switch($last) {
+ case 'g': $val *= 1024;
+ case 'm': $val *= 1024;
+ case 'k': $val *= 1024;
+ }
+ return $val;
+}
+
+/**
+ * Return a human readable size from bytes.
+ *
+ * @param int $bytes value
+ *
+ * @return string Human readable size
+ */
+function human_bytes($bytes)
+{
+ if ($bytes === '') {
+ return t('Setting not set');
+ }
+ if (! is_integer_mixed($bytes)) {
+ return $bytes;
+ }
+ $bytes = intval($bytes);
+ if ($bytes === 0) {
+ return t('Unlimited');
+ }
+
+ $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
+ for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) {
+ $bytes /= 1024;
+ }
+
+ return round($bytes) . $units[$i];
+}
+
+/**
+ * Try to determine max file size for uploads (POST).
+ * Returns an integer (in bytes) or formatted depending on $format.
+ *
+ * @param mixed $limitPost post_max_size PHP setting
+ * @param mixed $limitUpload upload_max_filesize PHP setting
+ * @param bool $format Format max upload size to human readable size
+ *
+ * @return int|string max upload file size
+ */
+function get_max_upload_size($limitPost, $limitUpload, $format = true)
+{
+ $size1 = return_bytes($limitPost);
+ $size2 = return_bytes($limitUpload);
+ // Return the smaller of two:
+ $maxsize = min($size1, $size2);
+ return $format ? human_bytes($maxsize) : $maxsize;
+}
+
+/**
+ * Sort the given array alphabetically using php-intl if available.
+ * Case sensitive.
+ *
+ * Note: doesn't support multidimensional arrays
+ *
+ * @param array $data Input array, passed by reference
+ * @param bool $reverse Reverse sort if set to true
+ * @param bool $byKeys Sort the array by keys if set to true, by value otherwise.
+ */
+function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
+{
+ $callback = function($a, $b) use ($reverse) {
+ // Collator is part of PHP intl.
+ if (class_exists('Collator')) {
+ $collator = new Collator(setlocale(LC_COLLATE, 0));
+ if (!intl_is_failure(intl_get_error_code())) {
+ return $collator->compare($a, $b) * ($reverse ? -1 : 1);
+ }
+ }
+
+ return strcasecmp($a, $b) * ($reverse ? -1 : 1);
+ };
+
+ if ($byKeys) {
+ uksort($data, $callback);
+ } else {
+ usort($data, $callback);
+ }
+}
use Shaarli\Api\Exceptions\ApiException;
use Shaarli\Api\Exceptions\ApiAuthorizationException;
+use Shaarli\Config\ConfigManager;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;
protected $container;
/**
- * @var \ConfigManager instance.
+ * @var ConfigManager instance.
*/
protected $conf;
*
* FIXME! LinkDB could use a refactoring to avoid this trick.
*
- * @param \ConfigManager $conf instance.
+ * @param ConfigManager $conf instance.
*/
protected function setLinkDb($conf)
{
/**
* Validates a JWT token authenticity.
*
- * @param string $token JWT token extracted from the headers.
+ * @param string $token JWT token extracted from the headers.
* @param string $secret API secret set in the settings.
*
* @throws ApiAuthorizationException the token is not valid.
/**
* Format a Link for the REST API.
*
- * @param array $link Link data read from the datastore.
+ * @param array $link Link data read from the datastore.
* @param string $indexUrl Shaarli's index URL (used for relative URL).
*
* @return array Link data formatted for the REST API.
}
return $out;
}
+
+ /**
+ * Convert a link given through a request, to a valid link for LinkDB.
+ *
+ * If no URL is provided, it will generate a local note URL.
+ * If no title is provided, it will use the URL as title.
+ *
+ * @param array $input Request Link.
+ * @param bool $defaultPrivate Request Link.
+ *
+ * @return array Formatted link.
+ */
+ public static function buildLinkFromRequest($input, $defaultPrivate)
+ {
+ $input['url'] = ! empty($input['url']) ? cleanup_url($input['url']) : '';
+ if (isset($input['private'])) {
+ $private = filter_var($input['private'], FILTER_VALIDATE_BOOLEAN);
+ } else {
+ $private = $defaultPrivate;
+ }
+
+ $link = [
+ 'title' => ! empty($input['title']) ? $input['title'] : $input['url'],
+ 'url' => $input['url'],
+ 'description' => ! empty($input['description']) ? $input['description'] : '',
+ 'tags' => ! empty($input['tags']) ? implode(' ', $input['tags']) : '',
+ 'private' => $private,
+ 'created' => new \DateTime(),
+ ];
+ return $link;
+ }
+
+ /**
+ * Update link fields using an updated link object.
+ *
+ * @param array $oldLink data
+ * @param array $newLink data
+ *
+ * @return array $oldLink updated with $newLink values
+ */
+ public static function updateLink($oldLink, $newLink)
+ {
+ foreach (['title', 'url', 'description', 'tags', 'private'] as $field) {
+ $oldLink[$field] = $newLink[$field];
+ }
+ $oldLink['updated'] = new \DateTime();
+
+ if (empty($oldLink['url'])) {
+ $oldLink['url'] = '?' . $oldLink['shorturl'];
+ }
+
+ if (empty($oldLink['title'])) {
+ $oldLink['title'] = $oldLink['url'];
+ }
+
+ return $oldLink;
+ }
}
namespace Shaarli\Api\Controllers;
+use Shaarli\Config\ConfigManager;
use \Slim\Container;
/**
protected $ci;
/**
- * @var \ConfigManager
+ * @var ConfigManager
*/
protected $conf;
*/
protected $linkDb;
+ /**
+ * @var \History
+ */
+ protected $history;
+
/**
* @var int|null JSON style option.
*/
$this->ci = $ci;
$this->conf = $ci->get('conf');
$this->linkDb = $ci->get('db');
+ $this->history = $ci->get('history');
if ($this->conf->get('dev.debug', false)) {
$this->jsonStyle = JSON_PRETTY_PRINT;
} else {
$this->jsonStyle = null;
}
}
+
+ /**
+ * Get the container.
+ *
+ * @return Container
+ */
+ public function getCi()
+ {
+ return $this->ci;
+ }
}
--- /dev/null
+<?php
+
+
+namespace Shaarli\Api\Controllers;
+
+use Shaarli\Api\Exceptions\ApiBadParametersException;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+/**
+ * Class History
+ *
+ * REST API Controller: /history
+ *
+ * @package Shaarli\Api\Controllers
+ */
+class History extends ApiController
+{
+ /**
+ * Service providing operation regarding Shaarli datastore and settings.
+ *
+ * @param Request $request Slim request.
+ * @param Response $response Slim response.
+ *
+ * @return Response response.
+ *
+ * @throws ApiBadParametersException Invalid parameters.
+ */
+ public function getHistory($request, $response)
+ {
+ $history = $this->history->getHistory();
+
+ // Return history operations from the {offset}th, starting from {since}.
+ $since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getParam('since'));
+ $offset = $request->getParam('offset');
+ if (empty($offset)) {
+ $offset = 0;
+ }
+ else if (ctype_digit($offset)) {
+ $offset = (int) $offset;
+ } else {
+ throw new ApiBadParametersException('Invalid offset');
+ }
+
+ // limit parameter is either a number of links or 'all' for everything.
+ $limit = $request->getParam('limit');
+ if (empty($limit)) {
+ $limit = count($history);
+ } else if (ctype_digit($limit)) {
+ $limit = (int) $limit;
+ } else {
+ throw new ApiBadParametersException('Invalid limit');
+ }
+
+ $out = [];
+ $i = 0;
+ foreach ($history as $entry) {
+ if ((! empty($since) && $entry['datetime'] <= $since) || count($out) >= $limit) {
+ break;
+ }
+ if (++$i > $offset) {
+ $out[$i] = $entry;
+ $out[$i]['datetime'] = $out[$i]['datetime']->format(\DateTime::ATOM);
+ }
+ }
+ $out = array_values($out);
+
+ return $response->withJson($out, 200, $this->jsonStyle);
+ }
+}
*/
public function getLink($request, $response, $args)
{
- if (! isset($this->linkDb[$args['id']])) {
+ if (!isset($this->linkDb[$args['id']])) {
throw new ApiLinkNotFoundException();
}
$index = index_url($this->ci['environment']);
$out = ApiUtils::formatLink($this->linkDb[$args['id']], $index);
+
return $response->withJson($out, 200, $this->jsonStyle);
}
+
+ /**
+ * Creates a new link from posted request body.
+ *
+ * @param Request $request Slim request.
+ * @param Response $response Slim response.
+ *
+ * @return Response response.
+ */
+ public function postLink($request, $response)
+ {
+ $data = $request->getParsedBody();
+ $link = ApiUtils::buildLinkFromRequest($data, $this->conf->get('privacy.default_private_links'));
+ // duplicate by URL, return 409 Conflict
+ if (! empty($link['url']) && ! empty($dup = $this->linkDb->getLinkFromUrl($link['url']))) {
+ return $response->withJson(
+ ApiUtils::formatLink($dup, index_url($this->ci['environment'])),
+ 409,
+ $this->jsonStyle
+ );
+ }
+
+ $link['id'] = $this->linkDb->getNextId();
+ $link['shorturl'] = link_small_hash($link['created'], $link['id']);
+
+ // note: general relative URL
+ if (empty($link['url'])) {
+ $link['url'] = '?' . $link['shorturl'];
+ }
+
+ if (empty($link['title'])) {
+ $link['title'] = $link['url'];
+ }
+
+ $this->linkDb[$link['id']] = $link;
+ $this->linkDb->save($this->conf->get('resource.page_cache'));
+ $this->history->addLink($link);
+ $out = ApiUtils::formatLink($link, index_url($this->ci['environment']));
+ $redirect = $this->ci->router->relativePathFor('getLink', ['id' => $link['id']]);
+ return $response->withAddedHeader('Location', $redirect)
+ ->withJson($out, 201, $this->jsonStyle);
+ }
+
+ /**
+ * Updates an existing link from posted request body.
+ *
+ * @param Request $request Slim request.
+ * @param Response $response Slim response.
+ * @param array $args Path parameters. including the ID.
+ *
+ * @return Response response.
+ *
+ * @throws ApiLinkNotFoundException generating a 404 error.
+ */
+ public function putLink($request, $response, $args)
+ {
+ if (! isset($this->linkDb[$args['id']])) {
+ throw new ApiLinkNotFoundException();
+ }
+
+ $index = index_url($this->ci['environment']);
+ $data = $request->getParsedBody();
+
+ $requestLink = ApiUtils::buildLinkFromRequest($data, $this->conf->get('privacy.default_private_links'));
+ // duplicate URL on a different link, return 409 Conflict
+ if (! empty($requestLink['url'])
+ && ! empty($dup = $this->linkDb->getLinkFromUrl($requestLink['url']))
+ && $dup['id'] != $args['id']
+ ) {
+ return $response->withJson(
+ ApiUtils::formatLink($dup, $index),
+ 409,
+ $this->jsonStyle
+ );
+ }
+
+ $responseLink = $this->linkDb[$args['id']];
+ $responseLink = ApiUtils::updateLink($responseLink, $requestLink);
+ $this->linkDb[$responseLink['id']] = $responseLink;
+ $this->linkDb->save($this->conf->get('resource.page_cache'));
+ $this->history->updateLink($responseLink);
+
+ $out = ApiUtils::formatLink($responseLink, $index);
+ return $response->withJson($out, 200, $this->jsonStyle);
+ }
+
+ /**
+ * Delete an existing link by its ID.
+ *
+ * @param Request $request Slim request.
+ * @param Response $response Slim response.
+ * @param array $args Path parameters. including the ID.
+ *
+ * @return Response response.
+ *
+ * @throws ApiLinkNotFoundException generating a 404 error.
+ */
+ public function deleteLink($request, $response, $args)
+ {
+ if (! isset($this->linkDb[$args['id']])) {
+ throw new ApiLinkNotFoundException();
+ }
+ $link = $this->linkDb[$args['id']];
+ unset($this->linkDb[(int) $args['id']]);
+ $this->linkDb->save($this->conf->get('resource.page_cache'));
+ $this->history->deleteLink($link);
+
+ return $response->withStatus(204);
+ }
}
$this->setEmpty('resource.updates', 'data/updates.txt');
$this->setEmpty('resource.log', 'data/log.txt');
$this->setEmpty('resource.update_check', 'data/lastupdatecheck.txt');
+ $this->setEmpty('resource.history', 'data/history.php');
$this->setEmpty('resource.raintpl_tpl', 'tpl/');
$this->setEmpty('resource.theme', 'default');
$this->setEmpty('resource.raintpl_tmp', 'tmp/');
--- /dev/null
+<?php
+
+/**
+ * Exception class thrown when a filesystem access failure happens
+ */
+class IOException extends Exception
+{
+ private $path;
+
+ /**
+ * Construct a new IOException
+ *
+ * @param string $path path to the resource that cannot be accessed
+ * @param string $message Custom exception message.
+ */
+ public function __construct($path, $message = '')
+ {
+ $this->path = $path;
+ $this->message = empty($message) ? 'Error accessing' : $message;
+ $this->message .= ' "' . $this->path .'"';
+ }
+}
},
{
"name": "squizlabs/php_codesniffer",
- "version": "2.8.1",
+ "version": "2.9.0",
"source": {
"type": "git",
"url": "https://github.com/squizlabs/PHP_CodeSniffer.git",
- "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d"
+ "reference": "f7dfecbee89d68ab475a6c9e17d22bc9b69aed97"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d",
- "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d",
+ "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/f7dfecbee89d68ab475a6c9e17d22bc9b69aed97",
+ "reference": "f7dfecbee89d68ab475a6c9e17d22bc9b69aed97",
"shasum": ""
},
"require": {
"phpcs",
"standards"
],
- "time": "2017-03-01T22:17:45+00:00"
+ "time": "2017-05-03T23:30:39+00:00"
},
{
"name": "symfony/config",
- "version": "v3.2.6",
+ "version": "v3.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/config.git",
- "reference": "741d6d4cd1414d67d48eb71aba6072b46ba740c2"
+ "reference": "e5533fcc0b3dd377626153b2852707878f363728"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/config/zipball/741d6d4cd1414d67d48eb71aba6072b46ba740c2",
- "reference": "741d6d4cd1414d67d48eb71aba6072b46ba740c2",
+ "url": "https://api.github.com/repos/symfony/config/zipball/e5533fcc0b3dd377626153b2852707878f363728",
+ "reference": "e5533fcc0b3dd377626153b2852707878f363728",
"shasum": ""
},
"require": {
],
"description": "Symfony Config Component",
"homepage": "https://symfony.com",
- "time": "2017-03-01T18:18:25+00:00"
+ "time": "2017-04-12T14:13:17+00:00"
},
{
"name": "symfony/console",
- "version": "v2.8.18",
+ "version": "v2.8.20",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
- "reference": "81508e6fac4476771275a3f4f53c3fee9b956bfa"
+ "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/console/zipball/81508e6fac4476771275a3f4f53c3fee9b956bfa",
- "reference": "81508e6fac4476771275a3f4f53c3fee9b956bfa",
+ "url": "https://api.github.com/repos/symfony/console/zipball/2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e",
+ "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e",
"shasum": ""
},
"require": {
],
"description": "Symfony Console Component",
"homepage": "https://symfony.com",
- "time": "2017-03-04T11:00:12+00:00"
+ "time": "2017-04-26T01:38:53+00:00"
},
{
"name": "symfony/debug",
},
{
"name": "symfony/dependency-injection",
- "version": "v3.2.6",
+ "version": "v3.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/dependency-injection.git",
- "reference": "74e0935e414ad33d5e82074212c0eedb4681a691"
+ "reference": "5e00857475b6d1fa31ff4c76f1fddf1cfa9e8d59"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/74e0935e414ad33d5e82074212c0eedb4681a691",
- "reference": "74e0935e414ad33d5e82074212c0eedb4681a691",
+ "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/5e00857475b6d1fa31ff4c76f1fddf1cfa9e8d59",
+ "reference": "5e00857475b6d1fa31ff4c76f1fddf1cfa9e8d59",
"shasum": ""
},
"require": {
],
"description": "Symfony DependencyInjection Component",
"homepage": "https://symfony.com",
- "time": "2017-03-05T00:06:55+00:00"
+ "time": "2017-04-26T01:39:17+00:00"
},
{
"name": "symfony/filesystem",
- "version": "v3.2.6",
+ "version": "v3.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/filesystem.git",
- "reference": "bc0f17bed914df2cceb989972c3b996043c4da4a"
+ "reference": "040651db13cf061827a460cc10f6e36a445c45b4"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/filesystem/zipball/bc0f17bed914df2cceb989972c3b996043c4da4a",
- "reference": "bc0f17bed914df2cceb989972c3b996043c4da4a",
+ "url": "https://api.github.com/repos/symfony/filesystem/zipball/040651db13cf061827a460cc10f6e36a445c45b4",
+ "reference": "040651db13cf061827a460cc10f6e36a445c45b4",
"shasum": ""
},
"require": {
],
"description": "Symfony Filesystem Component",
"homepage": "https://symfony.com",
- "time": "2017-03-06T19:30:27+00:00"
+ "time": "2017-04-12T14:13:17+00:00"
},
{
"name": "symfony/finder",
- "version": "v3.2.6",
+ "version": "v3.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/finder.git",
- "reference": "92d7476d2df60cd851a3e13e078664b1deb8ce10"
+ "reference": "9cf076f8f492f4b1ffac40aae9c2d287b4ca6930"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/finder/zipball/92d7476d2df60cd851a3e13e078664b1deb8ce10",
- "reference": "92d7476d2df60cd851a3e13e078664b1deb8ce10",
+ "url": "https://api.github.com/repos/symfony/finder/zipball/9cf076f8f492f4b1ffac40aae9c2d287b4ca6930",
+ "reference": "9cf076f8f492f4b1ffac40aae9c2d287b4ca6930",
"shasum": ""
},
"require": {
],
"description": "Symfony Finder Component",
"homepage": "https://symfony.com",
- "time": "2017-02-21T09:12:04+00:00"
+ "time": "2017-04-12T14:13:17+00:00"
},
{
"name": "symfony/polyfill-mbstring",
},
{
"name": "symfony/yaml",
- "version": "v3.2.6",
+ "version": "v3.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/yaml.git",
- "reference": "093e416ad096355149e265ea2e4cc1f9ee40ab1a"
+ "reference": "acec26fcf7f3031e094e910b94b002fa53d4e4d6"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/yaml/zipball/093e416ad096355149e265ea2e4cc1f9ee40ab1a",
- "reference": "093e416ad096355149e265ea2e4cc1f9ee40ab1a",
+ "url": "https://api.github.com/repos/symfony/yaml/zipball/acec26fcf7f3031e094e910b94b002fa53d4e4d6",
+ "reference": "acec26fcf7f3031e094e910b94b002fa53d4e4d6",
"shasum": ""
},
"require": {
],
"description": "Symfony Yaml Component",
"homepage": "https://symfony.com",
- "time": "2017-03-07T16:47:02+00:00"
+ "time": "2017-05-01T14:55:58+00:00"
},
{
"name": "theseer/fdomdocument",
- "version": "1.6.1",
+ "version": "1.6.5",
"source": {
"type": "git",
"url": "https://github.com/theseer/fDOMDocument.git",
- "reference": "d9ad139d6c2e8edf5e313ffbe37ff13344cf0684"
+ "reference": "8dcfd392135a5bd938c3c83ea71419501ad9855d"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/theseer/fDOMDocument/zipball/d9ad139d6c2e8edf5e313ffbe37ff13344cf0684",
- "reference": "d9ad139d6c2e8edf5e313ffbe37ff13344cf0684",
+ "url": "https://api.github.com/repos/theseer/fDOMDocument/zipball/8dcfd392135a5bd938c3c83ea71419501ad9855d",
+ "reference": "8dcfd392135a5bd938c3c83ea71419501ad9855d",
"shasum": ""
},
"require": {
],
"description": "The classes contained within this repository extend the standard DOM to use exceptions at all occasions of errors instead of PHP warnings or notices. They also add various custom methods and shortcuts for convenience and to simplify the usage of DOM.",
"homepage": "https://github.com/theseer/fDOMDocument",
- "time": "2015-05-27T22:58:02+00:00"
+ "time": "2017-04-21T14:50:31+00:00"
},
{
"name": "webmozart/assert",
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</div>
<h1 id="browsing-and-searching">Browsing and searching</h1>
<h1 id="browsing-and-searching-1">Browsing and Searching</h1>
-<p>Status: DRAFT</p>
<p><embed src="(http://pix.toile-libre.org/upload/original/1455571378.png).html" /></p>
<h2 id="plain-text-search">Plain text search</h2>
<p>Use the <code>Search text</code> field to search in <em>any</em> of the fields of all links (Title, URL, Description...)</p>
<p>Use the <code>Filter by tags</code> field to restrict displayed links to entries tagged with one or multiple tags (use space to separate tags).</p>
<p><strong>Hidden tags:</strong> Tags starting with a dot <code>.</code> (example <code>.secret</code>) are private. They can only be seen and searched when logged in.</p>
<p>Alternatively you can use the <code>Tag cloud</code> to discover all tags and click on any of them to display related links.</p>
+<p>To search for links that are not tagged, enter <code>""</code> in the tag search field.</p>
<h2 id="filtering-rss-feedspicture-wall">Filtering RSS feeds/Picture wall</h2>
<p>RSS feeds can also be restricted to only return items matching a text/tag search: see <a href="RSS-feeds.html">RSS feeds</a>.</p>
</body>
#Browsing and searching
# Browsing and Searching
-Status: DRAFT
-
![(http://pix.toile-libre.org/upload/original/1455571378.png)]((http://pix.toile-libre.org/upload/original/1455571378.png).html)
## Plain text search
Alternatively you can use the `Tag cloud` to discover all tags and click on any of them to display related links.
+To search for links that are not tagged, enter `""` in the tag search field.
+
## Filtering RSS feeds/Picture wall
RSS feeds can also be restricted to only return items matching a text/tag search: see [RSS feeds](RSS-feeds.html).
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli:history">Original revisions history</a><a href=".html"></a></li>
<li><a href="https://www.shaarli.fr/my.php">Shaarli.fr/my</a> - Unofficial, unsupported (old fork) hosted Shaarlis provider, courtesy of <a href="https://github.com/DMeloni">DMeloni</a><a href=".html"></a></li>
</ul>
+<h3 id="articles-and-social-media-discussions">Articles and social media discussions</h3>
+<ul>
+<li>2016-09-22 - Hacker News - <a href="https://news.ycombinator.com/item?id=12552176" class="uri">https://news.ycombinator.com/item?id=12552176</a></li>
+<li>2015-08-15 - Reddit - <a href="https://www.reddit.com/r/selfhosted/comments/3h3zwh/question_about_migrating_from_wordpress_to_shaarli/">Question about migrating from WordPress to Shaarli.</a><a href=".html"></a></li>
+<li>2015-06-22 - Hacker News - <a href="https://news.ycombinator.com/item?id=9755366" class="uri">https://news.ycombinator.com/item?id=9755366</a></li>
+<li>2015-05-12 - Reddit - <a href="https://www.reddit.com/r/selfhosted/comments/35pkkc/shaarli_self_hosted_bookmarking_delicious_php/">shaarli - Self hosted Bookmarking / Delicious (PHP, MySQL)</a><a href=".html"></a></li>
+</ul>
<h3 id="third-party-plugins">Third party plugins</h3>
<ul>
<li><a href="https://github.com/kalvn/shaarli-plugin-autosave">autosave</a> by <a href="https://github.com/kalvn">@kalvn</a>: Automatically saves data when editing a link to avoid any loss in case of crash or unexpected shutdown.<a href=".html"></a></li>
<li><a href="https://github.com/ArthurHoaro/code-coloration">Code Coloration</a> by <a href="https://github.com/ArthurHoaro">@ArthurHoaro</a>: client side code syntax highlighter.<a href=".html"></a></li>
<li><a href="https://github.com/kalvn/shaarli-plugin-disqus">Disqus</a> by <a href="https://github.com/kalvn">@kalvn</a>: Adds Disqus comment system to your Shaarli.<a href=".html"></a></li>
<li><a href="https://github.com/NerosTie/emojione">emojione</a> by <a href="https://github.com/NerosTie">@NerosTie</a>: Add colorful emojis to your Shaarli.<a href=".html"></a></li>
+<li><a href="https://github.com/ericjuden/Shaarli-Google-Analytics-Plugin">google analytics</a> by <a href="http://github.com/ericjuden">@ericjuden</a>: Adds Google Analytics tracking support<a href=".html"></a></li>
<li><a href="https://github.com/ArthurHoaro/launch-plugin">launch</a> - Launch Plugin is a plugin designed to enhance and customize Launch Theme for Shaarli.<a href=".html"></a></li>
<li><a href="https://github.com/alexisju/social">social</a> by <a href="https://github.com/alexisju">@alexisju</a>: share links to social networks.<a href=".html"></a></li>
<li><a href="https://github.com/ArthurHoaro/shaarli2twitter">shaarli2twitter</a> by <a href="https://github.com/ArthurHoaro">@ArthurHoaro</a> - Automatically tweet your shared links from Shaarli<a href=".html"></a></li>
- [Original revisions history](http://sebsauvage.net/wiki/doku.php?id=php:shaarli:history)[](.html)
- [Shaarli.fr/my](https://www.shaarli.fr/my.php) - Unofficial, unsupported (old fork) hosted Shaarlis provider, courtesy of [DMeloni](https://github.com/DMeloni)[](.html)
+### Articles and social media discussions
+- 2016-09-22 - Hacker News - https://news.ycombinator.com/item?id=12552176
+- 2015-08-15 - Reddit - [Question about migrating from WordPress to Shaarli.](https://www.reddit.com/r/selfhosted/comments/3h3zwh/question_about_migrating_from_wordpress_to_shaarli/)[](.html)
+- 2015-06-22 - Hacker News - https://news.ycombinator.com/item?id=9755366
+- 2015-05-12 - Reddit - [shaarli - Self hosted Bookmarking / Delicious (PHP, MySQL)](https://www.reddit.com/r/selfhosted/comments/35pkkc/shaarli_self_hosted_bookmarking_delicious_php/)[](.html)
### Third party plugins
* [Code Coloration](https://github.com/ArthurHoaro/code-coloration) by [@ArthurHoaro](https://github.com/ArthurHoaro): client side code syntax highlighter.[](.html)
* [Disqus](https://github.com/kalvn/shaarli-plugin-disqus) by [@kalvn](https://github.com/kalvn): Adds Disqus comment system to your Shaarli.[](.html)
* [emojione](https://github.com/NerosTie/emojione) by [@NerosTie](https://github.com/NerosTie): Add colorful emojis to your Shaarli.[](.html)
+ * [google analytics](https://github.com/ericjuden/Shaarli-Google-Analytics-Plugin) by [@ericjuden](http://github.com/ericjuden): Adds Google Analytics tracking support[](.html)
* [launch](https://github.com/ArthurHoaro/launch-plugin) - Launch Plugin is a plugin designed to enhance and customize Launch Theme for Shaarli.[](.html)
* [social](https://github.com/alexisju/social) by [@alexisju](https://github.com/alexisju): share links to social networks.[](.html)
* [shaarli2twitter](https://github.com/ArthurHoaro/shaarli2twitter) by [@ArthurHoaro](https://github.com/ArthurHoaro) - Automatically tweet your shared links from Shaarli[](.html)
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</div>
<h1 id="directory-structure">Directory structure</h1>
<p>Here is the directory structure of Shaarli and the purpose of the different files:</p>
-<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash"> <span class="ex">index.php</span> <span class="co"># Main program</span>
- <span class="ex">application/</span> <span class="co"># Shaarli classes</span>
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash"> <span class="ex">index.php</span> # Main program
+ <span class="ex">application/</span> # Shaarli classes
├── <span class="ex">LinkDB.php</span>
└── <span class="ex">Utils.php</span>
- <span class="ex">tests/</span> <span class="co"># Shaarli unitary & functional tests</span>
+ <span class="ex">tests/</span> # Shaarli unitary <span class="kw">&</span> <span class="ex">functional</span> tests
├── <span class="ex">LinkDBTest.php</span>
- ├── <span class="ex">utils</span> <span class="co"># utilities to ease testing</span>
+ ├── <span class="ex">utils</span> # utilities to ease testing
│ └── <span class="ex">ReferenceLinkDB.php</span>
└── <span class="ex">UtilsTest.php</span>
- <span class="ex">COPYING</span> <span class="co"># Shaarli license</span>
- <span class="ex">inc/</span> <span class="co"># static assets and 3rd party libraries</span>
- ├── <span class="ex">awesomplete.*</span> <span class="co"># tags autocompletion library</span>
- ├── <span class="ex">blazy.*</span> <span class="co"># picture wall lazy image loading library</span>
+ <span class="ex">COPYING</span> # Shaarli license
+ <span class="ex">inc/</span> # static assets and 3rd party libraries
+ ├── <span class="ex">awesomplete.*</span> # tags autocompletion library
+ ├── <span class="ex">blazy.*</span> # picture wall lazy image loading library
├── <span class="ex">shaarli.css</span>, reset.css <span class="co"># Shaarli stylesheet.</span>
- ├── <span class="ex">qr.*</span> <span class="co"># qr code generation library</span>
- └──<span class="ex">rain.tpl.class.php</span> <span class="co"># RainTPL templating library</span>
- <span class="ex">tpl/</span> <span class="co"># RainTPL templates for Shaarli. They are used to build the pages.</span>
- <span class="ex">images/</span> <span class="co"># Images and icons used in Shaarli</span>
- <span class="ex">data/</span> <span class="co"># data storage: bookmark database, configuration, logs, banlist…</span>
- ├── <span class="ex">config.php</span> <span class="co"># Shaarli configuration (login, password, timezone, title…)</span>
- ├── <span class="ex">datastore.php</span> <span class="co"># Your link database (compressed).</span>
- ├── <span class="ex">ipban.php</span> <span class="co"># IP address ban system data</span>
- ├── <span class="ex">lastupdatecheck.txt</span> <span class="co"># Update check timestamp file</span>
- └──<span class="ex">log.txt</span> <span class="co"># login/IPban log.</span>
- <span class="ex">cache/</span> <span class="co"># thumbnails cache</span>
+ ├── <span class="ex">qr.*</span> # qr code generation library
+ └──<span class="ex">rain.tpl.class.php</span> # RainTPL templating library
+ <span class="ex">tpl/</span> # RainTPL templates for Shaarli. They are used to build the pages.
+ <span class="ex">images/</span> # Images and icons used in Shaarli
+ <span class="ex">data/</span> # data storage: bookmark database, configuration, logs, banlist…
+ ├── <span class="ex">config.php</span> # Shaarli configuration (login, password, timezone, title…)
+ ├── <span class="ex">datastore.php</span> # Your link database (compressed)<span class="ex">.</span>
+ ├── <span class="ex">ipban.php</span> # IP address ban system data
+ ├── <span class="ex">lastupdatecheck.txt</span> # Update check timestamp file
+ └──<span class="ex">log.txt</span> # login/IPban log.
+ <span class="ex">cache/</span> # thumbnails cache
<span class="co"># This directory is automatically created. You can erase it anytime you want.</span>
- <span class="ex">tmp/</span> <span class="co"># Temporary directory for compiled RainTPL templates.</span>
+ <span class="ex">tmp/</span> # Temporary directory for compiled RainTPL templates.
<span class="co"># This directory is automatically created. You can erase it anytime you want.</span></code></pre></div>
</body>
</html>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<span class="ex">CONTAINER</span> ID IMAGE COMMAND CREATED STATUS PORTS NAMES
<span class="ex">d40b7af693d6</span> shaarli/shaarli /usr/bin/supervisor 15 seconds ago Up 4 seconds 0.0.0.0:8000-<span class="op">></span>80/tcp backstabbing_galileo</code></pre></div>
<h3 id="stop-and-destroy-a-container">Stop and destroy a container</h3>
-<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">docker</span> stop backstabbing_galileo <span class="co"># those docker guys are really rude to physicists!</span>
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">docker</span> stop backstabbing_galileo # those docker guys are really rude to physicists!
<span class="ex">backstabbing_galileo</span>
<span class="co"># check the container is stopped</span>
<span class="ex">d40b7af693d6</span> shaarli/shaarli /usr/bin/supervisor 5 minutes ago Exited (0) <span class="ex">48</span> seconds ago backstabbing_galileo
<span class="co"># destroy the container</span>
-$ <span class="ex">docker</span> rm backstabbing_galileo <span class="co"># let's put an end to these barbarian practices</span>
-<span class="ex">backstabbing_galileo</span>
+$ <span class="ex">docker</span> rm backstabbing_galileo # let<span class="st">'s put an end to these barbarian practices</span>
+<span class="st">backstabbing_galileo</span>
-$ <span class="ex">docker</span> ps -a
-<span class="ex">CONTAINER</span> ID IMAGE COMMAND CREATED STATUS PORTS NAMES</code></pre></div>
+<span class="st">$ docker ps -a</span>
+<span class="st">CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES</span></code></pre></div>
<h2 id="resources">Resources</h2>
<h3 id="docker-1">Docker</h3>
<ul>
+<li><a href="https://www.katacoda.com/courses/docker/">Interactive Docker training portal</a> on <a href="https://www.katacoda.com/">Katakoda</a><a href=".html"></a></li>
<li><a href="http://blog.thoward37.me/articles/where-are-docker-images-stored/">Where are Docker images stored?</a><a href=".html"></a></li>
<li><a href="https://docs.docker.com/reference/builder/">Dockerfile reference</a><a href=".html"></a></li>
<li><a href="https://docs.docker.com/articles/dockerfile_best-practices/">Dockerfile best practices</a><a href=".html"></a></li>
## Resources
### Docker
+- [Interactive Docker training portal](https://www.katacoda.com/courses/docker/) on [Katakoda](https://www.katacoda.com/)[](.html)
- [Where are Docker images stored?](http://blog.thoward37.me/articles/where-are-docker-images-stored/)[](.html)
- [Dockerfile reference](https://docs.docker.com/reference/builder/)[](.html)
- [Dockerfile best practices](https://docs.docker.com/articles/dockerfile_best-practices/)[](.html)
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<span class="kw">function</span> copyUserStyleFrom<span class="ot">(</span><span class="kw">$url</span><span class="ot">,</span> <span class="kw">$name</span><span class="ot">,</span> <span class="kw">$knownStyles</span><span class="ot">)</span> {
<span class="kw">$userStyle</span> = <span class="kw">$url</span>.<span class="st">"inc/user.css"</span><span class="ot">;</span>
<span class="kw">if</span><span class="ot">(</span><span class="fu">in_array</span><span class="ot">(</span><span class="kw">$url</span><span class="ot">,</span> <span class="kw">$knownStyles</span><span class="ot">))</span> {
- <span class="co">// TODO add log message</span>
+ <span class="co">// </span><span class="al">TODO</span><span class="co"> add log message</span>
} <span class="kw">else</span> {
<span class="kw">$statusCode</span> = get_http_response_code<span class="ot">(</span><span class="kw">$userStyle</span><span class="ot">);</span>
<span class="kw">if</span><span class="ot">(</span><span class="fu">intval</span><span class="ot">(</span><span class="kw">$statusCode</span><span class="ot">)</span><<span class="dv">300</span><span class="ot">)</span> {
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<h3 id="download-as-an-archive">Download as an archive</h3>
<p>Get the latest released version from the <a href="https://github.com/shaarli/Shaarli/releases">releases</a> page.<a href=".html"></a></p>
<p><strong>Download our <em>shaarli-full</em> archive</strong> to include dependencies.</p>
-<p>The current latest released version is <code>v0.8.0</code></p>
+<p>The current latest released version is <code>v0.8.4</code></p>
<p>Or in command lines:</p>
-<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="fu">wget</span> https://github.com/shaarli/Shaarli/releases/download/v0.8.0/shaarli-v0.8.0-full.zip
-$ <span class="fu">unzip</span> shaarli-v0.8.0-full.zip
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="fu">wget</span> https://github.com/shaarli/Shaarli/releases/download/v0.8.4/shaarli-v0.8.4-full.zip
+$ <span class="fu">unzip</span> shaarli-v0.8.4-full.zip
$ <span class="fu">mv</span> Shaarli /path/to/shaarli/</code></pre></div>
<table style="width:46%;">
<colgroup>
</table>
<h3 id="using-git">Using git</h3>
<pre><code>mkdir -p /path/to/shaarli && cd /path/to/shaarli/
-git clone -b v0.8.0 https://github.com/shaarli/Shaarli.git .
-composer update --no-dev</code></pre>
+git clone -b v0.8 https://github.com/shaarli/Shaarli.git .
+composer install --no-dev</code></pre>
<hr />
<h2 id="stable-version">Stable version</h2>
<p>The stable version has been experienced by Shaarli users, and will receive security updates.</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="fu">git</span> clone https://github.com/shaarli/Shaarli.git -b stable /path/to/shaarli/
<span class="co"># install/update third-party dependencies</span>
$ <span class="bu">cd</span> /path/to/shaarli/
-$ <span class="ex">composer</span> update --no-dev</code></pre></div>
+$ <span class="ex">composer</span> install --no-dev</code></pre></div>
<hr />
<h2 id="development-version-mainline">Development version (mainline)</h2>
<p><em>Use at your own risk!</em></p>
<p>To get the latest changes from the <code>master</code> branch:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash"><span class="co"># clone the repository </span>
-$ <span class="fu">git</span> clone https://github.com/shaarli/Shaarli.git master /path/to/shaarli/
+$ <span class="fu">git</span> clone https://github.com/shaarli/Shaarli.git -b master /path/to/shaarli/
<span class="co"># install/update third-party dependencies</span>
$ <span class="bu">cd</span> /path/to/shaarli
-$ <span class="ex">composer</span> update --no-dev</code></pre></div>
+$ <span class="ex">composer</span> install --no-dev</code></pre></div>
<hr />
<h2 id="finish-installation">Finish Installation</h2>
<p>Once Shaarli is downloaded and files have been placed at the correct location, open it this location your favorite browser.</p>
**Download our *shaarli-full* archive** to include dependencies.
-The current latest released version is `v0.8.0`
+The current latest released version is `v0.8.4`
Or in command lines:
```bash
-$ wget https://github.com/shaarli/Shaarli/releases/download/v0.8.0/shaarli-v0.8.0-full.zip
-$ unzip shaarli-v0.8.0-full.zip
+$ wget https://github.com/shaarli/Shaarli/releases/download/v0.8.4/shaarli-v0.8.4-full.zip
+$ unzip shaarli-v0.8.4-full.zip
$ mv Shaarli /path/to/shaarli/
```
```
mkdir -p /path/to/shaarli && cd /path/to/shaarli/
-git clone -b v0.8.0 https://github.com/shaarli/Shaarli.git .
-composer update --no-dev
+git clone -b v0.8 https://github.com/shaarli/Shaarli.git .
+composer install --no-dev
```
--------------------------------------------------------
$ git clone https://github.com/shaarli/Shaarli.git -b stable /path/to/shaarli/
# install/update third-party dependencies
$ cd /path/to/shaarli/
-$ composer update --no-dev
+$ composer install --no-dev
```
--------------------------------------------------------
```bash
# clone the repository
-$ git clone https://github.com/shaarli/Shaarli.git master /path/to/shaarli/
+$ git clone https://github.com/shaarli/Shaarli.git -b master /path/to/shaarli/
# install/update third-party dependencies
$ cd /path/to/shaarli
-$ composer update --no-dev
+$ composer install --no-dev
```
--------------------------------------------------------
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</ul>
</div>
<h1 id="plugin-system">Plugin System</h1>
-<blockquote>
-<p>Note: Plugin current status - in development (not merged into master).</p>
-</blockquote>
<p><a href="#developer-api"><strong>I am a developer.</strong> Developer API.</a><a href=".html"></a></p>
<p><a href="#guide-for-template-designer"><strong>I am a template designer.</strong> Guide for template designer.</a><a href=".html"></a></p>
<h2 id="developer-api">Developer API</h2>
| plugins/
|---| demo_plugin/
| |---| demo_plugin.php</code></pre>
+<h3 id="plugin-initialization">Plugin initialization</h3>
+<p>At the beginning of Shaarli execution, all enabled plugins are loaded. At this point, the plugin system looks for an <code>init()</code> function to execute and run it if it exists. This function must be named this way, and takes the <code>ConfigManager</code> as parameter.</p>
+<pre><code><plugin_name>_init($conf)</code></pre>
+<p>This function can be used to create initial data, load default settings, etc. But also to set <em>plugin errors</em>. If the initialization function returns an array of strings, they will be understand as errors, and displayed in the header to logged in users.</p>
<h3 id="understanding-hooks">Understanding hooks</h3>
<p>A plugin is a set of functions. Each function will be triggered by the plugin system at certain point in Shaarli execution.</p>
<p>These functions need to be named with this pattern:</p>
-<pre><code>hook_<plugin_name>_<hook_name></code></pre>
+<pre><code>hook_<plugin_name>_<hook_name>($data, $conf)</code></pre>
+<p>Parameters:</p>
+<ul>
+<li>data: see <a href="https://github.com/shaarli/Shaarli/wiki/Plugin-System#plugins-data">$data section</a><a href=".html"></a></li>
+<li>conf: the <code>ConfigManager</code> instance.</li>
+</ul>
<p>For exemple, if my plugin want to add data to the header, this function is needed:</p>
-<pre><code>hook_demo_plugin_render_header()</code></pre>
+<pre><code>hook_demo_plugin_render_header</code></pre>
<p>If this function is declared, and the plugin enabled, it will be called every time Shaarli is rendering the header.</p>
<h3 id="plugins-data">Plugin's data</h3>
<h4 id="parameters">Parameters</h4>
<ul>
<li><code>description</code>: plugin description</li>
<li><code>parameters</code>: user parameter names, separated by a <code>;</code>.</li>
+<li><code>parameter.<PARAMETER_NAME></code>: add a text description the specified parameter.</li>
</ul>
<blockquote>
<p>Note: In PHP, <code>parse_ini_file()</code> seems to want strings to be between by quotes <code>"</code> in the ini file.</p>
</tr>
<tr class="even">
<td><a href="#render_tagcloud">render_tagcloud</a></td>
-<td style="text-align: center;">Allow to add content at the top and bottom of the page.</td>
+<td style="text-align: center;">Allow to add content at the top and bottom of the page, and after all tags.</td>
</tr>
<tr class="odd">
+<td><a href="#render_taglist">render_taglist</a></td>
+<td style="text-align: center;">Allow to add content at the top and bottom of the page, and after all tags.</td>
+</tr>
+<tr class="even">
<td><a href="#render_daily">render_daily</a></td>
<td style="text-align: center;">Allow to add content at the top and bottom of the page, the bottom of each link and to alter data.</td>
</tr>
+<tr class="odd">
+<td><a href="#render_feed">render_feed</a></td>
+<td style="text-align: center;">Allow to do add tags in RSS and ATOM feeds.</td>
+</tr>
<tr class="even">
-<td><a href="#savelink">savelink</a></td>
+<td><a href="#save_link">save_link</a></td>
<td style="text-align: center;">Allow to alter the link being saved in the datastore.</td>
</tr>
+<tr class="odd">
+<td><a href="#delete_link">delete_link</a></td>
+<td style="text-align: center;">Allow to do an action before a link is deleted from the datastore.</td>
+</tr>
</tbody>
</table>
<h4 id="render_header">render_header</h4>
<li><p><code>plugin_start_zone</code>: before displaying the template content.</p></li>
<li><p><code>plugin_end_zone</code>: after displaying the template content.</p></li>
</ul>
+<p>For each tag, the following placeholder can be used:</p>
+<ul>
+<li><code>tag_plugin</code>: after each tag</li>
+</ul>
<p><img src="http://i.imgur.com/vHmyT3a.png" alt="plugin_start_end_zone_example" /><a href=".html"></a></p>
+<h4 id="render_taglist">render_taglist</h4>
+<p>Triggered when taglist is displayed.</p>
+<p>Allow to add content at the top and bottom of the page.</p>
+<h5 id="data-8">Data</h5>
+<p><code>$data</code> is an array containing:</p>
+<ul>
+<li><code>_LOGGEDIN_</code>: true if user is logged in, false otherwise.</li>
+<li>All templates data.</li>
+</ul>
+<h5 id="template-placeholders-8">Template placeholders</h5>
+<p>Items can be displayed in templates by adding an entry in <code>$data['<placeholder>']</code> array.<a href=".html"></a></p>
+<p>List of placeholders:</p>
+<ul>
+<li><p><code>plugin_start_zone</code>: before displaying the template content.</p></li>
+<li><p><code>plugin_end_zone</code>: after displaying the template content.</p></li>
+</ul>
+<p>For each tag, the following placeholder can be used:</p>
+<ul>
+<li><code>tag_plugin</code>: after each tag</li>
+</ul>
<h4 id="render_daily">render_daily</h4>
<p>Triggered when tagcloud is displayed.</p>
<p>Allow to add content at the top and bottom of the page, the bottom of each link and to alter data.</p>
-<h5 id="data-8">Data</h5>
+<h5 id="data-9">Data</h5>
<p><code>$data</code> is an array containing:</p>
<ul>
<li><code>_LOGGEDIN_</code>: true if user is logged in, false otherwise.</li>
<li>All templates data, including links.</li>
</ul>
-<h5 id="template-placeholders-8">Template placeholders</h5>
+<h5 id="template-placeholders-9">Template placeholders</h5>
<p>Items can be displayed in templates by adding an entry in <code>$data['<placeholder>']</code> array.<a href=".html"></a></p>
<p>List of placeholders:</p>
<ul>
<li><p><code>plugin_start_zone</code>: before displaying the template content.</p></li>
<li><p><code>plugin_end_zone</code>: after displaying the template content.</p></li>
</ul>
-<h4 id="savelink">savelink</h4>
+<h4 id="render_feed">render_feed</h4>
+<p>Triggered when the ATOM or RSS feed is displayed.</p>
+<p>Allow to add tags in the feed, either in the header or for each items. Items (links) can also be altered before being rendered.</p>
+<h5 id="data-10">Data</h5>
+<p><code>$data</code> is an array containing:</p>
+<ul>
+<li><code>_LOGGEDIN_</code>: true if user is logged in, false otherwise.</li>
+<li><code>_PAGE_</code>: containing either <code>rss</code> or <code>atom</code>.</li>
+<li>All templates data, including links.</li>
+</ul>
+<h5 id="template-placeholders-10">Template placeholders</h5>
+<p>Tags can be added in feeds by adding an entry in <code>$data['<placeholder>']</code> array.<a href=".html"></a></p>
+<p>List of placeholders:</p>
+<ul>
+<li><code>feed_plugins_header</code>: used as a header tag in the feed.</li>
+</ul>
+<p>For each links:</p>
+<ul>
+<li><code>feed_plugins</code>: additional tag for every link entry.</li>
+</ul>
+<h4 id="save_link">save_link</h4>
<p>Triggered when a link is save (new link or edit).</p>
<p>Allow to alter the link being saved in the datastore.</p>
-<h5 id="data-9">Data</h5>
+<h5 id="data-11">Data</h5>
<p><code>$data</code> is an array containing the link being saved:</p>
<ul>
+<li>id</li>
<li>title</li>
<li>url</li>
+<li>shorturl</li>
<li>description</li>
-<li>linkdate</li>
<li>private</li>
<li>tags</li>
+<li>created</li>
+<li>updated</li>
+</ul>
+<h4 id="delete_link">delete_link</h4>
+<p>Triggered when a link is deleted.</p>
+<p>Allow to execute any action before the link is actually removed from the datastore</p>
+<h5 id="data-12">Data</h5>
+<p><code>$data</code> is an array containing the link being saved:</p>
+<ul>
+<li>id</li>
+<li>title</li>
+<li>url</li>
+<li>shorturl</li>
+<li>description</li>
+<li>private</li>
+<li>tags</li>
+<li>created</li>
+<li>updated</li>
</ul>
<h2 id="guide-for-template-designer">Guide for template designer</h2>
<h3 id="plugin-administration">Plugin administration</h3>
{$value}
{/loop}
<span class="kw"></div></span></code></pre></div>
+<p><strong>feed.atom.xml</strong> and <strong>feed.rss.xml</strong>:</p>
+<p>In headers tags section:</p>
+<div class="sourceCode"><pre class="sourceCode xml"><code class="sourceCode xml">{loop="$feed_plugins_header"}
+ {$value}
+{/loop}</code></pre></div>
+<p>After each entry:</p>
+<div class="sourceCode"><pre class="sourceCode xml"><code class="sourceCode xml">{loop="$value.feed_plugins"}
+ {$value}
+{/loop}</code></pre></div>
</body>
</html>
#Plugin System
-> Note: Plugin current status - in development (not merged into master).
-
[**I am a developer.** Developer API.](#developer-api)[](.html)
[**I am a template designer.** Guide for template designer.](#guide-for-template-designer)[](.html)
| |---| demo_plugin.php
```
+### Plugin initialization
+
+At the beginning of Shaarli execution, all enabled plugins are loaded. At this point, the plugin system looks for an `init()` function to execute and run it if it exists. This function must be named this way, and takes the `ConfigManager` as parameter.
+
+ <plugin_name>_init($conf)
+
+This function can be used to create initial data, load default settings, etc. But also to set *plugin errors*. If the initialization function returns an array of strings, they will be understand as errors, and displayed in the header to logged in users.
+
### Understanding hooks
A plugin is a set of functions. Each function will be triggered by the plugin system at certain point in Shaarli execution.
These functions need to be named with this pattern:
```
-hook_<plugin_name>_<hook_name>
+hook_<plugin_name>_<hook_name>($data, $conf)
```
+Parameters:
+
+ - data: see [$data section](https://github.com/shaarli/Shaarli/wiki/Plugin-System#plugins-data)[](.html)
+ - conf: the `ConfigManager` instance.
+
For exemple, if my plugin want to add data to the header, this function is needed:
- hook_demo_plugin_render_header()
+ hook_demo_plugin_render_header
If this function is declared, and the plugin enabled, it will be called every time Shaarli is rendering the header.
* `description`: plugin description
* `parameters`: user parameter names, separated by a `;`.
+ * `parameter.<PARAMETER_NAME>`: add a text description the specified parameter.
> Note: In PHP, `parse_ini_file()` seems to want strings to be between by quotes `"` in the ini file.
| [render_editlink](#render_editlink) | Allow to add fields in the form, or display elements. |[](.html)
| [render_tools](#render_tools) | Allow to add content at the end of the page. |[](.html)
| [render_picwall](#render_picwall) | Allow to add content at the top and bottom of the page. |[](.html)
-| [render_tagcloud](#render_tagcloud) | Allow to add content at the top and bottom of the page. |[](.html)
+| [render_tagcloud](#render_tagcloud) | Allow to add content at the top and bottom of the page, and after all tags. |[](.html)
+| [render_taglist](#render_taglist) | Allow to add content at the top and bottom of the page, and after all tags. |[](.html)
| [render_daily](#render_daily) | Allow to add content at the top and bottom of the page, the bottom of each link and to alter data. |[](.html)
-| [savelink](#savelink) | Allow to alter the link being saved in the datastore. |[](.html)
+| [render_feed](#render_feed) | Allow to do add tags in RSS and ATOM feeds. |[](.html)
+| [save_link](#save_link) | Allow to alter the link being saved in the datastore. |[](.html)
+| [delete_link](#delete_link) | Allow to do an action before a link is deleted from the datastore. |[](.html)
+
#### render_header
* `plugin_end_zone`: after displaying the template content.
+For each tag, the following placeholder can be used:
+
+ * `tag_plugin`: after each tag
+
![plugin_start_end_zone_example](http://i.imgur.com/vHmyT3a.png)[](.html)
+
+#### render_taglist
+
+Triggered when taglist is displayed.
+
+Allow to add content at the top and bottom of the page.
+
+##### Data
+
+`$data` is an array containing:
+
+ * `_LOGGEDIN_`: true if user is logged in, false otherwise.
+ * All templates data.
+
+##### Template placeholders
+
+Items can be displayed in templates by adding an entry in `$data['<placeholder>']` array.[](.html)
+
+List of placeholders:
+
+ * `plugin_start_zone`: before displaying the template content.
+
+ * `plugin_end_zone`: after displaying the template content.
+
+For each tag, the following placeholder can be used:
+
+ * `tag_plugin`: after each tag
+
#### render_daily
Triggered when tagcloud is displayed.
* `plugin_end_zone`: after displaying the template content.
-#### savelink
+#### render_feed
+
+Triggered when the ATOM or RSS feed is displayed.
+
+Allow to add tags in the feed, either in the header or for each items. Items (links) can also be altered before being rendered.
+
+##### Data
+
+`$data` is an array containing:
+
+ * `_LOGGEDIN_`: true if user is logged in, false otherwise.
+ * `_PAGE_`: containing either `rss` or `atom`.
+ * All templates data, including links.
+
+##### Template placeholders
+
+Tags can be added in feeds by adding an entry in `$data['<placeholder>']` array.[](.html)
+
+List of placeholders:
+
+ * `feed_plugins_header`: used as a header tag in the feed.
+
+For each links:
+
+ * `feed_plugins`: additional tag for every link entry.
+
+#### save_link
Triggered when a link is save (new link or edit).
`$data` is an array containing the link being saved:
+ * id
+ * title
+ * url
+ * shorturl
+ * description
+ * private
+ * tags
+ * created
+ * updated
+
+
+#### delete_link
+
+Triggered when a link is deleted.
+
+Allow to execute any action before the link is actually removed from the datastore
+
+##### Data
+
+`$data` is an array containing the link being saved:
+
+ * id
* title
* url
+ * shorturl
* description
- * linkdate
* private
* tags
+ * created
+ * updated
## Guide for template designer
{/loop}
</div>
```
+
+**feed.atom.xml** and **feed.rss.xml**:
+
+In headers tags section:
+```xml
+{loop="$feed_plugins_header"}
+ {$value}
+{/loop}
+```
+
+After each entry:
+```xml
+{loop="$value.feed_plugins"}
+ {$value}
+{/loop}
+```
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="https://github.com/shaarli/Shaarli/blob/master/plugins/markdown/README.md"><code>markdown</code></a>: Render shaare description with Markdown syntax.<a href=".html"></a></li>
<li><a href="https://github.com/shaarli/Shaarli/blob/master/plugins/playvideos/README.md"><code>playvideos</code></a>: Add a button in the toolbar allowing to watch all videos.<a href=".html"></a></li>
<li><code>qrcode</code>: For each link, add a QRCode icon.</li>
-<li><code>readityourself</code>: For each link, add a ReadItYourself icon to save the shaared URL</li>
<li><a href="https://github.com/shaarli/Shaarli/blob/master/plugins/wallabag/README.md"><code>wallabag</code></a>: For each link, add a Wallabag icon to save it in your instance.<a href=".html"></a></li>
</ul>
<h4 id="third-party-plugins">Third party plugins</h4>
* [`markdown`](https://github.com/shaarli/Shaarli/blob/master/plugins/markdown/README.md): Render shaare description with Markdown syntax.[](.html)
* [`playvideos`](https://github.com/shaarli/Shaarli/blob/master/plugins/playvideos/README.md): Add a button in the toolbar allowing to watch all videos.[](.html)
* `qrcode`: For each link, add a QRCode icon.
- * `readityourself`: For each link, add a ReadItYourself icon to save the shaared URL
* [`wallabag`](https://github.com/shaarli/Shaarli/blob/master/plugins/wallabag/README.md): For each link, add a Wallabag icon to save it in your instance.[](.html)
--- /dev/null
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <meta name="generator" content="pandoc">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
+ <title>Shaarli – REST API</title>
+ <style type="text/css">code{white-space: pre;}</style>
+ <style type="text/css">
+div.sourceCode { overflow-x: auto; }
+table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
+ margin: 0; padding: 0; vertical-align: baseline; border: none; }
+table.sourceCode { width: 100%; line-height: 100%; }
+td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
+td.sourceCode { padding-left: 5px; }
+code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
+code > span.dt { color: #902000; } /* DataType */
+code > span.dv { color: #40a070; } /* DecVal */
+code > span.bn { color: #40a070; } /* BaseN */
+code > span.fl { color: #40a070; } /* Float */
+code > span.ch { color: #4070a0; } /* Char */
+code > span.st { color: #4070a0; } /* String */
+code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
+code > span.ot { color: #007020; } /* Other */
+code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
+code > span.fu { color: #06287e; } /* Function */
+code > span.er { color: #ff0000; font-weight: bold; } /* Error */
+code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
+code > span.cn { color: #880000; } /* Constant */
+code > span.sc { color: #4070a0; } /* SpecialChar */
+code > span.vs { color: #4070a0; } /* VerbatimString */
+code > span.ss { color: #bb6688; } /* SpecialString */
+code > span.im { } /* Import */
+code > span.va { color: #19177c; } /* Variable */
+code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
+code > span.op { color: #666666; } /* Operator */
+code > span.bu { } /* BuiltIn */
+code > span.ex { } /* Extension */
+code > span.pp { color: #bc7a00; } /* Preprocessor */
+code > span.at { color: #7d9029; } /* Attribute */
+code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
+code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
+code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
+code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
+ </style>
+ <link rel="stylesheet" href="github-markdown.css">
+ <!--[if lt IE 9]>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
+ <![endif]-->
+</head>
+<body>
+<div id="local-sidebar">
+<ul>
+<li><a href="Home.html">Home</a></li>
+<li>Setup
+<ul>
+<li><a href="Download-and-Installation.html">Download and Installation</a></li>
+<li><a href="Upgrade-and-migration.html">Upgrade and migration</a></li>
+<li><a href="Server-requirements.html">Server requirements</a></li>
+<li><a href="Server-configuration.html">Server configuration</a></li>
+<li><a href="Server-security.html">Server security</a></li>
+<li><a href="Shaarli-configuration.html">Shaarli configuration</a></li>
+<li><a href="Plugins.html">Plugins</a></li>
+</ul></li>
+<li><a href="Docker.html">Docker</a></li>
+<li><a href="Usage.html">Usage</a>
+<ul>
+<li><a href="Sharing-button.html">Sharing button</a> (bookmarklet)</li>
+<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
+<li><a href="Firefox-share.html">Firefox share</a></li>
+<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
+</ul></li>
+<li>How To
+<ul>
+<li><a href="Backup,-restore,-import-and-export.html">Backup, restore, import and export</a></li>
+<li><a href="Copy-an-existing-installation-over-SSH-and-serve-it-locally.html">Copy an existing installation over SSH and serve it locally</a></li>
+<li><a href="Create-and-serve-multiple-Shaarlis-(farm).html">Create and serve multiple Shaarlis (farm)</a></li>
+<li><a href="Download-CSS-styles-from-an-OPML-list.html">Download CSS styles from an OPML list</a></li>
+<li><a href="Datastore-hacks.html">Datastore hacks</a></li>
+</ul></li>
+<li><a href="Troubleshooting.html">Troubleshooting</a></li>
+<li><a href="Development.html">Development</a>
+<ul>
+<li><a href="GnuPG-signature.html">GnuPG signature</a></li>
+<li><a href="Coding-guidelines.html">Coding guidelines</a></li>
+<li><a href="Directory-structure.html">Directory structure</a></li>
+<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
+<li><a href="Plugin-System.html">Plugin System</a></li>
+<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
+<li><a href="Security.html">Security</a></li>
+<li><a href="Static-analysis.html">Static analysis</a></li>
+<li><a href="Theming.html">Theming</a></li>
+<li><a href="Unit-tests.html">Unit tests</a></li>
+</ul></li>
+<li>About
+<ul>
+<li><a href="FAQ.html">FAQ</a></li>
+<li><a href="Community-&-Related-software.html">Community & Related software</a></li>
+</ul></li>
+</ul>
+</div>
+<h1 id="rest-api">REST API</h1>
+<h2 id="usage">Usage</h2>
+<p>See the <a href="http://shaarli.github.io/api-documentation/">REST API documentation</a>.<a href=".html"></a></p>
+<h2 id="authentication">Authentication</h2>
+<p>All requests to Shaarli's API must include a JWT token to verify their authenticity.</p>
+<p>This token has to be included as an HTTP header called <code>Authentication: Bearer <jwt token></code>.</p>
+<p>JWT resources :</p>
+<ul>
+<li><a href="https://jwt.io">jwt.io</a> (including a list of client per language).<a href=".html"></a></li>
+<li>RFC : <a href="https://tools.ietf.org/html/rfc7519" class="uri">https://tools.ietf.org/html/rfc7519</a></li>
+<li><a href="https://float-middle.com/json-web-tokens-jwt-vs-sessions/" class="uri">https://float-middle.com/json-web-tokens-jwt-vs-sessions/</a></li>
+<li>HackerNews thread: <a href="https://news.ycombinator.com/item?id=11929267" class="uri">https://news.ycombinator.com/item?id=11929267</a></li>
+</ul>
+<h3 id="shaarli-jwt-token">Shaarli JWT Token</h3>
+<p>JWT tokens are composed by three parts, separated by a dot <code>.</code> and encoded in base64:</p>
+<pre><code>[header].[payload].[signature][](.html)</code></pre>
+<h4 id="header">Header</h4>
+<p>Shaarli only allow one hash algorithm, so the header will always be the same:</p>
+<div class="sourceCode"><pre class="sourceCode json"><code class="sourceCode json"><span class="fu">{</span>
+ <span class="dt">"typ"</span><span class="fu">:</span> <span class="st">"JWT"</span><span class="fu">,</span>
+ <span class="dt">"alg"</span><span class="fu">:</span> <span class="st">"HS512"</span>
+<span class="fu">}</span></code></pre></div>
+<p>Encoded in base64, it gives:</p>
+<pre><code>ewogICAgICAgICJ0eXAiOiAiSldUIiwKICAgICAgICAiYWxnIjogIkhTNTEyIgogICAgfQ==</code></pre>
+<h4 id="payload">Payload</h4>
+<p><strong>Validity duration</strong></p>
+<p>To avoid infinite token validity, JWT tokens must include their creation date in UNIX timestamp format (timezone independant - UTC) under the key <code>iat</code> (issued at). This token will be accepted during 9 minutes.</p>
+<div class="sourceCode"><pre class="sourceCode json"><code class="sourceCode json"><span class="fu">{</span>
+ <span class="dt">"iat"</span><span class="fu">:</span> <span class="dv">1468663519</span>
+<span class="fu">}</span></code></pre></div>
+<p>See <a href="https://tools.ietf.org/html/rfc7519#section-4.1.6">RFC reference</a>.<a href=".html"></a></p>
+<h4 id="signature">Signature</h4>
+<p>The signature authenticate the token validity. It contains the base64 of the header and the body, separated by a dot <code>.</code>, hashed in SHA512 with the API secret available in Shaarli administration page.</p>
+<p>Signature example with PHP:</p>
+<div class="sourceCode"><pre class="sourceCode php"><code class="sourceCode php"><span class="kw">$content</span> = <span class="fu">base64_encode</span><span class="ot">(</span><span class="kw">$header</span><span class="ot">)</span> . <span class="st">'.'</span> . <span class="fu">base64_encode</span><span class="ot">(</span><span class="kw">$payload</span><span class="ot">);</span>
+<span class="kw">$signature</span> = <span class="fu">hash_hmac</span><span class="ot">(</span><span class="st">'sha512'</span><span class="ot">,</span> <span class="kw">$content</span><span class="ot">,</span> <span class="kw">$secret</span><span class="ot">);</span></code></pre></div>
+<h3 id="complete-example">Complete example</h3>
+<h4 id="php">PHP</h4>
+<div class="sourceCode"><pre class="sourceCode php"><code class="sourceCode php"><span class="kw">function</span> generateToken<span class="ot">(</span><span class="kw">$secret</span><span class="ot">)</span> {
+ <span class="kw">$header</span> = <span class="fu">base64_encode</span><span class="ot">(</span><span class="st">'{</span>
+<span class="st"> "typ": "JWT",</span>
+<span class="st"> "alg": "HS512"</span>
+<span class="st"> }'</span><span class="ot">);</span>
+ <span class="kw">$payload</span> = <span class="fu">base64_encode</span><span class="ot">(</span><span class="st">'{</span>
+<span class="st"> "iat": '</span>. <span class="fu">time</span><span class="ot">()</span> .<span class="st">'</span>
+<span class="st"> }'</span><span class="ot">);</span>
+ <span class="kw">$signature</span> = <span class="fu">hash_hmac</span><span class="ot">(</span><span class="st">'sha512'</span><span class="ot">,</span> <span class="kw">$header</span> .<span class="st">'.'</span>. <span class="kw">$payload</span> <span class="ot">,</span> <span class="kw">$secret</span><span class="ot">);</span>
+ <span class="kw">return</span> <span class="kw">$header</span> .<span class="st">'.'</span>. <span class="kw">$payload</span> .<span class="st">'.'</span>. <span class="kw">$signature</span><span class="ot">;</span>
+}
+
+<span class="kw">$secret</span> = <span class="st">'mysecret'</span><span class="ot">;</span>
+<span class="kw">$token</span> = generateToken<span class="ot">(</span><span class="kw">$secret</span><span class="ot">);</span>
+<span class="fu">echo</span> <span class="kw">$token</span><span class="ot">;</span></code></pre></div>
+<blockquote>
+<p><code>ewogICAgICAgICJ0eXAiOiAiSldUIiwKICAgICAgICAiYWxnIjogIkhTNTEyIgogICAgfQ==.ewogICAgICAgICJpYXQiOiAxNDY4NjY3MDQ3CiAgICB9.1d2c54fa947daf594fdbf7591796195652c8bc63bffad7f6a6db2a41c313f495a542cbfb595acade79e83f3810d709b4251d7b940bbc10b531a6e6134af63a68</code></p>
+</blockquote>
+<div class="sourceCode"><pre class="sourceCode php"><code class="sourceCode php"><span class="kw">$options</span> = <span class="ot">[[](</span>.html<span class="ot">)</span>
+ <span class="st">'http'</span> => <span class="ot">[[](</span>.html<span class="ot">)</span>
+ <span class="st">'method'</span> => <span class="st">'GET'</span><span class="ot">,</span>
+ <span class="st">'jwt'</span> => <span class="kw">$token</span><span class="ot">,</span>
+ <span class="ot">],</span>
+<span class="ot">];</span>
+<span class="kw">$context</span> = <span class="fu">stream_context_create</span><span class="ot">(</span><span class="kw">$options</span><span class="ot">);</span>
+<span class="fu">file_get_contents</span><span class="ot">(</span><span class="kw">$apiEndpoint</span><span class="ot">,</span> <span class="kw">false</span><span class="ot">,</span> <span class="kw">$context</span><span class="ot">);</span></code></pre></div>
+</body>
+</html>
--- /dev/null
+#REST API
+## Usage
+
+See the [REST API documentation](http://shaarli.github.io/api-documentation/).[](.html)
+
+## Authentication
+
+All requests to Shaarli's API must include a JWT token to verify their authenticity.
+
+This token has to be included as an HTTP header called `Authentication: Bearer <jwt token>`.
+
+JWT resources :
+
+ * [jwt.io](https://jwt.io) (including a list of client per language).[](.html)
+ * RFC : https://tools.ietf.org/html/rfc7519
+ * https://float-middle.com/json-web-tokens-jwt-vs-sessions/
+ * HackerNews thread: https://news.ycombinator.com/item?id=11929267
+
+
+### Shaarli JWT Token
+
+JWT tokens are composed by three parts, separated by a dot `.` and encoded in base64:
+
+```
+[header].[payload].[signature][](.html)
+```
+
+#### Header
+
+Shaarli only allow one hash algorithm, so the header will always be the same:
+
+```json
+{
+ "typ": "JWT",
+ "alg": "HS512"
+}
+```
+
+Encoded in base64, it gives:
+
+```
+ewogICAgICAgICJ0eXAiOiAiSldUIiwKICAgICAgICAiYWxnIjogIkhTNTEyIgogICAgfQ==
+```
+
+#### Payload
+
+**Validity duration**
+
+To avoid infinite token validity, JWT tokens must include their creation date in UNIX timestamp format (timezone independant - UTC) under the key `iat` (issued at). This token will be accepted during 9 minutes.
+
+```json
+{
+ "iat": 1468663519
+}
+```
+
+See [RFC reference](https://tools.ietf.org/html/rfc7519#section-4.1.6).[](.html)
+
+
+#### Signature
+
+The signature authenticate the token validity. It contains the base64 of the header and the body, separated by a dot `.`, hashed in SHA512 with the API secret available in Shaarli administration page.
+
+Signature example with PHP:
+
+```php
+$content = base64_encode($header) . '.' . base64_encode($payload);
+$signature = hash_hmac('sha512', $content, $secret);
+```
+
+
+### Complete example
+
+#### PHP
+
+```php
+function generateToken($secret) {
+ $header = base64_encode('{
+ "typ": "JWT",
+ "alg": "HS512"
+ }');
+ $payload = base64_encode('{
+ "iat": '. time() .'
+ }');
+ $signature = hash_hmac('sha512', $header .'.'. $payload , $secret);
+ return $header .'.'. $payload .'.'. $signature;
+}
+
+$secret = 'mysecret';
+$token = generateToken($secret);
+echo $token;
+```
+
+> `ewogICAgICAgICJ0eXAiOiAiSldUIiwKICAgICAgICAiYWxnIjogIkhTNTEyIgogICAgfQ==.ewogICAgICAgICJpYXQiOiAxNDY4NjY3MDQ3CiAgICB9.1d2c54fa947daf594fdbf7591796195652c8bc63bffad7f6a6db2a41c313f495a542cbfb595acade79e83f3810d709b4251d7b940bbc10b531a6e6134af63a68`
+
+```php
+$options = [[](.html)
+ 'http' => [[](.html)
+ 'method' => 'GET',
+ 'jwt' => $token,
+ ],
+];
+$context = stream_context_create($options);
+file_get_contents($apiEndpoint, false, $context);
+```
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<span class="ex">gpg</span>: Signature made Thu 30 Jul 2015 11:46:34 CEST using RSA key ID 4100DF6F
<span class="ex">gpg</span>: Good signature from <span class="st">"VirtualTam <virtualtam@flibidi.net>"</span> [ultimate][](.html)</code></pre></div>
<h2 id="publish-the-github-release">Publish the GitHub release</h2>
+<h3 id="update-release-badges">Update release badges</h3>
+<p>Update <code>README.md</code> so version badges display and point to the newly released Shaarli version(s).</p>
<h3 id="create-a-github-release-from-a-git-tag">Create a GitHub release from a Git tag</h3>
<p>From the previously drafted release:</p>
<ul>
```
## Publish the GitHub release
+### Update release badges
+Update `README.md` so version badges display and point to the newly released Shaarli version(s).
+
### Create a GitHub release from a Git tag
From the previously drafted release:
- edit the release notes (if needed)
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<h3 id="htaccess">.htaccess</h3>
<p>Shaarli use <code>.htaccess</code> Apache files to deny access to files that shouldn't be directly accessed (datastore, config, etc.). You need the directive <code>AllowOverride All</code> in your virtual host configuration for them to work.</p>
<p><strong>Warning</strong>: If you use Apache 2.2 or lower, you need <a href="https://httpd.apache.org/docs/current/mod/mod_version.html">mod_version</a> to be installed and enabled.<a href=".html"></a></p>
+<p>Apache module <code>mod_rewrite</code> <strong>must</strong> be enabled to use the REST API. URL rewriting rules for the Slim microframework are stated in the root <code>.htaccess</code> file.</p>
<h2 id="lighthttpd">LightHttpd</h2>
<h2 id="nginx">Nginx</h2>
<h3 id="foreword">Foreword</h3>
error_log /var/log/nginx/error.log;
location /shaarli/ {
+ try_files $uri /shaarli/index.php$is_args$args;
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
location ~ (index)\.php$ {
+ try_files $uri =404;
+ fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
}</code></pre>
<pre class="nginx"><code># /etc/nginx/php.conf
location ~ (index)\.php$ {
+ # Slim - split URL path into (script_filename, path_info)
+ try_files $uri =404;
+ fastcgi_split_path_info ^(.+\.php)(/.+)$;
+
# filter and proxy PHP requests to PHP-FPM
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
server_name my.first.domain.org;
location /shaarli/ {
+ # Slim - rewrite URLs
+ try_files $uri /shaarli/index.php$is_args$args;
+
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
ssl_certificate_key /home/john/ssl/localhost.key;
location /shaarli/ {
+ # Slim - rewrite URLs
+ try_files $uri /index.php$is_args$args;
+
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
Shaarli use `.htaccess` Apache files to deny access to files that shouldn't be directly accessed (datastore, config, etc.). You need the directive `AllowOverride All` in your virtual host configuration for them to work.
**Warning**: If you use Apache 2.2 or lower, you need [mod_version](https://httpd.apache.org/docs/current/mod/mod_version.html) to be installed and enabled.[](.html)
+
+Apache module `mod_rewrite` **must** be enabled to use the REST API. URL rewriting rules for the Slim microframework are stated in the root `.htaccess` file.
## LightHttpd
error_log /var/log/nginx/error.log;
location /shaarli/ {
+ try_files $uri /shaarli/index.php$is_args$args;
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
location ~ (index)\.php$ {
+ try_files $uri =404;
+ fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
```nginx
# /etc/nginx/php.conf
location ~ (index)\.php$ {
+ # Slim - split URL path into (script_filename, path_info)
+ try_files $uri =404;
+ fastcgi_split_path_info ^(.+\.php)(/.+)$;
+
# filter and proxy PHP requests to PHP-FPM
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
server_name my.first.domain.org;
location /shaarli/ {
+ # Slim - rewrite URLs
+ try_files $uri /shaarli/index.php$is_args$args;
+
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
ssl_certificate_key /home/john/ssl/localhost.key;
location /shaarli/ {
+ # Slim - rewrite URLs
+ try_files $uri /index.php$is_args$args;
+
access_log /var/log/nginx/shaarli.access.log;
error_log /var/log/nginx/shaarli.error.log;
}
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</thead>
<tbody>
<tr class="odd">
+<td style="text-align: center;">7.1</td>
+<td style="text-align: center;">Supported (v0.9.x)</td>
+<td style="text-align: center;">✅</td>
+</tr>
+<tr class="even">
<td style="text-align: center;">7.0</td>
<td style="text-align: center;">Supported</td>
<td style="text-align: center;">✅</td>
</tr>
-<tr class="even">
+<tr class="odd">
<td style="text-align: center;">5.6</td>
<td style="text-align: center;">Supported</td>
<td style="text-align: center;">✅</td>
</tr>
-<tr class="odd">
+<tr class="even">
<td style="text-align: center;">5.5</td>
<td style="text-align: center;">EOL: 2016-07-10</td>
<td style="text-align: center;">✅</td>
</tr>
-<tr class="even">
+<tr class="odd">
<td style="text-align: center;">5.4</td>
<td style="text-align: center;">EOL: 2015-09-14</td>
<td style="text-align: center;">✅ (up to Shaarli 0.8.x)</td>
</tr>
-<tr class="odd">
+<tr class="even">
<td style="text-align: center;">5.3</td>
<td style="text-align: center;">EOL: 2014-08-14</td>
<td style="text-align: center;">✅ (up to Shaarli 0.8.x)</td>
<td style="text-align: center;">All</td>
<td>Import bookmarks from Netscape files<a href=".html"></a></td>
</tr>
+<tr class="even">
+<td><a href="https://packagist.org/packages/erusev/parsedown"><code>erusev/parsedown</code></a></td>
+<td style="text-align: center;">All</td>
+<td>Parse MarkDown syntax for the MarkDown plugin<a href=".html"></a></td>
+</tr>
+<tr class="odd">
+<td><a href="https://packagist.org/packages/slim/slim"><code>slim/slim</code></a></td>
+<td style="text-align: center;">All</td>
+<td>Handle routes and middleware for the REST API<a href=".html"></a></td>
+</tr>
</tbody>
</table>
<h3 id="extensions">Extensions</h3>
### Supported versions
Version | Status | Shaarli compatibility
:---:|:---:|:---:
+7.1 | Supported (v0.9.x) | :white_check_mark:
7.0 | Supported | :white_check_mark:
5.6 | Supported | :white_check_mark:
5.5 | EOL: 2016-07-10 | :white_check_mark:
Library | Required? | Usage
---|:---:|---
[`shaarli/netscape-bookmark-parser`](https://packagist.org/packages/shaarli/netscape-bookmark-parser) | All | Import bookmarks from Netscape files[](.html)
+[`erusev/parsedown`](https://packagist.org/packages/erusev/parsedown) | All | Parse MarkDown syntax for the MarkDown plugin[](.html)
+[`slim/slim`](https://packagist.org/packages/slim/slim) | All | Handle routes and middleware for the REST API[](.html)
### Extensions
Extension | Required? | Usage
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<h3 id="resources">Resources</h3>
<p><strong>data_dir</strong>: Data directory.<br />
<strong>datastore</strong>: Shaarli's links database file path.<br />
+<strong>history</strong>: Shaarli's operation history file path.<br />
<strong>updates</strong>: File path for the ran updates file.<br />
<strong>log</strong>: Log file path.<br />
<strong>update_check</strong>: Last update check file path.<br />
**data_dir**: Data directory.
**datastore**: Shaarli's links database file path.
+**history**: Shaarli's operation history file path.
**updates**: File path for the ran updates file.
**log**: Log file path.
**update_check**: Last update check file path.
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</ul>
</div>
<h1 id="theming">Theming</h1>
-<h2 id="user-css">User CSS</h2>
+<h2 id="foreword">Foreword</h2>
+<p>There are two ways of customizing how Shaarli looks:</p>
+<ol>
+<li>by using a custom CSS to override Shaarli's CSS</li>
+<li>by using a full theme that provides its own RainTPL templates, CSS and Javascript resources</li>
+</ol>
+<h2 id="custom-css">Custom CSS</h2>
+<p>Shaarli's appearance can be modified by adding CSS rules to:</p>
<ul>
-<li>Shaarli's apparence can be modified by editing CSS rules in <code>inc/user.css</code>. This file allows to override rules defined in the main <code>inc/shaarli.css</code> (only add changed rules), or define a whole new theme.</li>
-<li>Do not edit <code>inc/shaarli.css</code>! Your changes would be overriden when updating Shaarli.</li>
-<li>Some themes are available at <a href="https://github.com/shaarli/shaarli-themes" class="uri">https://github.com/shaarli/shaarli-themes</a>.</li>
+<li>Shaarli < <code>v0.9.0</code>: <code>inc/user.css</code></li>
+<li>Shaarli >= <code>v0.9.0</code>: <code>data/user.css</code></li>
</ul>
-<p>See also:</p>
-<ul>
-<li><a href="Download-CSS-styles-from-an-OPML-list.html">Download CSS styles from an OPML list</a></li>
-</ul>
-<h2 id="raintpl-template">RainTPL template</h2>
+<p>This file allows overriding rules defined in the template CSS files (only add changed rules), or define a whole new theme.</p>
+<p><strong>Note</strong>: Do not edit <code>tpl/default/css/shaarli.css</code>! Your changes would be overridden when updating Shaarli.</p>
+<p>See also <a href="Download-CSS-styles-from-an-OPML-list.html">Download CSS styles from an OPML list</a></p>
+<h2 id="themes">Themes</h2>
<p><em>WARNING - This feature is currently being worked on and will be improved in the next releases. Experimental.</em></p>
+<p>Installation:</p>
<ul>
-<li>Find the template you'd like to install (see the list of <a href="available-templates%7CTheming#community-themes--templates.html">available templates|Theming#community-themes--templates</a>)</li>
-<li>Find it's git clone URL or download the zip archive for the template.</li>
-<li>In your Shaarli <code>tpl/</code> directory, run <code>git clone https://url/of/my-template/</code> or unpack the zip archive.
+<li>find a theme you'd like to install</li>
+<li>copy or clone the theme folder under <code>tpl/<a_sweet_theme></code></li>
+<li>enable the theme:
<ul>
-<li>There should now be a <code>my-template/</code> directory under the <code>tpl/</code> dir, containing directly all the template files.</li>
+<li>Shaarli < <code>v0.9.0</code>: edit <code>data/config.json.php</code> and set the value of <code>raintpl_tpl</code> to the new theme name:<br />
+<code>"raintpl_tpl": "tpl\/my-template\/"</code></li>
+<li>Shaarli >= <code>v0.9.0</code>: select the theme through the <em>Tools</em> page</li>
</ul></li>
-<li><p>Edit <code>data/config.json.php</code> to have Shaarli use this template, in <code>"resource"</code> e.g.</p>
-<div class="sourceCode"><pre class="sourceCode json"><code class="sourceCode json"><span class="er">"raintpl_tpl":</span> <span class="er">"tpl\/my-template\/",</span></code></pre></div></li>
</ul>
-<h2 id="community-themes-templates">Community themes & templates</h2>
+<h2 id="community-css-themes">Community CSS & themes</h2>
+<h3 id="custom-css-1">Custom CSS</h3>
+<ul>
+<li><a href="https://github.com/mrjovanovic/serious-theme-shaarli">mrjovanovic/serious-theme-shaarli</a> - A serious theme for Shaarli<a href=".html"></a></li>
+<li><a href="https://github.com/shaarli/shaarli-themes">shaarli/shaarli-themes</a><a href=".html"></a></li>
+</ul>
+<h3 id="themes-1">Themes</h3>
<ul>
<li><a href="https://github.com/AkibaTech/Shaarli---SuperHero-Theme">AkibaTech/Shaarli Superhero Theme</a> - A template/theme for Shaarli<a href=".html"></a></li>
<li><a href="https://github.com/alexisju/albinomouse-template">alexisju/albinomouse-template</a> - A full template for Shaarli<a href=".html"></a></li>
-<li><a href="https://github.com/ArthurHoaro/shaarli-launch">ArthurHoaro/shaarli-launch</a> - Customizable Shaarli theme.<a href=".html"></a></li>
+<li><a href="https://github.com/ArthurHoaro/shaarli-launch">ArthurHoaro/shaarli-launch</a> - Customizable Shaarli theme<a href=".html"></a></li>
<li><a href="https://github.com/dhoko/ShaarliTemplate">dhoko/ShaarliTemplate</a> - A template/theme for Shaarli<a href=".html"></a></li>
<li><a href="https://github.com/kalvn/shaarli-blocks">kalvn/shaarli-blocks</a> - A template/theme for Shaarli<a href=".html"></a></li>
-<li><a href="https://github.com/kalvn/Shaarli-Material">kalvn/Shaarli-Material</a> - A theme (template) based on Google's Material Design for Shaarli, the superfast delicious clone.<a href=".html"></a></li>
-<li><a href="https://github.com/ManufacturaInd/shaarli-2004licious-theme">ManufacturaInd/shaarli-2004licious-theme</a> - A template/theme as a humble homage to the early looks of the del.icio.us site.<a href=".html"></a></li>
+<li><a href="https://github.com/kalvn/Shaarli-Material">kalvn/Shaarli-Material</a> - A theme (template) based on Google's Material Design for Shaarli, the superfast delicious clone<a href=".html"></a></li>
+<li><a href="https://github.com/ManufacturaInd/shaarli-2004licious-theme">ManufacturaInd/shaarli-2004licious-theme</a> - A template/theme as a humble homage to the early looks of the del.icio.us site<a href=".html"></a></li>
+</ul>
+<h3 id="shaarli-forks">Shaarli forks</h3>
+<ul>
<li><a href="https://github.com/misterair/limonade">misterair/Limonade</a> - A fork of (legacy) Shaarli with a new template<a href=".html"></a></li>
-<li><a href="https://github.com/mrjovanovic/serious-theme-shaarli">mrjovanovic/serious-theme-shaarli</a> - A serious theme for SHaarli.<a href=".html"></a></li>
<li><a href="https://github.com/vivienhaese/shaarlitheme">vivienhaese/shaarlitheme</a> - A Shaarli fork meant to be run in an openshift instance<a href=".html"></a></li>
</ul>
-<h3 id="example-installation-albinomouse-template">Example installation: AlbinoMouse template</h3>
+<h2 id="example-installation-albinomouse-theme">Example installation: AlbinoMouse theme</h2>
<p>With the following configuration:</p>
<ul>
<li>Apache 2 / PHP 5.6</li>
#Theming
-## User CSS
+## Foreword
+There are two ways of customizing how Shaarli looks:
-- Shaarli's apparence can be modified by editing CSS rules in `inc/user.css`. This file allows to override rules defined in the main `inc/shaarli.css` (only add changed rules), or define a whole new theme.
-- Do not edit `inc/shaarli.css`! Your changes would be overriden when updating Shaarli.
-- Some themes are available at https://github.com/shaarli/shaarli-themes.
+1. by using a custom CSS to override Shaarli's CSS
+2. by using a full theme that provides its own RainTPL templates, CSS and Javascript resources
-See also:
-- [Download CSS styles from an OPML list](Download-CSS-styles-from-an-OPML-list.html)
+## Custom CSS
+Shaarli's appearance can be modified by adding CSS rules to:
+- Shaarli < `v0.9.0`: `inc/user.css`
+- Shaarli >= `v0.9.0`: `data/user.css`
-## RainTPL template
+This file allows overriding rules defined in the template CSS files (only add changed rules), or define a whole new theme.
+**Note**: Do not edit `tpl/default/css/shaarli.css`! Your changes would be overridden when updating Shaarli.
+
+See also [Download CSS styles from an OPML list](Download-CSS-styles-from-an-OPML-list.html)
+
+## Themes
_WARNING - This feature is currently being worked on and will be improved in the next releases. Experimental._
-- Find the template you'd like to install (see the list of [available templates|Theming#community-themes--templates](available-templates|Theming#community-themes--templates.html))
-- Find it's git clone URL or download the zip archive for the template.
-- In your Shaarli `tpl/` directory, run `git clone https://url/of/my-template/` or unpack the zip archive.
- - There should now be a `my-template/` directory under the `tpl/` dir, containing directly all the template files.
-- Edit `data/config.json.php` to have Shaarli use this template, in `"resource"` e.g.
-```json
-"raintpl_tpl": "tpl\/my-template\/",
-```
+Installation:
+- find a theme you'd like to install
+- copy or clone the theme folder under `tpl/<a_sweet_theme>`
+- enable the theme:
+ - Shaarli < `v0.9.0`: edit `data/config.json.php` and set the value of `raintpl_tpl` to the new theme name:
+ `"raintpl_tpl": "tpl\/my-template\/"`
+ - Shaarli >= `v0.9.0`: select the theme through the _Tools_ page
-## Community themes & templates
+## Community CSS & themes
+### Custom CSS
+- [mrjovanovic/serious-theme-shaarli](https://github.com/mrjovanovic/serious-theme-shaarli) - A serious theme for Shaarli[](.html)
+- [shaarli/shaarli-themes](https://github.com/shaarli/shaarli-themes)[](.html)
+
+### Themes
- [AkibaTech/Shaarli Superhero Theme](https://github.com/AkibaTech/Shaarli---SuperHero-Theme) - A template/theme for Shaarli[](.html)
- [alexisju/albinomouse-template](https://github.com/alexisju/albinomouse-template) - A full template for Shaarli[](.html)
-- [ArthurHoaro/shaarli-launch](https://github.com/ArthurHoaro/shaarli-launch) - Customizable Shaarli theme.[](.html)
+- [ArthurHoaro/shaarli-launch](https://github.com/ArthurHoaro/shaarli-launch) - Customizable Shaarli theme[](.html)
- [dhoko/ShaarliTemplate](https://github.com/dhoko/ShaarliTemplate) - A template/theme for Shaarli[](.html)
- [kalvn/shaarli-blocks](https://github.com/kalvn/shaarli-blocks) - A template/theme for Shaarli[](.html)
-- [kalvn/Shaarli-Material](https://github.com/kalvn/Shaarli-Material) - A theme (template) based on Google's Material Design for Shaarli, the superfast delicious clone.[](.html)
-- [ManufacturaInd/shaarli-2004licious-theme](https://github.com/ManufacturaInd/shaarli-2004licious-theme) - A template/theme as a humble homage to the early looks of the del.icio.us site.[](.html)
+- [kalvn/Shaarli-Material](https://github.com/kalvn/Shaarli-Material) - A theme (template) based on Google's Material Design for Shaarli, the superfast delicious clone[](.html)
+- [ManufacturaInd/shaarli-2004licious-theme](https://github.com/ManufacturaInd/shaarli-2004licious-theme) - A template/theme as a humble homage to the early looks of the del.icio.us site[](.html)
+
+### Shaarli forks
- [misterair/Limonade](https://github.com/misterair/limonade) - A fork of (legacy) Shaarli with a new template[](.html)
-- [mrjovanovic/serious-theme-shaarli](https://github.com/mrjovanovic/serious-theme-shaarli) - A serious theme for SHaarli.[](.html)
- [vivienhaese/shaarlitheme](https://github.com/vivienhaese/shaarlitheme) - A Shaarli fork meant to be run in an openshift instance[](.html)
-### Example installation: AlbinoMouse template
+## Example installation: AlbinoMouse theme
With the following configuration:
- Apache 2 / PHP 5.6
- user sites are enabled, e.g. `/home/user/public_html/somedir` is served as `http://localhost/~user/somedir`
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li>If you have the error <code>Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in /…/index.php on line xxx</code>, it means that your host has disabled the ability to fetch a file by HTTP in the php config (Typically in 1and1 hosting). Bad host. Change host. Or comment the following lines:<a href=".html"></a></li>
</ul>
<div class="sourceCode"><pre class="sourceCode php"><code class="sourceCode php"><span class="co">//list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.</span>
-<span class="co">// FIXME: Decode charset according to charset specified in either 1) HTTP response headers or 2) <head> in html </span>
+<span class="co">// </span><span class="al">FIXME</span><span class="co">: Decode charset according to charset specified in either 1) HTTP response headers or 2) <head> in html </span>
<span class="co">//if (strpos($status,'200 OK')) $title=html_extract_title($data);</span></code></pre></div>
<ul>
<li>On hosts which forbid outgoing HTTP requests (such as free.fr), some thumbnails will not work.</li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li>a detailed HTML report with metrics for tested code</li>
<li>to open it in a web browser: <code>firefox coverage/index.html &</code></li>
</ul>
+<h3 id="executing-specific-tests">Executing specific tests</h3>
+<p>Add a <a href="https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.group"><code>@group</code></a> annotation in a test class or method comment:<a href=".html"></a></p>
+<div class="sourceCode"><pre class="sourceCode php"><code class="sourceCode php"><span class="co">/**</span>
+<span class="co"> * Netscape bookmark import</span>
+<span class="co"> * </span><span class="an">@group</span><span class="co"> WIP</span>
+<span class="co"> */</span>
+<span class="kw">class</span> BookmarkImportTest <span class="kw">extends</span> PHPUnit_Framework_TestCase
+{
+ <span class="ot">[</span><span class="st">...</span><span class="ot">][](</span>.html<span class="ot">)</span>
+}</code></pre></div>
+<p>To run all tests annotated with <code>@group WIP</code>:</p>
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">vendor/bin/phpunit</span> --group WIP tests/</code></pre></div>
</body>
</html>
* a summary in the console
* a detailed HTML report with metrics for tested code
* to open it in a web browser: `firefox coverage/index.html &`
+
+### Executing specific tests
+Add a [`@group`](https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.group) annotation in a test class or method comment:[](.html)
+
+```php
+/**
+ * Netscape bookmark import
+ * @group WIP
+ */
+class BookmarkImportTest extends PHPUnit_Framework_TestCase
+{
+ [...][](.html)
+}
+```
+
+To run all tests annotated with `@group WIP`:
+```bash
+$ vendor/bin/phpunit --group WIP tests/
+```
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
</div>
<h1 id="upgrade-and-migration">Upgrade and migration</h1>
<h2 id="preparation">Preparation</h2>
+<h3 id="note-your-current-version">Note your current version</h3>
+<p>If anything goes wrong, it's important for us to know which version you're upgrading from.<br />
+The current version is present in the <code>version.php</code> file.</p>
<h3 id="backup-your-data">Backup your data</h3>
<p>Shaarli stores all user data under the <code>data</code> directory:</p>
<ul>
<li><code>data/config.php</code> - main configuration file</li>
<li><code>data/datastore.php</code> - bookmarked links</li>
<li><code>data/ipbans.php</code> - banned IP addresses</li>
+<li><code>data/updates.txt</code> - contains all automatic update to the configuration and datastore files already run</li>
</ul>
<p>See <a href="Shaarli-configuration.html">Shaarli configuration</a> for more information about Shaarli resources.</p>
<p>It is recommended to backup this repository <em>before</em> starting updating/upgrading Shaarli:</p>
</ul></li>
<li>check or restore the <code>data</code> directory</li>
</ul>
-<h2 id="upgrading-from-release-archives">Upgrading from release archives</h2>
+<h2 id="recommended-upgrading-from-release-archives">Recommended : Upgrading from release archives</h2>
<p>All tagged revisions can be downloaded as tarballs or ZIP archives from the <a href="https://github.com/shaarli/Shaarli/releases">releases</a> page.<a href=".html"></a></p>
-<p>We <em>recommend</em> using the releases from the <code>stable</code> branch, which are available as:</p>
-<ul>
-<li>gzipped tarball - <a href="https://github.com/shaarli/Shaarli/archive/stable.tar.gz" class="uri">https://github.com/shaarli/Shaarli/archive/stable.tar.gz</a></li>
-<li>ZIP archive - <a href="https://github.com/shaarli/Shaarli/archive/stable.zip" class="uri">https://github.com/shaarli/Shaarli/archive/stable.zip</a></li>
-</ul>
-<p>Once downloaded, extract the archive locally and update your remote installation (e.g. via FTP) -be sure you keep the contents of the <code>data</code> directory!</p>
-<p>After upgrading, access your fresh Shaarli installation from a web browser; the configuration will then be automatically updated, and new settings added to <code>data/config.php</code> (see <a href="Shaarli-configuration.html">Shaarli configuration</a> for more details).</p>
+<p>We recommend that you use the latest release tarball with the <code>-full</code> suffix. It contains the dependencies, please read <a href="Download-and-installation.html">Download and installation</a> for <code>git</code> complete instructions.</p>
+<p>Once downloaded, extract the archive locally and update your remote installation (e.g. via FTP) -be sure you keep the content of the <code>data</code> directory!</p>
+<p>After upgrading, access your fresh Shaarli installation from a web browser; the configuration and data store will then be automatically updated, and new settings added to <code>data/config.json.php</code> (see <a href="Shaarli-configuration.html">Shaarli configuration</a> for more details).</p>
<h2 id="upgrading-with-git">Upgrading with Git</h2>
<h3 id="updating-a-community-shaarli">Updating a community Shaarli</h3>
<p>If you have installed Shaarli from the <a href="Download#clone-with-git-recommended">community Git repository</a>, simply <a href="https://www.git-scm.com/docs/git-pull">pull new changes</a> from your local clone:<a href=".html"></a></p>
<span class="ex">tests/Url/UrlTest.php</span> <span class="kw">|</span> <span class="ex">1</span> +
<span class="ex">3</span> files changed, 3 insertions(+), <span class="ex">1</span> deletion(-)</code></pre></div>
<p>Shaarli >= <code>v0.8.x</code>: install/update third-party PHP dependencies using <a href="https://getcomposer.org/">Composer</a>:<a href=".html"></a></p>
-<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">composer</span> update --no-dev
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">composer</span> install --no-dev
<span class="ex">Loading</span> composer repositories with package information
<span class="ex">Updating</span> dependencies
<span class="ex">master</span> 029f75f [sebsauvage/master] Update README.md[](.html)
<span class="ex">*</span> stable 890afc3 [origin/stable] Merge pull request <span class="co">#509 from ArthurHoaro/v0.6.5[](.html)</span></code></pre></div>
<p>Shaarli >= <code>v0.8.x</code>: install/update third-party PHP dependencies using <a href="https://getcomposer.org/">Composer</a>:<a href=".html"></a></p>
-<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">composer</span> update --no-dev
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">composer</span> install --no-dev
<span class="ex">Loading</span> composer repositories with package information
<span class="ex">Updating</span> dependencies
<span class="ex">Total</span> 3317 (delta 2050), <span class="ex">reused</span> 3301 (delta 2034)<span class="ex">to</span></code></pre></div>
<h4 id="step-3-configuration">Step 3: configuration</h4>
<p>After migrating, access your fresh Shaarli installation from a web browser; the configuration will then be automatically updated, and new settings added to <code>data/config.php</code> (see <a href="Shaarli-configuration.html">Shaarli configuration</a> for more details).</p>
+<h2 id="troubleshooting">Troubleshooting</h2>
+<p>If the solutions provided here doesn't work, please open an issue specifying which version you're upgrading from and to.</p>
+<h3 id="you-must-specify-an-integer-as-a-key">You must specify an integer as a key</h3>
+<p>In <code>v0.8.1</code> we changed how link keys are handled (from timestamps to incremental integers).<br />
+Take a look at <code>data/updates.txt</code> content.</p>
+<h4 id="updates.txt-contains-updatemethoddatastoreids"><code>updates.txt</code> contains <code>updateMethodDatastoreIds</code></h4>
+<p>Try to delete it and refresh your page while being logged in.</p>
+<h4 id="updates.txt-doesnt-exists-or-doesnt-contain-updatemethoddatastoreids"><code>updates.txt</code> doesn't exists or doesn't contain <code>updateMethodDatastoreIds</code></h4>
+<ol>
+<li>Create <code>data/updates.txt</code> if it doesn't exist.</li>
+<li>Paste this string in the update file <code>;updateMethodRenameDashTags;</code></li>
+<li>Login to Shaarli.</li>
+<li>Delete the update file.</li>
+<li>Refresh.</li>
+</ol>
</body>
</html>
#Upgrade and migration
## Preparation
+### Note your current version
+
+If anything goes wrong, it's important for us to know which version you're upgrading from.
+The current version is present in the `version.php` file.
+
### Backup your data
Shaarli stores all user data under the `data` directory:
- `data/config.php` - main configuration file
- `data/datastore.php` - bookmarked links
- `data/ipbans.php` - banned IP addresses
+- `data/updates.txt` - contains all automatic update to the configuration and datastore files already run
See [Shaarli configuration](Shaarli-configuration.html) for more information about Shaarli resources.
- update - see the following sections
- check or restore the `data` directory
-## Upgrading from release archives
+## Recommended : Upgrading from release archives
All tagged revisions can be downloaded as tarballs or ZIP archives from the [releases](https://github.com/shaarli/Shaarli/releases) page.[](.html)
-We _recommend_ using the releases from the `stable` branch, which are available as:
-- gzipped tarball - https://github.com/shaarli/Shaarli/archive/stable.tar.gz
-- ZIP archive - https://github.com/shaarli/Shaarli/archive/stable.zip
+We recommend that you use the latest release tarball with the `-full` suffix. It contains the dependencies, please read [Download and installation](Download-and-installation.html) for `git` complete instructions.
-Once downloaded, extract the archive locally and update your remote installation (e.g. via FTP) -be sure you keep the contents of the `data` directory!
+Once downloaded, extract the archive locally and update your remote installation (e.g. via FTP) -be sure you keep the content of the `data` directory!
-After upgrading, access your fresh Shaarli installation from a web browser; the configuration will then be automatically updated, and new settings added to `data/config.php` (see [Shaarli configuration](Shaarli-configuration.html) for more details).
+After upgrading, access your fresh Shaarli installation from a web browser; the configuration and data store will then be automatically updated, and new settings added to `data/config.json.php` (see [Shaarli configuration](Shaarli-configuration.html) for more details).
## Upgrading with Git
### Updating a community Shaarli
Shaarli >= `v0.8.x`: install/update third-party PHP dependencies using [Composer](https://getcomposer.org/):[](.html)
```bash
-$ composer update --no-dev
+$ composer install --no-dev
Loading composer repositories with package information
Updating dependencies
Shaarli >= `v0.8.x`: install/update third-party PHP dependencies using [Composer](https://getcomposer.org/):[](.html)
```bash
-$ composer update --no-dev
+$ composer install --no-dev
Loading composer repositories with package information
Updating dependencies
#### Step 3: configuration
After migrating, access your fresh Shaarli installation from a web browser; the configuration will then be automatically updated, and new settings added to `data/config.php` (see [Shaarli configuration](Shaarli-configuration.html) for more details).
+
+## Troubleshooting
+
+If the solutions provided here doesn't work, please open an issue specifying which version you're upgrading from and to.
+
+### You must specify an integer as a key
+
+In `v0.8.1` we changed how link keys are handled (from timestamps to incremental integers).
+Take a look at `data/updates.txt` content.
+
+#### `updates.txt` contains `updateMethodDatastoreIds`
+
+Try to delete it and refresh your page while being logged in.
+
+#### `updates.txt` doesn't exists or doesn't contain `updateMethodDatastoreIds`
+
+ 1. Create `data/updates.txt` if it doesn't exist.
+ 2. Paste this string in the update file `;updateMethodRenameDashTags;`
+ 3. Login to Shaarli.
+ 4. Delete the update file.
+ 5. Refresh.
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
--- /dev/null
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <meta name="generator" content="pandoc">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
+ <title>Shaarli – Versioning and Branches</title>
+ <style type="text/css">code{white-space: pre;}</style>
+ <style type="text/css">
+div.sourceCode { overflow-x: auto; }
+table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
+ margin: 0; padding: 0; vertical-align: baseline; border: none; }
+table.sourceCode { width: 100%; line-height: 100%; }
+td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
+td.sourceCode { padding-left: 5px; }
+code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
+code > span.dt { color: #902000; } /* DataType */
+code > span.dv { color: #40a070; } /* DecVal */
+code > span.bn { color: #40a070; } /* BaseN */
+code > span.fl { color: #40a070; } /* Float */
+code > span.ch { color: #4070a0; } /* Char */
+code > span.st { color: #4070a0; } /* String */
+code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
+code > span.ot { color: #007020; } /* Other */
+code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
+code > span.fu { color: #06287e; } /* Function */
+code > span.er { color: #ff0000; font-weight: bold; } /* Error */
+code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
+code > span.cn { color: #880000; } /* Constant */
+code > span.sc { color: #4070a0; } /* SpecialChar */
+code > span.vs { color: #4070a0; } /* VerbatimString */
+code > span.ss { color: #bb6688; } /* SpecialString */
+code > span.im { } /* Import */
+code > span.va { color: #19177c; } /* Variable */
+code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
+code > span.op { color: #666666; } /* Operator */
+code > span.bu { } /* BuiltIn */
+code > span.ex { } /* Extension */
+code > span.pp { color: #bc7a00; } /* Preprocessor */
+code > span.at { color: #7d9029; } /* Attribute */
+code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
+code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
+code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
+code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
+ </style>
+ <link rel="stylesheet" href="github-markdown.css">
+ <!--[if lt IE 9]>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
+ <![endif]-->
+</head>
+<body>
+<div id="local-sidebar">
+<ul>
+<li><a href="Home.html">Home</a></li>
+<li>Setup
+<ul>
+<li><a href="Download-and-Installation.html">Download and Installation</a></li>
+<li><a href="Upgrade-and-migration.html">Upgrade and migration</a></li>
+<li><a href="Server-requirements.html">Server requirements</a></li>
+<li><a href="Server-configuration.html">Server configuration</a></li>
+<li><a href="Server-security.html">Server security</a></li>
+<li><a href="Shaarli-configuration.html">Shaarli configuration</a></li>
+<li><a href="Plugins.html">Plugins</a></li>
+</ul></li>
+<li><a href="Docker.html">Docker</a></li>
+<li><a href="Usage.html">Usage</a>
+<ul>
+<li><a href="Sharing-button.html">Sharing button</a> (bookmarklet)</li>
+<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
+<li><a href="Firefox-share.html">Firefox share</a></li>
+<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
+</ul></li>
+<li>How To
+<ul>
+<li><a href="Backup,-restore,-import-and-export.html">Backup, restore, import and export</a></li>
+<li><a href="Copy-an-existing-installation-over-SSH-and-serve-it-locally.html">Copy an existing installation over SSH and serve it locally</a></li>
+<li><a href="Create-and-serve-multiple-Shaarlis-(farm).html">Create and serve multiple Shaarlis (farm)</a></li>
+<li><a href="Download-CSS-styles-from-an-OPML-list.html">Download CSS styles from an OPML list</a></li>
+<li><a href="Datastore-hacks.html">Datastore hacks</a></li>
+</ul></li>
+<li><a href="Troubleshooting.html">Troubleshooting</a></li>
+<li><a href="Development.html">Development</a>
+<ul>
+<li><a href="GnuPG-signature.html">GnuPG signature</a></li>
+<li><a href="Coding-guidelines.html">Coding guidelines</a></li>
+<li><a href="Directory-structure.html">Directory structure</a></li>
+<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
+<li><a href="Plugin-System.html">Plugin System</a></li>
+<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
+<li><a href="Security.html">Security</a></li>
+<li><a href="Static-analysis.html">Static analysis</a></li>
+<li><a href="Theming.html">Theming</a></li>
+<li><a href="Unit-tests.html">Unit tests</a></li>
+</ul></li>
+<li>About
+<ul>
+<li><a href="FAQ.html">FAQ</a></li>
+<li><a href="Community-&-Related-software.html">Community & Related software</a></li>
+</ul></li>
+</ul>
+</div>
+<h1 id="versioning-and-branches">Versioning and Branches</h1>
+<p>[<strong>WORK IN PROGRESS</strong>][](.html)</p>
+<p>It's important to understand how Shaarli branches work, especially if you're maintaining a 3rd party tools for Shaarli (theme, plugin, etc.), to be sure stay compatible.</p>
+<h2 id="master-branch"><code>master</code> branch</h2>
+<p>The <code>master</code> branch is the development branch. Any new change MUST go through this branch using Pull Requests.</p>
+<p>Remarks:</p>
+<ul>
+<li>This branch shouldn't be used for production as it isn't necessary stable.</li>
+<li>3rd party aren't required to be compatible with the latest changes.</li>
+<li>Official plugins, themes and libraries (contained within Shaarli organization repos) must be compatible with the master branch.</li>
+<li>The version in this branch is always <code>dev</code>.</li>
+</ul>
+<h2 id="v0.x-branch"><code>v0.x</code> branch</h2>
+<p>This <code>v0.x</code> branch, points to the latest <code>v0.x.y</code> release.</p>
+<p>Explanation:</p>
+<p>When a new version is released, it might contains a major bug which isn't detected right away. For example, a new PHP version is released, containing backward compatibility issue which doesn't work with Shaarli.</p>
+<p>In this case, the issue is fixed in the <code>master</code> branch, and the fix is backported the to the <code>v0.x</code> branch. Then a new release is made from the <code>v0.x</code> branch.</p>
+<p>This workflow allow us to fix any major bug detected, without having to release bleeding edge feature too soon.</p>
+<h2 id="latest-branch"><code>latest</code> branch</h2>
+<p>This branch point the latest release. It recommended to use it to get the latest tested changes.</p>
+<h2 id="stable-branch"><code>stable</code> branch</h2>
+<p>The <code>stable</code> branch doesn't contain any major bug, and is one major digit version behind the latest release.</p>
+<p>For example, the current latest release is <code>v0.8.3</code>, the stable branch is an alias to the latest <code>v0.7.x</code> release. When the <code>v0.9.0</code> version will be released, the stable will move to the latest <code>v0.8.x</code> release.</p>
+<p>Remarks:</p>
+<ul>
+<li>Shaarli release pace isn't fast, and the stable branch might be a few months behind the latest release.</li>
+</ul>
+<h2 id="releases">Releases</h2>
+<p>Releases are always made from the latest <code>v0.x</code> branch.</p>
+<p>Note that for every release, we manually generate a tarball which contains all Shaarli dependencies, making Shaarli's installation only one step.</p>
+<h2 id="advices-on-3rd-party-git-repos-workflow">Advices on 3rd party git repos workflow</h2>
+<h3 id="versioning">Versioning</h3>
+<p>Any time a new Shaarli release is published, you should publish a new release of your repo if the changes affected you since the latest release (take a look at the <a href="https://github.com/shaarli/Shaarli/releases">changelog</a> (<em>Draft</em> means not released yet) and the commit log (like <a href="https://github.com/shaarli/Shaarli/commits/master/tpl/default"><code>tpl</code> folder</a> for themes)). You can either:<a href=".html"></a></p>
+<ul>
+<li>use the Shaarli version number, with your repo version. For example, if Shaarli <code>v0.8.3</code> is released, publish a <code>v0.8.3-1</code> release, where <code>v0.8.3</code> states Shaarli compatibility and <code>-1</code> is your own version digit for the current Shaarli version.</li>
+<li>use your own versioning scheme, and state Shaarli compatibility in the release description.</li>
+</ul>
+<p>Using this, any user will be able to pick the release matching his own Shaarli version.</p>
+<h3 id="major-bugfix-backport-releases">Major bugfix backport releases</h3>
+<p>To be able to support backported fixes, it recommended to use our workflow:</p>
+<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash"><span class="co"># In master, fix the major bug</span>
+<span class="fu">git</span> commit -m <span class="st">"Katastrophe"</span>
+<span class="fu">git</span> push origin master
+<span class="co"># Get your commit hash</span>
+<span class="fu">git</span> log --format=<span class="st">"%H"</span> -n 1
+<span class="co"># Create a new branch from your latest release, let's say v0.8.2-1 (the tag name)</span>
+<span class="fu">git</span> checkout -b katastrophe v0.8.2-1
+<span class="co"># Backport the fix commit to your brand new branch</span>
+<span class="fu">git</span> cherry-pick <span class="op"><</span>fix commit hash<span class="op">></span>
+<span class="fu">git</span> push origin katastrophe
+<span class="co"># Then you just have to make a new release from the `katastrophe` branch tagged `v0.8.3-1`</span></code></pre></div>
+</body>
+</html>
--- /dev/null
+#Versioning and Branches
+[**WORK IN PROGRESS**][](.html)
+
+It's important to understand how Shaarli branches work, especially if you're maintaining a 3rd party tools for Shaarli (theme, plugin, etc.), to be sure stay compatible.
+
+## `master` branch
+
+The `master` branch is the development branch. Any new change MUST go through this branch using Pull Requests.
+
+Remarks:
+
+ * This branch shouldn't be used for production as it isn't necessary stable.
+ * 3rd party aren't required to be compatible with the latest changes.
+ * Official plugins, themes and libraries (contained within Shaarli organization repos) must be compatible with the master branch.
+ * The version in this branch is always `dev`.
+
+## `v0.x` branch
+
+This `v0.x` branch, points to the latest `v0.x.y` release.
+
+Explanation:
+
+When a new version is released, it might contains a major bug which isn't detected right away. For example, a new PHP version is released, containing backward compatibility issue which doesn't work with Shaarli.
+
+In this case, the issue is fixed in the `master` branch, and the fix is backported the to the `v0.x` branch. Then a new release is made from the `v0.x` branch.
+
+This workflow allow us to fix any major bug detected, without having to release bleeding edge feature too soon.
+
+## `latest` branch
+
+This branch point the latest release. It recommended to use it to get the latest tested changes.
+
+## `stable` branch
+
+The `stable` branch doesn't contain any major bug, and is one major digit version behind the latest release.
+
+For example, the current latest release is `v0.8.3`, the stable branch is an alias to the latest `v0.7.x` release. When the `v0.9.0` version will be released, the stable will move to the latest `v0.8.x` release.
+
+Remarks:
+
+ * Shaarli release pace isn't fast, and the stable branch might be a few months behind the latest release.
+
+## Releases
+
+Releases are always made from the latest `v0.x` branch.
+
+Note that for every release, we manually generate a tarball which contains all Shaarli dependencies, making Shaarli's installation only one step.
+
+## Advices on 3rd party git repos workflow
+
+### Versioning
+
+Any time a new Shaarli release is published, you should publish a new release of your repo if the changes affected you since the latest release (take a look at the [changelog](https://github.com/shaarli/Shaarli/releases) (*Draft* means not released yet) and the commit log (like [`tpl` folder](https://github.com/shaarli/Shaarli/commits/master/tpl/default) for themes)). You can either:[](.html)
+
+ - use the Shaarli version number, with your repo version. For example, if Shaarli `v0.8.3` is released, publish a `v0.8.3-1` release, where `v0.8.3` states Shaarli compatibility and `-1` is your own version digit for the current Shaarli version.
+ - use your own versioning scheme, and state Shaarli compatibility in the release description.
+
+Using this, any user will be able to pick the release matching his own Shaarli version.
+
+### Major bugfix backport releases
+
+To be able to support backported fixes, it recommended to use our workflow:
+
+```bash
+# In master, fix the major bug
+git commit -m "Katastrophe"
+git push origin master
+# Get your commit hash
+git log --format="%H" -n 1
+# Create a new branch from your latest release, let's say v0.8.2-1 (the tag name)
+git checkout -b katastrophe v0.8.2-1
+# Backport the fix commit to your brand new branch
+git cherry-pick <fix commit hash>
+git push origin katastrophe
+# Then you just have to make a new release from the `katastrophe` branch tagged `v0.8.3-1`
+```
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
- [Browsing and Searching](Browsing-and-Searching.html)
- [Firefox share](Firefox-share.html)
- [RSS feeds](RSS-feeds.html)
+ - [REST API](REST-API.html)
- How To
- [Backup, restore, import and export](Backup,-restore,-import-and-export.html)
- [Copy an existing installation over SSH and serve it locally](Copy-an-existing-installation-over-SSH-and-serve-it-locally.html)
- [3rd party libraries](3rd-party-libraries.html)
- [Plugin System](Plugin-System.html)
- [Release Shaarli](Release-Shaarli.html)
+ - [Versioning and Branches](Versioning-and-Branches.html)
- [Security](Security.html)
- [Static analysis](Static-analysis.html)
- [Theming](Theming.html)
<li><a href="Browsing-and-Searching.html">Browsing and Searching</a></li>
<li><a href="Firefox-share.html">Firefox share</a></li>
<li><a href="RSS-feeds.html">RSS feeds</a></li>
+<li><a href="REST-API.html">REST API</a></li>
</ul></li>
<li>How To
<ul>
<li><a href="3rd-party-libraries.html">3rd party libraries</a></li>
<li><a href="Plugin-System.html">Plugin System</a></li>
<li><a href="Release-Shaarli.html">Release Shaarli</a></li>
+<li><a href="Versioning-and-Branches.html">Versioning and Branches</a></li>
<li><a href="Security.html">Security</a></li>
<li><a href="Static-analysis.html">Static analysis</a></li>
<li><a href="Theming.html">Theming</a></li>
require_once 'application/config/ConfigPlugin.php';
require_once 'application/FeedBuilder.php';
require_once 'application/FileUtils.php';
+require_once 'application/History.php';
require_once 'application/HttpUtils.php';
require_once 'application/Languages.php';
require_once 'application/LinkDB.php';
}
$userIsLoggedIn = setup_login_state($conf);
-/**
- * PubSubHubbub protocol support (if enabled) [UNTESTED]
- * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
- *
- * @param ConfigManager $conf Configuration Manager instance.
- */
-function pubsubhub($conf)
-{
- $pshUrl = $conf->get('config.PUBSUBHUB_URL');
- if (!empty($pshUrl))
- {
- include_once './publisher.php';
- $p = new Publisher($pshUrl);
- $topic_url = array (
- index_url($_SERVER).'?do=atom',
- index_url($_SERVER).'?do=rss'
- );
- $p->publish_update($topic_url);
- }
-}
-
// ------------------------------------------------------------------------------------------
// Session management
}
}
-// ------------------------------------------------------------------------------------------
-// Misc utility functions:
-
-// Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
-function return_bytes($val)
-{
- $val = trim($val); $last=strtolower($val[strlen($val)-1]);
- switch($last)
- {
- case 'g': $val *= 1024;
- case 'm': $val *= 1024;
- case 'k': $val *= 1024;
- }
- return $val;
-}
-
-// Try to determine max file size for uploads (POST).
-// Returns an integer (in bytes)
-function getMaxFileSize()
-{
- $size1 = return_bytes(ini_get('post_max_size'));
- $size2 = return_bytes(ini_get('upload_max_filesize'));
- // Return the smaller of two:
- $maxsize = min($size1,$size2);
- // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
- return $maxsize;
-}
-
// ------------------------------------------------------------------------------------------
// Token management for XSRF protection
// Token should be used in any form which acts on data (create,update,delete,import...).
$dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
$data = array(
+ 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
'linksToDisplay' => $linksToDisplay,
'cols' => $columns,
'day' => $dayDate->getTimestamp(),
+ 'dayDate' => $dayDate,
'previousday' => $previousday,
'nextday' => $nextday,
);
* @param PluginManager $pluginManager Plugin Manager instance,
* @param LinkDB $LINKSDB
*/
-function renderPage($conf, $pluginManager, $LINKSDB)
+function renderPage($conf, $pluginManager, $LINKSDB, $history)
{
$updater = new Updater(
read_updates_file($conf->get('resource.updates')),
die($e->getMessage());
}
- $PAGE = new PageBuilder($conf);
+ $PAGE = new PageBuilder($conf, $LINKSDB);
$PAGE->assign('linkcount', count($LINKSDB));
$PAGE->assign('privateLinkcount', count_private($LINKSDB));
$PAGE->assign('plugin_errors', $pluginManager->getErrors());
// -------- Tag cloud
if ($targetPage == Router::$PAGE_TAGCLOUD)
{
- $tags= $LINKSDB->allTags();
+ $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
+ $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
+ $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
// We sort tags alphabetically, then choose a font size according to count.
// First, find max value.
$maxcount = max($maxcount, $value);
}
- // Sort tags alphabetically: case insensitive, support locale if available.
- uksort($tags, function($a, $b) {
- // Collator is part of PHP intl.
- if (class_exists('Collator')) {
- $c = new Collator(setlocale(LC_COLLATE, 0));
- if (!intl_is_failure(intl_get_error_code())) {
- return $c->compare($a, $b);
- }
- }
- return strcasecmp($a, $b);
- });
+ alphabetical_sort($tags, true, true);
$tagList = array();
foreach($tags as $key => $value) {
}
$data = array(
+ 'search_tags' => implode(' ', $filteringTags),
'tags' => $tagList,
);
$pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
$PAGE->assign($key, $value);
}
- $PAGE->renderPage('tagcloud');
+ $PAGE->renderPage('tag.cloud');
+ exit;
+ }
+
+ // -------- Tag cloud
+ if ($targetPage == Router::$PAGE_TAGLIST)
+ {
+ $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
+ $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
+ $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
+
+ if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
+ alphabetical_sort($tags, false, true);
+ }
+
+ $data = [
+ 'search_tags' => implode(' ', $filteringTags),
+ 'tags' => $tags,
+ ];
+ $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
+
+ foreach ($data as $key => $value) {
+ $PAGE->assign($key, $value);
+ }
+
+ $PAGE->renderPage('tag.list');
exit;
}
$conf->set('api.secret', escape($_POST['apiSecret']));
try {
$conf->write(isLoggedIn());
+ $history->updateSettings();
invalidateCaches($conf->get('resource.page_cache'));
}
catch(Exception $e) {
$PAGE->assign('theme', $conf->get('resource.theme'));
$PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
$PAGE->assign('redirector', $conf->get('redirector.url'));
- list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone'));
- $PAGE->assign('timezone_form', $timezone_form);
- $PAGE->assign('timezone_js',$timezone_js);
+ list($continents, $cities) = generateTimeZoneData(
+ timezone_identifiers_list(),
+ $conf->get('general.timezone')
+ );
+ $PAGE->assign('continents', $continents);
+ $PAGE->assign('cities', $cities);
$PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
$PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
$PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
if ($targetPage == Router::$PAGE_CHANGETAG)
{
if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
- $PAGE->assign('tags', $LINKSDB->allTags());
+ $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
$PAGE->renderPage('changetag');
exit;
}
unset($tags[array_search($needle,$tags)]); // Remove tag.
$value['tags']=trim(implode(' ',$tags));
$LINKSDB[$key]=$value;
+ $history->updateLink($LINKSDB[$key]);
}
$LINKSDB->save($conf->get('resource.page_cache'));
echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?do=changetag\';</script>';
$tags[array_search($needle, $tags)] = trim($_POST['totag']);
$value['tags'] = implode(' ', array_unique($tags));
$LINKSDB[$key] = $value;
+ $history->updateLink($LINKSDB[$key]);
}
$LINKSDB->save($conf->get('resource.page_cache')); // Save to disk.
echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode(escape($_POST['totag'])).'\';</script>';
$created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
$updated = new DateTime();
$shortUrl = $LINKSDB[$id]['shorturl'];
+ $new = false;
} else {
// New link
$created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
$updated = null;
$shortUrl = link_small_hash($created, $id);
+ $new = true;
}
// Remove multiple spaces.
$LINKSDB[$id] = $link;
$LINKSDB->save($conf->get('resource.page_cache'));
+ if ($new) {
+ $history->addLink($link);
+ } else {
+ $history->updateLink($link);
+ }
// If we are called from the bookmarklet, we must close the popup:
if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
// -------- User clicked the "Delete" button when editing a link: Delete link from database.
if ($targetPage == Router::$PAGE_DELETELINK)
{
- // We do not need to ask for confirmation:
- // - confirmation is handled by JavaScript
- // - we are protected from XSRF by the token.
-
if (! tokenOk($_GET['token'])) {
die('Wrong token.');
}
- $id = intval(escape($_GET['lf_linkdate']));
- $link = $LINKSDB[$id];
- $pluginManager->executeHooks('delete_link', $link);
- unset($LINKSDB[$id]);
+ if (strpos($_GET['lf_linkdate'], ' ') !== false) {
+ $ids = array_values(array_filter(preg_split('/\s+/', escape($_GET['lf_linkdate']))));
+ } else {
+ $ids = [$_GET['lf_linkdate']];
+ }
+ foreach ($ids as $id) {
+ $id = (int) escape($id);
+ $link = $LINKSDB[$id];
+ $pluginManager->executeHooks('delete_link', $link);
+ unset($LINKSDB[$id]);
+ }
$LINKSDB->save($conf->get('resource.page_cache')); // save to disk
+ $history->deleteLink($link);
// If we are called from the bookmarklet, we must close the popup:
if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
'link' => $link,
'link_is_new' => false,
'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
- 'tags' => $LINKSDB->allTags(),
+ 'tags' => $LINKSDB->linksCountPerTag(),
);
$pluginManager->executeHooks('render_editlink', $data);
'link_is_new' => $link_is_new,
'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
- 'tags' => $LINKSDB->allTags(),
+ 'tags' => $LINKSDB->linksCountPerTag(),
'default_private_links' => $conf->get('privacy.default_private_links', false),
);
$pluginManager->executeHooks('render_editlink', $data);
if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
// Show import dialog
- $PAGE->assign('maxfilesize', getMaxFileSize());
+ $PAGE->assign(
+ 'maxfilesize',
+ get_max_upload_size(
+ ini_get('post_max_size'),
+ ini_get('upload_max_filesize'),
+ false
+ )
+ );
+ $PAGE->assign(
+ 'maxfilesizeHuman',
+ get_max_upload_size(
+ ini_get('post_max_size'),
+ ini_get('upload_max_filesize'),
+ true
+ )
+ );
$PAGE->renderPage('import');
exit;
}
// The file is too big or some form field may be missing.
echo '<script>alert("The file you are trying to upload is probably'
.' bigger than what this webserver can accept ('
- .getMaxFileSize().' bytes).'
+ .get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize')).').'
.' Please upload in smaller chunks.");document.location=\'?do='
.Router::$PAGE_IMPORT .'\';</script>';
exit;
$_POST,
$_FILES,
$LINKSDB,
- $conf
+ $conf,
+ $history
);
echo '<script>alert("'.$status.'");document.location=\'?do='
.Router::$PAGE_IMPORT .'\';</script>';
$conf->set('general.enabled_plugins', save_plugin_config($_POST));
}
$conf->write(isLoggedIn());
+ $history->updateSettings();
}
catch (Exception $e) {
error_log(
exit;
}
+ // Get a fresh token
+ if ($targetPage == Router::$GET_TOKEN) {
+ header('Content-Type:text/plain');
+ echo getToken($conf);
+ exit;
+ }
+
// -------- Otherwise, simply display search form and links:
showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
exit;
'visibility' => ! empty($_SESSION['privateonly']) ? 'private' : '',
'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
'links' => $linkDisp,
- 'tags' => $LINKSDB->allTags(),
);
// If there is only a single link, we change on-the-fly the title of the page.
exit;
}
- // Display config form:
- list($timezone_form, $timezone_js) = generateTimeZoneForm();
- $timezone_html = '';
- if ($timezone_form != '') {
- $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
- }
-
$PAGE = new PageBuilder($conf);
- $PAGE->assign('timezone_html',$timezone_html);
- $PAGE->assign('timezone_js',$timezone_js);
+ list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
+ $PAGE->assign('continents', $continents);
+ $PAGE->assign('cities', $cities);
$PAGE->renderPage('install');
exit;
}
$conf->get('redirector.encode_url')
);
+try {
+ $history = new History($conf->get('resource.history'));
+} catch(Exception $e) {
+ die($e->getMessage());
+}
+
$container = new \Slim\Container();
$container['conf'] = $conf;
$container['plugins'] = $pluginManager;
+$container['history'] = $history;
$app = new \Slim\App($container);
// REST API routes
$app->group('/api/v1', function() {
- $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo');
- $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks');
- $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink');
+ $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
+ $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
+ $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
+ $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
+ $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
+ $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
+ $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
})->add('\Shaarli\Api\ApiMiddleware');
$response = $app->run(true);
if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
// We use UTF-8 for proper international characters handling.
header('Content-Type: text/html; charset=utf-8');
- renderPage($conf, $pluginManager, $linkDb);
+ renderPage($conf, $pluginManager, $linkDb, $history);
} else {
$app->respond($response);
}
+++ /dev/null
-<span><a href="%s?url=%s"><img class="linklist-plugin-icon" src="%s/readityourself/book-open.png" title="Read with Readityourself" alt="readityourself" /></a></span>
+++ /dev/null
-description="For each link, add a ReadItYourself icon to save the shaared URL."
-parameters=READITYOUSELF_URL;
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Plugin readityourself
- */
-
-// If we're talking about https://github.com/memiks/readityourself
-// it seems kinda dead.
-// Not tested.
-
-/**
- * Init function, return an error if the server is not set.
- *
- * @param $conf ConfigManager instance.
- *
- * @return array Eventual error.
- */
-function readityourself_init($conf)
-{
- $riyUrl = $conf->get('plugins.READITYOUSELF_URL');
- if (empty($riyUrl)) {
- $error = 'Readityourself plugin error: '.
- 'Please define the "READITYOUSELF_URL" setting in the plugin administration page.';
- return array($error);
- }
-}
-
-/**
- * Add readityourself icon to link_plugin when rendering linklist.
- *
- * @param mixed $data Linklist data.
- * @param ConfigManager $conf Configuration Manager instance.
- *
- * @return mixed - linklist data with readityourself plugin.
- */
-function hook_readityourself_render_linklist($data, $conf)
-{
- $riyUrl = $conf->get('plugins.READITYOUSELF_URL');
- if (empty($riyUrl)) {
- return $data;
- }
-
- $readityourself_html = file_get_contents(PluginManager::$PLUGINS_PATH . '/readityourself/readityourself.html');
-
- foreach ($data['links'] as &$value) {
- $readityourself = sprintf($readityourself_html, $riyUrl, $value['url'], PluginManager::$PLUGINS_PATH);
- $value['link_plugin'][] = $readityourself;
- }
-
- return $data;
-}
--- /dev/null
+<?php
+
+require_once 'application/FileUtils.php';
+
+/**
+ * Class FileUtilsTest
+ *
+ * Test file utility class.
+ */
+class FileUtilsTest extends PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string Test file path.
+ */
+ protected static $file = 'sandbox/flat.db';
+
+ /**
+ * Delete test file after every test.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$file);
+ }
+
+ /**
+ * Test writeDB, then readDB with different data.
+ */
+ public function testSimpleWriteRead()
+ {
+ $data = ['blue', 'red'];
+ $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0);
+ $this->assertTrue(startsWith(file_get_contents(self::$file), '<?php /*'));
+ $this->assertEquals($data, FileUtils::readFlatDB(self::$file));
+
+ $data = 0;
+ $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0);
+ $this->assertEquals($data, FileUtils::readFlatDB(self::$file));
+
+ $data = null;
+ $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0);
+ $this->assertEquals($data, FileUtils::readFlatDB(self::$file));
+
+ $data = false;
+ $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0);
+ $this->assertEquals($data, FileUtils::readFlatDB(self::$file));
+ }
+
+ /**
+ * File not writable: raise an exception.
+ *
+ * @expectedException IOException
+ * @expectedExceptionMessage Error accessing "sandbox/flat.db"
+ */
+ public function testWriteWithoutPermission()
+ {
+ touch(self::$file);
+ chmod(self::$file, 0440);
+ FileUtils::writeFlatDB(self::$file, null);
+ }
+
+ /**
+ * Folder non existent: raise an exception.
+ *
+ * @expectedException IOException
+ * @expectedExceptionMessage Error accessing "nopefolder"
+ */
+ public function testWriteFolderDoesNotExist()
+ {
+ FileUtils::writeFlatDB('nopefolder/file', null);
+ }
+
+ /**
+ * Folder non writable: raise an exception.
+ *
+ * @expectedException IOException
+ * @expectedExceptionMessage Error accessing "sandbox"
+ */
+ public function testWriteFolderPermission()
+ {
+ chmod(dirname(self::$file), 0555);
+ try {
+ FileUtils::writeFlatDB(self::$file, null);
+ } catch (Exception $e) {
+ chmod(dirname(self::$file), 0755);
+ throw $e;
+ }
+ }
+
+ /**
+ * Read non existent file, use default parameter.
+ */
+ public function testReadNotExistentFile()
+ {
+ $this->assertEquals(null, FileUtils::readFlatDB(self::$file));
+ $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test']));
+ }
+
+ /**
+ * Read non readable file, use default parameter.
+ */
+ public function testReadNotReadable()
+ {
+ touch(self::$file);
+ chmod(self::$file, 0220);
+ $this->assertEquals(null, FileUtils::readFlatDB(self::$file));
+ $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test']));
+ }
+}
--- /dev/null
+<?php
+
+require_once 'application/History.php';
+
+
+class HistoryTest extends PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string History file path
+ */
+ protected static $historyFilePath = 'sandbox/history.php';
+
+ /**
+ * Delete history file.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$historyFilePath);
+ }
+
+ /**
+ * Test that the history file is created if it doesn't exist.
+ */
+ public function testConstructLazyLoading()
+ {
+ new History(self::$historyFilePath);
+ $this->assertFileNotExists(self::$historyFilePath);
+ }
+
+ /**
+ * Test that the history file is created if it doesn't exist.
+ */
+ public function testAddEventCreateFile()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateSettings();
+ $this->assertFileExists(self::$historyFilePath);
+ }
+
+ /**
+ * Not writable history file: raise an exception.
+ *
+ * @expectedException Exception
+ * @expectedExceptionMessage History file isn't readable or writable
+ */
+ public function testConstructNotWritable()
+ {
+ touch(self::$historyFilePath);
+ chmod(self::$historyFilePath, 0440);
+ $history = new History(self::$historyFilePath);
+ $history->updateSettings();
+ }
+
+ /**
+ * Not parsable history file: raise an exception.
+ *
+ * @expectedException Exception
+ * @expectedExceptionMessageRegExp /Could not parse history file/
+ */
+ public function testConstructNotParsable()
+ {
+ file_put_contents(self::$historyFilePath, 'not parsable');
+ $history = new History(self::$historyFilePath);
+ // gzinflate generates a warning
+ @$history->updateSettings();
+ }
+
+ /**
+ * Test add link event
+ */
+ public function testAddLink()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->addLink(['id' => 0]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::CREATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(0, $actual['id']);
+
+ $history = new History(self::$historyFilePath);
+ $history->addLink(['id' => 1]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::CREATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+
+ $history = new History(self::$historyFilePath);
+ $history->addLink(['id' => 'str']);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::CREATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals('str', $actual['id']);
+ }
+
+ /**
+ * Test updated link event
+ */
+ public function testUpdateLink()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateLink(['id' => 1]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::UPDATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+ }
+
+ /**
+ * Test delete link event
+ */
+ public function testDeleteLink()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->deleteLink(['id' => 1]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::DELETED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+ }
+
+ /**
+ * Test updated settings event
+ */
+ public function testUpdateSettings()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateSettings();
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::SETTINGS, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEmpty($actual['id']);
+ }
+
+ /**
+ * Make sure that new items are stored at the beginning
+ */
+ public function testHistoryOrder()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateLink(['id' => 1]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::UPDATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+
+ $history->addLink(['id' => 1]);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::CREATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+ }
+
+ /**
+ * Re-read history from file after writing an event
+ */
+ public function testHistoryRead()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateLink(['id' => 1]);
+ $history = new History(self::$historyFilePath);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::UPDATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+ }
+
+ /**
+ * Re-read history from file after writing an event and make sure that the order is correct
+ */
+ public function testHistoryOrderRead()
+ {
+ $history = new History(self::$historyFilePath);
+ $history->updateLink(['id' => 1]);
+ $history->addLink(['id' => 1]);
+
+ $history = new History(self::$historyFilePath);
+ $actual = $history->getHistory()[0];
+ $this->assertEquals(History::CREATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+
+ $actual = $history->getHistory()[1];
+ $this->assertEquals(History::UPDATED, $actual['event']);
+ $this->assertTrue(new DateTime('-2 seconds') < $actual['datetime']);
+ $this->assertEquals(1, $actual['id']);
+ }
+
+ /**
+ * Test retention time: delete old entries.
+ */
+ public function testHistoryRententionTime()
+ {
+ $history = new History(self::$historyFilePath, 5);
+ $history->updateLink(['id' => 1]);
+ $this->assertEquals(1, count($history->getHistory()));
+ $arr = $history->getHistory();
+ $arr[0]['datetime'] = new DateTime('-1 hour');
+ FileUtils::writeFlatDB(self::$historyFilePath, $arr);
+
+ $history = new History(self::$historyFilePath, 60);
+ $this->assertEquals(1, count($history->getHistory()));
+ $this->assertEquals(1, $history->getHistory()[0]['id']);
+ $history->updateLink(['id' => 2]);
+ $this->assertEquals(1, count($history->getHistory()));
+ $this->assertEquals(2, $history->getHistory()[0]['id']);
+ }
+}
* Attempt to instantiate a LinkDB whereas the datastore is not writable
*
* @expectedException IOException
- * @expectedExceptionMessageRegExp /Error accessing\nnull/
+ * @expectedExceptionMessageRegExp /Error accessing "null"/
*/
public function testConstructDatastoreNotWriteable()
{
'sTuff' => 2,
'ut' => 1,
),
- self::$publicLinkDB->allTags()
+ self::$publicLinkDB->linksCountPerTag()
);
$this->assertEquals(
'tag4' => 1,
'ut' => 1,
),
- self::$privateLinkDB->allTags()
+ self::$privateLinkDB->linksCountPerTag()
+ );
+ $this->assertEquals(
+ array(
+ 'web' => 4,
+ 'cartoon' => 2,
+ 'gnu' => 1,
+ 'dev' => 1,
+ 'samba' => 1,
+ 'media' => 1,
+ 'html' => 1,
+ 'w3c' => 1,
+ 'css' => 1,
+ 'Mercurial' => 1,
+ '.hidden' => 1,
+ 'hashtag' => 1,
+ ),
+ self::$privateLinkDB->linksCountPerTag(['web'])
+ );
+ $this->assertEquals(
+ array(
+ 'web' => 1,
+ 'html' => 1,
+ 'w3c' => 1,
+ 'css' => 1,
+ 'Mercurial' => 1,
+ ),
+ self::$privateLinkDB->linksCountPerTag(['web'], 'private')
);
}
*/
protected static $testDatastore = 'sandbox/datastore.php';
+ /**
+ * @var string History file path
+ */
+ protected static $historyFilePath = 'sandbox/history.php';
+
/**
* @var LinkDB private LinkDB instance
*/
*/
protected $conf;
+ /**
+ * @var History instance.
+ */
+ protected $history;
+
/**
* @var string Save the current timezone.
*/
$this->linkDb = new LinkDB(self::$testDatastore, true, false);
$this->conf = new ConfigManager('tests/utils/config/configJson');
$this->conf->set('resource.page_cache', $this->pagecache);
+ $this->history = new History(self::$historyFilePath);
+ }
+
+ /**
+ * Delete history file.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$historyFilePath);
}
public static function tearDownAfterClass()
$this->assertEquals(
'File empty.htm (0 bytes) has an unknown file format.'
.' Nothing was imported.',
- NetscapeBookmarkUtils::import(NULL, $files, NULL, $this->conf)
+ NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history)
);
$this->assertEquals(0, count($this->linkDb));
}
$files = file2array('no_doctype.htm');
$this->assertEquals(
'File no_doctype.htm (350 bytes) has an unknown file format. Nothing was imported.',
- NetscapeBookmarkUtils::import(NULL, $files, NULL, $this->conf)
+ NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history)
);
$this->assertEquals(0, count($this->linkDb));
}
$this->assertEquals(
'File internet_explorer_encoding.htm (356 bytes) was successfully processed:'
.' 1 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(1, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_nested.htm (1337 bytes) was successfully processed:'
.' 8 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(8, count($this->linkDb));
$this->assertEquals(2, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(1, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(2, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(2, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 2 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 2 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(2, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 0 links imported, 0 links overwritten, 2 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File netscape_basic.htm (482 bytes) was successfully processed:'
.' 2 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(2, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->assertEquals(
'File same_date.htm (453 bytes) was successfully processed:'
.' 3 links imported, 0 links overwritten, 0 links skipped.',
- NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf)
+ NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf, $this->history)
);
$this->assertEquals(3, count($this->linkDb));
$this->assertEquals(0, count_private($this->linkDb));
$this->linkDb[2]['id']
);
}
+
+ public function testImportCreateUpdateHistory()
+ {
+ $post = [
+ 'privacy' => 'public',
+ 'overwrite' => 'true',
+ ];
+ $files = file2array('netscape_basic.htm');
+ $nbLinks = 2;
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history);
+ $history = $this->history->getHistory();
+ $this->assertEquals($nbLinks, count($history));
+ foreach ($history as $value) {
+ $this->assertEquals(History::CREATED, $value['event']);
+ $this->assertTrue(new DateTime('-5 seconds') < $value['datetime']);
+ $this->assertTrue(is_int($value['id']));
+ }
+
+ // re-import as private, enable overwriting
+ NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history);
+ $history = $this->history->getHistory();
+ $this->assertEquals($nbLinks * 2, count($history));
+ for ($i = 0 ; $i < $nbLinks ; $i++) {
+ $this->assertEquals(History::UPDATED, $history[$i]['event']);
+ $this->assertTrue(new DateTime('-5 seconds') < $history[$i]['datetime']);
+ $this->assertTrue(is_int($history[$i]['id']));
+ }
+ }
}
*/
class TimeZoneTest extends PHPUnit_Framework_TestCase
{
+ /**
+ * @var array of timezones
+ */
+ protected $installedTimezones;
+
+ public function setUp()
+ {
+ $this->installedTimezones = [
+ 'Antarctica/Syowa',
+ 'Europe/London',
+ 'Europe/Paris',
+ 'UTC'
+ ];
+ }
+
/**
* Generate a timezone selection form
*/
public function testGenerateTimeZoneForm()
{
- $generated = generateTimeZoneForm();
+ $expected = [
+ 'continents' => [
+ 'Antarctica',
+ 'Europe',
+ 'UTC',
+ 'selected' => '',
+ ],
+ 'cities' => [
+ ['continent' => 'Antarctica', 'city' => 'Syowa'],
+ ['continent' => 'Europe', 'city' => 'London'],
+ ['continent' => 'Europe', 'city' => 'Paris'],
+ ['continent' => 'UTC', 'city' => 'UTC'],
+ 'selected' => '',
+ ]
+ ];
- // HTML form
- $this->assertStringStartsWith('Continent:<select', $generated[0]);
- $this->assertContains('selected="selected"', $generated[0]);
- $this->assertStringEndsWith('</select><br />', $generated[0]);
+ list($continents, $cities) = generateTimeZoneData($this->installedTimezones);
- // Javascript handler
- $this->assertStringStartsWith('<script>', $generated[1]);
- $this->assertContains(
- '<option value=\"Bermuda\">Bermuda<\/option>',
- $generated[1]
- );
- $this->assertStringEndsWith('</script>', $generated[1]);
+ $this->assertEquals($expected['continents'], $continents);
+ $this->assertEquals($expected['cities'], $cities);
}
/**
*/
public function testGenerateTimeZoneFormPreselected()
{
- $generated = generateTimeZoneForm('Antarctica/Syowa');
-
- // HTML form
- $this->assertStringStartsWith('Continent:<select', $generated[0]);
- $this->assertContains(
- 'value="Antarctica" selected="selected"',
- $generated[0]
- );
- $this->assertContains(
- 'value="Syowa" selected="selected"',
- $generated[0]
- );
- $this->assertStringEndsWith('</select><br />', $generated[0]);
+ $expected = [
+ 'continents' => [
+ 'Antarctica',
+ 'Europe',
+ 'UTC',
+ 'selected' => 'Antarctica',
+ ],
+ 'cities' => [
+ ['continent' => 'Antarctica', 'city' => 'Syowa'],
+ ['continent' => 'Europe', 'city' => 'London'],
+ ['continent' => 'Europe', 'city' => 'Paris'],
+ ['continent' => 'UTC', 'city' => 'UTC'],
+ 'selected' => 'Syowa',
+ ]
+ ];
+ list($continents, $cities) = generateTimeZoneData($this->installedTimezones, 'Antarctica/Syowa');
- // Javascript handler
- $this->assertStringStartsWith('<script>', $generated[1]);
- $this->assertContains(
- '<option value=\"Bermuda\">Bermuda<\/option>',
- $generated[1]
- );
- $this->assertStringEndsWith('</script>', $generated[1]);
+ $this->assertEquals($expected['continents'], $continents);
+ $this->assertEquals($expected['cities'], $cities);
}
/**
rmdir('sandbox/'. $theme);
}
- /**
- * Test updateMethodDefaultThemeVintage with the default theme enabled.
- */
- public function testSetDefaultThemeToVintage()
- {
- $sandboxConf = 'sandbox/config';
- copy(self::$configFile . '.json.php', $sandboxConf . '.json.php');
- $this->conf = new ConfigManager($sandboxConf);
-
- $this->conf->set('resource.theme', 'default');
- $updater = new Updater([], [], $this->conf, true);
- $this->assertTrue($updater->updateMethodDefaultThemeVintage());
- $this->assertEquals('vintage', $this->conf->get('resource.theme'));
-
- // reload from file
- $this->conf = new ConfigManager($sandboxConf);
- $this->assertEquals('vintage', $this->conf->get('resource.theme'));
- }
-
- /**
- * Test updateMethodDefaultThemeVintage with custom theme enabled => nothing to do.
- */
- public function testSetDefaultThemeNothingToDo()
- {
- $sandboxConf = 'sandbox/config';
- copy(self::$configFile . '.json.php', $sandboxConf . '.json.php');
- $this->conf = new ConfigManager($sandboxConf);
-
- $theme = 'myawesometheme';
- $this->conf->set('resource.theme', $theme);
- $this->conf->write(true);
- $updater = new Updater([], [], $this->conf, true);
- $this->assertTrue($updater->updateMethodDefaultThemeVintage());
- $this->assertEquals($theme, $this->conf->get('resource.theme'));
-
- // reload from file
- $this->conf = new ConfigManager($sandboxConf);
- $this->assertEquals($theme, $this->conf->get('resource.theme'));
- }
-
/**
* Test updateMethodEscapeMarkdown with markdown plugin enabled
* => setting markdown_escape set to false.
*/
require_once 'application/Utils.php';
+require_once 'application/Languages.php';
require_once 'tests/utils/ReferenceSessionIdHashes.php';
// Initialize reference data before PHPUnit starts a session
$this->assertFalse(format_date([]));
$this->assertFalse(format_date(null));
}
+
+ /**
+ * Test is_integer_mixed with valid values
+ */
+ public function testIsIntegerMixedValid()
+ {
+ $this->assertTrue(is_integer_mixed(12));
+ $this->assertTrue(is_integer_mixed('12'));
+ $this->assertTrue(is_integer_mixed(-12));
+ $this->assertTrue(is_integer_mixed('-12'));
+ $this->assertTrue(is_integer_mixed(0));
+ $this->assertTrue(is_integer_mixed('0'));
+ $this->assertTrue(is_integer_mixed(0x0a));
+ }
+
+ /**
+ * Test is_integer_mixed with invalid values
+ */
+ public function testIsIntegerMixedInvalid()
+ {
+ $this->assertFalse(is_integer_mixed(true));
+ $this->assertFalse(is_integer_mixed(false));
+ $this->assertFalse(is_integer_mixed([]));
+ $this->assertFalse(is_integer_mixed(['test']));
+ $this->assertFalse(is_integer_mixed([12]));
+ $this->assertFalse(is_integer_mixed(new DateTime()));
+ $this->assertFalse(is_integer_mixed('0x0a'));
+ $this->assertFalse(is_integer_mixed('12k'));
+ $this->assertFalse(is_integer_mixed('k12'));
+ $this->assertFalse(is_integer_mixed(''));
+ }
+
+ /**
+ * Test return_bytes
+ */
+ public function testReturnBytes()
+ {
+ $this->assertEquals(2 * 1024, return_bytes('2k'));
+ $this->assertEquals(2 * 1024, return_bytes('2K'));
+ $this->assertEquals(2 * (pow(1024, 2)), return_bytes('2m'));
+ $this->assertEquals(2 * (pow(1024, 2)), return_bytes('2M'));
+ $this->assertEquals(2 * (pow(1024, 3)), return_bytes('2g'));
+ $this->assertEquals(2 * (pow(1024, 3)), return_bytes('2G'));
+ $this->assertEquals(374, return_bytes('374'));
+ $this->assertEquals(374, return_bytes(374));
+ $this->assertEquals(0, return_bytes('0'));
+ $this->assertEquals(0, return_bytes(0));
+ $this->assertEquals(-1, return_bytes('-1'));
+ $this->assertEquals(-1, return_bytes(-1));
+ $this->assertEquals('', return_bytes(''));
+ }
+
+ /**
+ * Test human_bytes
+ */
+ public function testHumanBytes()
+ {
+ $this->assertEquals('2kiB', human_bytes(2 * 1024));
+ $this->assertEquals('2kiB', human_bytes(strval(2 * 1024)));
+ $this->assertEquals('2MiB', human_bytes(2 * (pow(1024, 2))));
+ $this->assertEquals('2MiB', human_bytes(strval(2 * (pow(1024, 2)))));
+ $this->assertEquals('2GiB', human_bytes(2 * (pow(1024, 3))));
+ $this->assertEquals('2GiB', human_bytes(strval(2 * (pow(1024, 3)))));
+ $this->assertEquals('374B', human_bytes(374));
+ $this->assertEquals('374B', human_bytes('374'));
+ $this->assertEquals('232kiB', human_bytes(237481));
+ $this->assertEquals('Unlimited', human_bytes('0'));
+ $this->assertEquals('Unlimited', human_bytes(0));
+ $this->assertEquals('Setting not set', human_bytes(''));
+ }
+
+ /**
+ * Test get_max_upload_size with formatting
+ */
+ public function testGetMaxUploadSize()
+ {
+ $this->assertEquals('1MiB', get_max_upload_size(2097152, '1024k'));
+ $this->assertEquals('1MiB', get_max_upload_size('1m', '2m'));
+ $this->assertEquals('100B', get_max_upload_size(100, 100));
+ }
+
+ /**
+ * Test get_max_upload_size without formatting
+ */
+ public function testGetMaxUploadSizeRaw()
+ {
+ $this->assertEquals('1048576', get_max_upload_size(2097152, '1024k', false));
+ $this->assertEquals('1048576', get_max_upload_size('1m', '2m', false));
+ $this->assertEquals('100', get_max_upload_size(100, 100, false));
+ }
+
+ /**
+ * Test alphabetical_sort by value, not reversed, with php-intl.
+ */
+ public function testAlphabeticalSortByValue()
+ {
+ $arr = [
+ 'zZz',
+ 'éee',
+ 'éae',
+ 'eee',
+ 'A',
+ 'a',
+ 'zzz',
+ ];
+ $expected = [
+ 'a',
+ 'A',
+ 'éae',
+ 'eee',
+ 'éee',
+ 'zzz',
+ 'zZz',
+ ];
+
+ alphabetical_sort($arr);
+ $this->assertEquals($expected, $arr);
+ }
+
+ /**
+ * Test alphabetical_sort by value, reversed, with php-intl.
+ */
+ public function testAlphabeticalSortByValueReversed()
+ {
+ $arr = [
+ 'zZz',
+ 'éee',
+ 'éae',
+ 'eee',
+ 'A',
+ 'a',
+ 'zzz',
+ ];
+ $expected = [
+ 'zZz',
+ 'zzz',
+ 'éee',
+ 'eee',
+ 'éae',
+ 'A',
+ 'a',
+ ];
+
+ alphabetical_sort($arr, true);
+ $this->assertEquals($expected, $arr);
+ }
+
+ /**
+ * Test alphabetical_sort by keys, not reversed, with php-intl.
+ */
+ public function testAlphabeticalSortByKeys()
+ {
+ $arr = [
+ 'zZz' => true,
+ 'éee' => true,
+ 'éae' => true,
+ 'eee' => true,
+ 'A' => true,
+ 'a' => true,
+ 'zzz' => true,
+ ];
+ $expected = [
+ 'a' => true,
+ 'A' => true,
+ 'éae' => true,
+ 'eee' => true,
+ 'éee' => true,
+ 'zzz' => true,
+ 'zZz' => true,
+ ];
+
+ alphabetical_sort($arr, true, true);
+ $this->assertEquals($expected, $arr);
+ }
+
+ /**
+ * Test alphabetical_sort by keys, reversed, with php-intl.
+ */
+ public function testAlphabeticalSortByKeysReversed()
+ {
+ $arr = [
+ 'zZz' => true,
+ 'éee' => true,
+ 'éae' => true,
+ 'eee' => true,
+ 'A' => true,
+ 'a' => true,
+ 'zzz' => true,
+ ];
+ $expected = [
+ 'zZz' => true,
+ 'zzz' => true,
+ 'éee' => true,
+ 'eee' => true,
+ 'éae' => true,
+ 'A' => true,
+ 'a' => true,
+ ];
+
+ alphabetical_sort($arr, true, true);
+ $this->assertEquals($expected, $arr);
+ }
}
$this->assertEquals($expected, ApiUtils::formatLink($link, $indexUrl));
}
+
+ /**
+ * Test updateLink with valid data, and also unnecessary fields.
+ */
+ public function testUpdateLink()
+ {
+ $created = \DateTime::createFromFormat('Ymd_His', '20170107_160102');
+ $old = [
+ 'id' => 12,
+ 'url' => '?abc',
+ 'shorturl' => 'abc',
+ 'title' => 'Note',
+ 'description' => '',
+ 'tags' => '',
+ 'private' => '',
+ 'created' => $created,
+ ];
+
+ $new = [
+ 'id' => 13,
+ 'shorturl' => 'nope',
+ 'url' => 'http://somewhere.else',
+ 'title' => 'Le Cid',
+ 'description' => 'Percé jusques au fond du cœur [...]',
+ 'tags' => 'corneille rodrigue',
+ 'private' => true,
+ 'created' => 'creation',
+ 'updated' => 'updation',
+ ];
+
+ $result = ApiUtils::updateLink($old, $new);
+ $this->assertEquals(12, $result['id']);
+ $this->assertEquals('http://somewhere.else', $result['url']);
+ $this->assertEquals('abc', $result['shorturl']);
+ $this->assertEquals('Le Cid', $result['title']);
+ $this->assertEquals('Percé jusques au fond du cœur [...]', $result['description']);
+ $this->assertEquals('corneille rodrigue', $result['tags']);
+ $this->assertEquals(true, $result['private']);
+ $this->assertEquals($created, $result['created']);
+ $this->assertTrue(new \DateTime('5 seconds ago') < $result['updated']);
+ }
+
+ /**
+ * Test updateLink with minimal data.
+ */
+ public function testUpdateLinkMinimal()
+ {
+ $created = \DateTime::createFromFormat('Ymd_His', '20170107_160102');
+ $old = [
+ 'id' => 12,
+ 'url' => '?abc',
+ 'shorturl' => 'abc',
+ 'title' => 'Note',
+ 'description' => 'Interesting description!',
+ 'tags' => 'doggo',
+ 'private' => true,
+ 'created' => $created,
+ ];
+
+ $new = [
+ 'url' => '',
+ 'title' => '',
+ 'description' => '',
+ 'tags' => '',
+ 'private' => false,
+ ];
+
+ $result = ApiUtils::updateLink($old, $new);
+ $this->assertEquals(12, $result['id']);
+ $this->assertEquals('?abc', $result['url']);
+ $this->assertEquals('abc', $result['shorturl']);
+ $this->assertEquals('?abc', $result['title']);
+ $this->assertEquals('', $result['description']);
+ $this->assertEquals('', $result['tags']);
+ $this->assertEquals(false, $result['private']);
+ $this->assertEquals($created, $result['created']);
+ $this->assertTrue(new \DateTime('5 seconds ago') < $result['updated']);
+ }
}
--- /dev/null
+<?php
+
+
+namespace Shaarli\Api\Controllers;
+
+use Shaarli\Config\ConfigManager;
+use Slim\Container;
+use Slim\Http\Environment;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+class DeleteLinkTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testDatastore = 'sandbox/datastore.php';
+
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testHistory = 'sandbox/history.php';
+
+ /**
+ * @var ConfigManager instance
+ */
+ protected $conf;
+
+ /**
+ * @var \ReferenceLinkDB instance.
+ */
+ protected $refDB = null;
+
+ /**
+ * @var \LinkDB instance.
+ */
+ protected $linkDB;
+
+ /**
+ * @var \History instance.
+ */
+ protected $history;
+
+ /**
+ * @var Container instance.
+ */
+ protected $container;
+
+ /**
+ * @var Links controller instance.
+ */
+ protected $controller;
+
+ /**
+ * Before each test, instantiate a new Api with its config, plugins and links.
+ */
+ public function setUp()
+ {
+ $this->conf = new ConfigManager('tests/utils/config/configJson');
+ $this->refDB = new \ReferenceLinkDB();
+ $this->refDB->write(self::$testDatastore);
+ $this->linkDB = new \LinkDB(self::$testDatastore, true, false);
+ $refHistory = new \ReferenceHistory();
+ $refHistory->write(self::$testHistory);
+ $this->history = new \History(self::$testHistory);
+ $this->container = new Container();
+ $this->container['conf'] = $this->conf;
+ $this->container['db'] = $this->linkDB;
+ $this->container['history'] = $this->history;
+
+ $this->controller = new Links($this->container);
+ }
+
+ /**
+ * After each test, remove the test datastore.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$testDatastore);
+ @unlink(self::$testHistory);
+ }
+
+ /**
+ * Test DELETE link endpoint: the link should be removed.
+ */
+ public function testDeleteLinkValid()
+ {
+ $id = '41';
+ $this->assertTrue(isset($this->linkDB[$id]));
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'DELETE',
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->deleteLink($request, new Response(), ['id' => $id]);
+ $this->assertEquals(204, $response->getStatusCode());
+ $this->assertEmpty((string) $response->getBody());
+
+ $this->linkDB = new \LinkDB(self::$testDatastore, true, false);
+ $this->assertFalse(isset($this->linkDB[$id]));
+
+ $historyEntry = $this->history->getHistory()[0];
+ $this->assertEquals(\History::DELETED, $historyEntry['event']);
+ $this->assertTrue(
+ (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime']
+ );
+ $this->assertEquals($id, $historyEntry['id']);
+ }
+
+ /**
+ * Test DELETE link endpoint: reach not existing ID.
+ *
+ * @expectedException Shaarli\Api\Exceptions\ApiLinkNotFoundException
+ */
+ public function testDeleteLink404()
+ {
+ $id = -1;
+ $this->assertFalse(isset($this->linkDB[$id]));
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'DELETE',
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $this->controller->deleteLink($request, new Response(), ['id' => $id]);
+ }
+}
$this->container = new Container();
$this->container['conf'] = $this->conf;
$this->container['db'] = new \LinkDB(self::$testDatastore, true, false);
+ $this->container['history'] = null;
$this->controller = new Links($this->container);
}
$this->container = new Container();
$this->container['conf'] = $this->conf;
$this->container['db'] = new \LinkDB(self::$testDatastore, true, false);
+ $this->container['history'] = null;
$this->controller = new Links($this->container);
}
--- /dev/null
+<?php
+
+
+namespace Shaarli\Api\Controllers;
+
+
+use Shaarli\Config\ConfigManager;
+use Slim\Container;
+use Slim\Http\Environment;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+require_once 'tests/utils/ReferenceHistory.php';
+
+class HistoryTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testHistory = 'sandbox/history.php';
+
+ /**
+ * @var ConfigManager instance
+ */
+ protected $conf;
+
+ /**
+ * @var \ReferenceHistory instance.
+ */
+ protected $refHistory = null;
+
+ /**
+ * @var Container instance.
+ */
+ protected $container;
+
+ /**
+ * @var History controller instance.
+ */
+ protected $controller;
+
+ /**
+ * Before every test, instantiate a new Api with its config, plugins and links.
+ */
+ public function setUp()
+ {
+ $this->conf = new ConfigManager('tests/utils/config/configJson.json.php');
+ $this->refHistory = new \ReferenceHistory();
+ $this->refHistory->write(self::$testHistory);
+ $this->container = new Container();
+ $this->container['conf'] = $this->conf;
+ $this->container['db'] = true;
+ $this->container['history'] = new \History(self::$testHistory);
+
+ $this->controller = new History($this->container);
+ }
+
+ /**
+ * After every test, remove the test datastore.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$testHistory);
+ }
+
+ /**
+ * Test /history service without parameter.
+ */
+ public function testGetHistory()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->getHistory($request, new Response());
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+
+ $this->assertEquals($this->refHistory->count(), count($data));
+
+ $this->assertEquals(\History::DELETED, $data[0]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM),
+ $data[0]['datetime']
+ );
+ $this->assertEquals(124, $data[0]['id']);
+
+ $this->assertEquals(\History::SETTINGS, $data[1]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM),
+ $data[1]['datetime']
+ );
+ $this->assertNull($data[1]['id']);
+
+ $this->assertEquals(\History::UPDATED, $data[2]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170301_121214')->format(\DateTime::ATOM),
+ $data[2]['datetime']
+ );
+ $this->assertEquals(123, $data[2]['id']);
+
+ $this->assertEquals(\History::CREATED, $data[3]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170201_121214')->format(\DateTime::ATOM),
+ $data[3]['datetime']
+ );
+ $this->assertEquals(124, $data[3]['id']);
+
+ $this->assertEquals(\History::CREATED, $data[4]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM),
+ $data[4]['datetime']
+ );
+ $this->assertEquals(123, $data[4]['id']);
+ }
+
+ /**
+ * Test /history service with limit parameter.
+ */
+ public function testGetHistoryLimit()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ 'QUERY_STRING' => 'limit=1'
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->getHistory($request, new Response());
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+
+ $this->assertEquals(1, count($data));
+
+ $this->assertEquals(\History::DELETED, $data[0]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM),
+ $data[0]['datetime']
+ );
+ $this->assertEquals(124, $data[0]['id']);
+ }
+
+ /**
+ * Test /history service with offset parameter.
+ */
+ public function testGetHistoryOffset()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ 'QUERY_STRING' => 'offset=4'
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->getHistory($request, new Response());
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+
+ $this->assertEquals(1, count($data));
+
+ $this->assertEquals(\History::CREATED, $data[0]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM),
+ $data[0]['datetime']
+ );
+ $this->assertEquals(123, $data[0]['id']);
+ }
+
+ /**
+ * Test /history service with since parameter.
+ */
+ public function testGetHistorySince()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ 'QUERY_STRING' => 'since=2017-03-03T00:00:00%2B00:00'
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->getHistory($request, new Response());
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+
+ $this->assertEquals(1, count($data));
+
+ $this->assertEquals(\History::DELETED, $data[0]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM),
+ $data[0]['datetime']
+ );
+ $this->assertEquals(124, $data[0]['id']);
+ }
+
+ /**
+ * Test /history service with since parameter.
+ */
+ public function testGetHistorySinceOffsetLimit()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ 'QUERY_STRING' => 'since=2017-02-01T00:00:00%2B00:00&offset=1&limit=1'
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->getHistory($request, new Response());
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+
+ $this->assertEquals(1, count($data));
+
+ $this->assertEquals(\History::SETTINGS, $data[0]['event']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM),
+ $data[0]['datetime']
+ );
+ }
+}
$this->container = new Container();
$this->container['conf'] = $this->conf;
$this->container['db'] = new \LinkDB(self::$testDatastore, true, false);
+ $this->container['history'] = null;
$this->controller = new Info($this->container);
}
--- /dev/null
+<?php
+
+namespace Shaarli\Api\Controllers;
+
+
+use Shaarli\Config\ConfigManager;
+use Slim\Container;
+use Slim\Http\Environment;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+/**
+ * Class PostLinkTest
+ *
+ * Test POST Link REST API service.
+ *
+ * @package Shaarli\Api\Controllers
+ */
+class PostLinkTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testDatastore = 'sandbox/datastore.php';
+
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testHistory = 'sandbox/history.php';
+
+ /**
+ * @var ConfigManager instance
+ */
+ protected $conf;
+
+ /**
+ * @var \ReferenceLinkDB instance.
+ */
+ protected $refDB = null;
+
+ /**
+ * @var \History instance.
+ */
+ protected $history;
+
+ /**
+ * @var Container instance.
+ */
+ protected $container;
+
+ /**
+ * @var Links controller instance.
+ */
+ protected $controller;
+
+ /**
+ * Number of JSON field per link.
+ */
+ const NB_FIELDS_LINK = 9;
+
+ /**
+ * Before every test, instantiate a new Api with its config, plugins and links.
+ */
+ public function setUp()
+ {
+ $this->conf = new ConfigManager('tests/utils/config/configJson.json.php');
+ $this->refDB = new \ReferenceLinkDB();
+ $this->refDB->write(self::$testDatastore);
+
+ $refHistory = new \ReferenceHistory();
+ $refHistory->write(self::$testHistory);
+ $this->history = new \History(self::$testHistory);
+
+ $this->container = new Container();
+ $this->container['conf'] = $this->conf;
+ $this->container['db'] = new \LinkDB(self::$testDatastore, true, false);
+ $this->container['history'] = new \History(self::$testHistory);
+
+ $this->controller = new Links($this->container);
+
+ $mock = $this->getMock('\Slim\Router', ['relativePathFor']);
+ $mock->expects($this->any())
+ ->method('relativePathFor')
+ ->willReturn('api/v1/links/1');
+
+ // affect @property-read... seems to work
+ $this->controller->getCi()->router = $mock;
+
+ // Used by index_url().
+ $this->controller->getCi()['environment'] = [
+ 'SERVER_NAME' => 'domain.tld',
+ 'SERVER_PORT' => 80,
+ 'SCRIPT_NAME' => '/',
+ ];
+ }
+
+ /**
+ * After every test, remove the test datastore.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$testDatastore);
+ @unlink(self::$testHistory);
+ }
+
+ /**
+ * Test link creation without any field: creates a blank note.
+ */
+ public function testPostLinkMinimal()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'POST',
+ ]);
+
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->postLink($request, new Response());
+ $this->assertEquals(201, $response->getStatusCode());
+ $this->assertEquals('api/v1/links/1', $response->getHeader('Location')[0]);
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals(43, $data['id']);
+ $this->assertRegExp('/[\w-_]{6}/', $data['shorturl']);
+ $this->assertEquals('http://domain.tld/?' . $data['shorturl'], $data['url']);
+ $this->assertEquals('?' . $data['shorturl'], $data['title']);
+ $this->assertEquals('', $data['description']);
+ $this->assertEquals([], $data['tags']);
+ $this->assertEquals(false, $data['private']);
+ $this->assertTrue(new \DateTime('5 seconds ago') < \DateTime::createFromFormat(\DateTime::ATOM, $data['created']));
+ $this->assertEquals('', $data['updated']);
+
+ $historyEntry = $this->history->getHistory()[0];
+ $this->assertEquals(\History::CREATED, $historyEntry['event']);
+ $this->assertTrue(
+ (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime']
+ );
+ $this->assertEquals(43, $historyEntry['id']);
+ }
+
+ /**
+ * Test link creation with all available fields.
+ */
+ public function testPostLinkFull()
+ {
+ $link = [
+ 'url' => 'website.tld/test?foo=bar',
+ 'title' => 'new entry',
+ 'description' => 'shaare description',
+ 'tags' => ['one', 'two'],
+ 'private' => true,
+ ];
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'POST',
+ 'CONTENT_TYPE' => 'application/json'
+ ]);
+
+ $request = Request::createFromEnvironment($env);
+ $request = $request->withParsedBody($link);
+ $response = $this->controller->postLink($request, new Response());
+
+ $this->assertEquals(201, $response->getStatusCode());
+ $this->assertEquals('api/v1/links/1', $response->getHeader('Location')[0]);
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals(43, $data['id']);
+ $this->assertRegExp('/[\w-_]{6}/', $data['shorturl']);
+ $this->assertEquals('http://' . $link['url'], $data['url']);
+ $this->assertEquals($link['title'], $data['title']);
+ $this->assertEquals($link['description'], $data['description']);
+ $this->assertEquals($link['tags'], $data['tags']);
+ $this->assertEquals(true, $data['private']);
+ $this->assertTrue(new \DateTime('2 seconds ago') < \DateTime::createFromFormat(\DateTime::ATOM, $data['created']));
+ $this->assertEquals('', $data['updated']);
+ }
+
+ /**
+ * Test link creation with an existing link (duplicate URL). Should return a 409 HTTP error and the existing link.
+ */
+ public function testPostLinkDuplicate()
+ {
+ $link = [
+ 'url' => 'mediagoblin.org/',
+ 'title' => 'new entry',
+ 'description' => 'shaare description',
+ 'tags' => ['one', 'two'],
+ 'private' => true,
+ ];
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'POST',
+ 'CONTENT_TYPE' => 'application/json'
+ ]);
+
+ $request = Request::createFromEnvironment($env);
+ $request = $request->withParsedBody($link);
+ $response = $this->controller->postLink($request, new Response());
+
+ $this->assertEquals(409, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals(7, $data['id']);
+ $this->assertEquals('IuWvgA', $data['shorturl']);
+ $this->assertEquals('http://mediagoblin.org/', $data['url']);
+ $this->assertEquals('MediaGoblin', $data['title']);
+ $this->assertEquals('A free software media publishing platform #hashtagOther', $data['description']);
+ $this->assertEquals(['gnu', 'media', 'web', '.hidden', 'hashtag'], $data['tags']);
+ $this->assertEquals(false, $data['private']);
+ $this->assertEquals(
+ \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130614_184135'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['created'])
+ );
+ $this->assertEquals(
+ \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130615_184230'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['updated'])
+ );
+ }
+}
--- /dev/null
+<?php
+
+
+namespace Shaarli\Api\Controllers;
+
+
+use Shaarli\Config\ConfigManager;
+use Slim\Container;
+use Slim\Http\Environment;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+class PutLinkTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testDatastore = 'sandbox/datastore.php';
+
+ /**
+ * @var string datastore to test write operations
+ */
+ protected static $testHistory = 'sandbox/history.php';
+
+ /**
+ * @var ConfigManager instance
+ */
+ protected $conf;
+
+ /**
+ * @var \ReferenceLinkDB instance.
+ */
+ protected $refDB = null;
+
+ /**
+ * @var \History instance.
+ */
+ protected $history;
+
+ /**
+ * @var Container instance.
+ */
+ protected $container;
+
+ /**
+ * @var Links controller instance.
+ */
+ protected $controller;
+
+ /**
+ * Number of JSON field per link.
+ */
+ const NB_FIELDS_LINK = 9;
+
+ /**
+ * Before every test, instantiate a new Api with its config, plugins and links.
+ */
+ public function setUp()
+ {
+ $this->conf = new ConfigManager('tests/utils/config/configJson.json.php');
+ $this->refDB = new \ReferenceLinkDB();
+ $this->refDB->write(self::$testDatastore);
+
+ $refHistory = new \ReferenceHistory();
+ $refHistory->write(self::$testHistory);
+ $this->history = new \History(self::$testHistory);
+
+ $this->container = new Container();
+ $this->container['conf'] = $this->conf;
+ $this->container['db'] = new \LinkDB(self::$testDatastore, true, false);
+ $this->container['history'] = new \History(self::$testHistory);
+
+ $this->controller = new Links($this->container);
+
+ // Used by index_url().
+ $this->controller->getCi()['environment'] = [
+ 'SERVER_NAME' => 'domain.tld',
+ 'SERVER_PORT' => 80,
+ 'SCRIPT_NAME' => '/',
+ ];
+ }
+
+ /**
+ * After every test, remove the test datastore.
+ */
+ public function tearDown()
+ {
+ @unlink(self::$testDatastore);
+ @unlink(self::$testHistory);
+ }
+
+ /**
+ * Test link update without value: reset the link to default values
+ */
+ public function testPutLinkMinimal()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'PUT',
+ ]);
+ $id = '41';
+ $request = Request::createFromEnvironment($env);
+
+ $response = $this->controller->putLink($request, new Response(), ['id' => $id]);
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals($id, $data['id']);
+ $this->assertEquals('WDWyig', $data['shorturl']);
+ $this->assertEquals('http://domain.tld/?WDWyig', $data['url']);
+ $this->assertEquals('?WDWyig', $data['title']);
+ $this->assertEquals('', $data['description']);
+ $this->assertEquals([], $data['tags']);
+ $this->assertEquals(false, $data['private']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20150310_114651'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['created'])
+ );
+ $this->assertTrue(new \DateTime('5 seconds ago') < \DateTime::createFromFormat(\DateTime::ATOM, $data['updated']));
+
+ $historyEntry = $this->history->getHistory()[0];
+ $this->assertEquals(\History::UPDATED, $historyEntry['event']);
+ $this->assertTrue(
+ (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime']
+ );
+ $this->assertEquals($id, $historyEntry['id']);
+ }
+
+ /**
+ * Test link update with new values
+ */
+ public function testPutLinkWithValues()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'PUT',
+ 'CONTENT_TYPE' => 'application/json'
+ ]);
+ $id = 41;
+ $update = [
+ 'url' => 'http://somewhere.else',
+ 'title' => 'Le Cid',
+ 'description' => 'Percé jusques au fond du cœur [...]',
+ 'tags' => ['corneille', 'rodrigue'],
+ 'private' => true,
+ ];
+ $request = Request::createFromEnvironment($env);
+ $request = $request->withParsedBody($update);
+
+ $response = $this->controller->putLink($request, new Response(), ['id' => $id]);
+ $this->assertEquals(200, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals($id, $data['id']);
+ $this->assertEquals('WDWyig', $data['shorturl']);
+ $this->assertEquals('http://somewhere.else', $data['url']);
+ $this->assertEquals('Le Cid', $data['title']);
+ $this->assertEquals('Percé jusques au fond du cœur [...]', $data['description']);
+ $this->assertEquals(['corneille', 'rodrigue'], $data['tags']);
+ $this->assertEquals(true, $data['private']);
+ $this->assertEquals(
+ \DateTime::createFromFormat('Ymd_His', '20150310_114651'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['created'])
+ );
+ $this->assertTrue(new \DateTime('5 seconds ago') < \DateTime::createFromFormat(\DateTime::ATOM, $data['updated']));
+ }
+
+ /**
+ * Test link update with an existing URL: 409 Conflict with the existing link as body
+ */
+ public function testPutLinkDuplicate()
+ {
+ $link = [
+ 'url' => 'mediagoblin.org/',
+ 'title' => 'new entry',
+ 'description' => 'shaare description',
+ 'tags' => ['one', 'two'],
+ 'private' => true,
+ ];
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'PUT',
+ 'CONTENT_TYPE' => 'application/json'
+ ]);
+
+ $request = Request::createFromEnvironment($env);
+ $request = $request->withParsedBody($link);
+ $response = $this->controller->putLink($request, new Response(), ['id' => 41]);
+
+ $this->assertEquals(409, $response->getStatusCode());
+ $data = json_decode((string) $response->getBody(), true);
+ $this->assertEquals(self::NB_FIELDS_LINK, count($data));
+ $this->assertEquals(7, $data['id']);
+ $this->assertEquals('IuWvgA', $data['shorturl']);
+ $this->assertEquals('http://mediagoblin.org/', $data['url']);
+ $this->assertEquals('MediaGoblin', $data['title']);
+ $this->assertEquals('A free software media publishing platform #hashtagOther', $data['description']);
+ $this->assertEquals(['gnu', 'media', 'web', '.hidden', 'hashtag'], $data['tags']);
+ $this->assertEquals(false, $data['private']);
+ $this->assertEquals(
+ \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130614_184135'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['created'])
+ );
+ $this->assertEquals(
+ \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130615_184230'),
+ \DateTime::createFromFormat(\DateTime::ATOM, $data['updated'])
+ );
+ }
+
+ /**
+ * Test link update on non existent link => ApiLinkNotFoundException.
+ *
+ * @expectedException Shaarli\Api\Exceptions\ApiLinkNotFoundException
+ * @expectedExceptionMessage Link not found
+ */
+ public function testGetLink404()
+ {
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'PUT',
+ ]);
+ $request = Request::createFromEnvironment($env);
+
+ $this->controller->putLink($request, new Response(), ['id' => -1]);
+ }
+}
public function testDateFormat()
{
$date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
- $this->assertRegExp('/1. Januar 2017 (um )?10:11:12 GMT\+0?3(:00)?/', format_date($date, true));
+ $this->assertRegExp('/1\. Januar 2017 (um )?10:11:12 GMT\+0?3(:00)?/', format_date($date, true, true));
+ }
+
+ /**
+ * Test date_format() without time.
+ */
+ public function testDateFormatNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
+ $this->assertRegExp('/1\. Januar 2017/', format_date($date, false,true));
}
/**
public function testDateFormatDefault()
{
$date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
- $this->assertEquals('So 01 Jan 2017 10:11:12 EAT', format_date($date, false));
+ $this->assertEquals('So 01 Jan 2017 10:11:12 EAT', format_date($date, true, false));
+ }
+
+ /**
+ * Test date_format() using builtin PHP function strftime without time.
+ */
+ public function testDateFormatDefaultNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170201_101112');
+ $this->assertEquals('01.02.2017', format_date($date, false, false));
}
/**
public function testDateFormat()
{
$date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
- $this->assertRegExp('/January 1, 2017 (at )?10:11:12 AM GMT\+0?3(:00)?/', format_date($date, true));
+ $this->assertRegExp('/January 1, 2017 (at )?10:11:12 AM GMT\+0?3(:00)?/', format_date($date, true, true));
+ }
+
+ /**
+ * Test date_format() without time.
+ */
+ public function testDateFormatNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
+ $this->assertRegExp('/January 1, 2017/', format_date($date, false, true));
}
/**
public function testDateFormatDefault()
{
$date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
- $this->assertEquals('Sun 01 Jan 2017 10:11:12 AM EAT', format_date($date, false));
+ $this->assertEquals('Sun 01 Jan 2017 10:11:12 AM EAT', format_date($date, true, false));
+ }
+
+ /**
+ * Test date_format() using builtin PHP function strftime without time.
+ */
+ public function testDateFormatDefaultNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170201_101112');
+ $this->assertEquals('02/01/2017', format_date($date, false, false));
}
/**
$this->assertRegExp('/1 janvier 2017 (à )?10:11:12 UTC\+0?3(:00)?/', format_date($date));
}
+ /**
+ * Test date_format() without time.
+ */
+ public function testDateFormatNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
+ $this->assertRegExp('/1 janvier 2017/', format_date($date, false, true));
+ }
+
/**
* Test date_format() using builtin PHP function strftime.
*/
public function testDateFormatDefault()
{
$date = DateTime::createFromFormat('Ymd_His', '20170101_101112');
- $this->assertEquals('dim. 01 janv. 2017 10:11:12 EAT', format_date($date, false));
+ $this->assertEquals('dim. 01 janv. 2017 10:11:12 EAT', format_date($date, true, false));
+ }
+
+ /**
+ * Test date_format() using builtin PHP function strftime without time.
+ */
+ public function testDateFormatDefaultNoTime()
+ {
+ $date = DateTime::createFromFormat('Ymd_His', '20170201_101112');
+ $this->assertEquals('01/02/2017', format_date($date, false, false));
}
/**
+++ /dev/null
-<?php
-use Shaarli\Config\ConfigManager;
-
-/**
- * PluginReadityourselfTest.php.php
- */
-
-require_once 'plugins/readityourself/readityourself.php';
-
-/**
- * Class PluginWallabagTest
- * Unit test for the Wallabag plugin
- */
-class PluginReadityourselfTest extends PHPUnit_Framework_TestCase
-{
- /**
- * Reset plugin path
- */
- public function setUp()
- {
- PluginManager::$PLUGINS_PATH = 'plugins';
- }
-
- /**
- * Test Readityourself init without errors.
- */
- public function testReadityourselfInitNoError()
- {
- $conf = new ConfigManager('');
- $conf->set('plugins.READITYOUSELF_URL', 'value');
- $errors = readityourself_init($conf);
- $this->assertEmpty($errors);
- }
-
- /**
- * Test Readityourself init with errors.
- */
- public function testReadityourselfInitError()
- {
- $conf = new ConfigManager('');
- $errors = readityourself_init($conf);
- $this->assertNotEmpty($errors);
- }
-
- /**
- * Test render_linklist hook.
- */
- public function testReadityourselfLinklist()
- {
- $conf = new ConfigManager('');
- $conf->set('plugins.READITYOUSELF_URL', 'value');
- $str = 'http://randomstr.com/test';
- $data = array(
- 'title' => $str,
- 'links' => array(
- array(
- 'url' => $str,
- )
- )
- );
-
- $data = hook_readityourself_render_linklist($data, $conf);
- $link = $data['links'][0];
- // data shouldn't be altered
- $this->assertEquals($str, $data['title']);
- $this->assertEquals($str, $link['url']);
-
- // plugin data
- $this->assertEquals(1, count($link['link_plugin']));
- $this->assertNotFalse(strpos($link['link_plugin'][0], $str));
- }
-
- /**
- * Test without config: nothing should happened.
- */
- public function testReadityourselfLinklistWithoutConfig()
- {
- $conf = new ConfigManager('');
- $conf->set('plugins.READITYOUSELF_URL', null);
- $str = 'http://randomstr.com/test';
- $data = array(
- 'title' => $str,
- 'links' => array(
- array(
- 'url' => $str,
- )
- )
- );
-
- $data = hook_readityourself_render_linklist($data, $conf);
- $link = $data['links'][0];
- // data shouldn't be altered
- $this->assertEquals($str, $data['title']);
- $this->assertEquals($str, $link['url']);
-
- // plugin data
- $this->assertArrayNotHasKey('link_plugin', $link);
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Populates a reference history
+ */
+class ReferenceHistory
+{
+ private $count;
+
+ private $history = [];
+
+ /**
+ * Populates the test DB with reference data
+ */
+ public function __construct()
+ {
+ $this->addEntry(
+ History::DELETED,
+ DateTime::createFromFormat('Ymd_His', '20170303_121216'),
+ 124
+ );
+
+ $this->addEntry(
+ History::SETTINGS,
+ DateTime::createFromFormat('Ymd_His', '20170302_121215')
+ );
+
+ $this->addEntry(
+ History::UPDATED,
+ DateTime::createFromFormat('Ymd_His', '20170301_121214'),
+ 123
+ );
+
+ $this->addEntry(
+ History::CREATED,
+ DateTime::createFromFormat('Ymd_His', '20170201_121214'),
+ 124
+ );
+
+ $this->addEntry(
+ History::CREATED,
+ DateTime::createFromFormat('Ymd_His', '20170101_121212'),
+ 123
+ );
+ }
+
+ /**
+ * Adds a new history entry
+ *
+ * @param string $event Event identifier
+ * @param DateTime $datetime creation date
+ * @param int $id optional: related link ID
+ */
+ protected function addEntry($event, $datetime, $id = null)
+ {
+ $link = [
+ 'event' => $event,
+ 'datetime' => $datetime,
+ 'id' => $id,
+ ];
+ $this->history[] = $link;
+ $this->count++;
+ }
+
+ /**
+ * Writes data to the datastore
+ *
+ * @param string $filename write history content to.
+ */
+ public function write($filename)
+ {
+ FileUtils::writeFlatDB($filename, $this->history);
+ }
+
+ /**
+ * Returns the number of links in the reference data
+ */
+ public function count()
+ {
+ return $this->count;
+ }
+}
0,
DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20130614_184135'),
'gnu media web .hidden hashtag',
- null,
+ DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20130615_184230'),
'IuWvgA'
);
<h2 class="window-title">{"Manage tags"|t}</h2>
<form method="POST" action="#" name="changetag" id="changetag">
<div>
- <input type="text" name="fromtag" placeholder="{'Tag'|t}"
+ <input type="text" name="fromtag" placeholder="{'Tag'|t}" value="{$fromtag}"
list="tagsList" autocomplete="off" class="awesomplete autofocus" data-minChars="1">
<datalist id="tagsList">
{loop="$tags"}<option>{$key}</option>{/loop}
<input type="submit" value="{'Delete'|t}" name="deletetag" class="button button-red confirm-delete">
</div>
</form>
+
+ <p>You can also edit tags in the <a href="?do=taglist&sort=usage">tag list</a>.</p>
</div>
</div>
{include="page.footer"}
<div class="pure-u-lg-{$ratioLabel} pure-u-1">
<div class="form-label">
<label for="titleLink">
- <span class="label-name">{'Title link'|t}</span><br>
+ <span class="label-name">{'Home link'|t}</span><br>
<span class="label-desc">{'Default value'|t}: ?</span>
</label>
</div>
<div class="pure-u-lg-{$ratioLabel} pure-u-1 ">
<div class="form-label">
<label>
- <span class="label-name">{'Timezone'|t}</span>
+ <span class="label-name">{'Timezone'|t}</span><br>
+ <span class="label-desc">{'Continent'|t} · {'City'|t}</span>
</label>
</div>
</div>
<div class="pure-u-lg-{$ratioInput} pure-u-1 ">
<div class="form-input">
- {ignore}FIXME! too hackish, needs to be fixed upstream{/ignore}
- <div class="timezone" id="timezone-remove">{$timezone_form}</div>
- <div class="timezone" id="timezone-add"></div>
+ <div class="timezone">
+ <select id="continent" name="continent">
+ {loop="$continents"}
+ {if="$key !== 'selected'"}
+ <option value="{$value}" {if="$continents.selected === $value"}selected{/if}>
+ {$value}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ <select id="city" name="city">
+ {loop="$cities"}
+ {if="$key !== 'selected'"}
+ <option value="{$value.city}"
+ {if="$cities.selected === $value.city"}selected{/if}
+ data-continent="{$value.continent}">
+ {$value.city}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ </div>
</div>
</div>
</div>
}
}
-#search, #search-linklist {
+#search, #search-linklist, #search-tagcloud {
text-align: center;
width: 100%;
}
}
#search button,
+#search-tagcloud button,
#search-linklist button {
background: transparent;
border: none;
#search-linklist button:hover {
color: #fff;
}
+#search-tagcloud button:hover {
+ color: #d0d0d0;
+}
#search-linklist {
padding: 5px 0;
}
}
+.subheader-form a.button {
+ color: #f5f5f5;
+ font-weight: bold;
+ text-decoration: none;
+ border: 2px solid #f5f5f5;
+ border-radius: 5px;
+ padding: 3px 10px;
+}
+
+.linklist-item-editbuttons .delete-checkbox {
+ display: none;
+}
+
#header-login-form input[type="text"], #header-login-form input[type="password"] {
width: 200px;
}
.page-form a {
color: #1b926c;
font-weight: bold;
+ text-decoration: none;
}
.page-form p {
- padding: 0 10px;
+ padding: 5px 10px;
margin: 0;
}
}
#cloudtag, #cloudtag a {
- color: #000;
+ color: #252525;
text-decoration: none;
}
color: #7f7f7f;
}
+/**
+ * TAG LIST
+ */
+#taglist {
+ padding: 0 10px;
+}
+
+#taglist a {
+ color: #252525;
+ text-decoration: none;
+}
+
+#taglist .count {
+ display: inline-block;
+ width: 35px;
+ text-align: right;
+ color: #7f7f7f;
+}
+
+#taglist .rename-tag-form {
+ display: none;
+}
+
+#taglist .delete-tag {
+ color: #ac2925;
+ display: none;
+}
+
+#taglist .rename-tag {
+ color: #0b5ea6;
+}
+
+#taglist .validate-rename-tag {
+ color: #1b926c;
+}
+
/**
* Picture wall CSS
*/
.pure-button {
-moz-user-select: auto;
}
+
+.tag-sort {
+ margin-top: 30px;
+ text-align: center;
+}
+
+.tag-sort a {
+ display: inline-block;
+ margin: 0 15px;
+ color: white;
+ text-decoration: none;
+ font-weight: bold;
+}
</div>
</div>
<div>
- <h3 class="window-subtitle">{function="strftime('%A %d, %B %Y', $day)"}</h3>
+ <h3 class="window-subtitle">{function="format_date($dayDate, false)"}</h3>
<div id="plugin_zone_about_daily" class="plugin_zone">
{loop="$daily_about_plugin"}
<div class="center" id="import-field">
<input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
<input type="file" name="filetoupload">
+ <p><br>Maximum size allowed: <strong>{$maxfilesizeHuman}</strong></p>
</div>
<div class="pure-g">
<link type="text/css" rel="stylesheet" href="css/font-awesome.min.css" />
<link type="text/css" rel="stylesheet" href="inc/awesomplete.css#" />
<link type="text/css" rel="stylesheet" href="css/shaarli.css" />
-{if="is_file('inc/user.css')"}
+{if="is_file('data/user.css')"}
<link type="text/css" rel="stylesheet" href="data/user.css#" />
{/if}
{loop="$plugins_includes.css_files"}
</div>
<div class="pure-u-lg-{$ratioInput} pure-u-1">
<div class="form-input">
- <input type="text" name="setpassword" id="password">
+ <input type="password" name="setpassword" id="password">
</div>
</div>
</div>
<div class="pure-g">
- <div class="pure-u-lg-{$ratioLabel} pure-u-1 ">
+ <div class="pure-u-lg-{$ratioLabel} pure-u-1">
<div class="form-label">
- <label>
- <span class="label-name">{'Timezone'|t}</span>
+ <label for="title">
+ <span class="label-name">{'Shaarli title'|t}</span>
</label>
</div>
</div>
- <div class="pure-u-lg-{$ratioInput} pure-u-1 ">
+ <div class="pure-u-lg-{$ratioInput} pure-u-1">
<div class="form-input">
- {ignore}FIXME! too hackish, needs to be fixed upstream{/ignore}
- <div class="timezone" id="timezone-remove">{$timezone_html}</div>
- <div class="timezone" id="timezone-add"></div>
+ <input type="text" name="title" id="title" placeholder="{'My links'|t}">
</div>
</div>
</div>
<div class="pure-g">
<div class="pure-u-lg-{$ratioLabel} pure-u-1">
<div class="form-label">
- <label for="title">
- <span class="label-name">{'Shaarli title'|t}</span>
+ <label>
+ <span class="label-name">{'Timezone'|t}</span><br>
+ <span class="label-desc">{'Continent'|t} · {'City'|t}</span>
</label>
</div>
</div>
<div class="pure-u-lg-{$ratioInput} pure-u-1">
<div class="form-input">
- <input type="text" name="title" id="title" placeholder="{'My links'|t}">
+ <div class="timezone">
+ <select id="continent" name="continent">
+ {loop="$continents"}
+ {if="$key !== 'selected'"}
+ <option value="{$value}" {if="$continents.selected === $value"}selected{/if}>
+ {$value}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ <select id="city" name="city">
+ {loop="$cities"}
+ {if="$key !== 'selected'"}
+ <option value="{$value.city}"
+ {if="$cities.selected === $value.city"}selected{/if}
+ data-continent="{$value.continent}">
+ {$value.city}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ </div>
</div>
</div>
</div>
}
}
- document.getElementById('menu-toggle').addEventListener('click', function (e) {
- toggleMenu();
- });
+ var menuToggle = document.getElementById('menu-toggle');
+ if (menuToggle != null) {
+ menuToggle.addEventListener('click', function (e) {
+ toggleMenu();
+ });
+ }
window.addEventListener(WINDOW_CHANGE_EVENT, closeMenu);
})(this, this.document);
/**
* Autofocus text fields
*/
- // ES6 syntax
- let autofocusElements = document.querySelectorAll('.autofocus');
- for (let autofocusElement of autofocusElements) {
- if (autofocusElement.value == '') {
+ var autofocusElements = document.querySelectorAll('.autofocus');
+ var breakLoop = false;
+ [].forEach.call(autofocusElements, function(autofocusElement) {
+ if (autofocusElement.value == '' && ! breakLoop) {
autofocusElement.focus();
- break;
+ breakLoop = true;
}
- }
+ });
/**
* Handle sub menus/forms
});
}
- /**
- * TimeZome select
- * FIXME! way too hackish
- */
- var toRemove = document.getElementById('timezone-remove');
- if (toRemove != null) {
- var firstSelect = toRemove.getElementsByTagName('select')[0];
- var secondSelect = toRemove.getElementsByTagName('select')[1];
- toRemove.parentNode.removeChild(toRemove);
- var toAdd = document.getElementById('timezone-add');
- var newTimezone = '<span class="timezone-continent">Continent ' + firstSelect.outerHTML + '</span>';
- newTimezone += ' <span class="timezone-country">Country ' + secondSelect.outerHTML + '</span>';
- toAdd.innerHTML = newTimezone;
- }
-
/**
* Awesomplete trigger.
*/
}
});
});
+
+ var continent = document.getElementById('continent');
+ var city = document.getElementById('city');
+ if (continent != null && city != null) {
+ continent.addEventListener('change', function (event) {
+ hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
+ });
+ hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
+ }
+
+ /**
+ * Bulk actions
+ */
+ var linkCheckboxes = document.querySelectorAll('.delete-checkbox');
+ var bar = document.getElementById('actions');
+ [].forEach.call(linkCheckboxes, function(checkbox) {
+ checkbox.style.display = 'block';
+ checkbox.addEventListener('click', function(event) {
+ var count = 0;
+ var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
+ [].forEach.call(linkCheckedCheckboxes, function(checkbox) {
+ count++;
+ });
+ if (count == 0 && bar.classList.contains('open')) {
+ bar.classList.toggle('open');
+ } else if (count > 0 && ! bar.classList.contains('open')) {
+ bar.classList.toggle('open');
+ }
+ });
+ });
+
+ var deleteButton = document.getElementById('actions-delete');
+ var token = document.querySelector('input[type="hidden"][name="token"]');
+ if (deleteButton != null && token != null) {
+ deleteButton.addEventListener('click', function(event) {
+ event.preventDefault();
+
+ var links = [];
+ var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
+ [].forEach.call(linkCheckedCheckboxes, function(checkbox) {
+ links.push({
+ 'id': checkbox.value,
+ 'title': document.querySelector('.linklist-item[data-id="'+ checkbox.value +'"] .linklist-link').innerHTML
+ });
+ });
+
+ var message = 'Are you sure you want to delete '+ links.length +' links?\n';
+ message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
+ var ids = '';
+ links.forEach(function(item) {
+ message += ' - '+ item['title'] +'\n';
+ ids += item['id'] +'+';
+ });
+
+ if (window.confirm(message)) {
+ window.location = '?delete_link&lf_linkdate='+ ids +'&token='+ token.value;
+ }
+ });
+ }
+
+ /**
+ * Tag list operations
+ *
+ * TODO: support error code in the backend for AJAX requests
+ */
+ var existingTags = document.querySelector('input[name="taglist"]').value.split(' ');
+ var awesomepletes = [];
+
+ // Display/Hide rename form
+ var renameTagButtons = document.querySelectorAll('.rename-tag');
+ [].forEach.call(renameTagButtons, function(rename) {
+ rename.addEventListener('click', function(event) {
+ event.preventDefault();
+ var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
+ var form = block.querySelector('.rename-tag-form');
+ if (form.style.display == 'none' || form.style.display == '') {
+ form.style.display = 'block';
+ } else {
+ form.style.display = 'none';
+ }
+ block.querySelector('input').focus();
+ });
+ });
+
+ // Rename a tag with an AJAX request
+ var renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
+ [].forEach.call(renameTagSubmits, function(rename) {
+ rename.addEventListener('click', function(event) {
+ event.preventDefault();
+ var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
+ var input = block.querySelector('.rename-tag-input');
+ var totag = input.value.replace('/"/g', '\\"');
+ if (totag.trim() == '') {
+ return;
+ }
+ var fromtag = block.getAttribute('data-tag');
+ var token = document.getElementById('token').value;
+
+ xhr = new XMLHttpRequest();
+ xhr.open('POST', '?do=changetag');
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+ xhr.onload = function() {
+ if (xhr.status !== 200) {
+ alert('An error occurred. Return code: '+ xhr.status);
+ location.reload();
+ } else {
+ block.setAttribute('data-tag', totag);
+ input.setAttribute('name', totag);
+ input.setAttribute('value', totag);
+ findParent(input, 'div', {'class': 'rename-tag-form'}).style.display = 'none';
+ block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
+ block.querySelector('a.tag-link').setAttribute('href', '?searchtags='+ encodeURIComponent(totag));
+ block.querySelector('a.rename-tag').setAttribute('href', '?do=changetag&fromtag='+ encodeURIComponent(totag));
+
+ // Refresh awesomplete values
+ for (var key in existingTags) {
+ if (existingTags[key] == fromtag) {
+ existingTags[key] = totag;
+ }
+ }
+ awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
+ }
+ };
+ xhr.send('renametag=1&fromtag='+ encodeURIComponent(fromtag) +'&totag='+ encodeURIComponent(totag) +'&token='+ token);
+ refreshToken();
+ });
+ });
+
+ // Validate input with enter key
+ var renameTagInputs = document.querySelectorAll('.rename-tag-input');
+ [].forEach.call(renameTagInputs, function(rename) {
+
+ rename.addEventListener('keypress', function(event) {
+ if (event.keyCode === 13) { // enter
+ findParent(event.target, 'div', {'class': 'tag-list-item'}).querySelector('.validate-rename-tag').click();
+ }
+ });
+ });
+
+ // Delete a tag with an AJAX query (alert popup confirmation)
+ var deleteTagButtons = document.querySelectorAll('.delete-tag');
+ [].forEach.call(deleteTagButtons, function(rename) {
+ rename.style.display = 'inline';
+ rename.addEventListener('click', function(event) {
+ event.preventDefault();
+ var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
+ var tag = block.getAttribute('data-tag');
+ var token = document.getElementById('token').value;
+
+ if (confirm('Are you sure you want to delete the tag "'+ tag +'"?')) {
+ xhr = new XMLHttpRequest();
+ xhr.open('POST', '?do=changetag');
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+ xhr.onload = function() {
+ block.remove();
+ };
+ xhr.send(encodeURI('deletetag=1&fromtag='+ tag +'&token='+ token));
+ refreshToken();
+ }
+ });
+ });
+
+ updateAwesompleteList('.rename-tag-input', document.querySelector('input[name="taglist"]').value.split(' '), awesomepletes);
};
+/**
+ * Find a parent element according to its tag and its attributes
+ *
+ * @param element Element where to start the search
+ * @param tagName Expected parent tag name
+ * @param attributes Associative array of expected attributes (name=>value).
+ *
+ * @returns Found element or null.
+ */
+function findParent(element, tagName, attributes)
+{
+ while (element) {
+ if (element.tagName.toLowerCase() == tagName) {
+ var match = true;
+ for (var key in attributes) {
+ if (! element.hasAttribute(key)
+ || (attributes[key] != '' && element.getAttribute(key).indexOf(attributes[key]) == -1)
+ ) {
+ match = false;
+ break;
+ }
+ }
+
+ if (match) {
+ return element;
+ }
+ }
+ element = element.parentElement;
+ }
+ return null;
+}
+
+/**
+ * Ajax request to refresh the CSRF token.
+ */
+function refreshToken()
+{
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', '?do=token');
+ xhr.onload = function() {
+ var token = document.getElementById('token');
+ token.setAttribute('value', xhr.responseText);
+ };
+ xhr.send();
+}
+
+/**
+ * Update awesomplete list of tag for all elements matching the given selector
+ *
+ * @param selector CSS selector
+ * @param tags Array of tags
+ * @param instances List of existing awesomplete instances
+ */
+function updateAwesompleteList(selector, tags, instances)
+{
+ // First load: create Awesomplete instances
+ if (instances.length == 0) {
+ var elements = document.querySelectorAll(selector);
+ [].forEach.call(elements, function (element) {
+ instances.push(new Awesomplete(
+ element,
+ {'list': tags}
+ ));
+ });
+ } else {
+ // Update awesomplete tag list
+ for (var key in instances) {
+ instances[key].list = tags;
+ }
+ }
+ return instances;
+}
+
+/**
+ * html_entities in JS
+ *
+ * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
+ */
+function htmlEntities(str)
+{
+ return str.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
+ return '&#'+i.charCodeAt(0)+';';
+ });
+}
+
function activateFirefoxSocial(node) {
var loc = location.href;
var baseURL = loc.substring(0, loc.lastIndexOf("/"));
var activate = new CustomEvent("ActivateSocialFeature");
node.dispatchEvent(activate);
}
+
+/**
+ * Add the class 'hidden' to city options not attached to the current selected continent.
+ *
+ * @param cities List of <option> elements
+ * @param currentContinent Current selected continent
+ * @param reset Set to true to reset the selected value
+ */
+function hideTimezoneCities(cities, currentContinent) {
+ var first = true;
+ if (reset == null) {
+ reset = false;
+ }
+ [].forEach.call(cities, function (option) {
+ if (option.getAttribute('data-continent') != currentContinent) {
+ option.className = 'hidden';
+ } else {
+ option.className = '';
+ if (reset === true && first === true) {
+ option.setAttribute('selected', 'selected');
+ first = false;
+ }
+ }
+ });
+}
{/if}
</div>
+<input type="hidden" name="token" value="{$token}">
+
<div id="search-linklist">
<div class="pure-g">
<div class="pure-u-lg-20-24 pure-u-22-24">
{loop="links"}
<div class="anchor" id="{$value.shorturl}"></div>
- <div class="linklist-item{if="$value.class"} {$value.class}{/if}">
+ <div class="linklist-item linklist-item{if="$value.class"} {$value.class}{/if}" data-id="{$value.id}">
<div class="linklist-item-title">
{if="isLoggedIn()"}
{if="$value.private"}
<span class="label label-private">{'Private'|t}</span>
{/if}
+ <input type="checkbox" class="delete-checkbox" value="{$value.id}">
<!-- FIXME! JS translation -->
<a href="?edit_link={$value.id}" title="{'Edit'|t}"><i class="fa fa-pencil-square-o edit-link"></i></a>
<a href="#" title="{'Fold'|t}" class="fold-button"><i class="fa fa-chevron-up"></i></a>
</div>
<div class="pure-u-2-24"></div>
</div>
+
+<input type="hidden" name="token" value="{$token}" id="token" />
+
{loop="$plugins_footer.endofpage"}
{$value}
{/loop}
</div>
</div>
</div>
+ <div id="actions" class="subheader-form">
+ <div class="pure-g">
+ <div class="pure-u-1">
+ <a href="" id="actions-delete" class="button">Delete</a>
+ </div>
+ </div>
+ </div>
{if="!isLoggedIn()"}
<form method="post" name="loginform">
<div class="subheader-form" id="header-login-form">
<body>
{include="page.header"}
+{include="tag.sort"}
+
<div class="pure-g">
<div class="pure-u-lg-1-6 pure-u-1-24"></div>
<div class="pure-u-lg-2-3 pure-u-22-24 page-form page-visitor">
{$countTags=count($tags)}
<h2 class="window-title">{'Tag cloud'|t} - {$countTags} {'tags'|t}</h2>
+ <div id="search-tagcloud" class="pure-g">
+ <div class="pure-u-lg-1-4"></div>
+ <div class="pure-u-1 pure-u-lg-1-2">
+ <form method="GET">
+ <input type="hidden" name="do" value="tagcloud">
+ <input type="text" name="searchtags" placeholder="{'Filter by tag'|t}"
+ {if="!empty($search_tags)"}
+ value="{$search_tags}"
+ {/if}
+ autocomplete="off" data-multiple data-autofirst data-minChars="1"
+ data-list="{loop="$tags"}{$key}, {/loop}"
+ >
+ <button type="submit" class="search-button"><i class="fa fa-search"></i></button>
+ </form>
+ </div>
+ <div class="pure-u-lg-1-4"></div>
+ </div>
+
<div id="plugin_zone_start_tagcloud" class="plugin_zone">
{loop="$plugin_start_zone"}
{$value}
<div id="cloudtag">
{loop="tags"}
<a href="?searchtags={$key|urlencode}" style="font-size:{$value.size}em;">{$key}</a
- ><span class="count">{$value.count}</span>
+ ><a href="?addtag={$key|urlencode}" title="{'Filter by tag'|t}" class="count">{$value.count}</a>
{loop="$value.tag_plugin"}
{$value}
{/loop}
</div>
</div>
+{include="tag.sort"}
+
{include="page.footer"}
</body>
</html>
--- /dev/null
+<!DOCTYPE html>
+<html>
+<head>
+ {include="includes"}
+</head>
+<body>
+{include="page.header"}
+
+{include="tag.sort"}
+
+<div class="pure-g">
+ <div class="pure-u-lg-1-6 pure-u-1-24"></div>
+ <div class="pure-u-lg-2-3 pure-u-22-24 page-form page-visitor">
+ {$countTags=count($tags)}
+ <h2 class="window-title">{'Tag list'|t} - {$countTags} {'tags'|t}</h2>
+
+ <div id="search-tagcloud" class="pure-g">
+ <div class="pure-u-lg-1-4"></div>
+ <div class="pure-u-1 pure-u-lg-1-2">
+ <form method="GET">
+ <input type="hidden" name="do" value="taglist">
+ <input type="text" name="searchtags" placeholder="{'Filter by tag'|t}"
+ {if="!empty($search_tags)"}
+ value="{$search_tags}"
+ {/if}
+ autocomplete="off" data-multiple data-autofirst data-minChars="1"
+ data-list="{loop="$tags"}{$key}, {/loop}"
+ >
+ <button type="submit" class="search-button"><i class="fa fa-search"></i></button>
+ </form>
+ </div>
+ <div class="pure-u-lg-1-4"></div>
+ </div>
+
+ <div id="plugin_zone_start_tagcloud" class="plugin_zone">
+ {loop="$plugin_start_zone"}
+ {$value}
+ {/loop}
+ </div>
+
+ <div id="taglist">
+ {loop="tags"}
+ <div class="tag-list-item pure-g" data-tag="{$key}">
+ <div class="pure-u-1">
+ {if="isLoggedIn()===true"}
+ <a href="#" class="delete-tag"><i class="fa fa-trash"></i></a>
+ <a href="?do=changetag&fromtag={$key|urlencode}" class="rename-tag">
+ <i class="fa fa-pencil-square-o {$key}"></i>
+ </a>
+ {/if}
+
+ <a href="?addtag={$key|urlencode}" title="{'Filter by tag'|t}" class="count">{$value}</a>
+ <a href="?searchtags={$key|urlencode}" class="tag-link">{$key}</a>
+
+ {loop="$value.tag_plugin"}
+ {$value}
+ {/loop}
+ </div>
+ {if="isLoggedIn()===true"}
+ <div class="rename-tag-form pure-u-1">
+ <input type="text" name="{$key}" value="{$key}" class="rename-tag-input" />
+ <a href="#" class="validate-rename-tag"><i class="fa fa-check"></i></a>
+ </div>
+ {/if}
+ </div>
+ {/loop}
+ </div>
+
+ <div id="plugin_zone_end_tagcloud" class="plugin_zone">
+ {loop="$plugin_end_zone"}
+ {$value}
+ {/loop}
+ </div>
+ </div>
+</div>
+
+{if="isLoggedIn()===true"}
+ <input type="hidden" name="taglist" value="{loop="$tags"}{$key} {/loop}"
+{/if}
+
+{include="tag.sort"}
+
+{include="page.footer"}
+</body>
+</html>
+
--- /dev/null
+<div class="pure-g">
+ <div class="pure-u-1 pure-alert pure-alert-success tag-sort">
+ {'Sort by:'|t}
+ <a href="?do=tagcloud" title="cloud">{'Cloud'|t}</a> ·
+ <a href="?do=taglist&sort=usage" title="cloud">{'Most used'|t}</a> ·
+ <a href="?do=taglist&sort=alpha" title="cloud">{'Alphabetical'|t}</a>
+ </div>
+</div>
\ No newline at end of file
<div class="tools-item">
<a title="{'Drag this link to your bookmarks toolbar or right-click it and Bookmark This Link'|t},
{'Then click ✚Add Note button anytime to start composing a private Note (text post) to your Shaarli'|t}"
- href="?private=1&post="
- class="bookmarklet-link">
+ class="bookmarklet-link"
+ href="javascript:(
+ function(){
+ window.open(
+ '{$pageabsaddr}?private=1&post='+
+ '&description='%20+%20encodeURIComponent(document.getSelection())+
+ '&source=bookmarklet','_blank','menubar=no,height=800,width=600,toolbar=no,scrollbars=yes,status=no,dialog=1'
+ );
+ }
+ )();">
<span class="pure-button pure-u-lg-2-3 pure-u-3-4">✚ {'Add Note'|t}</span>
</a>
</div>
value="{'Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link'|t}">
</body>
</html>
-
<body onload="document.configform.title.focus();">
<div id="pageheader">
{include="page.header"}
- {$timezone_js}
<form method="POST" action="#" name="configform" id="configform">
<input type="hidden" name="token" value="{$token}">
<table id="configuration_table">
</tr>
<tr>
- <td><b>Title link:</b></td>
+ <td><b>Home link:</b></td>
<td><input type="text" name="titleLink" id="titleLink" size="50" value="{$titleLink}"><br/><label
for="titleLink">(default value is: ?)</label></td>
</tr>
<tr>
<td><b>Timezone:</b></td>
- <td>{$timezone_form}</td>
+ <td>
+ <select id="continent" name="continent">
+ {loop="$continents"}
+ {if="$key !== 'selected'"}
+ <option value="{$value}" {if="$continents.selected === $value"}selected{/if}>
+ {$value}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ <select id="city" name="city">
+ {loop="$cities"}
+ {if="$key !== 'selected'"}
+ <option value="{$value.city}"
+ {if="$cities.selected === $value.city"}selected{/if}
+ data-continent="{$value.continent}">
+ {$value.city}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ </td>
</tr>
<tr>
font-weight: bold;
}
+.hidden {
+ display: none;
+}
+
/* Buttons */
.bigbutton, #pageheader a.bigbutton {
background-color: #c0c0c0;
<div id="pageheader">
{include="page.header"}
<div id="uploaddiv">
- Import Netscape HTML bookmarks (as exported from Firefox/Chrome/Opera/Delicious/Diigo...) (Max: {$maxfilesize} bytes).
+ Import Netscape HTML bookmarks (as exported from Firefox/Chrome/Opera/Delicious/Diigo...) (Max: {$maxfilesize}).
<form method="POST" action="?do=import" enctype="multipart/form-data"
name="uploadform" id="uploadform">
<input type="hidden" name="token" value="{$token}">
<!DOCTYPE html>
<html>
-<head>{include="includes"}{$timezone_js}</head>
+<head>{include="includes"}</head>
<body onload="document.installform.setlogin.focus();">
<div id="install">
<h1>Shaarli</h1>
<table>
<tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
<tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
- {$timezone_html}
+ <tr>
+ <td><b>Timezone:</b></td>
+ <td>
+ <select id="continent" name="continent">
+ {loop="$continents"}
+ {if="$key !== 'selected'"}
+ <option value="{$value}" {if="$continents.selected === $value"}selected{/if}>
+ {$value}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ <select id="city" name="city">
+ {loop="$cities"}
+ {if="$key !== 'selected'"}
+ <option value="{$value.city}"
+ {if="$cities.selected === $value.city"}selected{/if}
+ data-continent="{$value.continent}">
+ {$value.city}
+ </option>
+ {/if}
+ {/loop}
+ </select>
+ </td>
+ </tr>
<tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
<tr><td valign="top"><b>Update:</b></td><td>
<input type="checkbox" name="updateCheck" id="updateCheck" checked="checked"><label for="updateCheck"> Notify me when a new release is ready</label></td>
--- /dev/null
+window.onload = function () {
+ var continent = document.getElementById('continent');
+ var city = document.getElementById('city');
+ if (continent != null && city != null) {
+ continent.addEventListener('change', function(event) {
+ hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
+ });
+ hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
+ }
+};
+
+/**
+ * Add the class 'hidden' to city options not attached to the current selected continent.
+ *
+ * @param cities List of <option> elements
+ * @param currentContinent Current selected continent
+ * @param reset Set to true to reset the selected value
+ */
+function hideTimezoneCities(cities, currentContinent, reset = false) {
+ var first = true;
+ [].forEach.call(cities, function(option) {
+ if (option.getAttribute('data-continent') != currentContinent) {
+ option.className = 'hidden';
+ } else {
+ option.className = '';
+ if (reset === true && first === true) {
+ option.setAttribute('selected', 'selected');
+ first = false;
+ }
+ }
+ });
+}
<script>function confirmDeleteLink() { var agree=confirm("Are you sure you want to delete this link ?"); if (agree) return true ; else return false ; }</script>
{/if}
+<script src="js/shaarli.js"></script>
{loop="$plugins_footer.js_files"}
<script src="{$value}#"></script>
{/loop}
-<div id="logo" title="Share your links !" onclick="document.location='?';"></div>
+<div id="logo" title="Share your links !" onclick="document.location='{$titleLink}';"></div>
<div id="linkcount" class="nomobile">
{if="!empty($linkcount)"}{$linkcount} links{/if}<br>
{if="!empty($_GET['source']) && $_GET['source']=='bookmarklet'"}
{ignore} When called as a popup from bookmarklet, do not display menu. {/ignore}
{else}
-<li><a href="?" class="nomobile">Home</a></li>
+<li><a href="{$titleLink}" class="nomobile">Home</a></li>
{if="isLoggedIn()"}
<li><a href="?do=logout">Logout</a></li>
<li><a href="?do=tools">Tools</a></li>
<div id="cloudtag">
{loop="$tags"}
- <span class="count">{$value.count}</span><a
+ <a href="?addtag={$key|urlencode}" class="count">{$value.count}</a><a
href="?searchtags={$key|urlencode}" style="font-size:{$value.size}em;">{$key}</a>
{loop="$value.tag_plugin"}
{$value}
</a><br><br>
<a class="smallbutton"
onclick="return alertBookmarklet();"
- href="?private=1&post="><b>✚Add Note</b></a>
+ href="javascript:(
+ function(){
+ window.open(
+ '{$pageabsaddr}?private=1&post='+
+ '&description='%20+%20encodeURIComponent(document.getSelection())+
+ '&source=bookmarklet','_blank','menubar=no,height=800,width=600,toolbar=no,scrollbars=yes,status=no,dialog=1'
+ );
+ }
+ )();"><b>✚Add Note</b></a>
<a href="#" onclick="return alertBookmarklet();">
<span>
⇐ Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....).<br>