Scripting and Development Guide

From Site5Wiki

Jump to: navigation, search

Contents

PHP

The php scripting language is available on all Site5 hosting accounts. You do not need to do anything specific to your account. Just name your script file with a .php extension and it will be processed as a php script. php4 is the default used at Site5.

Using a custom php.ini file

There are many reasons why you may want to use a custom php.ini file. The php.ini file is used to alter the php default parameters. There is a robust Site5 Forum discussion on this topic here:

http://forums.site5.com/showthread.php?t=3689

Using php5 and php4

php5 is the default at Site5 so if you wish to use PHP 5 you do not need to add any special handlers. If you want to use php4 you can do so using this method:

  1. put this line in the .htaccess file in public_html or the directory you want to have use PHP 4, then all php scripts in that directory will use php4:
  AddHandler application/x-httpd-php4 .php

To avoid receiving a "No input file specified" error, you will need to add the following line to your public_html directory's .htaccess file:

   RewriteEngine On
   Rewritecond %{REQUEST_FILENAME} !-f
   RewriteRule \.php$ /error404.html

Parsing html files as php

If you want to parse html files through php you can add this line to your htaccess file:

Important Note: Having your web site configured to parse regular .html documents as PHP documents will result in some degradation to performance. The parser will be called regardless of if there is PHP within the document and thus it is strongly recommended that you avoid this type of configuration if at all possible.

 AddHandler application/x-httpd-php .php .html

Embedding PHP Scripts Into HTML

The easiest way to handle this would be to convert your SSI include calls to PHP, that way you avoid the need to double-parse each page served. Although includes through SSI are easy, they are just as easy in PHP. Simply convert them to:

 include("/path/to/file.html");

That will also allow you to put PHP code in the included file as well, which could be handy.

If you really need both, you can write a PHP wrapper script to call load the file through the web server (so you get the server parsing) and then run it through PHP using eval(). The code would look like this:

 $code = file_get_contents("http://yoursite.com/some_file.html"); eval('?>' . $code);

Just put that PHP code in a file like some_file.php, and have your visitors go to some_file.php. The page they see will have been parsed twice.

Originally found in this forum thread.

How To Setup Your Own PHP PEAR Environment

