How To Update a WordPress Password Through MySQL

Description

There are plenty of tutorials on how to update a password (password required when you to to http://yourdomain.com/wp-admin) for a WordPress installation through phpMyAdmin, but there are not many that will do it for those who want to be a little bit more robust and try it through a command line. This tutorial is going to show both. First the easy way through phpMyAdmin and then all through command line.

phpMyAdmin

Step 1: Find the Right Database

Log into your cpanel and determine the appropriate database for your WordPress. Browse to the directory where the your WordPress is installed and look for a file called wp-config.php. Open the wp-config.php and look for the lines that look like the following:
[bash]
// ** MySQL settings – You can get this info from your web host ** //
/** The name of the database for WordPress */
define(‘DB_NAME’, ‘username_wrd2’);

/** MySQL database username */
define(‘DB_USER’, ‘username_wrd2’);

/** MySQL database password */
define(‘DB_PASSWORD’, ‘database_user_password’);

/** MySQL hostname */
define(‘DB_HOST’, ‘localhost’);
[/bash]
This shows us that the database name (DB_NAME) is username_wrd2.

Step 2: Open phpMyAdmin.

  • Log into the CPanel and select phpMyAdmin.
  • Select the appropriate database on the top left of the screen. The database naming schema for most hosts is username_. This is why we want to find the right database to use from step one. For the example we are using username_wrd2 and phpMyAdmin will just show it as _wrd2. Select _wrd2
  • There will now be a list of tables in the database. Click wrd2_users.



Step 3: Edit the User Information

Once you click the wp_users link there will be a list of all the users associated with your WordPress. Find the row with the user you want to change the password.

  • Click edit for the user for whom you want to change the password.

  • Now all the information for that user should be showing and all you have to do is change the password.
  • Select MD5 for the password encryption type. MD5 is what WoordPress will use by default.
  • Click GO in the bottom left corner of the user section and now the new password should be saved. You can now go to http://yourdomain.com/wp-admin and log in with the new credentials.

Command Line

Step 1: Connect to the right database.

The wp-config.php file contains the right database, username, and password that are needed in order to log into mysql.
[bash]
mysql -u <username> -h <host> -p
Enter password:
[/bash]

Then from the wp-config.php file we know the database that we want to connect to and thus implement the following command.
[bash]
mysql>use <database>;
[/bash]

Step 2: Show current users and update password for right user.

[bash wraplines=”0″]
mysql> SELECT * FROM wp_users;
+—-+————–+————————————+—————+—————————–+————————-+———————+———————-+————-+————–+
| ID | user_login | user_pass | user_nicename | user_email | user_url | user_registered | user_activation_key | user_status | display_name |
+—-+————–+————————————+—————+—————————–+————————-+———————+———————-+————-+————–+
| 1 | admin | 1fab43ee6db8eeb65a2bd8f5ed354500a5 | admin | youremail@domain.com | http://www.yourdomain.com | 2010-01-11 23:15:05 | Daa5960a123FF55e594be | 0 | John Doe |

+—-+————–+————————————+—————+—————————–+————————-+———————+———————-+————-+————–+
[/bash]
Then all you need to do to update the password in mysql is the following command. Note however, you can choose whatever kind of encryption you would like. For this example I am encoding in an md5sum.
[bash]
mysql>UPDATE wp_users set user_pass=MD5("YourNewPassword") WHERE user_login = "username";
SELECT * FROM wp_users;
[/bash]

How to Repair a Hacked Website and Cpanel

Description

This is a howto or a step-by-step post on successfully repairing a hacked site. This guide is meant to walk you through repairing your current problem and preventing it from happening again in the future. Just simply restoring the files is not enough to fix the site. We need to implement stronger security measures to prevent hackers from invading your site again in the future.

Repair

Step 1: Log into your cpanel

Cpanel Stats

If you are using any of the name brand hosting platforms they usually provide an application called cpanel, which allows you to edit your server side information. The Cpanel for Just Host for example can be reached by going to http://justhost.com/login. On the cpanel there is a usually a Stats section on the left that will have the last logged IP address for the person who accessed your cpanel last. Go to whatismyip.com and see if the IP address the cpanel gives and the website whatismyip have the same. If they are not this may be the IP address of the hacker, however, don’t jump to conclusions because IP addresses get reset often and it may have been yours previously or your web hosts IP address if they have accessed your cpanel recently. Simply write the IP address the Cpanel gives if it is different and we can use this later.



Step 2: Check log files

All servers should keep log files that show every connection to your site. There are several different types of logging software such as AWStats or Webalizer. Almost all webhosting servers will have what is called Raw Access Logs (name may vary from platform to platform). Go ahead and and download the log file for each of your domains. This can be used later to further track down possibly where the hacker is located.

Step 3: Contact your hosting company

Most webhosts will have courtesy backups available. If you know when your website was hacked ask if there is a backup before that date they can use to restore your site. It is ALWAYS a good idea to have your own backups saved on your local machine in case there is something wrong with the server.

Step 4: Download all of your content and scan it

Research in 2009 has shown the number one reason for website hacking is the personal computer used to maintain the website has been compromised with malware or viruses. Here is a list of commonly used antiviruses: Trend Micro Housecall, Kaspersky, Malwarebytes, Symantec (Norton), BitDefender, Windows Live OneCare, Computer Associates, McAfee, F-Secure, AVG, and ClamAV.

Step 5: Change ALL passwords

There are several passwords that give access to various parts of your account. You will need to change your Cpanel , MySQL User ,FTP Account , Web Application (e.g. WordPress, Joomla, etc), and Email Account passwords. When changing your passwords follow our guide near the bottom under the Prevent section.

First change your Cpanel password. If you cannot log into your Cpanel contact your webhost to get the password changed. Second is to change all your database user passwords. If you are using a webhost that uses Cpanel there is no way to change the password for your database users. You must delete the user and recreate it with a new password. To view which databases you are using and the users attached to them go to the MySQL Databases section of your cpanel.

Don’t forget once you delete the user and create a new one you will need to connect that user with the appropriate database. Give that user all the permissions for that database. The last part of updating MySQL users is you will need to change the configuration file for your website where your web program connects to the appropriate database. For example WordPress installations keep this information in a file called wp-config.php.

[bash]
// ** MySQL settings – You can get this info from your web host ** //
/** The name of the database for WordPress */
define(‘DB_NAME’, ‘username_wrd2’);

/** MySQL database username */
define(‘DB_USER’, ‘username_wrd2’);

/** MySQL database password */
define(‘DB_PASSWORD’, ‘new_user_password’);

/** MySQL hostname */
define(‘DB_HOST’, ‘localhost’);
[/bash]

Third we will want to change all the FTP user passwords. This is done through the FTP Accounts section of the Cpanel. If you have added any ftp users change the passwords for each user. The Special FTP Accounts is set by the cpanel username and password and the password for this changes when the password for the cpanel changes.
Special FTP Accounts

Next we will want to change the login passwords for your web application. Here are a couple examples of common password resets for the following popular web applications: WordPress, Joomla, Prestashop.
Lastly you will want to change the email passwords for every email account you created. This is done through the cpanel in the Email Accounts section.

Step 6: Make sure your code is up-to-date

Always make sure your code is up-to-date. Here is a list of common scripts and the security advisories for each. Also always be wary of plugins and themes because they are also places of weakness.

Latest Version Info Security Advisories at Secunia.com
CKEditor / FCKeditor Security Advisories
Coppermine Photo Gallery Security Advisories
CubeCart Security Advisories
Drupal Security Advisories
Joomla Security Advisories From Joomla
More Advisories
Joomla Vulnerable Extensions List (VEL)
Mambo Security Advisories
Noah’s Classifieds Security Advisories
Nucleus CMS Security Advisories
osCommerce Security Advisories
Prestashop Security Advisories
TinyMCE Security Advisories
vBulletin Security Advisories
WordPress Security Advisories
Zen Cart Security Advisories

Step 7: Examine your code for weak points

Check your code for basic vulnerabilities. Some really common hacks include inserts of small lines of code that are hidden in your scripts. The following is just an example of a single line of hidden code that could be inserted into one of your files.
[php]
eval(base64_decode(‘WW91J3JlIHNpdGUgaGFzIGJlZW4gaGFja2VkIQ==’));
[/php]
The last thing to check security is to make sure your folder permissions are secure. You should almost never have a folder that has permissions set to 777. Most folders and files should either be set to 755 or 644.

Step 8: Identify and block the attacker’s IP address

If you have been able to identify the IP address of the hacker you can block that IP address from ever accessing your site in the future. In the folder where your domain is stored is a hidden file called .htaccess. Open this file in any text editor and and add the following lines of code near the top.

[bash]
order allow,deny
deny from 123.45.6.7
deny from 012.34.5.
allow from all
[/bash]

By saying deny from IP Address you will have successfully blocked that IP of the hacker. Most likely a hacker will have used a proxy or IP address that does not belong to him/her, but this small preventive measure is always a good practice. Also be aware that IP addresses assigned to people can change and in the future the blocked IP address may be assigned to a different person that had nothing to do with hacking your site. The last thing you should do if you are confident you have the right IP address is contact the Internet Service Provider that issued that IP address and report the hack to them. Most of the time the ISP will take action against that IP address because hacking is another person’s site is against their terms of service.

Prevent

  1. Strengthen security on the computer you use to maintain and manage your website
  2. If your own personal computer is at risk then so is your website. Certain viruses will keep track of every key that you hit on your computer and this will give the hacker all the information needed to break into your website, bank account, etc.

    • Make sure your computer has good antivirus software installed and up-to-date.
    • Make sure each week you’re computer has all the necessary security updates.
    • Make sure your web browser (e.g. Firefox, Internet Explorer, etc) and all the plugins are up-to-date.
    • Be weary about using open wireless access points. These can be very easy for someone to watch and grab all the internet content you use.

  1. Make strong passwords
  2. Making a strong passwords is VITALLY important to securing your website and cpanel. Passwords with generic words in them are easily broken. A strong password will be at least eight characters long, contain both upper and lower cases, use numbers, and other random characters. StrongPasswordGenerator.com has a really good tool you can use to generate passwords that are resistant to cracking. Furthermore, changing your passwords periodically is also highly recommended.

  3. Use SSH or shell access carefully
  4. Change your shell password at least every 90 days. If you do not use shell or do not know what SSH is make sure your webhosting company has shell access turned off for your account.

  5. Keep your website software up-to-date
  6. Weather you are using a 3rd party software like WordPress or using your own programming code, always make sure you have the most up-to-date versions. Most3rd party programs like Joomla, WordPress, Drupal, or etc have the ability to update everything from the administrative section of the software. For example, WordPress can update all the software right through it’s dashboard.

  7. Use the .htaccess file to block suspicious activity.
  8. The .htaccess is a file we are going to utilize now in order to implement some more security precautions.

    • Ban Suspicious URL String Queries
    • Open your .htaccess in any text editor and put the following lines of code either at the top or the bottom. This code will block attacks using something called “libwww-perl”, which is a common way of hacking sites.
      [bash]
      SetEnvIfNoCase User-Agent libwww-perl block_bad_bots
      # to deny more User-Agents, copy the line above and change
      # only libwww-perl, to match the new name.
      deny from env=block_bad_bots
      [/bash]

    • Ban Other String Queries
    • Ban IP Addresses That Cause Suspicious Activity
    • Just reference step 8 above.

  9. Back up your information regularly
  10. Your webhosting service should provide a way for you to backup your data on your own and download it. If your webhosting doesn’t have a backup utility or you wish to automate it a bit more you can look into writing a cron job to handle this automatically for you.




.htaccess pdf file redirect

Description

I recently added my resume to my site and needed to make the permalink wordpress makes get redirected to my resume ‘resume.pdf’

Solution

Open the .htaccess file in your web folder and add the following code.
[bash]
RewriteEngine On
Redirect /about/resume-pdf/ /resume.pdf
[/bash]

That’s all, and now you can redirect wordpress permalinks to the proper file.

Setting Up Gentoo Apache for CGI and Perl

Description

There are a few things that need to be done to set up apache2 to run a CGI bin directory so you can run perl scripts. The first is to set apache modules and then then configure the apache vhost conf file.

Setting Up Modules

I edit my /etc/make.conf file to keep all my modules for the my apache installation.
[bash]
#/etc/make.conf
APACHE2_MODULES="actions alias auth_basic authn_alias authn_anon authn_dbm authn_default authn_file authz_dbm authz_default authz_groupfile authz_host authz_owner authz_user autoindex cache dav dav_fs dav_lock deflate dir disk_cache env expires ext_filter file_cache filter headers include info log_config logio mem_cache mime mime_magic negotiation rewrite setenvif speling status unique_id userdir usertrack vhost_alias proxy cgi cgid"
[/bash]

Setup Vhost conf file

These are the things you need to setup your apache vhost conf
[bash]
ScriptAlias /cgi-bin/ "/var/www/zaphinath/cgi-bin/"
AddHandler cgi-script .cgi .pl

<directory /var/www/yourdirectory/>
Options Indexes FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
[/bash]

So that now all you have to do is make sure you run the following commands to make sure your apache is reconfigured and vhosts is set up.

[bash]
emerge -av apache
apachectl graceful
[/bash]

Backing Up Data With Cron Jobs

Description

There are various ways and programs of backing up your systems, but I prefer to control all aspects of my backups and therefore will use cron jobs to do my backups. There are several different types of crons, but they all function the same way.

First you need to open your crontab for editing by simply using
[bash]
crontab -e
[/bash]

Example:

The example I am using to show backups will be for my website here, but this can work with anything. The ‘-u’ is for the username and ‘-p’ is for the password
[bash]
0 2 * * * mysqldump -u zaphinath -p password -h zaphinath > /system/backup/zaphinath.daily.sql
0 2 * * * tar cjf /system/backup/zaphinath.daily.tar.bz2 /var/www/zaphinath/
10 2 * * * bzip2 /system/backup | ssh minastirith.zaphinath.com
[/bash]
This will backup my sql database and my files for my website at 2:00 A.M. and then backup my backup folder at 2:10 and send it to one of my servers. The one thing this requires is keygen to be set up. For a complete list of crontab options go to my cron cheat sheet.

Iptables, Firewalls, Linux

Description

When using iptables I like to keep a text file of my firewall so I can see everything when I need to edit it, open ports, etc. . . There is no requirement where this file is stored, however, I store the file in /system/configuration/firewall.txt.

firewall.txt

[bash]
# Generated by iptables-save v1.4.2 on Fri Mar 20 14:20:07 2009
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [16059:5970755]
:BADFLAGS – [0:0]
:FIREWALL – [0:0]
:REJECTWALL – [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp –tcp-flags FIN,ACK FIN -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags PSH,ACK PSH -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags ACK,URG URG -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,RST FIN,RST -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN FIN,SYN -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags SYN,RST SYN,RST -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,PSH,URG -j BADFLAGS
-A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j BADFLAGS
-A INPUT -p icmp -m icmp –icmp-type 0 -j ACCEPT
-A INPUT -p icmp -m icmp –icmp-type 3 -j ACCEPT
-A INPUT -p icmp -m icmp –icmp-type 11 -j ACCEPT
-A INPUT -p icmp -m icmp –icmp-type 8 -m limit –limit 1/sec -j ACCEPT
-A INPUT -p icmp -j FIREWALL
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 20 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 21 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 53 -j ACCEPT
-A INPUT -i eth0 -p udp -m state –state NEW -m udp –dport 53 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 80 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 139 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 443 -j ACCEPT
#-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 445 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 902 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 3306 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 3688 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 3689 -j ACCEPT
-A INPUT -i eth0 -p udp -m state –state NEW -m udp –dport 4444 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 6881 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 8222 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 8333 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 9312 -j ACCEPT
-A INPUT -s dornick.alunduil.com -i eth0 -p tcp -m state –state NEW -m tcp –dport 9101:9103 -j ACCEPT
-A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p udp -m udp –dport 1024:65535 -j DROP
-A INPUT -i eth0 -p tcp -m tcp –dport 1024:65535 -j DROP
-A INPUT -j REJECTWALL
-A FORWARD -o eth0 -m state –state NEW,RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i eth0 -m state –state RELATED,ESTABLISHED -j ACCEPT
-A BADFLAGS -m limit –limit 10/min -j LOG –log-prefix "BADFLAGS: "
-A BADFLAGS -j DROP
-A FIREWALL -m limit –limit 10/min -j LOG –log-prefix "FIREWALL: "
-A FIREWALL -j DROP
-A REJECTWALL -m limit –limit 10/min -j LOG –log-prefix "REJECTWALL: "
-A REJECTWALL -j REJECT –reject-with icmp-host-unreachable
COMMIT
# Completed on Fri Mar 20 14:20:07 2009
[/bash]

How to update your iptables with this firewall

I use fail2ban, which you can set up if you desire and I highly recommend it. Each time the firewall.txt file is edited this is how you update it.
[bash]
/etc/init.d/fail2ban stop
iptables-restore < /system/configuration/firewall.txt
/etc/init.d/iptables save
/etc/init.d/fail2ban start
[/bash]

WordPress With Multiple Subdomains

Description

I recently edited my WordPress to give me subdomains so that I can keep various different blogs. Example my main site is www.zaphinath.com and I want to add a another blog called einblick.zaphinath.com. This is easy enough to do and I will show you how, the thing that got me however was how do you add themes and plugins through WordPress after this is set up. This feature seemed to disappear, but in reality it just moved. With this in mind lets start and get a multi-site wordpress started.

Step 1: Edit wp-config.php file

Open the file in your WordPress directory called wp-config.php and add this line near the bottom.

[php]
// Add this line for multi-site option
define(‘WP_ALLOW_MULTISITE’, true);
/** Absolute path to the WordPress directory. */
if ( !defined(‘ABSPATH’) )
define(‘ABSPATH’, dirname(__FILE__) . ‘/’);
[/php]

Step 2: Access Tools >> Network

You need to change the Network settings so that you can have proper subdomains created through WordPress. Just go to Tools -> Network and select the type you want.

After you save changes you may be required by WordPress to make some changes. E.G. I had to make my DNS have a wild card in it because the subdomains are now being made by WordPress.

Step 3: Making Edits to all WordPress blogs

Now you have a separate admin for each blog you have and you can create as many different blogs as you wish. However, if you want to add a theme or plugin you will need to go to a separate network admin page that allows you to install plugins that can be used by each blog. Just go to http://www.yourdomain.com/wp-admin/network/. After you search and install plugins, widgits, themes, and etc you will need to access each individual blog’s admin page to activate them.

Change Default SSH Port in Gentoo Linux

Description

If you have a need, for whatever reason, to change the port you use for ssh into your Linux system it’s really easy to do. This small tutorial will show how to do it specifically for a Gentoo Linux OS, but it should be similar for all Linux OS’s. **Note: You don’t have to use port 222 which is sometimes used for rsh-spx. Feel free to use any port that isn’t being used on your server.

Step 1: Open the ssh configuration file

[bash]
su
vim /etc/ssh/sshd_config
[/bash]

Step 2: Change the port

[bash]
Port 22
Port 222
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
[/bash]
I use both port 22 and 222 which tells the ssh daemon to listen for connections from those two ports. Port 222 is just a random unofficial port that can be used. For a complete list of ports just check out the ports wiki for help.

Step 3: Restart ssh daemon

[bash]
/etc/init.d/sshd restart
[/bash]

Step 4: Make sure port 222 is open

Run an nmap command to discover if the port is open.
[bash]
nmap -p 222 server_name
results
[/bash]
My port is blocked by iptables so I will need to edit my firewall and restart my iptables. I save a txt file of my firewall so I just have to update it and then save it to my iptables instead of having to continually edit iptables and not know what is going on.
[bash]
vim /system/configuration/firewall.txt
[/bash]

firewall.txt
[bash]
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 80 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 139 -j ACCEPT
#-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 222 -j ACCEPT
-A INPUT -i eth0 -p tcp -m state –state NEW -m tcp –dport 902 -j ACCEPT
[/bash]

[bash]
/etc/init.d/fail2ban stop
iptables-restore < /system/configuration/firewall.txt
/etc/init.d/iptables save
/etc/init.d/fail2ban start
[/bash]

Step 5: You are ready to ssh

[bash]
ssh -p 222 username@servername
[/bash]

Ruby on Rails 5 Star Rating with Star Rating Widget

Description

With countless rating systems out there I decided to go with JQuery’s Star Rating Widget Plugin for one of my pet sites: www.recisphere.com. The only problem with this is a complete lack of documentation on how to go about using it. I did a dirty hack but it seems to work great so I am going to show you how to set up a rating system with ruby on rails and then use the star rating widget.

Step 1:

I won’t go through this in detail but you will need to have Rails <= 3.09 installed (possibly works in earlier versions but it's not tested) and include the most recent Jquery and plugin javascript and css files. Just follow the Star Rating Widget’s install and required documents section. Also note I use the gem ‘simple_form’, but this can easily be edited to your specific needs.

Step 2:

The plugin pretty much puts makeup on an already existing rating system. You will need to determine the best way to store your ratings and work with that data. Here I will simply show the input. The Star Rating Widget can take input from a few different types. I prefer to use radio buttons. Thus what I did was
[bash]
rails g scaffold user_rating user_id:integer recipe_id:integer user_rating:decimal
[/bash]
This gives us a scaffold and controller to work with. The next step was to edit the controller.
[ruby]
def create
@user_rating = UserRating.find_or_initialize_by_user_id_and_recipe_id(params[:user_rating])
@user_rating.update_attributes(params[:user_rating])
respond_to do |format|
if @user_rating.save
format.html { redirect_to(@user_rating,
:notice => ‘Recipe was successfully created.’) }
format.js
format.xml { render :xml => @user_rating,
:status => :created, :location => @user_rating }
else
format.html { render :action => "new" }
format.xml { render :xml => @user_rating.errors,
:status => :unprocessable_entity }
end
end
end
def edit
@user_rating = UserRating.find_by_user_id_and_recipe_id(params[:user_rating])
end

def update
@user_rating = UserRating.find_by_user_id_and_recipe_id(params[:user_rating])
respond_to do |format|
if @user_rating.update_attributes(params[:user_rating])
format.html { redirect_to(@user_rating, :notice => ‘Recipe was successfully updated.’) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user_rating.errors, :status => :unprocessable_entity }
end
end
end
end
[/ruby]

UserRating.find_or_initialize_by_user_id_and_recipe_id(params[:user_rating]) allows us to create if it doesn’t exist and edit later if it does exist.

Step 3:

Edit wherever you want your form to be kept. The Star Rating Widget is going to change the input from 10 (or how ever many radio buttons you want) into 5 stars. This will have a hidden input that will need to get submitted. The widget has a callback function that will allow any number of functions to be called everytime a rating is changed. By using the callback function with the widget we can successfully change the rating at any time, which is similar to how Netflix operates.
[ruby]

<%= simple_form_for :user_rating, :url => user_ratings_path, :remote => true do |f| %>
<div id="stars-wrapper<%= @recipe.id.to_s %>">
<% (1…11).each do |rates| %>
<%= f.radio_button :user_rating, rates, :class => ["star", @recipe], :checked => rates == (checked)? true : false %>
<% end %>
<% if user_signed_in? %>
<%= f.input :user_id, :as => :hidden, :input_html => { :value => current_user.id } %>
<% end %>
<%= f.input :recipe_id, :as => :hidden, :input_html => { :value => @recipe.id } %>
<%= f.button :submit, :id => "starbutton" %>
</div>
<% end %>
<script type="text/javascript">
$j("<%= "#stars-wrapper" << @recipe.id.to_s %>").stars({
callback: function(value, link){
document.getElementById("starbutton").click();
}
});
</script>
[/ruby]

Step 4:

Now that we have a form submitting and storing values we need to add a little bit of ajax into this so that the page doesn’t get redirected continually. The secret to getting the ajax to work is in the format.js in the controller. Since format.js is a respond call in the create definition it will look for a create.js in the views directory.

Open “ROOTDIR”/app/views/user_ratings/create.js.rjs
[ruby]
page.replace_html(‘stars_show’, render("recipes/star_fields"))
[/ruby]
This uses the prototype library which comes with Rails. Be warned Prototype and JQuery do not work together very well. I had to make a hack to allow me to call jquery calls by making a javascript file called ‘noconflict.js’ and putting the following code in. This is why you see a $j in my javascript calls earlier.
[javascript]
jQuery.noConflict();
var $j = jQuery;
[/javascript]

Conclusion

We just made a rating system for a rails site. Made the controller which will allow us to make a form and submit data to our database. We then made sure we had a working form and covered it with some pretty stars from the Jquery Star Rating Widget Plugin. Then we added a touch of ajax to allow us to not have to redirect or refresh an entire page each time a rating is made or changed.

Facebook Access Vietnam

Description

Due to lovely government restrictions of freedom of speech in Vietnam the website www.facebook.com has now been blocked. The enforcement of this is not very strick and is rather easy to work around. The solution is to reroute the dns services coming to your computer instead of using the default ones provided by any isp in Vietnam. Always use two DNS providers, I have provided a few common DNS servers (Google and Norton), but any DNS server outside of Vietnam and China will work.

DNS Addresses

Google

  • 8.8.8.8
  • 8.8.4.4

Norton

  • 198.153.192.1
  • 198.153.194.1

Change DNS Mac OSX

[text]System Preferences> Network> Built-in Ethernet> Advanced> DNS tab> DNS Servers in Section 8.8.8.8 and 8.8.4.4 added 2 lines[/text]

System Preferences

Internet Preferences

Change Ethernet

DNS Change

Mapping the IP Addresses

Edit the /etc/hosts files in order to redirect the calls to facebook through servers outside of Vietnam.
[bash]
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##

125.252.224.88 facebook.com
125.252.224.88 www.facebook.com
69.63.181.12 apps.facebook.com
153.16.15.71 upload.facebook.com
153.16.15.71 graph.facebook.com
153.16.15.71 facebook.com
153.16.15.71 http://www.facebook.com
153.16.15.71 apps.facebook.com
153.16.15.71 login.facebook.com
153.16.15.71 graph.facebook.com
153.16.15.71 static.ak.connect.facebook.com
153.16.15.71 developers.facebook.com
153.16.15.71 error.facebook.com
153.16.15.71 upload.facebook.com
153.16.15.71 register.facebook.com
153.16.15.71 bigzipfiles.facebook.com
153.16.15.71 pixel.facebook.com

127.0.0.1 localhost
[/bash]

Now just go to www.facebook.com and everything should work.

Change DNS Windows

[text]
Go to Control Panel->Network Connections->local network->Properties->Internet Protocol (TCP/IP)->Properties.
[/text]

windows dns

Mapping the IP Addresses

This file is the same as Mac OSX but is located C:WindowsSystem32driversetchosts