1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8function wikiplugin_sort_info()
9{
10	return [
11		'name' => tra('Sort'),
12		'documentation' => 'PluginSort',
13		'description' => tra('Sort lines of text'),
14		'prefs' => [ 'wikiplugin_sort' ],
15		'body' => tra('Data to sort, one entry per line.'),
16		'filter' => 'text',
17		'iconname' => 'sort-desc',
18		'introduced' => 1,
19		'tags' => [ 'basic' ],
20		'params' => [
21			'sort' => [
22				'required' => false,
23				'name' => tra('Order'),
24				'description' => tra('Set the sort order of lines of content (default is ascending)'),
25				'since' => '1',
26				'filter' => 'alpha',
27				'default' => 'asc',
28				'options' => [
29					['text' => '', 'value' => ''],
30					['text' => tra('Ascending'), 'value' => 'asc'],
31					['text' => tra('Descending'), 'value' => 'desc'],
32					['text' => tra('Reverse'), 'value' => 'reverse'],
33					['text' => tra('Shuffle'), 'value' => 'shuffle']
34				]
35			]
36		]
37	];
38}
39
40function wikiplugin_sort($data, $params)
41{
42	global $tikilib;
43
44	extract($params, EXTR_SKIP);
45
46	$sort = (isset($sort)) ? $sort : "asc";
47
48	$lines = preg_split("/\n+/", $data, -1, PREG_SPLIT_NO_EMPTY); // separate lines into array
49	// $lines = array_filter( $lines, "chop" ); // remove \n
50	srand((float) microtime() * 1000000); // needed for shuffle;
51
52	if ($sort == "asc") {
53		natcasesort($lines);
54	} elseif ($sort == "desc") {
55		natcasesort($lines);
56		$lines = array_reverse($lines);
57	} elseif ($sort == "reverse") {
58		$lines = array_reverse($lines);
59	} elseif ($sort == "shuffle") {
60		shuffle($lines);
61	}
62
63	reset($lines);
64
65	if (is_array($lines)) {
66		$data = implode("\n", $lines);
67	}
68
69	$data = trim($data);
70	return $data;
71}
72