aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2015-09-06 21:31:37 +0200
committerVirtualTam <virtualtam@flibidi.net>2015-09-14 20:27:16 +0200
commit482d67bd523bf12f36508a0131d09fe299ee02f4 (patch)
treeb4e7c6ddaa1d88cc49bc96c2524f12431d8fcce0 /index.php
parent7b114771d337af3bfd51d8fda1e8f2fd5b39535d (diff)
downloadShaarli-482d67bd523bf12f36508a0131d09fe299ee02f4.tar.gz
Shaarli-482d67bd523bf12f36508a0131d09fe299ee02f4.tar.zst
Shaarli-482d67bd523bf12f36508a0131d09fe299ee02f4.zip
HTTP: move server URL functions to `HttpUtils.php`
Relates to #333 Modifications: - refactor server URL utility functions - do not access global `$_SERVER` variables - add test coverage - improve readability - apply coding conventions Signed-off-by: VirtualTam <virtualtam@flibidi.net>
Diffstat (limited to 'index.php')
-rwxr-xr-xindex.php78
1 files changed, 25 insertions, 53 deletions
diff --git a/index.php b/index.php
index 7818ee88..c1ddf4b7 100755
--- a/index.php
+++ b/index.php
@@ -131,7 +131,7 @@ header("Pragma: no-cache");
131if (!is_writable(realpath(dirname(__FILE__)))) die('<pre>ERROR: Shaarli does not have the right to write in its own directory.</pre>'); 131if (!is_writable(realpath(dirname(__FILE__)))) die('<pre>ERROR: Shaarli does not have the right to write in its own directory.</pre>');
132 132
133// Handling of old config file which do not have the new parameters. 133// Handling of old config file which do not have the new parameters.
134if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.escape(indexUrl()); 134if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.escape(index_url($_SERVER));
135if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get(); 135if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
136if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']=''; 136if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
137if (empty($GLOBALS['disablesessionprotection'])) $GLOBALS['disablesessionprotection']=false; 137if (empty($GLOBALS['disablesessionprotection'])) $GLOBALS['disablesessionprotection']=false;
@@ -277,8 +277,8 @@ function pubsubhub()
277 { 277 {
278 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']); 278 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
279 $topic_url = array ( 279 $topic_url = array (
280 indexUrl().'?do=atom', 280 index_url($_SERVER).'?do=atom',
281 indexUrl().'?do=rss' 281 index_url($_SERVER).'?do=rss'
282 ); 282 );
283 $p->publish_update($topic_url); 283 $p->publish_update($topic_url);
284 } 284 }
@@ -458,34 +458,6 @@ if (isset($_POST['login']))
458// ------------------------------------------------------------------------------------------ 458// ------------------------------------------------------------------------------------------
459// Misc utility functions: 459// Misc utility functions:
460 460
461// Returns the server URL (including port and http/https), without path.
462// e.g. "http://myserver.com:8080"
463// You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
464function serverUrl()
465{
466 $https = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS'])=='on')) || $_SERVER["SERVER_PORT"]=='443' || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); // HTTPS detection.
467 $serverport = ($_SERVER["SERVER_PORT"]=='80' || ($https && $_SERVER["SERVER_PORT"]=='443') ? '' : ':'.$_SERVER["SERVER_PORT"]);
468 return 'http'.($https?'s':'').'://'.$_SERVER['SERVER_NAME'].$serverport;
469}
470
471// Returns the absolute URL of current script, without the query.
472// (e.g. http://sebsauvage.net/links/)
473function indexUrl()
474{
475 $scriptname = $_SERVER["SCRIPT_NAME"];
476 // If the script is named 'index.php', we remove it (for better looking URLs,
477 // e.g. http://mysite.com/shaarli/?abcde instead of http://mysite.com/shaarli/index.php?abcde)
478 if (endswith($scriptname,'index.php')) $scriptname = substr($scriptname,0,strlen($scriptname)-9);
479 return serverUrl() . $scriptname;
480}
481
482// Returns the absolute URL of current script, WITH the query.
483// (e.g. http://sebsauvage.net/links/?toto=titi&spamspamspam=humbug)
484function pageUrl()
485{
486 return indexUrl().(!empty($_SERVER["QUERY_STRING"]) ? '?'.$_SERVER["QUERY_STRING"] : '');
487}
488
489// Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes. 461// Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
490function return_bytes($val) 462function return_bytes($val)
491{ 463{
@@ -591,14 +563,14 @@ class pageBuilder
591 { 563 {
592 $this->tpl = new RainTPL; 564 $this->tpl = new RainTPL;
593 $this->tpl->assign('newversion',escape(checkUpdate())); 565 $this->tpl->assign('newversion',escape(checkUpdate()));
594 $this->tpl->assign('feedurl',escape(indexUrl())); 566 $this->tpl->assign('feedurl',escape(index_url($_SERVER)));
595 $searchcrits=''; // Search criteria 567 $searchcrits=''; // Search criteria
596 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.urlencode($_GET['searchtags']); 568 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.urlencode($_GET['searchtags']);
597 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.urlencode($_GET['searchterm']); 569 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.urlencode($_GET['searchterm']);
598 $this->tpl->assign('searchcrits',$searchcrits); 570 $this->tpl->assign('searchcrits',$searchcrits);
599 $this->tpl->assign('source',indexUrl()); 571 $this->tpl->assign('source',index_url($_SERVER));
600 $this->tpl->assign('version',shaarli_version); 572 $this->tpl->assign('version',shaarli_version);
601 $this->tpl->assign('scripturl',indexUrl()); 573 $this->tpl->assign('scripturl',index_url($_SERVER));
602 $this->tpl->assign('pagetitle','Shaarli'); 574 $this->tpl->assign('pagetitle','Shaarli');
603 $this->tpl->assign('privateonly',!empty($_SESSION['privateonly'])); // Show only private links? 575 $this->tpl->assign('privateonly',!empty($_SESSION['privateonly'])); // Show only private links?
604 if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']); 576 if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']);
@@ -639,7 +611,7 @@ function showRSS()
639 $query = $_SERVER["QUERY_STRING"]; 611 $query = $_SERVER["QUERY_STRING"];
640 $cache = new CachedPage( 612 $cache = new CachedPage(
641 $GLOBALS['config']['PAGECACHE'], 613 $GLOBALS['config']['PAGECACHE'],
642 pageUrl(), 614 page_url($_SERVER),
643 startsWith($query,'do=rss') && !isLoggedIn() 615 startsWith($query,'do=rss') && !isLoggedIn()
644 ); 616 );
645 $cached = $cache->cachedVersion(); 617 $cached = $cache->cachedVersion();
@@ -668,7 +640,7 @@ function showRSS()
668 $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ; 640 $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ;
669 } 641 }
670 642
671 $pageaddr=escape(indexUrl()); 643 $pageaddr=escape(index_url($_SERVER));
672 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">'; 644 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
673 echo '<channel><title>'.$GLOBALS['title'].'</title><link>'.$pageaddr.'</link>'; 645 echo '<channel><title>'.$GLOBALS['title'].'</title><link>'.$pageaddr.'</link>';
674 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n"; 646 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
@@ -706,7 +678,7 @@ function showRSS()
706 echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable($link['description']))).$descriptionlink.']]></description>'."\n</item>\n"; 678 echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable($link['description']))).$descriptionlink.']]></description>'."\n</item>\n";
707 $i++; 679 $i++;
708 } 680 }
709 echo '</channel></rss><!-- Cached version of '.escape(pageUrl()).' -->'; 681 echo '</channel></rss><!-- Cached version of '.escape(page_url($_SERVER)).' -->';
710 682
711 $cache->cache(ob_get_contents()); 683 $cache->cache(ob_get_contents());
712 ob_end_flush(); 684 ob_end_flush();
@@ -727,7 +699,7 @@ function showATOM()
727 $query = $_SERVER["QUERY_STRING"]; 699 $query = $_SERVER["QUERY_STRING"];
728 $cache = new CachedPage( 700 $cache = new CachedPage(
729 $GLOBALS['config']['PAGECACHE'], 701 $GLOBALS['config']['PAGECACHE'],
730 pageUrl(), 702 page_url($_SERVER),
731 startsWith($query,'do=atom') && !isLoggedIn() 703 startsWith($query,'do=atom') && !isLoggedIn()
732 ); 704 );
733 $cached = $cache->cachedVersion(); 705 $cached = $cache->cachedVersion();
@@ -756,7 +728,7 @@ function showATOM()
756 $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ; 728 $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ;
757 } 729 }
758 730
759 $pageaddr=escape(indexUrl()); 731 $pageaddr=escape(index_url($_SERVER));
760 $latestDate = ''; 732 $latestDate = '';
761 $entries=''; 733 $entries='';
762 $i=0; 734 $i=0;
@@ -794,7 +766,7 @@ function showATOM()
794 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">'; 766 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
795 $feed.='<title>'.$GLOBALS['title'].'</title>'; 767 $feed.='<title>'.$GLOBALS['title'].'</title>';
796 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.escape($latestDate).'</updated>'; 768 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.escape($latestDate).'</updated>';
797 $feed.='<link rel="self" href="'.escape(serverUrl().$_SERVER["REQUEST_URI"]).'" />'; 769 $feed.='<link rel="self" href="'.escape(server_url($_SERVER).$_SERVER["REQUEST_URI"]).'" />';
798 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) 770 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
799 { 771 {
800 $feed.='<!-- PubSubHubbub Discovery -->'; 772 $feed.='<!-- PubSubHubbub Discovery -->';
@@ -804,7 +776,7 @@ function showATOM()
804 $feed.='<author><name>'.$pageaddr.'</name><uri>'.$pageaddr.'</uri></author>'; 776 $feed.='<author><name>'.$pageaddr.'</name><uri>'.$pageaddr.'</uri></author>';
805 $feed.='<id>'.$pageaddr.'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do. 777 $feed.='<id>'.$pageaddr.'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
806 $feed.=$entries; 778 $feed.=$entries;
807 $feed.='</feed><!-- Cached version of '.escape(pageUrl()).' -->'; 779 $feed.='</feed><!-- Cached version of '.escape(page_url($_SERVER)).' -->';
808 echo $feed; 780 echo $feed;
809 781
810 $cache->cache(ob_get_contents()); 782 $cache->cache(ob_get_contents());
@@ -821,7 +793,7 @@ function showDailyRSS() {
821 $query = $_SERVER["QUERY_STRING"]; 793 $query = $_SERVER["QUERY_STRING"];
822 $cache = new CachedPage( 794 $cache = new CachedPage(
823 $GLOBALS['config']['PAGECACHE'], 795 $GLOBALS['config']['PAGECACHE'],
824 pageUrl(), 796 page_url($_SERVER),
825 startsWith($query,'do=dailyrss') && !isLoggedIn() 797 startsWith($query,'do=dailyrss') && !isLoggedIn()
826 ); 798 );
827 $cached = $cache->cachedVersion(); 799 $cached = $cache->cachedVersion();
@@ -866,7 +838,7 @@ function showDailyRSS() {
866 838
867 // Build the RSS feed. 839 // Build the RSS feed.
868 header('Content-Type: application/rss+xml; charset=utf-8'); 840 header('Content-Type: application/rss+xml; charset=utf-8');
869 $pageaddr = escape(indexUrl()); 841 $pageaddr = escape(index_url($_SERVER));
870 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">'; 842 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
871 echo '<channel>'; 843 echo '<channel>';
872 echo '<title>Daily - '. $GLOBALS['title'] . '</title>'; 844 echo '<title>Daily - '. $GLOBALS['title'] . '</title>';
@@ -879,7 +851,7 @@ function showDailyRSS() {
879 foreach ($days as $day => $linkdates) { 851 foreach ($days as $day => $linkdates) {
880 $daydate = linkdate2timestamp($day.'_000000'); // Full text date 852 $daydate = linkdate2timestamp($day.'_000000'); // Full text date
881 $rfc822date = linkdate2rfc822($day.'_000000'); 853 $rfc822date = linkdate2rfc822($day.'_000000');
882 $absurl = escape(indexUrl().'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page. 854 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
883 855
884 // Build the HTML body of this RSS entry. 856 // Build the HTML body of this RSS entry.
885 $html = ''; 857 $html = '';
@@ -893,7 +865,7 @@ function showDailyRSS() {
893 $l['thumbnail'] = thumbnail($l['url']); 865 $l['thumbnail'] = thumbnail($l['url']);
894 $l['timestamp'] = linkdate2timestamp($l['linkdate']); 866 $l['timestamp'] = linkdate2timestamp($l['linkdate']);
895 if (startsWith($l['url'], '?')) { 867 if (startsWith($l['url'], '?')) {
896 $l['url'] = indexUrl() . $l['url']; // make permalink URL absolute 868 $l['url'] = index_url($_SERVER) . $l['url']; // make permalink URL absolute
897 } 869 }
898 $links[$linkdate] = $l; 870 $links[$linkdate] = $l;
899 } 871 }
@@ -909,7 +881,7 @@ function showDailyRSS() {
909 881
910 echo $html . PHP_EOL; 882 echo $html . PHP_EOL;
911 } 883 }
912 echo '</channel></rss><!-- Cached version of '. escape(pageUrl()) .' -->'; 884 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
913 885
914 $cache->cache(ob_get_contents()); 886 $cache->cache(ob_get_contents());
915 ob_end_flush(); 887 ob_end_flush();
@@ -1201,7 +1173,7 @@ function renderPage()
1201 { 1173 {
1202 $PAGE = new pageBuilder; 1174 $PAGE = new pageBuilder;
1203 $PAGE->assign('linkcount',count($LINKSDB)); 1175 $PAGE->assign('linkcount',count($LINKSDB));
1204 $PAGE->assign('pageabsaddr',indexUrl()); 1176 $PAGE->assign('pageabsaddr',index_url($_SERVER));
1205 $PAGE->renderPage('tools'); 1177 $PAGE->renderPage('tools');
1206 exit; 1178 exit;
1207 } 1179 }
@@ -1767,7 +1739,7 @@ function buildLinkList($PAGE,$LINKSDB)
1767 1739
1768 if ($link["url"][0] === '?' && // Check for both signs of a note: starting with ? and 7 chars long. I doubt that you'll post any links that look like this. 1740 if ($link["url"][0] === '?' && // Check for both signs of a note: starting with ? and 7 chars long. I doubt that you'll post any links that look like this.
1769 strlen($link["url"]) === 7) { 1741 strlen($link["url"]) === 7) {
1770 $link["url"] = indexUrl() . $link["url"]; 1742 $link["url"] = index_url($_SERVER) . $link["url"];
1771 } 1743 }
1772 1744
1773 $linkDisp[$keys[$i]] = $link; 1745 $linkDisp[$keys[$i]] = $link;
@@ -1902,7 +1874,7 @@ function computeThumbnail($url,$href=false)
1902 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL. 1874 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1903 } 1875 }
1904 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) 1876 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
1905 return array('src'=>indexUrl().'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), 1877 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1906 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); 1878 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1907 } 1879 }
1908 1880
@@ -1913,7 +1885,7 @@ function computeThumbnail($url,$href=false)
1913 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') 1885 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1914 { 1886 {
1915 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) 1887 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
1916 return array('src'=>indexUrl().'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), 1888 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1917 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); 1889 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1918 } 1890 }
1919 return array(); // No thumbnail. 1891 return array(); // No thumbnail.
@@ -1999,11 +1971,11 @@ function install()
1999 if (!isset($_SESSION['session_tested'])) 1971 if (!isset($_SESSION['session_tested']))
2000 { // Step 1 : Try to store data in session and reload page. 1972 { // Step 1 : Try to store data in session and reload page.
2001 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session. 1973 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
2002 header('Location: '.indexUrl().'?test_session'); // Redirect to check stored data. 1974 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
2003 } 1975 }
2004 if (isset($_GET['test_session'])) 1976 if (isset($_GET['test_session']))
2005 { // Step 3: Sessions are OK. Remove test parameter from URL. 1977 { // Step 3: Sessions are OK. Remove test parameter from URL.
2006 header('Location: '.indexUrl()); 1978 header('Location: '.index_url($_SERVER));
2007 } 1979 }
2008 1980
2009 1981
@@ -2020,7 +1992,7 @@ function install()
2020 $GLOBALS['login'] = $_POST['setlogin']; 1992 $GLOBALS['login'] = $_POST['setlogin'];
2021 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. 1993 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
2022 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); 1994 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
2023 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.escape(indexUrl()) : $_POST['title'] ); 1995 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.escape(index_url($_SERVER)) : $_POST['title'] );
2024 $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']); 1996 $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']);
2025 try { 1997 try {
2026 writeConfig($GLOBALS, isLoggedIn()); 1998 writeConfig($GLOBALS, isLoggedIn());