How to do arithmetic operation in .rewriteRule function? - .htaccess

Is this possible to do arithmetic operation in .rewriteRule function?I want to rewrite my url.
From this
/view.php?id=2
To
/?p=6 (id*2+2)

You can use a rewrite map to call an external program, it's going to be a bit slower under heavy load though. The rewrite map can only be defined in the server's config or vhost config, not in an htaccess file. But it can be used in an htaccess file.
So you have a simple script that reads from stdin and does your math:
#!/usr/bin/perl
$| = 1; # Turn off I/O buffering
while (true) {
print <STDIN> * 2 + 2;
}
Then declare the mapping:
RewriteMap math prg:/path/to/script.pl
Then use the mapping in the htaccess file in your document root:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^view\.php$ /?p=${math:%1} [L]

To redirect http://example.com/view.php?id=2 to http://example.com/?p=6 you would do this:
in .htaccess:
RewriteEngine On
RewriteCond %{QUERY_STRING} id=([0-9]*)
RewriteRule view.php calc.php?id=%1 [L]
And in calc.php:
<?php
$base_url = 'http://example.com/?p=';
$id = $_GET['id'];
$new_id = $id * 2 + 2;
$url = $base_url.$new_id;
header("Location: $url");
exit();

Related

eslint enforce space after the single-line-if parentheses

