aboutsummaryrefslogtreecommitdiffhomepage
path: root/application
diff options
context:
space:
mode:
Diffstat (limited to 'application')
-rw-r--r--application/HttpUtils.php62
-rw-r--r--application/LinkDB.php35
-rw-r--r--application/LinkFilter.php2
-rw-r--r--application/LinkUtils.php22
-rw-r--r--application/NetscapeBookmarkUtils.php54
-rw-r--r--application/PageBuilder.php145
-rw-r--r--application/Router.php26
-rw-r--r--application/TimeZone.php4
-rw-r--r--application/Url.php43
-rw-r--r--application/Utils.php16
10 files changed, 369 insertions, 40 deletions
diff --git a/application/HttpUtils.php b/application/HttpUtils.php
index af7cb371..2e0792f9 100644
--- a/application/HttpUtils.php
+++ b/application/HttpUtils.php
@@ -27,7 +27,9 @@
27function get_http_response($url, $timeout = 30, $maxBytes = 4194304) 27function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
28{ 28{
29 $urlObj = new Url($url); 29 $urlObj = new Url($url);
30 if (! filter_var($url, FILTER_VALIDATE_URL) || ! $urlObj->isHttp()) { 30 $cleanUrl = $urlObj->idnToAscii();
31
32 if (! filter_var($cleanUrl, FILTER_VALIDATE_URL) || ! $urlObj->isHttp()) {
31 return array(array(0 => 'Invalid HTTP Url'), false); 33 return array(array(0 => 'Invalid HTTP Url'), false);
32 } 34 }
33 35
@@ -35,22 +37,27 @@ function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
35 'http' => array( 37 'http' => array(
36 'method' => 'GET', 38 'method' => 'GET',
37 'timeout' => $timeout, 39 'timeout' => $timeout,
38 'user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0)' 40 'user_agent' => 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:45.0)'
39 .' Gecko/20100101 Firefox/23.0', 41 .' Gecko/20100101 Firefox/45.0',
40 'request_fulluri' => true, 42 'accept_language' => substr(setlocale(LC_COLLATE, 0), 0, 2) . ',en-US;q=0.7,en;q=0.3',
41 ) 43 )
42 ); 44 );
43 45
44 $context = stream_context_create($options);
45 stream_context_set_default($options); 46 stream_context_set_default($options);
47 list($headers, $finalUrl) = get_redirected_headers($cleanUrl);
48 if (! $headers || strpos($headers[0], '200 OK') === false) {
49 $options['http']['request_fulluri'] = true;
50 stream_context_set_default($options);
51 list($headers, $finalUrl) = get_redirected_headers($cleanUrl);
52 }
46 53
47 list($headers, $finalUrl) = get_redirected_headers($urlObj->cleanup());
48 if (! $headers || strpos($headers[0], '200 OK') === false) { 54 if (! $headers || strpos($headers[0], '200 OK') === false) {
49 return array($headers, false); 55 return array($headers, false);
50 } 56 }
51 57
52 try { 58 try {
53 // TODO: catch Exception in calling code (thumbnailer) 59 // TODO: catch Exception in calling code (thumbnailer)
60 $context = stream_context_create($options);
54 $content = file_get_contents($finalUrl, false, $context, -1, $maxBytes); 61 $content = file_get_contents($finalUrl, false, $context, -1, $maxBytes);
55 } catch (Exception $exc) { 62 } catch (Exception $exc) {
56 return array(array(0 => 'HTTP Error'), $exc->getMessage()); 63 return array(array(0 => 'HTTP Error'), $exc->getMessage());
@@ -60,16 +67,19 @@ function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
60} 67}
61 68
62/** 69/**
63 * Retrieve HTTP headers, following n redirections (temporary and permanent). 70 * Retrieve HTTP headers, following n redirections (temporary and permanent ones).
64 * 71 *
65 * @param string $url initial URL to reach. 72 * @param string $url initial URL to reach.
66 * @param int $redirectionLimit max redirection follow.. 73 * @param int $redirectionLimit max redirection follow.
67 * 74 *
68 * @return array 75 * @return array HTTP headers, or false if it failed.
69 */ 76 */
70function get_redirected_headers($url, $redirectionLimit = 3) 77function get_redirected_headers($url, $redirectionLimit = 3)
71{ 78{
72 $headers = get_headers($url, 1); 79 $headers = get_headers($url, 1);
80 if (!empty($headers['location']) && empty($headers['Location'])) {
81 $headers['Location'] = $headers['location'];
82 }
73 83
74 // Headers found, redirection found, and limit not reached. 84 // Headers found, redirection found, and limit not reached.
75 if ($redirectionLimit-- > 0 85 if ($redirectionLimit-- > 0
@@ -79,6 +89,7 @@ function get_redirected_headers($url, $redirectionLimit = 3)
79 89
80 $redirection = is_array($headers['Location']) ? end($headers['Location']) : $headers['Location']; 90 $redirection = is_array($headers['Location']) ? end($headers['Location']) : $headers['Location'];
81 if ($redirection != $url) { 91 if ($redirection != $url) {
92 $redirection = getAbsoluteUrl($url, $redirection);
82 return get_redirected_headers($redirection, $redirectionLimit); 93 return get_redirected_headers($redirection, $redirectionLimit);
83 } 94 }
84 } 95 }
@@ -87,6 +98,35 @@ function get_redirected_headers($url, $redirectionLimit = 3)
87} 98}
88 99
89/** 100/**
101 * Get an absolute URL from a complete one, and another absolute/relative URL.
102 *
103 * @param string $originalUrl The original complete URL.
104 * @param string $newUrl The new one, absolute or relative.
105 *
106 * @return string Final URL:
107 * - $newUrl if it was already an absolute URL.
108 * - if it was relative, absolute URL from $originalUrl path.
109 */
110function getAbsoluteUrl($originalUrl, $newUrl)
111{
112 $newScheme = parse_url($newUrl, PHP_URL_SCHEME);
113 // Already an absolute URL.
114 if (!empty($newScheme)) {
115 return $newUrl;
116 }
117
118 $parts = parse_url($originalUrl);
119 $final = $parts['scheme'] .'://'. $parts['host'];
120 $final .= (!empty($parts['port'])) ? $parts['port'] : '';
121 $final .= '/';
122 if ($newUrl[0] != '/') {
123 $final .= substr(ltrim($parts['path'], '/'), 0, strrpos($parts['path'], '/'));
124 }
125 $final .= ltrim($newUrl, '/');
126 return $final;
127}
128
129/**
90 * Returns the server's base URL: scheme://domain.tld[:port] 130 * Returns the server's base URL: scheme://domain.tld[:port]
91 * 131 *
92 * @param array $server the $_SERVER array 132 * @param array $server the $_SERVER array
@@ -153,7 +193,7 @@ function server_url($server)
153function index_url($server) 193function index_url($server)
154{ 194{
155 $scriptname = $server['SCRIPT_NAME']; 195 $scriptname = $server['SCRIPT_NAME'];
156 if (endswith($scriptname, 'index.php')) { 196 if (endsWith($scriptname, 'index.php')) {
157 $scriptname = substr($scriptname, 0, -9); 197 $scriptname = substr($scriptname, 0, -9);
158 } 198 }
159 return server_url($server) . $scriptname; 199 return server_url($server) . $scriptname;
diff --git a/application/LinkDB.php b/application/LinkDB.php
index 4c1a45b5..b1072e07 100644
--- a/application/LinkDB.php
+++ b/application/LinkDB.php
@@ -66,21 +66,39 @@ class LinkDB implements Iterator, Countable, ArrayAccess
66 private $_redirector; 66 private $_redirector;
67 67
68 /** 68 /**
69 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
70 *
71 * Example:
72 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
73 *
74 * @var boolean $redirectorEncode parameter: true or false
75 */
76 private $redirectorEncode;
77
78 /**
69 * Creates a new LinkDB 79 * Creates a new LinkDB
70 * 80 *
71 * Checks if the datastore exists; else, attempts to create a dummy one. 81 * Checks if the datastore exists; else, attempts to create a dummy one.
72 * 82 *
73 * @param string $datastore datastore file path. 83 * @param string $datastore datastore file path.
74 * @param boolean $isLoggedIn is the user logged in? 84 * @param boolean $isLoggedIn is the user logged in?
75 * @param boolean $hidePublicLinks if true all links are private. 85 * @param boolean $hidePublicLinks if true all links are private.
76 * @param string $redirector link redirector set in user settings. 86 * @param string $redirector link redirector set in user settings.
87 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
77 */ 88 */
78 function __construct($datastore, $isLoggedIn, $hidePublicLinks, $redirector = '') 89 function __construct(
90 $datastore,
91 $isLoggedIn,
92 $hidePublicLinks,
93 $redirector = '',
94 $redirectorEncode = true
95 )
79 { 96 {
80 $this->_datastore = $datastore; 97 $this->_datastore = $datastore;
81 $this->_loggedIn = $isLoggedIn; 98 $this->_loggedIn = $isLoggedIn;
82 $this->_hidePublicLinks = $hidePublicLinks; 99 $this->_hidePublicLinks = $hidePublicLinks;
83 $this->_redirector = $redirector; 100 $this->_redirector = $redirector;
101 $this->redirectorEncode = $redirectorEncode === true;
84 $this->_checkDB(); 102 $this->_checkDB();
85 $this->_readDB(); 103 $this->_readDB();
86 } 104 }
@@ -278,7 +296,12 @@ You use the community supported version of the original Shaarli project, by Seba
278 296
279 // Do not use the redirector for internal links (Shaarli note URL starting with a '?'). 297 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
280 if (!empty($this->_redirector) && !startsWith($link['url'], '?')) { 298 if (!empty($this->_redirector) && !startsWith($link['url'], '?')) {
281 $link['real_url'] = $this->_redirector . urlencode($link['url']); 299 $link['real_url'] = $this->_redirector;
300 if ($this->redirectorEncode) {
301 $link['real_url'] .= urlencode(unescape($link['url']));
302 } else {
303 $link['real_url'] .= $link['url'];
304 }
282 } 305 }
283 else { 306 else {
284 $link['real_url'] = $link['url']; 307 $link['real_url'] = $link['url'];
diff --git a/application/LinkFilter.php b/application/LinkFilter.php
index 5e0d8015..e693b284 100644
--- a/application/LinkFilter.php
+++ b/application/LinkFilter.php
@@ -322,7 +322,7 @@ class LinkFilter
322 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8'); 322 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
323 $tagsOut = str_replace(',', ' ', $tagsOut); 323 $tagsOut = str_replace(',', ' ', $tagsOut);
324 324
325 return array_filter(explode(' ', trim($tagsOut)), 'strlen'); 325 return array_values(array_filter(explode(' ', trim($tagsOut)), 'strlen'));
326 } 326 }
327} 327}
328 328
diff --git a/application/LinkUtils.php b/application/LinkUtils.php
index d8dc8b5e..da04ca97 100644
--- a/application/LinkUtils.php
+++ b/application/LinkUtils.php
@@ -9,8 +9,8 @@
9 */ 9 */
10function html_extract_title($html) 10function html_extract_title($html)
11{ 11{
12 if (preg_match('!<title>(.*?)</title>!is', $html, $matches)) { 12 if (preg_match('!<title.*?>(.*?)</title>!is', $html, $matches)) {
13 return trim(str_replace("\n", ' ', $matches[1])); 13 return trim(str_replace("\n", '', $matches[1]));
14 } 14 }
15 return false; 15 return false;
16} 16}
@@ -70,10 +70,26 @@ function headers_extract_charset($headers)
70function html_extract_charset($html) 70function html_extract_charset($html)
71{ 71{
72 // Get encoding specified in HTML header. 72 // Get encoding specified in HTML header.
73 preg_match('#<meta .*charset="?([^">/]+)"? */?>#Usi', $html, $enc); 73 preg_match('#<meta .*charset=["\']?([^";\'>/]+)["\']? */?>#Usi', $html, $enc);
74 if (!empty($enc[1])) { 74 if (!empty($enc[1])) {
75 return strtolower($enc[1]); 75 return strtolower($enc[1]);
76 } 76 }
77 77
78 return false; 78 return false;
79} 79}
80
81/**
82 * Count private links in given linklist.
83 *
84 * @param array $links Linklist.
85 *
86 * @return int Number of private links.
87 */
88function count_private($links)
89{
90 $cpt = 0;
91 foreach ($links as $link) {
92 $cpt = $link['private'] == true ? $cpt + 1 : $cpt;
93 }
94 return $cpt;
95}
diff --git a/application/NetscapeBookmarkUtils.php b/application/NetscapeBookmarkUtils.php
new file mode 100644
index 00000000..fdbb0ad7
--- /dev/null
+++ b/application/NetscapeBookmarkUtils.php
@@ -0,0 +1,54 @@
1<?php
2
3/**
4 * Utilities to import and export bookmarks using the Netscape format
5 */
6class NetscapeBookmarkUtils
7{
8
9 /**
10 * Filters links and adds Netscape-formatted fields
11 *
12 * Added fields:
13 * - timestamp link addition date, using the Unix epoch format
14 * - taglist comma-separated tag list
15 *
16 * @param LinkDB $linkDb Link datastore
17 * @param string $selection Which links to export: (all|private|public)
18 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
19 * @param string $indexUrl Absolute URL of the Shaarli index page
20 *
21 * @throws Exception Invalid export selection
22 *
23 * @return array The links to be exported, with additional fields
24 */
25 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
26 {
27 // see tpl/export.html for possible values
28 if (! in_array($selection, array('all', 'public', 'private'))) {
29 throw new Exception('Invalid export selection: "'.$selection.'"');
30 }
31
32 $bookmarkLinks = array();
33
34 foreach ($linkDb as $link) {
35 if ($link['private'] != 0 && $selection == 'public') {
36 continue;
37 }
38 if ($link['private'] == 0 && $selection == 'private') {
39 continue;
40 }
41 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
42 $link['timestamp'] = $date->getTimestamp();
43 $link['taglist'] = str_replace(' ', ',', $link['tags']);
44
45 if (startsWith($link['url'], '?') && $prependNoteUrl) {
46 $link['url'] = $indexUrl . $link['url'];
47 }
48
49 $bookmarkLinks[] = $link;
50 }
51
52 return $bookmarkLinks;
53 }
54}
diff --git a/application/PageBuilder.php b/application/PageBuilder.php
new file mode 100644
index 00000000..82580787
--- /dev/null
+++ b/application/PageBuilder.php
@@ -0,0 +1,145 @@
1<?php
2
3/**
4 * This class is in charge of building the final page.
5 * (This is basically a wrapper around RainTPL which pre-fills some fields.)
6 * $p = new PageBuilder();
7 * $p->assign('myfield','myvalue');
8 * $p->renderPage('mytemplate');
9 */
10class PageBuilder
11{
12 /**
13 * @var RainTPL RainTPL instance.
14 */
15 private $tpl;
16
17 /**
18 * PageBuilder constructor.
19 * $tpl is initialized at false for lazy loading.
20 */
21 function __construct()
22 {
23 $this->tpl = false;
24 }
25
26 /**
27 * Initialize all default tpl tags.
28 */
29 private function initialize()
30 {
31 $this->tpl = new RainTPL();
32
33 try {
34 $version = ApplicationUtils::checkUpdate(
35 shaarli_version,
36 $GLOBALS['config']['UPDATECHECK_FILENAME'],
37 $GLOBALS['config']['UPDATECHECK_INTERVAL'],
38 $GLOBALS['config']['ENABLE_UPDATECHECK'],
39 isLoggedIn(),
40 $GLOBALS['config']['UPDATECHECK_BRANCH']
41 );
42 $this->tpl->assign('newVersion', escape($version));
43 $this->tpl->assign('versionError', '');
44
45 } catch (Exception $exc) {
46 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], $exc->getMessage());
47 $this->tpl->assign('newVersion', '');
48 $this->tpl->assign('versionError', escape($exc->getMessage()));
49 }
50
51 $this->tpl->assign('feedurl', escape(index_url($_SERVER)));
52 $searchcrits = ''; // Search criteria
53 if (!empty($_GET['searchtags'])) {
54 $searchcrits .= '&searchtags=' . urlencode($_GET['searchtags']);
55 }
56 if (!empty($_GET['searchterm'])) {
57 $searchcrits .= '&searchterm=' . urlencode($_GET['searchterm']);
58 }
59 $this->tpl->assign('searchcrits', $searchcrits);
60 $this->tpl->assign('source', index_url($_SERVER));
61 $this->tpl->assign('version', shaarli_version);
62 $this->tpl->assign('scripturl', index_url($_SERVER));
63 $this->tpl->assign('pagetitle', 'Shaarli');
64 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
65 if (!empty($GLOBALS['title'])) {
66 $this->tpl->assign('pagetitle', $GLOBALS['title']);
67 }
68 if (!empty($GLOBALS['titleLink'])) {
69 $this->tpl->assign('titleLink', $GLOBALS['titleLink']);
70 }
71 if (!empty($GLOBALS['pagetitle'])) {
72 $this->tpl->assign('pagetitle', $GLOBALS['pagetitle']);
73 }
74 $this->tpl->assign('shaarlititle', empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title']);
75 if (!empty($GLOBALS['plugin_errors'])) {
76 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
77 }
78 }
79
80 /**
81 * The following assign() method is basically the same as RainTPL (except lazy loading)
82 *
83 * @param string $placeholder Template placeholder.
84 * @param mixed $value Value to assign.
85 */
86 public function assign($placeholder, $value)
87 {
88 // Lazy initialization
89 if ($this->tpl === false) {
90 $this->initialize();
91 }
92 $this->tpl->assign($placeholder, $value);
93 }
94
95 /**
96 * Assign an array of data to the template builder.
97 *
98 * @param array $data Data to assign.
99 *
100 * @return false if invalid data.
101 */
102 public function assignAll($data)
103 {
104 // Lazy initialization
105 if ($this->tpl === false) {
106 $this->initialize();
107 }
108
109 if (empty($data) || !is_array($data)){
110 return false;
111 }
112
113 foreach ($data as $key => $value) {
114 $this->assign($key, $value);
115 }
116 }
117
118 /**
119 * Render a specific page (using a template file).
120 * e.g. $pb->renderPage('picwall');
121 *
122 * @param string $page Template filename (without extension).
123 */
124 public function renderPage($page)
125 {
126 // Lazy initialization
127 if ($this->tpl===false) {
128 $this->initialize();
129 }
130 $this->tpl->draw($page);
131 }
132
133 /**
134 * Render a 404 page (uses the template : tpl/404.tpl)
135 * usage : $PAGE->render404('The link was deleted')
136 *
137 * @param string $message A messate to display what is not found
138 */
139 public function render404($message = 'The page you are trying to reach does not exist or has been deleted.')
140 {
141 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
142 $this->tpl->assign('error_message', $message);
143 $this->renderPage('404');
144 }
145}
diff --git a/application/Router.php b/application/Router.php
index a1e594a0..2c3934b0 100644
--- a/application/Router.php
+++ b/application/Router.php
@@ -63,19 +63,19 @@ class Router
63 return self::$PAGE_LINKLIST; 63 return self::$PAGE_LINKLIST;
64 } 64 }
65 65
66 if (startswith($query, 'do='. self::$PAGE_LOGIN) && $loggedIn === false) { 66 if (startsWith($query, 'do='. self::$PAGE_LOGIN) && $loggedIn === false) {
67 return self::$PAGE_LOGIN; 67 return self::$PAGE_LOGIN;
68 } 68 }
69 69
70 if (startswith($query, 'do='. self::$PAGE_PICWALL)) { 70 if (startsWith($query, 'do='. self::$PAGE_PICWALL)) {
71 return self::$PAGE_PICWALL; 71 return self::$PAGE_PICWALL;
72 } 72 }
73 73
74 if (startswith($query, 'do='. self::$PAGE_TAGCLOUD)) { 74 if (startsWith($query, 'do='. self::$PAGE_TAGCLOUD)) {
75 return self::$PAGE_TAGCLOUD; 75 return self::$PAGE_TAGCLOUD;
76 } 76 }
77 77
78 if (startswith($query, 'do='. self::$PAGE_OPENSEARCH)) { 78 if (startsWith($query, 'do='. self::$PAGE_OPENSEARCH)) {
79 return self::$PAGE_OPENSEARCH; 79 return self::$PAGE_OPENSEARCH;
80 } 80 }
81 81
@@ -96,23 +96,23 @@ class Router
96 return self::$PAGE_LINKLIST; 96 return self::$PAGE_LINKLIST;
97 } 97 }
98 98
99 if (startswith($query, 'do='. self::$PAGE_TOOLS)) { 99 if (startsWith($query, 'do='. self::$PAGE_TOOLS)) {
100 return self::$PAGE_TOOLS; 100 return self::$PAGE_TOOLS;
101 } 101 }
102 102
103 if (startswith($query, 'do='. self::$PAGE_CHANGEPASSWORD)) { 103 if (startsWith($query, 'do='. self::$PAGE_CHANGEPASSWORD)) {
104 return self::$PAGE_CHANGEPASSWORD; 104 return self::$PAGE_CHANGEPASSWORD;
105 } 105 }
106 106
107 if (startswith($query, 'do='. self::$PAGE_CONFIGURE)) { 107 if (startsWith($query, 'do='. self::$PAGE_CONFIGURE)) {
108 return self::$PAGE_CONFIGURE; 108 return self::$PAGE_CONFIGURE;
109 } 109 }
110 110
111 if (startswith($query, 'do='. self::$PAGE_CHANGETAG)) { 111 if (startsWith($query, 'do='. self::$PAGE_CHANGETAG)) {
112 return self::$PAGE_CHANGETAG; 112 return self::$PAGE_CHANGETAG;
113 } 113 }
114 114
115 if (startswith($query, 'do='. self::$PAGE_ADDLINK)) { 115 if (startsWith($query, 'do='. self::$PAGE_ADDLINK)) {
116 return self::$PAGE_ADDLINK; 116 return self::$PAGE_ADDLINK;
117 } 117 }
118 118
@@ -120,19 +120,19 @@ class Router
120 return self::$PAGE_EDITLINK; 120 return self::$PAGE_EDITLINK;
121 } 121 }
122 122
123 if (startswith($query, 'do='. self::$PAGE_EXPORT)) { 123 if (startsWith($query, 'do='. self::$PAGE_EXPORT)) {
124 return self::$PAGE_EXPORT; 124 return self::$PAGE_EXPORT;
125 } 125 }
126 126
127 if (startswith($query, 'do='. self::$PAGE_IMPORT)) { 127 if (startsWith($query, 'do='. self::$PAGE_IMPORT)) {
128 return self::$PAGE_IMPORT; 128 return self::$PAGE_IMPORT;
129 } 129 }
130 130
131 if (startswith($query, 'do='. self::$PAGE_PLUGINSADMIN)) { 131 if (startsWith($query, 'do='. self::$PAGE_PLUGINSADMIN)) {
132 return self::$PAGE_PLUGINSADMIN; 132 return self::$PAGE_PLUGINSADMIN;
133 } 133 }
134 134
135 if (startswith($query, 'do='. self::$PAGE_SAVE_PLUGINSADMIN)) { 135 if (startsWith($query, 'do='. self::$PAGE_SAVE_PLUGINSADMIN)) {
136 return self::$PAGE_SAVE_PLUGINSADMIN; 136 return self::$PAGE_SAVE_PLUGINSADMIN;
137 } 137 }
138 138
diff --git a/application/TimeZone.php b/application/TimeZone.php
index e363d90a..26f2232d 100644
--- a/application/TimeZone.php
+++ b/application/TimeZone.php
@@ -101,10 +101,6 @@ function generateTimeZoneForm($preselectedTimezone='')
101 */ 101 */
102function isTimeZoneValid($continent, $city) 102function isTimeZoneValid($continent, $city)
103{ 103{
104 if ($continent == 'UTC' && $city == 'UTC') {
105 return true;
106 }
107
108 return in_array( 104 return in_array(
109 $continent.'/'.$city, 105 $continent.'/'.$city,
110 timezone_identifiers_list() 106 timezone_identifiers_list()
diff --git a/application/Url.php b/application/Url.php
index af38c4d9..c166ff6e 100644
--- a/application/Url.php
+++ b/application/Url.php
@@ -62,7 +62,21 @@ function add_trailing_slash($url)
62{ 62{
63 return $url . (!endsWith($url, '/') ? '/' : ''); 63 return $url . (!endsWith($url, '/') ? '/' : '');
64} 64}
65/**
66 * Converts an URL with an IDN host to a ASCII one.
67 *
68 * @param string $url Input URL.
69 *
70 * @return string converted URL.
71 */
72function url_with_idn_to_ascii($url)
73{
74 $parts = parse_url($url);
75 $parts['host'] = idn_to_ascii($parts['host']);
65 76
77 $httpUrl = new \http\Url($parts);
78 return $httpUrl->toString();
79}
66/** 80/**
67 * URL representation and cleanup utilities 81 * URL representation and cleanup utilities
68 * 82 *
@@ -85,6 +99,7 @@ class Url
85 'action_type_map=', 99 'action_type_map=',
86 'fb_', 100 'fb_',
87 'fb=', 101 'fb=',
102 'PHPSESSID=',
88 103
89 // Scoop.it 104 // Scoop.it
90 '__scoop', 105 '__scoop',
@@ -221,6 +236,22 @@ class Url
221 } 236 }
222 237
223 /** 238 /**
239 * Converts an URL with an International Domain Name host to a ASCII one.
240 * This requires PHP-intl. If it's not available, just returns this->cleanup().
241 *
242 * @return string converted cleaned up URL.
243 */
244 public function idnToAscii()
245 {
246 $out = $this->cleanup();
247 if (! function_exists('idn_to_ascii') || ! isset($this->parts['host'])) {
248 return $out;
249 }
250 $asciiHost = idn_to_ascii($this->parts['host']);
251 return str_replace($this->parts['host'], $asciiHost, $out);
252 }
253
254 /**
224 * Get URL scheme. 255 * Get URL scheme.
225 * 256 *
226 * @return string the URL scheme or false if none is provided. 257 * @return string the URL scheme or false if none is provided.
@@ -233,6 +264,18 @@ class Url
233 } 264 }
234 265
235 /** 266 /**
267 * Get URL host.
268 *
269 * @return string the URL host or false if none is provided.
270 */
271 public function getHost() {
272 if (empty($this->parts['host'])) {
273 return false;
274 }
275 return $this->parts['host'];
276 }
277
278 /**
236 * Test if the Url is an HTTP one. 279 * Test if the Url is an HTTP one.
237 * 280 *
238 * @return true is HTTP, false otherwise. 281 * @return true is HTTP, false otherwise.
diff --git a/application/Utils.php b/application/Utils.php
index 5b8ca508..da521cce 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -41,8 +41,14 @@ function smallHash($text)
41 41
42/** 42/**
43 * Tells if a string start with a substring 43 * Tells if a string start with a substring
44 *
45 * @param string $haystack Given string.
46 * @param string $needle String to search at the beginning of $haystack.
47 * @param bool $case Case sensitive.
48 *
49 * @return bool True if $haystack starts with $needle.
44 */ 50 */
45function startsWith($haystack, $needle, $case=true) 51function startsWith($haystack, $needle, $case = true)
46{ 52{
47 if ($case) { 53 if ($case) {
48 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0); 54 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
@@ -52,8 +58,14 @@ function startsWith($haystack, $needle, $case=true)
52 58
53/** 59/**
54 * Tells if a string ends with a substring 60 * Tells if a string ends with a substring
61 *
62 * @param string $haystack Given string.
63 * @param string $needle String to search at the end of $haystack.
64 * @param bool $case Case sensitive.
65 *
66 * @return bool True if $haystack ends with $needle.
55 */ 67 */
56function endsWith($haystack, $needle, $case=true) 68function endsWith($haystack, $needle, $case = true)
57{ 69{
58 if ($case) { 70 if ($case) {
59 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); 71 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);