lighttpd url.rewrite to remove part of url - url

I'm trying to replace a part of my url before before delivering the file.
I call
localhost:8080/files/page_home.d41d8.js
and would like to modify the call to
/files/page_home.js
After that the file shall be delivered directly by lighttpd and not be forwareded to the fastcgi backend.
I tried the following:
server.modules += ( "mod_fastcgi", "mod_rewrite" )
url.rewrite = ("^/files/(([a-zA-Z0-9_]+))\.(([a-zA-Z0-9]))\.js$" => "/files/$1.js")
$HTTP["url"] !~ "^/files/" {
fastcgi.server = (
"/" => ((
"bin-path" => "/srv/www/cppapp/dist/Debug/GNU-Linux/cppapp.exe",
"bin-environment" => (
"LD_LIBRARY_PATH" => ""
),
"socket" => "/tmp/cppapp-fastcgi-socket",
# # only 1 process !
"max-procs" => 1,
"check-local" => "disable",
# "broken-scriptfilename" => "enable"
"fix-root-scriptname" => "enable",
))
)
}
When I'm looking into the log, the part ".d41d8." is not replaced.
Does anyone of you have a tip for replacing that part?
Thank you very much,
Alex

If someone is searching for answer in future: The problem was the regular expression "^/files/(([a-zA-Z0-9_]+)).(([a-zA-Z0-9])).js$". The second part was only matching one char / number. The correct version is "^/files/(([a-zA-Z0-9_]+)).(([a-zA-Z0-9]+)).js$"

Related

Validate Twilio Notify deliveryCallbackUrl - What is the desired format for a nested request?

I'm working on a project that uses Twilio Notify for mass text notifications. I would like to track the status of individual messages, so I added a deliveryCallbackUrl to the notification resource.
$notification = $service->notifications->create([
"toBinding" => $binding,
"body" => $message_text,
"deliveryCallbackUrl" => "https://username:password#mysite/notification_delivery_callback.php"
]);
I can successfully receive the callback payload, but when I attempt to validate the request, it fails.
use Twilio\Rest\Client;
use Twilio\Security\RequestValidator;
$configs = get_configs();
$signature = $_SERVER["HTTP_X_TWILIO_SIGNATURE"];
$request_url = $_SERVER['SCRIPT_URI'];
$validator = new RequestValidator($configs['twilio_auth_token']);
$request = $_REQUEST;
// $is_valid always returns false
$is_valid = $validator->validate($signature, $request_url, $request);
The payload is nested and includes json.
Array(
[NotificationSid] => NTxxxxxxxxx
[ServiceSid] => ISxxxxxxxxx
[Count] => 4
[IsFinal] => true
[DeliveryState] => Array(
[3] => {"status":"SENT","type":"sms","identity":"xxxxxxxxx","sid":"SMxxxxxxxxx"}
[2] => {"status":"SENT","type":"sms","identity":"xxxxxxxxx","sid":"SMxxxxxxxxx"}
[1] => {"status":"SENT","type":"sms","identity":"xxxxxxxxx","sid":"SMxxxxxxxxx"}
[0] => {"status":"SENT","type":"sms","identity":"xxxxxxxxx","sid":"SMxxxxxxxxx"}
)
[AccountSid] => ACxxxxxxxxx
[SequenceId] => 0
)
It seems the DeliveryState array is the issue, as I am able to successfully validate non-nested requests for other webhooks. I've crawled through Twilio help docs, but so far, haven't found anything about how to validate nested requests. I've attempted to flatten the array and escape the json (one or the other, both at the same time), but no luck.
Array(
...
[DeliveryState] => Array(
[0] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[1] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[2] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[3] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
)
...
)
Array(
...
[0] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[1] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[2] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
[3] => "{\"status\":\"SENT\",\"type\":\"sms\",\"identity\":\"xxxxxxxxx\",\"sid\":\"SMxxxxxxxxx\"}"
...
)
Does anyone know what the desired format is to validate this properly?
Worked with Twilio Support to solve the issue.
There was a bug in the sdk: The PHP library didn't support multi-dimensional arrays in the RequestValidator (twilio/sdk has been fixed and updated to 6.42.1)
Format: The validator is looking for a specific format -- need to unnest the DeliveryState array and reformat the keys (order is also important)
Example format that passes validation
(
[NotificationSid] => NTxxx
[ServiceSid] => ISxxx
[Count] => 5
[IsFinal] => true
[DeliveryState[0]] => {"status":"SENT","type":"sms","identity":"xxxxxxxxxx","sid":"SMxxx"}
[DeliveryState[1]] => {"status":"SENT","type":"sms","identity":"xxxxxxxxxx","sid":"SMxxx"}
[DeliveryState[2]] => {"status":"SENT","type":"sms","identity":"xxxxxxxxxx","sid":"SMxxx"}
[DeliveryState[3]] => {"status":"SENT","type":"sms","identity":"xxxxxxxxxx","sid":"SMxxx"}
[DeliveryState[4]] => {"status":"SENT","type":"sms","identity":"xxxxxxxxxx","sid":"SMxxx"}
[AccountSid] => ACxxx
[SequenceId] => 0
)