We regularly receive requests for PEAR library installations, so I thought it would be a good idea to explain how to setup your own PEAR environment (http://pear.php.net) so you can install the libraries yourself inside your home directory.

In this tutorial, I will be using the $HOME environment variable to represent the home directory (/home/user). The $HOME variable will work in the shell, so most of the commands I show (unless stated otherwise) can simply be copy and pasted into your own shell. You may alternatively use the tilde (~) to represent your home directory, that choice is up to you.

To begin, if you have already attempted to configure your own PEAR environment, please make sure to revert your modifications. Specifically, remove the $HOME/pear directory and the $HOME/.pearrc file, if they exist (WARNING: this will remove any libraries you may already have installed).

The first step you need to take is logging in to the server via SSH. Once logged in, you will see a prompt similar to the one below:

 [user@servername ~]$

To confirm that you are using our version of PEAR and not any locally installed versions, please type the following command:

 which pear

If it returns anything that starts with “/home/” you have not correctly reverted your changes. Please go back through your account and make sure everything has been reverted. You may simply need to run a “source ~/.bash_profile” to pickup the changes or logout and then log back in to your SSH session. If everything is configured properly, the “which pear” command should return the following:

 /usr/local/bin/pear


The first command you need to run is the PEAR configuration file creator. Run the command exactly as shown below:

 pear config-create $HOME $HOME/.pearrc

This command will output a large amount of data showing you where PEAR will be configured to store its various files and directories. It also writes the “.pearrc” file to your home directory. By default, PEAR will keep all binaries installed with PEAR in the main PEAR directory. Some people would rather these be stored in a separate directory ($HOME/bin), so I will show you how to make this change. Simply run the following command:

 pear config-set bin_dir $HOME/bin

Any binaries installed through PEAR will now be installed in the $HOME/bin directory. After that command is run, you will be presented with a “config-set succeeded” message confirming that it was successful. At this point, you need to take note of two configuration values in PEAR, the bin_dir and the php_dir. To get these values, run both of the following commands:

For “bin_dir”:

 pear config-show | grep bin_dir | awk '{print $5}'

For “php_dir”:

 pear config-show | grep php_dir | awk '{print $4}'

We will use both of these later, so make sure to save them somewhere.

You should now be able to install some PEAR libraries. Let’s try to install one called XML_Parser. Run the following command:

 pear install XML_Parser

You should see the following output towards the end, which indicates a successful install:

 install ok: channel://pear.php.net/XML_Parser-1.3.2

Now that PEAR is configured, the next step is ensuring that these libraries are recognized by PHP. By default, PHP only looks in system directories, so you need to make the changes below in order for PHP to see the PEAR libraries you have installed.

First, go to the directory where you are installing your PHP script. If your PHP script is in the public_html directory, you would type “cd $HOME/public_html” at the prompt and hit enter. You then need to copy the default php.ini file into this directory with the following command:

 cp /usr/local/lib/php.ini .

(the period at the end is important, don’t forget to include it)

After the file has been copied, open the file in your favorite command line text editor (vim, pico, or nano) and find the “include_path” line. It will look like this:

 include_path = ".:/usr/lib/php:/usr/local/lib/php"

Note: If you are not comfortable using a command line editor, you can download the file to your computer, make the changes, and then re-upload the file to the server (overwriting the original).

You need to modify the “include_path” line by adding the php_dir path we retrieved earlier. To add it, simply append a colon (:) after /usr/local/lib/php and add the path you retrieved earlier with the “pear config-show” command for php_dir. The final result should look something like this:

 include_path = ".:/usr/lib/php:/usr/local/lib/php:/home/username/pear/php"

(username needs to be your actual user name)

Close that file and save the changes you made. The php.ini file you have created can now be used inside any directory on your account. Remember, if you have another PHP script in a sub-directory that requires any PEAR libraries, you need to copy the modified php.ini file into that directory also.

Your account should now be all set to use PEAR. If you install any PEAR libraries that include binaries (symfony, for example), you may simply call them via the binary name as they will be installed in $HOME/bin. Our default .bash_profile adds the $HOME/bin path to your $PATH environment variable, which is why this works.

Please remember that some PEAR libraries are not in the default PEAR channel and you must do a “pear channel-discover” on the third party channel in order for PEAR to find the requested library.


PHP code snippets

MySQL

The MySQL Database is available on all Site5 hosting accounts. You do not need to do anything specific to your account.

Setting up a MySQL Database

There are three steps to setting up a MySQL database.

  1. SiteAdmin > MySQL databases > manage databases, you must create the database.
  2. SiteAdmin > MySQL databases > manage databases, you must create a user.
  3. SiteAdmin > MySQL databases > manage databases, you must grant permission for the user to access the database.

What is my server name?

Typically a script configuration will require you to specify the MySQL server. The server should be specified as "localhost" when configuring scripts that run on your account, as the MySQL database runs on the same server where your files are served.

If you will be accessing the database remotely (I.E. through a client on your local computer or from an application hosted on a different Site5 account or third-party hosting service), you need to use your domain name as the server name.

Ruby on Rails

Current Versions

All Site5 servers currently have the below versions of Ruby and Rails installed.

  • Ruby: v1.8.7
  • Rails: v.2.3.3
  • Passenger v2.2.4

The following gems are also installed by default (with current versions installed)

Most servers also have older versions as well, but for the sake of readability have been omitted

  • actionmailer (2.3.3, 2.3.2, 2.2.2, 2.0.2): Service layer for easy email delivery and testing.
  • actionpack (2.3.3, 2.3.2, 2.2.2, 2.0.2): Web-flow and rendering framework putting the VC in MVC.
  • actionwebservice (1.2.6, 1.2.5, 1.2.3): Web service support for Action Pack.
  • activerecord (2.3.3, 2.3.2, 2.2.2, 2.0.2): Implements the ActiveRecord pattern for ORM.
  • activesupport (2.3.3, 2.3.2, 2.2.2, 2.0.2): Support and utility classes used by the Rails framework.
  • ferret (0.11.6): Powerful search capabilities.
  • mysql (2.7): MySQL/Ruby provides the same functions for Ruby programs that the MySQL C API provides for C programs.
  • Rails (2.3.3): Web-application framework with template engine, control-flow layer, and ORM.
  • rake (0.8.7): Ruby based make-like utility.
  • sources (0.0.1): Provides download sources for remote gem installation

Additional versions of Rails and gems may be installed on the server depending on the requests of the user base hosted there. However, if you require another version of Rails or gems that are not listed above we recommend that you install it locally on your account so that your applications are not effected by problems caused by any changes made to the globally installed Rails system on the server.

How To Deploy Your Rails Application With Phusion Passenger

With the addition of Phusion Passenger to all our servers, deploying Ruby on Rails applications is now much easier. Phusion Passenger is now the preferred way to use Rails at Site5, but FastCGI is still provided. For most users, adding Phusion is as simple as creating a blank .htaccess file in your application "public" directory with the following lines:

 PassengerEnabled on
 PassengerAppRoot /path/to/your/application/directory

As an example, if your application root directory is located at "/home/username/my_apps/forum" then your PassengerAppRoot line would look like this:

 PassengerAppRoot /home/username/my_apps/forum

It is very important that you put the path to your application root directory, not the path to the "public" directory within your application directory.


If you were recently using FastCGI, it is important that you remove the previous FastCGI mod_rewrite lines in your .htaccess file as they will interfere with the Passenger configuration. The FastCGI lines will look something like this:

 RewriteRule ^$ index.html [QSA]
 RewriteRule ^([^.]+)$ $1.html [QSA]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

Deploying To A Sub Directory With Phusion Passenger

NOTICE: The section below involving modifications to the environment.rb file are not needed if you are deploying to a subdomain (rails.domain.tld) or a main domain (domain.tld). It is only needed if you are deploying to a sub-directory (domain.tld/subdirectory/).

You will need to add one line to the environment.rb file for your application (if you have not already). This file is found in the "config" directory in your application directory. Here is the line you need to add:

 config.action_controller.relative_url_root = "/approot"

The "approot" line should be the name of the root of your application directory. This line must be added within the config block or it will not work correctly. The start of the config block will look like this:

 Rails::Initializer.run do |config|

The "approot" part would be what you want to use as the root URL of your application. For example, let's say your application resides in "/home/user/mygreatapp/" and you want it to be accessible via http://yourdomain.tld/approot/.

You would then make a symbolic link in your public_html directory (/home/user/public_html/) called "approot" that would point to the "public" directory in your application. The symbolic link creation would look like this:

 ln -s /home/user/mygreatapp/public /home/user/public_html/approot

So, now that you have added the necessary lines to your .htaccess file and modified your application accordingly, you should now be up and running with Phusion Passenger.

Routing Errors & 404 Code

If you receive a 404 “page doesn’t exist” error when accessing your application, this is most likely due to your routes not being configured properly (config/routes.rb file). The Rails log file is usually very informative and will tell you why your application is not working correctly. Check the log file in the “log” directory for more information. The routing error will probably look something like this:

 ActionController::RoutingError (No route matches "/approot/" with {:method=>:get}):

If you receive an error similar to that, you will need to adjust your routes accordingly to accommodate the base URL. You can get a good overview of your routes by running “rake routes” from anywhere within your application directory.

Restarting Your Application

Since adding Phusion, we have received quite a few requests regarding the best way to restart a Rails application. Phusion has provided a very simple mechanism for accomplishing this. All you need to do is create or modify a “restart.txt” file within the “tmp” directory of your application. If your application is located at “/home/user/mygreatapp/” you would simply run:

 touch /home/user/mygreatapp/tmp/restart.txt

In previous versions of Phusion, the restart.txt file would be automatically deleted after the restart was accomplished, but this is no longer the case. Phusion just checks if the file was modified, so you can keep the empty file there and touch it whenever you want to force a restart.

For more tips and tricks on using Phusion Passenger, please check out the official Phusion documentation.

Configure your Rails Application for Production Mode with FastCGI

So you've provisioned your application and you're ready to go live. Simply follow the steps outlined below and you'll be up and running in Production mode using FastCGI in no time at all!

    1. Make sure you production database is properly configured ( and of course populated ) by reviewing the settings in your "APPNAME/config/database.yml".
    2. Un-comment the "#ENV['RAILS_ENV'] ||= 'production'" line within your "APPNAME/config/environment.rb".
    3. Within your "APPNAME/public/.htaccess" modify the following line:
"RewriteRule ^(.*)$ dispatch.cgi [QSA,L]"
To:
"RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]"

That's it! You're done! Fire up your application by visiting the URL you've previously configured it to function under.


Installing Ruby Gems

If your application requires extra ruby gems installed we would recommend that you install them locally to your account rather then request that customer service install them globally for you. Installing them locally will allow you more freedom to modify the gems as well as install gems that are not located in the public gem repository. Site5 administrators will be unable to install any gems which are not located in the public gem repository for security reasons.

A member of our forums, dusty.doris, has compiled a wonderful Howto Install your own Gems for Rails Guide.

You may also want to check out The New user's guide to freezing a Ruby on Rails application which was created by another member of our forums by the name of davesailor. This guide describes how to freeze your application along with the gems that it uses to ensure that it remains in a working state.

Testing Before Changing DNS — Ruby and /~username

Adam Greenfield notes in this forums post that to you need to use a rewritebase of /~username:

RewriteEngine on
RewriteBase /~username

Replace username with the correct one for your account.

Example of How to Install a Basic RoR Application

For this example, we'll be installing Solunas 2 in order to demonstrate the installation of an application that has a fairly basic setup from downloading to a working installation.

  • This example assumes Solunas 2 (RoR) is already downloaded to your local computer. The release/filename for this tutorial is solunas2.0.1.zip, however that may change in the future.
  • For this example, the user name will be "myuser" without the quotes. When applying this to your own account, this would change to the same username as used for your primary FTP username.


First, create a directory in your account for this application. This should NOT be under public_html, for this example we will create the "apps" directory under document root:

 mkdir ~/apps


# Upload the solunas2.0.1.zip file to the above location. Use any method you like.


Now, change to the above directory and unarchive it:

 cd ~/apps
 unzip solunas2.0.1.zip


This will create the sub-directory "solunas" which is part of the archive, change to the new directory.

 cd solunas


Now, with any new rails application it is good practice to ensure the correct permissions on files and directories. This can be done multiple ways, however the below should work for the majority of rails applications. This should be done from the root of the application's directory, and since we're already in that directory, lets proceed:

 find . -type d -exec chmod 755 {} \;
 find . -type f -exec chmod 644 {} \;
 chmod -R 755 script
 chmod 755 public/dispatch.*


Now, since we want to run in *FastCGI, lets modify the .htaccess file to do this. First we'll also change to the "public" directory, noting that in this example we'll use vi, however you can use any editor you feel like:

 cd public
 vi .htaccess


Image:Warning.png This tutorial assumes familiarity with VI, please use any editor you are familiar with.

Change the line

 "RewriteRule ^(.*)$ dispatch.cgi [QSA,L]"

to

 "RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]"

save the file, and and quit.


Note that the only change above was simply changing "dispatch.cgi" to "dispatch.fcgi" in the mentioned line.

Now, depending on your application you may already know which rails version is required for an application to run -- if you're developing your own, it would be the same version you're developing under. Since we don't know what version is required for Solunas 2, running the dispatch.fcgi script will let us know:

 ./dispatch.fcgi


The above will output:

 "Cannot find gem for Rails =1.1.6: Install the missing gem with 'gem install -v=1.1.6 rails',
 or change environment.rb to define RAILS_GEM_VERSION with your desired version."


Since Rails version 1.1.6 appears required, freeze it to the application's vendor directory. This should be done even if the version of rails is available on the server, to ensure future compatibility and to avoid any potential issues with server changes.

Change back to the applications root directory, which should be one level up:

 cd ..


Run svn export to download the needed version of rails and place it in vendor/rails.

 svn export http://dev.rubyonrails.org/svn/rails/tags/rel_1-1-6 vendor/rails


Now, the basics for any ruby application have been completed. Lets continue with the actual Solunas setup instructions provided on their website.

Create DB and Mysql user using your SiteAdmin or cPanel control panel (depending on account type), assign the newly created Mysql user to the newly created database giving it "all" permissions. Take note of the username, password, and database name you create, this will be needed later.


Now, moving back to the shell/terminal. Lets edit the database.yml file to setup the new database login details.

 vi config/database.yml

#Enter appropriate details per the above, save, and quit. You should enter the details in both production and development in the configuration file, but NOT under the "test" section.


Now, we'll import the default data that Solunas provided for the database.

 mysql --user=myuser_USER --pass=MYPASS myuser_MYDB < db/solunas.sql 

(again, replace appropriate details with created details earlier)


Now, the final step is to create a symlink under public_html to be able to view the application from the web.

 ln -s ~/apps/solunas/public ~/public_html/solunas


The installation is complete at this point, visit your new installation of Solunas 2:

http://mydomain.com/solunas/

Specifying a HELO for use with Central Mail

If you are setting up an application to use SMTP authentication, you will need to specify a HELO domain using ':domain'.

Source: http://api.rubyonrails.org/classes/ActionMailer/Base.html

More Information

More programming and installation tips, tricks, and instruction may be found on this wiki's Ruby page.

Using Subversion

Site5 customer and forum member patram1121 was nice enough to document the process of setting up and using Subversion on a Site5 account. Rather than copying and pasting his tutorial here, we figured we'd just send you directly to the source (which is a thread at the Site5 forums):

http://forums.site5.com/showthread.php?t=11008

The great thing is that if you have problems or questions, you can post a reply and patram1121 will receive notification of such and possibly be kind enough to help you out.

Subversion with Rails and Capistrano (formerly Switchtower)

If you're going to be hitting the Rails development train at full speed, you'll probably want all the cool toys that make using Rails such a joy. Site5 forum user jbnorthrup has documented the process marvelously in the following forum thread:

http://forums.site5.com/showthread.php?t=7348

The thread has grown quite a bit since the initial post, but include lots of additional troubleshooting info and even instructions on how to get Subclipse (an extension of the Eclipse IDE that uses Subversion) working with your new setup.

When it comes to Capistrano on Site5, forum user aficionado did his research and wrote the authoritative source on the topic: http://www.thebitguru.com/articles/9

Note: The latest versions of Capistrano use a set of permissions that do not work well with the SuExec environment, under which FastCGI runs. You can put this in your deploy.rb file to prevent Capistrano from changing the permissions of your files and directories:

task :set_permissions do
donothing = true
end

Porting Python 2.x applications to Python 3.0

Upgrading your application from Python 2.x to 3.x should be fairly simple with the help of some great tools by the Python community. The first step will be making sure it runs well under Python 2.6, with out warnings and errors of course. Afterwards, you can run the application with the '-3' argument to the python interpreter and receive all the warnings about your code that will not be compatible under 3.0. You can also use the python script '2to3' (included with the 2.6 distribution) and it will automatically rewrite your script for 3.0, the best it can.

Changes in 3.0

http://docs.python.org/3.0/whatsnew/3.0.html


Py3k is NOT backwards compatible with the 2.x branch, some of the major changes are as follows..

  • 'print' is now an actual function, IE: print()
  • various widely used api's now return views or iterators instead of the expected (in 2.x) lists.
  • simplified rules for ordering comparisons
  • integers,floats and octals have changed - IE: int is now by default long
  • switched to text and data vs. unicode and 8bit
  • syntax changes - modified/removed
  • various library changes
  • new string format (% is still understood but -will- be removed in 3.1)
  • exception handling has been cleaned up and revamped with new features
  • operators and special methods have been renamed or work differently now


It's important to note that is not recommended to try and write code that is compatible with both 2.x and 3.0 - there are just to many major changes.

Important scripts and programs

The location on the servers for all the necessary scripts and programs are going to be located under /usr/local/bin/

  • 2to3
  • python2.6
  • python3.0

At the top of your python scripts you will have the following line, depending on which version you will be using.

#!/usr/local/bin/python2.6
#!/usr/local/bin/python3.0

Getting a preview of necessary source modifications

You can use the '-3' argument to python in order to view the relevant changes that will need to be implemented in order to be compatible with 3.0. Note that the application will still run as normal, it will just print out warnings so you know what is not compatible. Also note that it will not give you warnings about -all- necessary changes, for example nothing is warned about 'print' statements.

DeprecationWarning: dict.has_key() not supported in 3.x; use the in operator
  if cnf.has_key('class_'):
callable() not supported in 3.x; use hasattr(o, '__call__')
  if callable(v):

Using the automated source translator

Once you are ready to take the plunge and port your code to 3.0, there is a very hand tool ready to use that can do most of the work for you - aptly named '2to3'.


http://docs.python.org/library/2to3.html


The following code is normal Py2k source...

# cat cel.py 
import string, sys

if len(sys.argv)==1:
    print 'Usage: ',sys.argv[0],' temp1 temp2 ...'
    sys.exit(0) 

for X in sys.argv[1:]:
    try: 
       F=float(string.atoi(X))
    except string.atoi_error: 
       print 'Hmmm... Cant convert',repr(X),'- try a number...'
    else:
       C=(F-32)*5.0/9.0
       print '%iF = %iC' % (int(F), int(C+.5))

The following output is the 2to3 script with no arguments.. The preceding '-' is what will be removed from the original source, and the following lines preceding with a '+' with be inserted in it's place, the lines with out a '-' or '+' will be left alone. Each 'fixer' is a module designed to handle the syntax and required changes for that particular situation, you can obtain a list of available 'fixers' with the '-l' argument, you can also write your own which is not covered here but you can follow the above link for more information.

# /usr/local/bin/2to3 cel.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
--- cel.py (original)
+++ cel.py (refactored)
@@ -1,15 +1,15 @@
 import string, sys
 
 if len(sys.argv)==1:
-    print 'Usage: ',sys.argv[0],' temp1 temp2 ...'
+    print('Usage: ',sys.argv[0],' temp1 temp2 ...')
     sys.exit(0)
 
 for X in sys.argv[1:]:
     try: 
         F=float(string.atoi(X))
     except string.atoi_error:
-	print 'Hmmm... Cant convert',repr(X),'- try a number...'
+	print('Hmmm... Cant convert',repr(X),'- try a number...')
    else:
	C=(F-32)*5.0/9.0
-	print '%iF = %iC' % (int(F), int(C+.5))
+	print('%iF = %iC' % (int(F), int(C+.5)))

RefactoringTool: Files that need to be modified:
RefactoringTool: cel.py

Executing '2to3' with the '-w' argument will write the changes back to your source code, and give a backup copy of the original 2.x source. You can run the script against multiple files (*.py) or against a directory and it will translate everything it can in one run.

Below is the resulting source compatible with 3.0

import string, sys

if len(sys.argv)==1:
    print('Usage: ',sys.argv[0],' temp1 temp2 ...')
    sys.exit(0)

for X in sys.argv[1:]:
    try: 
        F=float(string.atoi(X))
    except string.atoi_error: 
        print('Hmmm... Cant convert',repr(X),'- try a number...')
    else:
        C=(F-32)*5.0/9.0
        print('%iF = %iC' % (int(F), int(C+.5)))
# ll
total 68
-rw-r--r-- 1 penguin penguin  312 2009-02-20 11:30 cel.py
-rw-r--r-- 1 penguin penguin  309 2009-02-20 11:24 cel.py.bak


Image:Tag_red.png Related wiki pages: MySQL. PHP. Ruby, Ruby on Rails, Rails, Gems, Ferret, ERuby, PEAR, .htaccess

Personal tools