Skip to content

Commit

Permalink
Security fixes. (2017-08-25)
Browse files Browse the repository at this point in the history
Refactored Sanitize::fullUrl to work with all forms of URLs.
Renamed Sanitize::fullUrl to Sanitize::url.

(cherry picked from OHM commit d59c0468fb323de1e175fa5b6c364fe3ec5ac8fe)
  • Loading branch information
kittysnacks committed Sep 29, 2017
1 parent c885bf8 commit fe3eecc
Show file tree
Hide file tree
Showing 23 changed files with 116 additions and 64 deletions.
4 changes: 2 additions & 2 deletions admin/userlti.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function removelti(el,type,id) {
if ($alt==0) {echo "<tr class=even>"; $alt=1;} else {echo "<tr class=odd>"; $alt=0;}
echo '<td>',Sanitize::encodeStringForDisplay($u['org']),'</td>';
echo '<td>',Sanitize::encodeStringForDisplay($u['ltiuserid']),'</td>';
echo '<td><a onclick="return removeuserlti(this,'.$u['id'].')" href="#">';
echo '<td><a onclick="return removeuserlti(this,'.Sanitize::encodeStringForJavascript($u['id']).')" href="#">';
echo _('Remove connection').'</a></td>';
echo '</tr>';
}
Expand All @@ -147,7 +147,7 @@ function removelti(el,type,id) {
echo '<td>',Sanitize::encodeStringForDisplay($u['courseid']),'</td>';
echo '<td>',Sanitize::encodeStringForDisplay($u['org']),'</td>';
echo '<td>',Sanitize::encodeStringForDisplay($u['contextid']),'</td>';
echo '<td><a onclick="return removecourselti(this,'.$u['id'].')" href="#">';
echo '<td><a onclick="return removecourselti(this,'.Sanitize::encodeStringForJavascript($u['id']).')" href="#">';
echo _('Remove connection').'</a></td>';
echo '</tr>';
}
Expand Down
5 changes: 3 additions & 2 deletions assessment/showtest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3532,8 +3532,9 @@ function showscores($questions,$attempts,$testsettings) {
$stm = $DBH->prepare("SELECT * from imas_users WHERE id=:id");
$stm->execute(array(':id'=>$userid));
$userinfo = $stm->fetch(PDO::FETCH_ASSOC);
echo "<h3>{$userinfo['LastName']}, {$userinfo['FirstName']}: ";
echo substr($userinfo['SID'],0,strpos($userinfo['SID'],'~'));
printf("<h3>%s, %s: ", Sanitize::encodeStringForDisplay($userinfo['LastName']),
Sanitize::encodeStringForDisplay($userinfo['FirstName']));
echo Sanitize::encodeStringForDisplay(substr($userinfo['SID'],0,strpos($userinfo['SID'],'~')));
echo "</h3>\n";
}