OAuth signature generation using HMAC-SHA1?

I apologize for asking so many questions but none of them seem to be getting answered and I really need help on this. I'm using LTI to integrate my program into a learning management system, and I need to authenticate using OAuth. I have no trouble generating a signature following the guidelines here but the signature I generate never matches the one passed to me by the LMS, and I can't figure out for the life of me why they never match. I'm hoping that it's something I'm oblivious to, but I really need some assistance on this.
When I launch my program from the LMS, I am sent this array via POST in what is called the LTI launch:
array(
'launch_presentation_locale' => 'EN-US__',
'tool_consumer_instance_guid' => 'key',
'tool_consumer_instance_name' => 'MyProgram',
'tool_consumer_instance_description' => 'MyProgram',
'tool_consumer_instance_contact_email' => 'johndoe#email.com',
'tool_consumer_info_version' => '10.3.0 SP5',
'tool_consumer_info_product_family_code' => 'desire2learn',
'context_id' => '2440554',
'context_title' => 'ContextTitle',
'context_label' => 'ContextTitle',
'context_type' => '',
'user_id' => 'USER_ID',
'roles' => 'None',
'lis_person_name_given' => 'John',
'lis_person_name_family' => 'Doe',
'lis_person_name_full' => 'John Doe',
'lis_person_contact_email_primary' => 'johndoe#email.com',
'ext_tc_profile_url' => 'https://profileurl.com',
'ext_d2l_token_id' => '123456789',
'ext_d2l_link_id' => '1234',
'ext_d2l_token_digest' => 'AbCdEfGhIjKlMnOpQrStUvWxYzi=',
'resource_link_id' => '',
'resource_link_title' => 'MyProgram',
'resource_link_description' => 'MyProgram',
'lis_result_sourcedid' => 'abcdefgh-ijkl-mnop-qrst-uvwxyz012345',
'lis_outcome_service_url' => 'https://outcomeserviceurl.com',
'lti_version' => 'LTI-1p0',
'lti_message_type' => 'basic-lti-launch-request',
'oauth_version' => '1.0',
'oauth_nonce' => '123456789',
'oauth_timestamp' => '1234567890',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_consumer_key' => 'key',
'oauth_callback' => 'about:blank',
'oauth_signature' => 'eFUR8O5xVydLrj4PDj37nF4cq6A=',
'basiclti_submit' => 'Launch Endpoint with BasicLTI Data'
);
Here is what I'm trying. I've added comments to clarify the steps:
// Set variables that are required for the signature to be generated.
$OAUTH_KEY = 'key';
$OAUTH_SECRET = 'secret';
$httpMethod = 'POST';
$SITE_URL = 'https://localhost/test.php';
// make array copy of entire POST data, remove the 'oauth_signature' field as specified in the oauth spec from the copy array, then sort alphabetically. After that, url encode the key/value of each item in the copy array and store into a string for later use.
$request_parameter_array = $_POST;
unset($request_parameter_array['oauth_signature']);
ksort($request_parameter_array);
$request_parameter_str = '';
foreach($request_parameter_array as $key => $value) {
$request_parameter_str .= rawurlencode($key) . '=' . rawurlencode($value) . '&';
}
// create the signature base string (string variable that the actual signature is created from) by following these steps from the OAuth documentation:
// 1. The HTTP request method in uppercase. For example: "HEAD",
// "GET", "POST", etc. If the request uses a custom HTTP method, it
// MUST be encoded (Section 3.6).
// 2. An "&" character (ASCII code 38).
// 3. The base string URI from Section 3.4.1.2, after being encoded
// (Section 3.6).
// 4. An "&" character (ASCII code 38).
// 5. The request parameters as normalized in Section 3.4.1.3.2, after
// being encoded (Section 3.6).
$key = rawurlencode($OAUTH_SECRET) . '&';
$signature_base = strtoupper($httpMethod) . '&' . rawurlencode($SITE_URL) . '&';
$signature_base .= rawurlencode($request_parameter_str);
$signature = base64_encode(hash_hmac("sha1", $signature_base, $key, true));
echo $signature;
I guess my own stupidity was the issue, here. The issue was arising from D2L itself because I misunderstood what the difference was between using a tool link vs. a tool provider for my integrations. I literally deleted my tool provider and went with a tool link and now I'm able to authenticate every time.
Turns out there wasn't a problem with the code at all here.