I'm quite new to ESLint and I couldn't find a rule that does what I want. Consider the following code:
if(someCondition)i++;
I want to enforce a single space after the parentheses, so that we should have the following instead:
if(someCondition) i++;
However I simply couldn't find such a rule; it's not space-before-function-paren (obviously), keyword-spacing (which only affects the spacing after if) or space-before-blocks (since this is a single-line-if, there's no block). Please help. Thanks!
P.S. Same rule should apply to single-line-while as well.
https://github.com/eslint/eslint/discussions/15267#discussioncomment-1597748
I think we don't have that rule in the core.
keyword-spacing can disallow if (foo)return;, space-before-blocks can disallow if (foo){, but it seems that there is no rule that would disallow if (foo)bar; and enforce if (foo) bar;
Simple, but effective:
$ cat input
if (condition)i++;
if (condition)i--
while ( this ^ foo || bar )continue
for (true ||
true )z--
Naive solution, but probably ok.
$ cat input | busybox sed -e 's/)\([a-zA-Z_]\)/) \1/'
if (condition) i++;
if (condition) i--
while ( this ^ foo || bar ) continue
for (true ||
true ) z--
This will put a space between ) and the first letter of a variable name (a-z_).
Consider my answer here (and others') for tips on how to process all files that contain the undesired pattern:
https://unix.stackexchange.com/questions/675881/remove-trailing-spaces-from-text-files-only-when-necessary/676367#676367

Perl URL replace

I am trying to achieve following task,
Extract all urls from the text.
If domain belongs to white list, then replace them with modified urls.
Following is the code.
$text = '<img src="http://www.testurl.de/Sasdfhopr.jpg" width="80%">';
$regex = '(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?';
#whiteList = ("www.amazon.de");
while ($text =~ /$regex/g) {
# regex result has following groups as matches
# $1 = scheme
# $2 = domain
# $3 = query parameters
# check if domain is in white list
if ( grep( /^$2$/, #whiteList ) ) {
# build new url
$new = "http://test.xyz.pqr/url=".$1."://".$2.$3;
# recreate old url
$old = $1."://".$2.$3;
# replace it here, but its not replacing
$text =~ s/$old/$new/g;
# but as an example replacing
# domain name with test, its working.
# it appears to be something to with back slash or forward
# slashes
$text =~ s/$2/test/g;
}
} print $text;
Any help or hint would be great. As I am new to perl programming.
I would use Regexp::Common in conjunction with Regexp::Common::URI to locate the URLs, and
URI to parse and transform them
Your very minimal data sample doesn't help, but here is a proof of my idea using that data
use strict;
use warnings 'all';
use Regexp::Common 'URI';
use URI;
use List::Util 'any';
use constant NEW_HOST => 'test.xyz.pqr';
my $text = <<'END';
<a href="http://www.amazon.de/Lenovo-Moto-Smartphone-Android-schwarz/dp/B01FLZC8ZI">
<img src="http://www.testurl.de/Sasdfhopr.jpg" width="80%">
</a>
END
my #white_list = qw/ www.amazon.de /;
$text =~ s{ ( $RE{URI}{HTTP} ) } {
my $uri = URI->new($1);
my $host = $uri->host;
$uri->host(NEW_HOST) if any { $host eq $_ } #white_list;
$uri->as_string;
}exg;
print $text, "\n";
output
<a href="http://test.xyz.pqr/Lenovo-Moto-Smartphone-Android-schwarz/dp/B01FLZC8ZI">
<img src="http://www.testurl.de/Sasdfhopr.jpg" width="80%">
</a>
The URL in $old contains characters that Perl's regex engine treats as part of the pattern, not as literal characters, when you use it inside the pattern match.
$text =~ s/$old/$new/g;
You need to escape those. You can do that with the \Q and \E commands.
$text =~ s/\Q$old\E/$new/g;
That should do the trick, assuming the rest of your code is working, which I have not tried.

Can't understand this error using Xcart [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
We have a website which is built on Xcart 5.2. I imported database on my local system then I set database configuration under rootfolder/etc/config.php after that when I go to site using url "localhost/FSM/"
It showing :-
config.php
; <?php /*
; WARNING: Do not change the line above
;
; +-------------------------------------+
; | X-Cart 5 configuration file |
; +-------------------------------------+
;
; -----------------
; About this file
; -----------------
;
;
; ----------------------
; SQL Database details
; ----------------------
;
[database_details]
hostspec = "localhost"
socket = "/opt/lampp/var/mysql/mysql.sock"
port = "3306"
database = "florist_singapore"
username = "root"
password = ""
table_prefix = "xc_"
;
; ----------------------
; Cache settings
; ----------------------
;
[cache]
; Type of cache used. Can take auto, memcache, apc, xcache, file values.
type=file
; Cache namespace
namespace=XLite
; List of memcache servers. Semicolon is used as a delimiter.
; Each server is specified with a host name and port number, divided
; by a colon. If the port is not specified, the default
; port 11211 is used.
servers=
;
; -----------------------------------------------------------------------
; X-Cart 5 HTTP & HTTPS host, web directory where cart installed
; and allowed domains
; -----------------------------------------------------------------------
;
; NOTE:
; You should put here hostname ONLY without http:// or https:// prefixes
; Do not put slashes after the hostname
; Web dir is the directory in the URL, not the filesystem path
; Web dir must start with slash and have no slash at the end
; The only exception is when you configure for the root of the site,
; in which case you write single slash in it
; Domains should be listed separated by commas.
;
; WARNING: Do not set the "$" sign before the parameter names!
;
; EXAMPLE 1:
;
; http_host = "www.yourhost.com"
; https_host = "www.securedirectories.com/yourhost.com"
; web_dir = "/shop"
; domains = "www.yourhost2.com,yourhost3.com"
;
; will result in the following URLs:
;
; http://www.yourhost.com/shop
; https://www.securedirectories.com/yourhost.com/shop
;
;
; EXAMPLE 2:
;
; http_host = "www.yourhost.com"
; https_host = "www.yourhost.com"
; web_dir = "" (don't use "/")
;
; will result in the following URLs:
;
; http://www.yourhost.com
; https://www.yourhost.com
;
[host_details]
http_host = "localhost"
https_host = "localhost"
web_dir = "/FSM"
domains = ""
[clean_urls]
; String with one or more chars.
; It will be used to autogenerate clean URLs.
; By default, only the "-" or "_" characters are allowed.
; Empty string is also allowed.
default_separator = "-"
; Get clean URLs capitalized for every starting letter of a word
capitalize_words = Off
; Use canonical URL for product page
use_canonical_urls_only = On
;
; -----------------
; Logging details
; -----------------
;
[log_details]
type = file
name = "var/log/xlite.log.php"
level = LOG_WARNING
ident = "XLite"
suppress_errors = On
suppress_log_errors = Off
;
; Skin details
;
[skin_details]
skin = default
locale = en
;
; Default image settings
;
[images]
default_image = "images/no_image.png"
default_image_width = 110
default_image_height = 110
unsharp_mask_filter_on_resize = off
; Installation path of Image Magick executables:
; for example:
; image_magick_path = "C:\\Program Files\\ImageMagick-6.7.0-Q16\\" (in Windows)
; image_magick_path = "/usr/local/imagemagick/" (in Unix/Linux )
; You should consult with your hosting provider to find where Image Magick is installed
; If you leave it empty then PHP GD library will be used.
;
image_magick_path =
;
; Installer authcode.
; A person who do not know the auth code can not access the installation script.
; Installation authcode is created authomatically and stored in this section.
;
[installer_details]
auth_code = "3JT6GWX7"
shared_secret_key = "55a77ea79a7c93.31452261"
;
; Some options to optimize the store
;
[performance]
developer_mode = Off
skins_cache = off
compress_php_core = off
;
; Decorator options
;
[decorator]
time_limit = 600
use_tokenizer = Off
disable_software_reset = Off
use_output = Off
quick_data_rebuilding = Off
;
; Error handling options
;
[error_handling]
; Template for error pages
page = "public/error.html"
page_customer = "public/customer/error.html"
; Template for maintenance pages
maintenance = "public/maintenance.html"
;
; Marketplace
;
[marketplace]
url = "http://my.x-cart.com/index.php?q=api"
log_data = Off
upgrade_step_time_limit = 240
banner_url = "http://my.x-cart.com/xcinfo"
;
; Language options
;
[language]
default = en
;
; Installation parameters
;
[installation]
installation_lng = en
;
; AMQP server
;
[amqp]
host = "localhost"
port = "3306"
user = "guest"
password = ""
vhost = "/"
exchange = "xlite"
;
; HTML Purifier options
; See http://htmlpurifier.org/live/configdoc/plain.html for more details on HTML Purifier options
;
[html_purifier]
; Allow link 'target' attribute
Attr.AllowedFrameTargets = On
; List of allowed values for 'target' attribute
Attr.AllowedFrameTargets[] = _blank
Attr.AllowedFrameTargets[] = _self
Attr.AllowedFrameTargets[] = _top
Attr.AllowedFrameTargets[] = _parent
; Allow 'id' attribute
Attr.EnableID = On
; Allow embed tags
HTML.SafeEmbed = On
; Allow object tags
HTML.SafeObject = On
; Allow iframe tags
HTML.SafeIframe = On
; List of allowed URI (without http:// or https:// part) for iframe tags
; If there are no allowed URIs specified then any src will be allowed for iframe tags
;
; Examples:
;
; URI.SafeIframeRegexp[] = "www.youtube.com/embed/"
; URI.SafeIframeRegexp[] = "www.youtube-nocookie.com/embed/"
; URI.SafeIframeRegexp[] = "player.vimeo.com/video/"
;
; Other options
;
[other]
; Translation drive code - auto / gettext / db
translation_driver = auto
; Event driver code - auto / db / amqp
event_driver = auto
; List of trusted domains.
; This option prevents redirecting to untrusted URLs passed via returnURL parameter.
; Examples:
; trusted_domains = "google.com"
; trusted_domains = "google.com, yahoo.com"
trusted_domains =
; X-Frame-Options value
; For possible values see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
; Examples:
; x_frame_options = 'disabled'
; x_frame_options = 'sameorigin'
x_frame_options = 'sameorigin'
; WARNING: Do not change the line below
; */ ?>
.htaccess at root folder
Options -Indexes
DirectoryIndex cart.php
FileETag none
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
<IfModule mod_rewrite.c>
RewriteEngine on
# #BUG-772 Add HTTP_AUTHORIZATION header for fastCGI (need for XC\Qiwi)
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule (^|/)\. - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^sitemap.xml(\?.+)?$ cart.php?target=sitemap [NC,L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((([/_a-z0-9-]+)/)?([_a-z0-9-]+)/)?([_a-z0-9-]+)(/?)(\.([_a-z0-9-]+))?$ cart.php?url=$5&last=$4&rest=$3&ext=$7 [NC,L,QSA]
RewriteBase /FSM
</IfModule>
<IfModule mod_expires.c>
# Expire images/js/css header
ExpiresActive On
ExpiresDefault A0
# Images expires in 2 weeks
ExpiresByType image/png A1209600
ExpiresByType image/gif A1209600
ExpiresByType image/jpg A1209600
ExpiresByType image/jpeg A1209600
ExpiresByType image/ico A1209600
ExpiresByType image/x-icon A1209600
# CSS/JS now work with dynamic unique query string. 1 year expires
ExpiresByType text/css A31104000
ExpiresByType text/javascript A31104000
ExpiresByType application/javascript A31104000
</IfModule>
# Clean URLs [[[
Options +FollowSymLinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(payment|admin|provider|partner)/
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpe?g|png|js|css|swf|php|ico)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ dispatcher.php [L]
#/Clean URLs
I doubt it may be issue of .htaccess so I shared this files too Please help me to resolve this problem.
Can you please share the var/log/php_errors.log.<date>.php and xlite.log.<date>.php files?
The actual error should be there. Also, yon can set suppress_errors = Off and developer_mode = On in the etc/config.php file and run X-Cart again to see if it shows the actual error right in the browser.
You can check out the http://kb.x-cart.com/en/general_setup/moving_x-cart_to_another_location.html tutorial to see if you've completed each step correctly.

Rewriterule with optional parameter

this is my .htaccess file
..
RewriteRule ^songbook(?:/([a-z]))?/?$ music/songbook.php?char=$1 [L]
with that rule i can use the following url's:
http://www.example.com/songbook
http://www.example.com/songbook/
http://www.example.com/songbook/a
http://www.example.com/songbook/a/
So far so good. The problem occurs when i try the get the char in PHP, like so:
if (isset($_GET['char'])) {
echo 'FOUND a char';
} else {
echo 'there is NO char';
}
For some reason, it always finds a char, even when there is no char provided.
My rewrite rule says that the char is optional, but i guess i'm doing something wrong.
How do i write the rewriterule so that the char is optional so the if condition in PHP works?
Thanks
Problem is that your rewrite rule always defines char in query string even if it's an empty string.
You have two options :
1- Edit your php:
if (isset($_GET['char']) && !empty($_GET['char'])) {
echo 'FOUND a char';
} else {
echo 'there is NO char';
}
2- Edit your .htaccess:
You can change the .htaccess:
RewriteRule ^songbook/?$ music/songbook.php [L]
RewriteRule ^songbook/([a-z])/?$ music/songbook.php?char=$1 [L]

.htaccess Wildcard 301 redirect domain AND subfolders

So, I'm running into this problem with this relatively complicated wildcard 301 redirect. My .htaccess-foo is terrible, so I'm hoping for some help here!
I need to change any uppercase to lowercase.
I need to change "gfoldername" to "g"
I need to replace any "-" with "_"
To show an example, this is what I'm trying to accomplish
example.com/gfoldername/Another-Folder/
to
example.com/g/another_folder/
I've tried quite a bit with no luck. Again, any help is greatly appreciated!
EDIT:
Ended up resolving this myself with php. For those interested:
$urls = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$url = explode('/',$urls);
$f = $url[4];
$f = strtolower($f);
$f = str_replace("-", "_", $f);
$url = "http://example.com/g/".$f;
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$url);

Resources