Expand Down
8 changes: 4 additions & 4 deletions assessment/watchvid.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
}
$doembed = true;
$videoUrl = $urlmode.'www.youtube.com/embed/'.$vidid.$timestart;
$out = '<iframe width="640" height="510" src="'.Sanitize::fullUrl($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
$out = '<iframe width="640" height="510" src="'.Sanitize::url($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
}
if (strpos($url,'youtu.be/')!==false) {
//youtube
Expand All @@ -60,14 +60,14 @@
}
$doembed = true;
$videoUrl = $urlmode.'www.youtube.com/embed/'.$vidid.$timestart;
$out = '<iframe width="640" height="510" src="'.Sanitize::fullUrl($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
$out = '<iframe width="640" height="510" src="'.Sanitize::url($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
}
if (strpos($url,'vimeo.com/')!==false) {
//youtube
$vidid = substr($url,strpos($url,'.com/')+5);
$doembed = true;
$videoUrl = 'http://player.vimeo.com/video/'.$vidid;
$out = '<iframe width="640" height="510" src="'.Sanitize::fullUrl($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
$out = '<iframe width="640" height="510" src="'.Sanitize::url($videoUrl).'" frameborder="0" allowfullscreen></iframe>';
}
if ($doembed) {
echo '<html><head><title>Video</title>';
Expand All @@ -77,6 +77,6 @@
echo '</head>';
echo '<body>'.$out.'</body></html>';
} else {
header("Location:". Sanitize::fullUrl($url));
header("Location:". Sanitize::url($url));
}
?>
2 changes: 1 addition & 1 deletion course/addassessment.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
$cid, Sanitize::encodeStringForDisplay($coursename));
$body .= sprintf("&gt; <a href=\"addassessment.php?cid=%s&id=%d\">Modify Assessment</a> &gt; Clear Attempts</div>\n",
$cid, Sanitize::onlyInt($_GET['id']));
$body .= sprintf("<h3>%s</h3>", $assessmentname);
$body .= sprintf("<h3>%s</h3>", Sanitize::encodeStringForDisplay($assessmentname));
$body .= "<p>Are you SURE you want to delete all attempts (grades) for this assessment?</p>";
$body .= '<form method="POST" action="'.sprintf('addassessment.php?cid=%s&id=%d',$cid, Sanitize::onlyInt($_GET['id'])).'">';
$body .= '<p><button type=submit name=clearattempts value=confirmed>'._('Yes, Clear').'</button>';
Expand Down
4 changes: 2 additions & 2 deletions course/addgrades.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
echo '<p><button type=submit name=confirm value=true>'._('Delete Item').'</button>';

printf(" <input type=button value=\"Nevermind\" class=\"secondarybtn\" onClick=\"window.location='addgrades.php?stu=%s&cid=%s&gbitem=%d&grades=all'\" />",
Sanitize::encodeUrlParam($_GET['stu']), $cid, $_GET['del']);

Sanitize::encodeUrlParam($_GET['stu']), $cid, Sanitize::encodeUrlParam($_GET['del']));
echo '</p></form>';
require("../footer.php");
exit;
Expand Down
4 changes: 2 additions & 2 deletions course/course.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,14 @@
//DB $sendcrumb .= "<a href=\"course.php?cid=$cid&folder={$backtrack[$i][1]}\">".stripslashes($backtrack[$i][0]).'</a>';
$sendcrumb .= "<a href=\"course.php?cid=$cid&folder={$backtrack[$i][1]}\">".Sanitize::encodeStringForDisplay($backtrack[$i][0]).'</a>';
//DB $curBreadcrumb .= stripslashes($backtrack[$i][0]);
$curBreadcrumb .= $backtrack[$i][0];
$curBreadcrumb .= Sanitize::encodeStringForDisplay($backtrack[$i][0]);
if ($i!=count($backtrack)-1) {
$curBreadcrumb .= "</a>";
}
}
$curname = $backtrack[count($backtrack)-1][0];
if (count($backtrack)>$depth) {
$backlink = "<span class=right><a href=\"course.php?cid=$cid&folder=".$backtrack[count($backtrack)-2][1]."\">" . _('Back') . "</a></span><br class=\"form\" />";
$backlink = "<span class=right><a href=\"course.php?cid=$cid&folder=".Sanitize::encodeUrlParam($backtrack[count($backtrack)-2][1])."\">" . _('Back') . "</a></span><br class=\"form\" />";
}
$_SESSION['backtrack'] = array($sendcrumb,$backtrack[count($backtrack)-1][1]);

Expand Down
7 changes: 6 additions & 1 deletion course/courseshowitems.php
Original file line number Diff line number Diff line change
Expand Up @@ -1540,6 +1540,9 @@ function generateadditem($blk,$tb) {
$html = '<div class="additembox"><span><b>' . _('Add here:') . '</b> ';
}

$blk = Sanitize::encodeUrlParam($blk);
$tb = Sanitize::encodeUrlParam($tb);

