I need bit help as I am facing two issues.
Links without domain extension (.com, .net, ect) will be stored in
database as single words
Script allows for self shortening the shortner url which is a major
issue.
How can I
Check for domain extension else fail submit
and
Check if user is trying to shorten my own link and fail as well.
My code:
function remove_http($url)
{
$disallowed = array('http://', 'https://', 'http//', 'https//');
foreach($disallowed as $d) {
if(strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
$url_to_shorten = get_magic_quotes_gpc() ? stripslashes(trim($_REQUEST['url'])) : trim($_REQUEST['url']);
if(!empty($url_to_shorten) || parse_url($url_to_shorten, PHP_URL_SCHEME) )
{
require('framework/core/config.xml.php');
// check if the URL has already been shortened
$already_shortened = mysql_result(mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string(remove_http($url_to_shorten)) . '"'), 0);
if(!empty($already_shortened))
{
// URL has already been shortened
$shortened_url = getShortenedURLFromID($already_shortened);
}
else
{
// URL not in database, insert
mysql_query('LOCK TABLES ' . DB_TABLE . ' WRITE;');
mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, created, creator) VALUES ("' . mysql_real_escape_string(remove_http($url_to_shorten)) . '", "' . time() . '", "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '")');
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
}
echo BASE_HREF . $shortened_url;
}
function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$length = strlen($base);
while($integer > $length - 1)
{
$out = $base[fmod($integer, $length)] . $out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out;
}
Related
I recenlythave tried to convert the preg_replace() line to preg_replace_callback, but with no success. I did try the methods on Stackoverflow, but they seem to be different.
Hope I could get some help with it.
function ame_process_bbcode(&$parser, &$param1, $param2 = '')
{
if (class_exists('vB_BbCodeParser_Wysiwyg') AND is_a($parser, 'vB_BbCodeParser_Wysiwyg'))
{
return $text;
}
else
{
global $vbulletin;
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_start')) ? eval($hook) : false;
$ameinfo = fetch_full_ameinfo();
$text = preg_replace($ameinfo['find'], $ameinfo['replace'], ($param2 ? $param2 : $param1), 1);
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_end')) ? eval($hook) : false;
return $text;
}
}
Updates: Thanks to #Barmar, I know now that the issue is related to the fetch_full_ameinfo function.. I will add function below. Maybe it will help others in the long run. I will also include the fix whenever I am done. Thanks to #Barmar for the help.
function &fetch_full_ameinfo($findonly = false, $refresh = false)
{
global $db, $vbulletin, $vbphrase, $stylevar;
static $ameinfo = array();
static $inied, $lastfind;
if ($refresh)
{
$inied = false;
}
if ($lastfind && !$findonly)
{
$inied = false;
$ameinfo = array();
}
if (!$inied)
{
if (!$refresh AND $vbulletin->options['automediaembed_cache'])
{
$path = $vbulletin->options['automediaembed_cache_path'];
if (file_exists($path . "findonly.php"));
{
if ($findonly)
{
include($path . "findonly.php");
}
else
{
include($path . "ameinfo.php");
}
$inied = true;
$lastfind = $findonly;
return $ameinfo;
}
}
if ($vbulletin->options['automediaembed_resolve'])
{
$embed = ",IF(extraction=1 AND embedregexp!= '', embedregexp, '') as embedregexp, IF(extraction=1 AND validation!= '', validation, '') as validation";
$embedwhere = " AND ((extraction = 0 AND embedregexp = '') OR (extraction = 1)) ";
}
else
{
$embedwhere = " AND embedregexp = ''";
}
$sql = "SELECT findcode" . (!$findonly ? ", replacecode,title,container,ameid" : ",extraction$embed") . " FROM " . TABLE_PREFIX . "automediaembed WHERE status=1 $embedwhere
ORDER BY displayorder, title ASC";
$results = $db->query_read_slave($sql);
while ($result = $db->fetch_array($results))
{
if ($result['findcode'])
{
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~ie";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'\\1\', \'\\2\', \'\\3\', \'\\4\', \'\\5\', \'\\6\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~ie";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~ie";
$ameinfo['replace'][] = 'ame_match("\1", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("\1", "\2", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
}
}
$inied = true;
}
$lastfind = $findonly;
return $ameinfo;
}
You can't put the replacement function in fetch_full_ameinfo(), because it needs to refer to the $param1 and $param2 variables, which are local to this function.
This means it needs to use eval() in the current function (this is essentially what preg_replace() does internally when it processes the /e flag).
You need to change the replacement string that fetch_full_ameinfo() creates so that it uses a variable instead of \1, \2, etc. to refer to the capture groups, because the callback function receives the captured matches as an array. So replace the block beginning with if (!$findonly) with this:
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~i";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'$match[1]\', \'$match[2]\', \'$match[3]\', \'$match[4]\', \'$match[5]\', \'$match[6]\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~i";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~i";
$ameinfo['replace'][] = 'ame_match("$match[1]", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("$match[1]", "$match[2]", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
Then change your code to:
$text = preg_replace_callback($ameinfo['find'], function($match) use (&$param1, &$param2, &$ameinfo) {
return eval($ameinfo['replace']);
}, ($param2 ? $param2 : $param1), 1);
I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -
$post_name = $this->input->post('post_title');
function clean($post_name) {
$name = trim($post_name);
$post_name = str_replace(' ', '-', $name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url = clean($post_name);
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
I am getting output as -
post-url
post-url-1
post-url-1-1
post-url-1-1-1
But I want output as -
post-url
post-url-1
post-url-2
post-url-3
What is a problem in my code?
Please help me.
Thanks.
function UniqueSlugGenerator($p){
include("conn.php");
$RowCou=0;
$slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p))));
$qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn));
$RowCou = mysqli_num_rows($qq);
return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug;
}
Change your code in the following way
$post_url = clean($post_name);
$post_url1 = $post_url;
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
$post_url = $post_url1;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
I have strange problem with PHP. When I set the string like '<' and if I make new string with few strings then when is go to '<' is stop to working and go to next row of the script
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '>?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '<?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '=?';
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
$this->_where = ' WHERE ' . $column . chr(0x3c) . '?';
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
And the result is:
1< WHERE id c
And my question is why less < is cannot get like string. The > and = operators is OK. But the < just is not recognize. What I'm doing wrong?
Remove one line and it will work (test one below yourself):-
<?php
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors',1); // display those if any happen
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?'; // added space
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?'; // added space
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?'; // added space
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
//$this->_where = ' WHERE ' . $column . chr(0x3c) . '?'; remove this line
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
Note:-
Reason for not working:-
You have to add spaces too to make it correct(commented by #RiggsFolly) (For browser showing sake)
You are just over-writing your conditions. (commented and example by #JonStirling :- https://3v4l.org/vCO5Z) (for working purpose)
In this line:
$this->_where = ' WHERE ' . $column . chr(0x3e) . '?';
you overwrite your all previous changes so no wonder you can not see right result
Please try with this function and let me know will it gives you desired output
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?';
} else {
$this->_where = ' WHERE ' . $column . $operator . ' ?';
}
if($this->_where != '')
{
$this->_where .= ' and ' . $column . chr(0x3e) . ' ?';
}
else
{
$this->_where = ' WHERE ' . $column . chr(0x3e) . ' ?';
}
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
i have a code to shorten multiple links but that code ( with an Optional Suffix ) the code is work from the second link only:
$url_to_shorten = $_POST[links];
$ownshuff = $_POST[shuff];
$theurls = explode("\n",$url_to_shorten);
foreach($theurls as $urlmulti){
shortcreate($urlmulti,$shuffss,$ownshuff);
}
here is an example :
my links are
http://www.123.com
http://www.1234.com
http://www.1235.com
and my Suffix is : ( Hello_Man ).
with the above code it prints
http://www.mysite.com/IUo
http://www.mysite.com/kOl-Hello_Man
http://www.mysite.com/Rww-Hello_Man
and it not print the Suffix for the first link.
the shortcreate function is :
function shortcreate($url_long, $Suffix, $ownshuf){
global $db;
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
$url = $url_long;
$url = trim($url);
$url = mysql_real_escape_string($url);
if (!shortisThere($url)) {
$q = "INSERT INTO `shorturls` (url, unique_chars) VALUES ('" . $url . "', '" . $chars . "')";
//echo $q;
$r = $db->query($q);
if (mysql_affected_rows()):
$q = "SELECT * FROM `shorturls` WHERE `url`='" . $url . "'";
$r = $db->query($q);
$row = $db->fetch($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
else:
$the_url = NULL;
return false;
endif;
}
else {
$q = "SELECT * FROM `shorturls` WHERE `url` = '" . $url . "'";
$r = mysql_query($q);
$row = mysql_fetch_row($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
}
}
i need that code to work for all the links. any help
regards
I guess that the problem is in the next block of code:
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
You give the $chars variable the value of the suffix and you check if it's unique (guess not because it's getting into the loop) and that condition of $ownshuf != "" returns false from some reason (consider to share with us what's that parameter's value), otherwise the output of $chars would return a string with "-".
REMINDER: Share with us what's that parameter's value
My language bar generation function looks like that. It works, but, feels like, it's not optimal way and this function has bunch of extra lines that can be removed. How you'd minify it?
public function generateLangs($url, $curlang, $langs) {
$i = 0;
$countlng = count($langs);
foreach ($langs as $lang) {
if (strstr($url, '?')) {
if (strstr($url, 'lang')) {
$newurl = preg_replace('&lang=(\w+)&', 'lang=' . $lang, $url);
} else {
$newurl = $url . '&lang=' . $lang;
}
}
else {
$newurl = $url . '?lang=' . $lang;
}
$result = '<a ';
if ($curlang == $lang) {
$result .= 'class="active" ';
}
$result .= 'href="' . $newurl . '">' . $lang . '</a>' . "\n";
if ($i != $countlng - 1)
$result .= ' | ';
echo $result;
$i++;
}
}
First of all you could make the language value a parameter of the URL by using a simple placeholder, like %s or %lang%:
$url = 'http://example.com/site/?lang=%lang%';
$newurl = str_replace('%lang%', $lang, $url);
You can either do this or you should encapsulate the logic to replace some query parameter of an URI into a function of it's own and use built-in functions in there instead rolling your own (e.g. parse_url, parse_str, ...).
Similar to that, same applies to your output, you could use the existing index (0 based I guess) and therefore streamline the whole:
public function generateLangs($url, $currentLanguage, $languages)
{
$urlPattern = preg_replace('~^(.*[?&]lang=)([a-z]+)((?:&.*)?)$~', '\1%lang%\3', $url, 1, $count);
$count || $urlPattern .= '?lang=%lang%';
unset($count);
foreach ($languages as $i => $lang)
{
$newUrl = str_replace('%lang%', $lang, $urlPattern);
printf("%s<a href=\"%s\"%s>%s</a>\n", $i ? ' | ' : '', $newUrl,
$curlang === $lang ? ' class="active"' : '', $lang);
}
}
The key point more or less is that you group code next to each other that belongs to each other. This more or less automatically reduces the complexity of the code and therefore often as well it's length. But take care that length is not that crucial, it's more important that you can read it cleanly.