Feb 22 2014

Rails Error: Using Devise, I was getting “Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true”

I’ve been learning Rails for awhile now and I just recently started using Devise for user authentication. It’s been great until I got stuck on the following Error:

ArgumentError in Devise::Passwords#create

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
Extracted source (around line #5):

Someone has requested a link to change your password. You can do this through the link below.

<%= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @token) %>

If you didn’t request this, please ignore this email.

Your password won’t change until you access the link above and create a new one.

I spent some time on Google and none of the solutions I found seemed to work at all. I was getting frustrated so I ran some updates and rebooted and sure enough, when I restarted the rails server the emails worked. It would appear the config methods in the environment files don’t reload unless the server is restarted. Hopefully this is helpful to anyone else who is going through the same thing.

The code that finally worked for me in my development.rb file (after I rebooted) was:


  config.assets.debug = true
  config.action_mailer.delivery_method = :sendmail
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {from: 'mailer@domain.net'}
  config.action_mailer.default_url_options = {:host => "localhost:3000"}

I am using sendmail. For using smtp check The Ruby Docs

Share

Jul 2 2010

Django on Dreamhost: Virtual Python Install

After writing the backend for a new web app in python I went to start working on the Django portion. I was planning on hosting this application with a Dreamhost shared hosting plan which already has Python 2.5 installed. After trying unsuccessfully to install some new middleware with easy_install, I started looking for a solution that gives me more control over what I want to do with Python without having to purchase dreamhost vps hosting. It seems that you can set up a virtual python install in your home directory and it was surprisingly easy. I’ve only had the need to use this virtual python install on Dreamhost, which is using Debian, but I can’t see any reason why it wouldn’t work on other environments.

Note that this is completely unnecessary if you have root access.

Assuming you already have a shell account and you are ssh’d in, execute these commands to install your virtual python environment:

$ wget http://peak.telecommunity.com/dist/virtual-python.py 
$ python virtual-python.py

Those commands copy the Python binary to your /home/user/bin directory and sets up symbolic links to the system wide libraries. This means that the ~/bin/python executable will have access to the same libraries as the system Python but that any extra installed software will not affect the system wide Python install.

Next you should add the ~/bin directory to your PATH by adding this block to your .bash_profile:

 if [ -d ~/bin ] ; then     
    PATH=~/bin:"${PATH}" 
fi 

You’ll have to log out and back in for this to take effect.
After you’re logged back in, run these commands to install easy_setup:
$ wget http://peak.telecommunity.com/dist/ez_setup.py 
$ python ez_setup.py 

Now you should be able to install whatever you want using easy_install. The first thing I did was install django-db-log using this command:
$ easy_install django-db-log

Share

Nov 9 2009

This is How Credit Card Numbers Are Generated

I was reading an article today in one of my favorite publications about how to get free trials without actually using your credit card by generating valid credit card numbers using a simple algorithm called the Luhn check. So I wrote a little script that generates credit card numbers that will be deemed valid by most software checks. This will work because the service won’t know that the credit card is invalid until they actually try to charge it. Well, the card may be valid since my script uses random numbers. Obviously this if for informational purposes only and should never actually be used.

Most credit card numbers are validated using an algorithm called the “Luhn check”. This is a very simple algorithm that doubles the odd digits and does a sum to see if the number is divisible by 10. The credit card companies use a slightly different version that involves a check digit as the last digit. To generate a credit card number that will pass most validation software (as long as they don’t actually try to process the credit card) one only needs to follow these steps to make sure that the generated credit card is valid.

Choose 16 random numbers starting with a 3,4,5 or 6.
Starting with the first digit, double every other number.

If doubling a number results in a two digit number, add those digits together to produce a single digit number

Replace the odd digits with the new ones just created. You should now have 16 numbers consisting of all the new numbers and the original even numbers

Add up all sixteen numbers.

Manipulate the check digit so that the sum is divisible by 10.

Replace the last digit of the original random string with the new manipulated check digit.

Thats really all there is to it. Check out the source of my javascript credit card generator if you want to see how to generate and validate the credit card numbers.

The reason for starting with a 3,4,5, or 6 is that different card types start with different digit. The 3 is American Express, 4 is Visa, 5 is Master Card, 6 is a Discover Card.