$html .= "<a href=\"addassessment.php?block=$blk&tb=$tb&cid=$cid\">";
if (isset($CFG['CPS']['miniicons']['assess'])) {
$html .= "<img alt=\"assessment\" class=\"mida\" src=\"$imasroot/img/{$CFG['CPS']['miniicons']['assess']}\"/> ";
Expand Down Expand Up @@ -1598,7 +1601,9 @@ function generateadditem($blk,$tb) {
$html .= '</div>';

} else {
$html = "<select name=addtype id=\"addtype$blk-$tb\" onchange=\"additem('$blk','$tb')\" ";
$html = sprintf("<select name=addtype id=\"addtype%s-%s\" onchange=\"additem('%s','%s')\" ",
Sanitize::encodeStringForDisplay($blk), Sanitize::encodeStringForDisplay($tb),
Sanitize::encodeStringForJavascript($blk), Sanitize::encodeStringForJavascript($tb));
if ($tb=='t') {
$html .= 'style="margin-bottom:5px;"';
}
Expand Down
2 changes: 1 addition & 1 deletion course/exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@
<script type="text/javascript">
function nextpage() {
var aid = document.getElementById('aidselect').value;
var togo = '<?php echo Sanitize::fullUrl($address); ?>&aid=' + aid;
var togo = '<?php echo Sanitize::url($address); ?>&aid=' + aid;
window.location = togo;
}
</script>
Expand Down
2 changes: 1 addition & 1 deletion course/moddataset.php
Original file line number Diff line number Diff line change
Expand Up @@ -1279,7 +1279,7 @@ function decboxsize(box) {
if ($extrefpt[0]=='video' && count($extrefpt)>2 && $extrefpt[2]==1) {
echo ' (cc)';
}
echo ', URL: <a href="'.Sanitize::encodeStringForDisplay($extrefpt[1]).'">'.Sanitize::encodeStringForDisplay($extrefpt[1])."</a>. Delete? <input type=\"checkbox\" name=\"delhelp-$i\"/></li>";
echo ', URL: <a href="'.Sanitize::url($extrefpt[1]).'">'.Sanitize::encodeStringForDisplay($extrefpt[1])."</a>. Delete? <input type=\"checkbox\" name=\"delhelp-$i\"/></li>";
}
}
echo '</ul></div>'; //helpbtnlist, helpbtnwrap
Expand Down
2 changes: 1 addition & 1 deletion course/printlayout.php
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ function packheights() {
}
if ($isfinal) {
$licurl = $GLOBALS['basesiteurl'] . '/course/showlicense.php?id=' . implode('-',$qn);
echo '<hr/><p style="font-size:70%">License info at: <a href="'.Sanitize::fullUrl($licurl).'">'.Sanitize::encodeStringForDisplay($licurl).'</a></p>';
echo '<hr/><p style="font-size:70%">License info at: <a href="'.Sanitize::url($licurl).'">'.Sanitize::encodeStringForDisplay($licurl).'</a></p>';
echo "<div class=cbutn><a href=\"course.php?cid=$cid\">Return to course page</a></div>\n";
}
echo "</form>\n";
Expand Down
2 changes: 1 addition & 1 deletion course/printlayoutbare.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@
}
}
$licurl = $GLOBALS['basesiteurl'] . '/course/showlicense.php?id=' . implode('-',$qn);
echo '<hr/><p style="font-size:70%">License info at: <a href="'.Sanitize::fullUrl($licurl).'">'.Sanitize::encodeStringForDisplay($licurl).'</a></p>';
echo '<hr/><p style="font-size:70%">License info at: <a href="'.Sanitize::url($licurl).'">'.Sanitize::encodeStringForDisplay($licurl).'</a></p>';

echo "<div class=cbutn><a href=\"course.php?cid=$cid\">Return to course page</a></div>\n";