hybridauth's social_hub/login.php doesn't work

I install the hybridauth on windows IIS, and setup the hybridauth\config.php as below:
array(
"base_url" => "http:///hybridauth/",
"providers" => array (
.....
"Google" => array (
"enabled" => true,
"keys" => array ( "id" => "<myappkey>", "secret" => "<myappsecret>" ),
"scope" => "email"
),
)
But when I click "Sign-in with Google" in http:///examples/social_hub/login.php, it just redirect me to http:///hybridauth/?hauth.start=Google&hauth.time=1401608000 which show the files under "localhost - /hybridauth/"
Anyone know how to fix it?
Thank you!
1) i am not sure if your scope is properly set up (you should have probably set it to "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
2) did you set up the return address in google api correct?

FedEx 556 - No valid services available. when there should be

Hi I'm trying to use the wsdl api to get shipping cost calculated for my website.
I'm using opencart and this module (http://www.opencart.com/index.php?route=extension/extension/info&extension_id=2055&filter_search=fedex&sort=e.date_modified&order=DESC).
On checkout I'm getting this error:
WARNING::556::There are no valid services available.
But I tried the same from and to address on the calculator on the fedex website and it gives me two services: International Priority and International Economy
This is the debug data I have:
Array
(
[WebAuthenticationDetail] => Array
(
[UserCredential] => Array
(
[Key] => REDACTED
[Password] => REDACTED
)
)
[ClientDetail] => Array
(
[AccountNumber] => REDACTED
[MeterNumber] => REDACTED
)
[TransactionDetail] => Array
(
[CustomerTransactionId] => *** Rate Request v9 using PHP ***
)
[Version] => Array
(
[ServiceId] => crs
[Major] => 9
[Intermediate] => 0
[Minor] => 0
)
[ReturnTransitAndCommit] => 1
[RequestedShipment] => Array
(
[DropoffType] => REQUEST_COURIER
[ShipTimestamp] => 2011-09-28T09:02:01+00:00
[PackagingType] => YOUR_PACKAGING
[TotalInsuredValue] => Array
(
[Amount] => 2000
[Currency] => EUR
)
[Shipper] => Array
(
[Address] => Array
(
[StreetLines] => Array
(
[0] =>
[1] =>
)
[City] => Ronchis
[StateOrProvinceCode] =>
[PostalCode] => 33050
[CountryCode] => IT
[Residential] => 1
)
)
[Recipient] => Array
(
[Address] => Array
(
[StreetLines] => Array
(
[0] =>
[1] =>
)
[City] => villach
[StateOrProvinceCode] =>
[PostalCode] => 9500
[CountryCode] => AT
[Residential] => 1
)
)
[ShippingChargesPayment] => Array
(
[PaymentType] => SENDER
[Payor] => Array
(
[AccountNumber] => 263150082
[CountryCode] => IT
)
)
[RateRequestTypes] => LIST
[PackageCount] => 1
[PackageDetailSpecified] => 1
[PackageDetail] => INDIVIDUAL_PACKAGES
[RequestedPackageLineItems] => Array
(
[0] => Array
(
[Weight] => Array
(
[Value] => 34
[Units] => KG
)
[Dimensions] => Array
(
[Length] => 48
[Width] => 53
[Height] => 122
[Units] => CM
)
)
)
)
)
----------
-- NUSOAP -- Array
(
[HighestSeverity] => WARNING
[Notifications] => Array
(
[Severity] => WARNING
[Source] => crs
[Code] => 556
[Message] => There are no valid services available.
[LocalizedMessage] => There are no valid services available.
)
[TransactionDetail] => Array
(
[CustomerTransactionId] => *** Rate Request v9 using PHP ***
)
[Version] => Array
(
[ServiceId] => crs
[Major] => 9
[Intermediate] => 0
[Minor] => 0
)
)
What should I do?
I just ran into this error, and it turned out that the issue was an invalid postal code. Double check that you are specifying the "Shipper" information correctly.
Also, if that doesn't work give the FedEx customer support phone number a try. We would not have figured this issue out without their help.
I was also having this issue .. but with Joomla, Virtuemart. Because the FedEx server is the same so may be my solution could help somebody else too..
Here are the main things what I fixed to fix this issue.
Product's Weight should be less than the limit if you've set any as Maximum Weight.
If you are using any packaging has more weight than FedEx's provided box i.e. 25KG BOX or 10KG box, then always use "Your Own packaging"
it's true, do keep an eye on ZIP===States (i was testing and put wrong state with different zip) And this ZIP should be added in "Shop's Address" because this is considered as FROM and the destination address as well.
Do note if products have added weights. LWH (Length, Width, Height).
Mine issue resolved after weeks of trouble! I wish somebody else could also resolve this issue if facing.
I was facing following error
"10 kg packaging box is **only** Available at FedEx World Service CenterĀ® locations!"
which was a big help to resolve the limitation i've set.
This issue happen when one of the bellow cases.
Country given is not associated with FedEx account.
Origin address is not real, Especially the post code.
The given packagingType is available in your country.
You need to provide a ServiceType. One of these:
EUROPE_FIRST_INTERNATIONAL_PRIORITY
FEDEX_1_DAY_FREIGHT
FEDEX_2_DAY
FEDEX_2_DAY_AM
FEDEX_2_DAY_FREIGHT
FEDEX_3_DAY_FREIGHT
FEDEX_EXPRESS_SAVER
FEDEX_FIRST_FREIGHT
FEDEX_FREIGHT_ECONOMY
FEDEX_FREIGHT_PRIORITY
FEDEX_GROUND
FIRST_OVERNIGHT
GROUND_HOME_DELIVERY
INTERNATIONAL_ECONOMY
INTERNATIONAL_ECONOMY_FREIGHT
INTERNATIONAL_FIRST
INTERNATIONAL_PRIORITY
INTERNATIONAL_PRIORITY_FREIGHT
PRIORITY_OVERNIGHT
SMART_POST
STANDARD_OVERNIGHT
Use it in the same level as the DropoffType
Make sure that you have the Zip Code set to required.
You can do that in System -> Localization -> Countries.
It is not required by default in opencart, and the fedex shipping system will not work without it.
This issue can also be caused by requesting insurance in a country that doesn't support it, such as Canada.
I also ran into this problem and the solution was trimming extra spaces from the end of the address, city & postal code. After that, all was well again.
I don't know why FedEx's API all of a sudden stopped accepting the extra spaces, but who knows...
In my case, this was caused by trying to ship internationally from the US to Italy, and having specified a SignatureOptionDetail of NO_SIGNATURE_REQUIRED. Changing this to SERVICE_DEFAULT fixed it.