Some companies use more digits to show that the card is from them. For example 5254 is a Master Card from the Bank of America and 4013 shows that it is a Visa card from Citibank. Also note that the expiry date has nothing at all to do with the card number.

Share

Sep 21 2009

Vim Syntax Highlighting In Ubuntu

Spending a lot of time on the command line lately I noticed that Ubuntu does not come with Vim syntax highlighting by default. Apparently it installs a version of Vim called vim-tiny which doesn’t include any syntax highlighting.

There are two packages that you can install to get syntax highlighting to work in Vim: vim-full and vim-common. Because I didn’t have gnome installed vim-full was a very large download (like 50MB) and it errored out anyway. vim-common is definitely the way to go.


sudo apt-get install vim

The above line will replace vim-tiny with vim-common and will allow for syntax highlighting. A lot of the time you will have to enable syntax highlighting by editing the vimrc config file either in /etc/vim or in yur home directory. You will need to uncomment the line “syntax on”.

Share

Aug 11 2009

Create A Simple Captcha With PHP and GD

Everyone hates captchas. I know I do. It sucks but they are a necessary evil. Most captchas are difficult (sometimes impossible) to read and they will consistantly drive visitors from your site. I’ve been on sites where the captcha was so hard to decipher that I’ve never gone back.

During the development of a new site I was forced to create one of these evil entities. It was surprisingly simple and painless. The captcha that I outline here is very, very simple and should never be used in production without a fair amount of tweaking.

Having developed my site using php I naturally turned to the GD library.

Firstly I generated a random string to display on the captcha :


//generate a random alphanumeric string of a specific length
function gen_random_string($length) 
{
  $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ".
        "abcdefghijklmnopqrstuvwxyz";
  $real_string_length = strlen($characters) - 1;
  for($p=0;$p<$length;$p++)
  { $string .= $characters[mt_rand(0, $real_string_length)]; }
  return $string;
}

//add to session array so other scripts can access it for the comparison
$_SESSION['image_text']= gen_random_string(8);

//split into character array - str_split only works in PHP 5
$text_array = str_split($_SESSION['image_text']);


Now that I have my string I need to create the image. Make sure that GD is installed on your php apache server.

//create the image with a background image
$NewImage =imagecreatefrompng("bg1.png");
$cntr = 0;
foreach($text_array as $letter)
{
  //generate a random color for each letter
  $r = rand(0,200);
  $g = rand(0,200);
  $b = rand(0,200);
  $textcolor = imagecolorallocate($NewImage, $r, $g, $b);

  //random horizontal spacing
  $spacing = (rand(5,10)+($cntr*10));
  
  //add the character to the image
  imagestring($NewImage, 5, $spacing, rand(0,10), $letter, $textcolor);
  $cntr++;
}


The code above will generate a GD captcha image with random coloring and random horizontal and vertical spacing on top of a background image.
Now we just need to output it.

//output the headers than the image as a PNG
header('Content-type: image/png');
header('Cache-Control: max-age=0');
header('Expires: '.gmdate('r',time()-3600*24*365));
header('Pragma:');
ImagePNG($NewImage);
imagedestroy($NewImage);


So if I called this file simple-captcha.php I could call it with this html:

<img id='captcha' name='captcha' src="simple-captcha.php">


Here is what it looks like :

This captcha can be strengthened by using other GD image functions such as imagefilledellipse and imageline to create artifacts in the background. It also helps to use different fonts and to change the angle of the letters.

Share

Jul 1 2009

Decode Obfuscated WordPress Strings Which Use eval, gzinflate, And base64_decode.

I’ve been using wordpress for awhile and it seems that whenever I find a useful plugin or theme on the web the author always seems to embed some affiliate link or some other garbage on my main page. Usually they make sure that these links show up on every page and sometimes they even make other features of the software depend on it. Usually when I try to edit out the code it’s not as easy as removing an anchor or a bit of javascript. They always seem to obfuscate what they are doing as much as possible.

The most popular way to do this is to use a combination of gzinflate, base64_decodes, eval, and str_rot13. For most users this is really difficult to decode to figure out what is really going on. I wrote this function to hopefully make peoples lives easier (or harder, depending on who you are).
Usually the obfuscated code is written in the wordpress add-on like this :