Expand Down
2 changes: 1 addition & 1 deletion course/testquestion.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ function chguseinfixed(state) {
$license = array('Copyrighted','IMathAS Community License','Public Domain','Creative Commons Attribution-NonCommercial-ShareAlike','Creative Commons Attribution-ShareAlike');
echo $license[$line['license']];
if ($line['otherattribution']!='') {
echo '<br/>Other Attribution: '.$line['otherattribution'];
echo '<br/>Other Attribution: '.Sanitize::encodeStringForDisplay($line['otherattribution']);
}
echo '</p>';

Expand Down
22 changes: 11 additions & 11 deletions course/treereader.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,13 +312,13 @@ function printlist($items) {
$isopen = true;
}
if ($bisopen) {
$out .= "<li class=lihdr aria-expanded=true ><span class=hdr><span class=btn id=\"b{$item['id']}\">-</span> <img src=\"$imasroot/img/folder_tiny.png\" alt=\"Folder\"> ";
$out .= "<span class=blocklbl>{$item['name']}</span></span>\n";
$out .= '<ul class="nomark" id="'.$item['id'].'">';
$out .= "<li class=lihdr aria-expanded=true ><span class=hdr><span class=btn id=\"b".Sanitize::encodeStringForDisplay($item['id'])."\">-</span> <img src=\"$imasroot/img/folder_tiny.png\" alt=\"Folder\"> ";
$out .= "<span class=blocklbl>".Sanitize::encodeStringForDisplay($item['name'])."</span></span>\n";
$out .= '<ul class="nomark" id="'.Sanitize::encodeStringForDisplay($item['id']).'">';
} else {
$out .= "<li class=lihdr aria-expanded=false><span class=hdr><span class=btn id=\"b{$item['id']}\">+</span> <img src=\"$imasroot/img/folder_tiny.png\" alt=\"Folder\"> ";
$out .= "<span class=blocklbl>{$item['name']}</span></span>\n";
$out .= '<ul class="nomark" id="'.$item['id'].'">';
$out .= "<li class=lihdr aria-expanded=false><span class=hdr><span class=btn id=\"b".Sanitize::encodeStringForDisplay($item['id'])."\">+</span> <img src=\"$imasroot/img/folder_tiny.png\" alt=\"Folder\"> ";
$out .= "<span class=blocklbl>".Sanitize::encodeStringForDisplay($item['name'])."</span></span>\n";
$out .= '<ul class="nomark" id="'.Sanitize::encodeStringForDisplay($item['id']).'">';
}
$out .= $subcontent;
$out .= '</ul></li>';
Expand Down Expand Up @@ -357,10 +357,10 @@ function printlist($items) {
}
if ($viewall || ($line['avail']==1 && $line['startdate']<$now && ($line['enddate']>$now || $line['reviewdate']>$now))) {
if ($openitem=='' && $foundfirstitem=='') {
$foundfirstitem = '/assessment/showtest.php?cid='.$cid.'&amp;id='.$typeid; $isopen = true;
$foundfirstitem = '/assessment/showtest.php?cid='.$cid.'&amp;id='.Sanitize::encodeUrlParam($typeid); $isopen = true;
}
if ($itemtype.$typeid===$openitem) {
$foundopenitem = '/assessment/showtest.php?cid='.$cid.'&amp;id='.$typeid; $isopen = true; $opentxt = ' aria-selected="true" ';
$foundopenitem = '/assessment/showtest.php?cid='.$cid.'&amp;id='.Sanitize::encodeUrlParam($typeid); $isopen = true; $opentxt = ' aria-selected="true" ';
}
$out .= '<li '.$opentxt.'>';
if ($line['displaymethod']!='Embed') {
Expand Down Expand Up @@ -408,7 +408,7 @@ function printlist($items) {
} else {
$onclick = 'onclick="recordlasttreeview(\''.$itemtype.$typeid.'\')"';
}
$out .= '<a tabindex="-1" href="'.$imasroot.'/assessment/showtest.php?cid='.$cid.'&amp;id='.$typeid.'" '.$onclick.' target="readerframe">'.$line['name'].'</a></li>';
$out .= '<a tabindex="-1" href="'.$imasroot.'/assessment/showtest.php?cid='.$cid.'&amp;id='.$typeid.'" '.$onclick.' target="readerframe">'.Sanitize::encodeStringForDisplay($line['name']).'</a></li>';
}
} else if ($line['itemtype']=='LinkedText') {
//TODO check availability, etc.
Expand All @@ -425,7 +425,7 @@ function printlist($items) {
if ($itemtype.$typeid===$openitem) {
$foundopenitem = '/course/showlinkedtext.php?cid='.$cid.'&amp;id='.$typeid; $isopen = true; $opentxt = ' aria-selected="true" ';
}
$out .= '<li '.$opentxt.'><img src="'.$imasroot.'/img/html_tiny.png" alt="Link"> <a tabindex="-1" href="showlinkedtext.php?cid='.$cid.'&amp;id='.$typeid.'" onclick="recordlasttreeview(\''.$itemtype.$typeid.'\')" target="readerframe">'.$line['title'].'</a></li>';
$out .= '<li '.$opentxt.'><img src="'.$imasroot.'/img/html_tiny.png" alt="Link"> <a tabindex="-1" href="showlinkedtext.php?cid='.$cid.'&amp;id='.Sanitize::encodeUrlParam($typeid).'" onclick="recordlasttreeview(\''.$itemtype.Sanitize::encodeStringForJavascript($typeid).'\')" target="readerframe">'.Sanitize::encodeStringForDisplay($line['title']).'</a></li>';
}
} /*else if ($line['itemtype']=='Forum') {
//TODO check availability, etc.
Expand Down Expand Up @@ -454,7 +454,7 @@ function printlist($items) {
if ($itemtype.$typeid===$openitem) {
$foundopenitem = '/wikis/viewwiki.php?cid='.$cid.'&amp;id='.$typeid.'&framed=true'; $isopen = true; $opentxt = ' aria-selected="true" ';
}
$out .= '<li '.$opentxt.'><img src="'.$imasroot.'/img/wiki_tiny.png" alt="Wiki"> <a tabindex="-1" href="'.$imasroot.'/wikis/viewwiki.php?cid='.$cid.'&amp;id='.$typeid.'&framed=true" onclick="recordlasttreeview(\''.$itemtype.$typeid.'\')" target="readerframe">'.$line['name'].'</a></li>';
$out .= '<li '.$opentxt.'><img src="'.$imasroot.'/img/wiki_tiny.png" alt="Wiki"> <a tabindex="-1" href="'.$imasroot.'/wikis/viewwiki.php?cid='.$cid.'&amp;id='.Sanitize::encodeUrlParam($typeid).'&framed=true" onclick="recordlasttreeview(\''.$itemtype.Sanitize::encodeStringForJavascript($typeid).'\')" target="readerframe">'.Sanitize::encodeStringForDisplay($line['name']).'</a></li>';
}
}

Expand Down
2 changes: 1 addition & 1 deletion course/uploadmultgrades.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ function fopen_utf8 ($filename, $mode) {
if ($data[3]==0) {echo 'selected="selected"';}
echo '>Add as new item</option>';
if ($data[3]>0) {
echo '<option value="'.$data[3].'" selected="selected">Overwrite existing scores</option>';
echo '<option value="'.Sanitize::encodeStringForDisplay($data[3]).'" selected="selected">Overwrite existing scores</option>';
}
echo '</select></td>';
echo '<td><input type="text" size="20" name="colname'.$col.'" value="'.htmlentities($data[0]).'" /></td>';
Expand Down
10 changes: 5 additions & 5 deletions course/viewactionlog.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,11 @@
if (isset($r[3])) {
$r3pts = explode('::',$r[3]);
if (count($r3pts)==2) {
$thelink = '<a href="'.Sanitize::fullUrl($r3pts[0]).'" target="_blank">'.Sanitize::encodeStringForDisplay($r3pts[1]).'</a>';
$href = Sanitize::fullUrl($r3pts[0]);
$thelink = '<a href="'.Sanitize::url($r3pts[0]).'" target="_blank">'.Sanitize::encodeStringForDisplay($r3pts[1]).'</a>';
$href = Sanitize::url($r3pts[0]);
} else {
$thelink = Sanitize::fullUrl($r[3]);
$href = Sanitize::fullUrl($r[3]);
$thelink = Sanitize::url($r[3]);
$href = Sanitize::url($r[3]);
}
}
echo '<tr>';
Expand Down Expand Up @@ -190,7 +190,7 @@
break;
case 'extref':
$p = explode(': ',$r[3]);
echo 'In assessment '.Sanitize::encodeStringForDisplay($exnames[$r[1]]).', clicked help for <a target="_blank" href="'.Sanitize::fullUrl($p[1]).'">'.Sanitize::encodeStringForDisplay($p[0]).'</a>';
echo 'In assessment '.Sanitize::encodeStringForDisplay($exnames[$r[1]]).', clicked help for <a target="_blank" href="'.Sanitize::url($p[1]).'">'.Sanitize::encodeStringForDisplay($p[0]).'</a>';
break;
case 'assessintro':
echo 'In assessment '.Sanitize::encodeStringForDisplay($asnames[$r[1]]).' intro, clicked link to '.$thelink;
Expand Down
2 changes: 1 addition & 1 deletion forums/posthandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@
$sendemail = false;
require("../header.php");
echo '<h2>Error:</h2><p>It looks like the post you were replying to was deleted. Your post is below in case you ';
echo 'want to copy-and-paste it somewhere. <a href="'.Sanitize::fullUrl($returnurl).'">Continue</a></p>';
echo 'want to copy-and-paste it somewhere. <a href="'.Sanitize::url($returnurl).'">Continue</a></p>';
echo '<hr>';
//DB echo '<p>Message:</p><div class="editor">'.filter(stripslashes($_POST['message'])).'</div>';
echo '<p>Message:</p><div class="editor">'.filter($_POST['message']).'</div>';
Expand Down
6 changes: 3 additions & 3 deletions forums/thread.php
Original file line number Diff line number Diff line change
Expand Up @@ -449,11 +449,11 @@
echo '<div id="postreplyinstr" style="display:none;" class="intro">';
if ($postinstr != '') {
echo '<h4>'._('Posting Instructions').'</h4>';
echo $postinstr;
echo Sanitize::encodeStringForDisplay($postinstr);
}
if ($replyinstr != '') {
echo '<h4>'._('Reply Instructions').'</h4>';
echo $replyinstr;
echo Sanitize::encodeStringForDisplay($replyinstr);
}
echo '</div><br/>';
}
Expand Down Expand Up @@ -642,7 +642,7 @@
if ($taglist!='') {
$p = strpos($taglist,':');

$tagselect = 'Filter by '.substr($taglist,0,$p).': ';
$tagselect = 'Filter by '.Sanitize::encodeStringForDisplay(substr($taglist,0,$p)).': ';
$tagselect .= '<select id="tagfilter" onChange="chgtagfilter()"><option value="" ';
if ($tagfilter=='') {
$tagselect .= 'selected="selected"';
Expand Down
1 change: 1 addition & 0 deletions includes/filehandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,7 @@ function deletefilebykey($key) {
}

function deleteallpostfiles($postid) {
$postid = Sanitize::onlyInt($postid);
$delcnt = 0;
if (getfilehandlertype('filehandlertype') == 's3') {
$s3 = new S3($GLOBALS['AWSkey'],$GLOBALS['AWSsecret']);
Expand Down
36 changes: 30 additions & 6 deletions includes/sanitize.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,20 @@ public static function rawurlencodePath($string)
}

/**
* Sanitize a full URL string. This should include the protocol (http/https), port, path,
* and any query parameters.
* An alias for Sanitize::url().
* TODO: Remove this after merges between all repos are complete and all references to fullUrl() are removed.
*
* @param string $url The full URL string.
* @return string A sanitized URL.
* @see url
*/
public static function fullUrl($url) {
return self::url($url);
}

/**
* Sanitize a URL string. At minimum, this must contain a path.
* Optional URL components: protocol (http/https), hostname authentication, port, query parameters, fragments.
*
* Warning: This method is NOT secure if any part of the URL was generated with data obtained from user input!
*
Expand All @@ -184,14 +196,16 @@ public static function rawurlencodePath($string)
* @return string A sanitized URL.
* @see generateQueryStringFromMap
*/
public static function fullUrl($url)
public static function url($url)
{
// Sanitize url parts
$parsed_url = parse_url($url);
$scheme = preg_replace('/[^a-z]/i', '', $parsed_url['scheme']);
$scheme = isset($parsed_url['scheme'])
? preg_replace('/[^a-z]/i', '', $parsed_url['scheme']) : '';
$user = isset($parsed_url['user']) ? rawurlencode($parsed_url['user']) : '';
$pass = isset($parsed_url['pass']) ? rawurlencode($parsed_url['pass']) : '';
$host = preg_replace('/[^\da-z\.-]/i', '', $parsed_url['host']);
$host = isset($parsed_url['host'])
? preg_replace('/[^\da-z\.-]/i', '', $parsed_url['host']) : '';
$port = isset($parsed_url['port']) ? preg_replace('/[^\d]/', '', $parsed_url['port']) : '';
$fragment = isset($parsed_url['fragment']) ? rawurlencode($parsed_url['fragment']) : '';

Expand All @@ -215,7 +229,17 @@ public static function fullUrl($url)
$encoded_query = '' != $encoded_query ? '?' . $encoded_query : '';

// Put it all together.
$safeUrl = sprintf("%s://%s%s%s%s%s%s", $scheme, $auth, $host, $port, $path, $encoded_query, $fragment);
$safeUrl = null;
if ('' != $scheme) {
// A fully formed URL.
$safeUrl = sprintf("%s://%s%s%s%s%s%s", $scheme, $auth, $host, $port, $path, $encoded_query, $fragment);
} elseif ('' != $host) {
// URL beginning with host:port.
$safeUrl = sprintf("//%s%s%s%s%s", $host, $port, $path, $encoded_query, $fragment);
} else {
// URL beginning with path.
$safeUrl = sprintf("%s%s%s", $path, $encoded_query, $fragment);
}

return $safeUrl;
}
Expand Down
Loading

0 comments on commit fe3eecc

Please sign in to comment.