Is there equivalent for PHP's print_r in Ruby / Rails?

In PHP you can do:
print_r($var) or vardump($var)
which prints "human-readible" information about variable.
Is there equivalent functions / helpers for those in Ruby / Rails ?
In Rails templates you can do
<%= debug an_object %>
and it will do nice HTML PRE output.
Try using pp.
You will need to require it in scripts (or in irb if your .irbc doesn't already do this):
require 'pp'
Then you can 'PrettyPrint' an object thus:
pp object
Instead of requiring 'pp' and using pp, you can simply do
p object
Tested example
require 'pp'
class A
def initialize
#a = 'somevar'
#b = [1,2,3]
#c = {'var' => 'val'}
end
end
a = A.new
pp a # Gives -> #<A:0x2c6d048 #a="somevar", #b=[1, 2, 3], #c={"var"=>"val"}>
p a # Gives -> #<A:0x2c6d048 #a="somevar", #b=[1, 2, 3], #c={"var"=>"val"}>. No need to require 'pp'
There's the method inspect which helps. Sometimes calling the to_s method on an object will help (to_s returns a string representation of the object). You can also query methods, local_variables, class_variables, instance_variables, constants and global_variables.
p ['Hello',"G'day",'Bonjour','Hola'].inspect
# >> "[\"Hello\", \"G'day\", \"Bonjour\", \"Hola\"]"
p ['Hello',"G'day",'Bonjour','Hola'].to_s
# >> "HelloG'dayBonjourHola"
p Array.new.methods
# >> ["select", "[]=", "inspect", "compact"...]
monkey = 'baboon'
p local_variables
# >> ["monkey"]
class Something
def initialize
#x, #y = 'foo', 'bar'
##class_variable = 'gorilla'
end
end
p Something.class_variables
# >> ["##class_variable"]
s = Something.new
p s.instance_variables
# >> ["#x", "#y"]
p IO.constants
# >> ["TRUNC", "SEEK_END", "LOCK_SH"...]
p global_variables
# >> ["$-d", "$\"", "$$", "$<", "$_", "$-K"...]
I know this is an old post, but it is the first thing that Google pops up when searching for "Ruby equivalent of PHP print_r". I'm using Ruby in the command line mode, and there's really not a very good equivalent. "pp" is ok for fairly simple structures, but as soon as you start nesting hashes in arrays in hashes in more arrays, it turns into a jumble pretty fast. Since I haven't found a good emulation of print_r, I wrote one myself. It's good enough for my purposes, not overly complicated and I thought I'd share it to save other people some headache. Compare the output with the real PHP print_r
def print_r(inHash, *indent)
#indent = indent.join
if (inHash.class.to_s == "Hash") then
print "Hash\n#{#indent}(\n"
inHash.each { |key, value|
if (value.class.to_s =~ /Hash/) || (value.class.to_s =~ /Array/) then
print "#{#indent} [#{key}] => "
self.print_r(value, "#{#indent} ")
else
puts "#{#indent} [#{key}] => #{value}"
end
}
puts "#{#indent})\n"
elsif (inHash.class.to_s == "Array") then
print "Array\n#{#indent}(\n"
inHash.each_with_index { |value,index|
if (value.class.to_s == "Hash") || (value.class.to_s == "Array") then
print "#{#indent} [#{index}] => "
self.print_r(value, "#{#indent} ")
else
puts "#{#indent} [#{index}] => #{value}"
end
}
puts "#{#indent})\n"
end
# Pop last indent off
8.times {#indent.chop!}
end
Here's an example (made messy on purpose to show why the PHP print_r is so nice):
carTools = [ "Socket Set", "Combination Wrenches", "Oil Filter puller", "Brake Compressor" ]
houseTools =[ "Circular Saw", "Miter Saw", "Drill" ]
garageItems = Hash["Car1" => "Ford Mustang", "Car2" => "Honda Civic", "Bike1" => "IronHorse"]
garageItems["Tools"] = Hash["Car Tools" => carTools, "House Tools" => houseTools]
constructionSupplies = Hash["Plywood" => ["3/4\" T&G Plywood Sheets", "1/2\" Plywood Sheets"],
"Boards" => ["2x4s", "2x6s", "Engineered I-Joists"],
"Drywall" => ["4x8 1/2\" Sheetrock", "Mesh tape", "Paper tape", "Joint compount"]]
carParts = Hash["Mustang" => ["Clutch", "Transmission", "3.55 Ring & Pinion Gears", "Differential", "30# Injectors", "Pro-M 77mm MAF"]]
garageItems["Supplies"] = ["Oil", "WD40", constructionSupplies, carParts, "Brake Fluid"]
print_r(garageItems)
Output of print_r (actually comprehensible by a human):
Hash
(
[Car1] => Ford Mustang
[Car2] => Honda Civic
[Bike1] => IronHorse
[Tools] => Hash
(
[Car Tools] => Array
(
[0] => Socket Set
[1] => Combination Wrenches
[2] => Oil Filter puller
[3] => Brake Compressor
)
[House Tools] => Array
(
[0] => Circular Saw
[1] => Miter Saw
[2] => Drill
)
)
[Supplies] => Array
(
[0] => Oil
[1] => WD40
[2] => Hash
(
[Plywood] => Array
(
[0] => 3/4" T&G Plywood Sheets
[1] => 1/2" Plywood Sheets
)
[Boards] => Array
(
[0] => 2x4s
[1] => 2x6s
[2] => Engineered I-Joists
)
[Drywall] => Array
(
[0] => 4x8 1/2" Sheetrock
[1] => Mesh tape
[2] => Paper tape
[3] => Joint compount
)
)
[3] => Hash
(
[Mustang] => Array
(
[0] => Clutch
[1] => Transmission
[2] => 3.55 Ring & Pinion Gears
[3] => Differential
[4] => 30# Injectors
[5] => Pro-M 77mm MAF
)
)
[4] => Brake Fluid
)
)
Check out the guide for debugging rails:
http://guides.rubyonrails.com/debugging_rails_applications.html
hints:
script/console is great to try stuff in the context of your app
script/server --debugger to start the server with a debugger turned on, you can then use 'debug' in your code to break into an interactive shell
One approach I lean on a lot is this:
logger.debug "OBJECT: #{an_object.to_yaml}"
Easy to read, although it can get a little unwieldy for large objects.
Guess I'm a little late to this, but what about logger.info [debug|warning]? Use this from Controllers and Models. It will show up in your log files (development.log when in dev mode); and the above mentioned <%= debug("str: " + str) %> for views.
These aren't exact answers to your questions but you can also use script/console to load your rails app in to an interactive session.
Lastly, you can place debugger in a line of your rails application and the browser will "hang" when your app executes this line and you'll be able to be in a debug session from the exact line your placed your debugger in the source code.

Resources