$coded_string = "eval(gzinflate(base64_decode('FZfFDs..sdff/7nr/8B')));"

If your string looks like that then the function that follows should take decode it and return the html code pretty easily.

function decode_goofy_string($coded_string)
{
  while(preg_match("/eval\(gzinflate/",$coded_string)) 
  {
    $contents=preg_replace("/<\?|\?>/", "", $coded_string); 
    eval(preg_replace("/eval/", "\$coded_string=", $coded_string)); 
  }
  
  return trim($coded_string);
}

This function is pretty straight forward but if anyone has any troubles then leave a comment or send me an email at cody@codytaylor.org

Share

Jun 29 2009

WordPress Shortcode To Generate A TinyURL For Any Post

TinyURLs can be very useful when you have a long url to type into something like an iphone or some other mobile device where the keyboard is rather tedious. On a few of my sites I was looking for a way to automatically generate a tinyURL with the least amount of effort. Since I use wordpress for most of them I decided to go with a shortcode.

Shortcodes seem to be gaining a fair amount of attention in the wordpress community and with good reason. The Shortcode API, which was new in wordpress 2.5, is a simple set of functions for creating macro codes for use in your posts. Shortcodes are written by providing a handler function and they accept parameters too. Here is a wordpress shortcode to generate a tinyURL for a post.


//Generate Tiny URLS For A Post 
function get_tiny_url($arguments)
{
  if(empty($arguments))
    $url = get_permalink($post->ID);
  else
    $url = urlencode($arguments['url']);
  if($url)
    {
      $tiny_url = 'http://tinyurl.com/api-create.php?url='.$url;
      $new_url = file_get_contents($tiny_url);
    }
    else
      $new_url = "Error";
    return $new_url;
}

add_shortcode('small_url', 'get_tiny_url');

If the url parameter is not defined then the function will attempt to use the wordpress function get_permalink($post->ID) which will return the current posts url. Also you can pass in a parameter if you want to show a tinyURL to another location. Using curl instead of file_get_contents would probably be faster but I didn’t want to make the example to long. The add_shortcode function is what tells the API to use the get_tiny_url function when it encounters the small_url shortcode. Note that this will call on the tinyurl api every page view so it would probably be prudent to set the tiny urls in the database so you only have to check once on a production site although I’m not sure if they expire or not.
This shortcode can be called in the post by typing :

[small_url]  // or
[small_url url='http://codytaylor.org']

Share

Jun 26 2009

Make Your PHP Faster

I was reading about some php performance tips at work today and decided to throw together some of the ways to make your php site faster.

Here’s a couple of short tips to avoid making your site lag for the user:

  1. Unset your variables. This frees up a surprising amount of memory
  2. Use memcache
  3. Turn on apache’s mod_deflate
  4. If your database is local then close your connections when you’re done with them
  5. If your database is remote then use persistant connections
  6. Don’t use functions inside of a for loop control expression unless absolutely necessary. Example :
    
    for($i=0;$i<some_big_calculation(20);$i++)
    

    The some_big_calculation function will be called every iteration.
  7. Use string concatenation instead of embedding variables in strings.
    
    $some_string = "asdf $asdf2 asdf"; //bad
    $some_string = 'asdf '.$asdf2.' asdf'; //good
    
  8. When including files, use at least a relative path so PHP doesn’t have to look in the entire path.
    
    include("./some_file.php"); // looks in the current directory
    include("wrong.php"); // searches every directory in the path
    
  9. Try not to use include_once or require_once. They are more expensive and it really isn’t that hard to only include files once
  10. Not everything needs to be an object. There is a fair amount of overhead when doing everything OOP.
  11. Use output buffering to make everything seem faster.

Hopefully I didn’t miss any of the big ones.

Share

Jun 22 2009

Update Twitter using Command Line, Javascript, Or PHP.

Everyone seems to be all about Twitter so here’s some simple examples of how to update your Twitter status from a command line prompt, web server or simple html web site. These three examples require curl so install it if you don’t already have it. For these examples I’ll be using my Twitter user name ‘codytaylor1234’. My password is not ‘mypassword’ so make sure you put in your own information.

The easiest way to update your Twitter account is to just call curl from the command line with this command.


curl --basic --user "codytaylor1234:mypassword" --data-ascii 
"status=This Twitter update brought to you by curl on the command line" 
"http://twitter.com/statuses/update.json"


To update your Twitter status with PHP you are going to want to do the same sort of thing but with a bit more typing.

<?php
$username = 'codytaylor1234';
$password = 'mypassword';

$update = 'This Twitter update is from a php script using curl';

$url = 'http://twitter.com/statuses/update.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".$update);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
$result = curl_exec($ch);
curl_close($ch);

if($result)
    echo 'success';

?>;

Since a cross-domain request in Javascript isn’t really an option we have to create a proxy using PHP in order to authenticate the user on the Twitter API. If anyone knows an easy way authenticate a Twitter user using only javascript I’d love to hear it. Anyway if we replace a small amount of code in the above example and put it in a file then we can use a simple ajax request to update our Twitter status. So the new PHP file would be:


<?php
$username = $_POST['username'];
$password = $_POST['password'];

$update = $_POST['update'];

$url = 'http://twitter.com/statuses/update.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".$update);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
$result = curl_exec($ch);
curl_close($ch);

?>

For this example I called that php file ‘twitter-update.php’. Now that we have our simple proxy we can update our twitter status with a simple html form and a little ajax. I used the prototype framework for my javascript.


<script src="includes/prototype.js" type="text/javascript">
<script type='text/javascript'>
function update_twitter()
{
  var param_string = "username="+$('username').value+"&password="+
        $('password').value+"&update="+$('update').value;
  alert(param_string);
  var options = {
    method: "post",
    parameters: param_string,
    onSuccess: function (xhr, Json) {
      alert("Response received successfully.");
    },
    onFailure: function (xhr, Json) {
      alert("Request was unsuccessful.");
    }
  };
  
  var oRequest = new Ajax.Request("twitter-update.php", options);
}

</script>

Obviously this is for example purposes only and if you’re actually using it for production then you should edit it a lot. Now for the last little bit here’s the simple html form that starts it all.


User Name : <input type='text' id='username' value='codytaylor1234'><br>
Password  : <input type='password' id='password' value='mypassword'><br>
New Status : <input type='text' id='update' 
value='Twitter Update from html/javascript/php'><br>
<input type='button' value="Update Twitter" onclick='update_twitter();'>

Share

Jun 20 2009

Get Integer Bit Parity In PHP

I was forced to use php to generate a cyclic redundancy check (CRC) byte earlier this week. When generating this CRC I needed to check the bit parity of a byte. At first I thought that there would be an example that I could just cut and paste into my code or a library including the function somewhere. I guess that most PHP users don’t really have to work with bits and bytes very often because I couldn’t find an example of doing this. Granted I didn’t really search that hard because writing it was pretty simple. But hopefully the next guy searching for this actually finds this example.

Most of the time we don’t really have to think about types in php. But if you’re dealing with this kind of thing then you usually want to know what you’re working with. This php function example will only work with integers and will return a value of -1 if the first parameter is not a number. The function returns 1 if the number of bits set in the number pased in is odd. Otherwise it will return 0. The second parameter defaults to 4 because that is the number of bytes in a normal php integer. In php if a number becomes larger than an integer can handle, which is called an overflow, it becomes a float. The default integer size is platform dependant but it’s usually 4 bytes. It can be set using the constant PHP_INT_SIZE if you need to change it.


<?php

function odd_parity($something,$number_of_bytes_to_check=4,$double_check=0)
{
    //test to make sure it's a number
    if(!is_numeric($something)) {return -1;}  

    $setbits = 0;

    //get the number of bits that are set
    for($i=0;$i<$number_of_bytes_to_check*8;$i++)
    {
        if($something & (1<<$i)) $setbits++;
    }

    //check if the number of bits set is even or odd   
    $result =  $setbits % 2;
   
    //spit out the results to double check it's working 
    if($double_check)
    echo   "<br>Parity of : ".$something." is ".
    $result." In Binary : ".decbin((int)$something).
    " Checking the right ".($number_of_bytes_to_check*8).
    " Bits";

    return $result;
}

//will return 0 because it's defaulting to 4 bytes
echo odd_parity(0x0100010001);  

?>

Share