Cibul Tech Blog - Fiddling with PHP, javascript and things

Posts Tagged ‘php’

Install Maxmind’s GeoIP IP database on Ubuntu for PHP

Tuesday, October 19th, 2010

Maxmind provides a useful database and API for server side IP Geolocation. It is useful when you don’t want your server to hang on external services each time fetching a location from an IP address is needed. This posts goes through the installation process of the database with a PHP extension on an Ubuntu platform. I’m writing this for my own use. If it can be useful to you, yeepee.

See it working here. I’ll appreciate it if you can comment at the bottom of the page on how off from the result showed on the page is from your actual location.

Open a terminal

Download the C library in any location on your system (the latest as of today is here):

wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.6.tar.gz

Decompress it: tar -xvzf GeoIP-1.4.6.tar.gz and go into the folder to type the following:

sudo ./configure
sudo make
sudo make check
sudo make install

Download the latest PHP extension (today its here)

Decompress it, go in the geoip folder and type

sudo phpize
sudo ./configure
sudo make
sudo make install

Add the following line in your php.ini file used by apache (in my case: /etc/php5/apache2/php.ini): extension=geoip.so

To see if things have been working well until now, create a php test web page. We’ll make it prettier later on.

<html>
  <head>
    <title>Testing Maxmind GeoLite</title>
  </head>
  <body>
    <?php echo var_dump(geoip_db_get_all_info()) ?>
  </body>
</html>

To complete the installation, unzip and set GeoLiteCity database in the folder indicated by the test page (here /usr/local/share/GeoIP/GeoIPCity.dat).

Once the database is downloaded and placed in the correct location, use the following functions to get the latitude or longitude from the ip address:

$ip_location = geoip_record_by_name($_SERVER['REMOTE_ADDR']);
$ip_location['latitude'];
$ip_location['longitude'];

To wrap things up, the following code puts the retrieved latitude and longitude on a neat little google map. Paste this in your test page:

<html>
  <head>
    <title>Testing Maxmind GeoLite</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    <?php $ip_location = geoip_record_by_name($_SERVER['REMOTE_ADDR']); ?>
   
    var initialize = function(){

      var map = new google.maps.Map(document.getElementById("map"),{
        zoom: 13,
        center: new google.maps.LatLng(<?php echo $ip_location['latitude'] ?>,<?php echo $ip_location['longitude'] ?>),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

    }

    </script>
  </head>
  <body onload="initialize()">
    <h1>IP Geolocation with Maxmind</h1>
    <div id="map" style="width:300px; height:300px; margin: 10px;"></div>
  </body>
</html>

Things should be working now.

Tags: , ,
Posted in Geolocation | 3 Comments »

A really simple sfGuard with user profile setup

Wednesday, May 12th, 2010

When you start trying to see how something works, it’s always nice to see the thing in action and try it out in a simple environment where nothing else can interfere. In the case of this post, the subject is the sfGuard plugin and in particular how it is possible to use it together with an application specific User model. This post gives you a setup with a working sfGuard plugin in a Doctrine & symfony 1.4.4 environment. To have it work, simply decompress this file, do a symfony doctrine:build –all –and-load, configure your server to point to the project and that should be enough.

The model used in this setup is a simple list of users which can be accessed through a user module, where only the access of the show action is restricted to authenticated users. sfGuardAuth signin and signout actions & modules are also used.

Let me know if something doesn’t work as it should.

These posts where helpful:

  • The readme of the plugin itself
  • More details are given on this page. They are definitely worth a read (or 10).


Here is a summary of the steps taken to reach this setup at its downloadable form. The details can be found in the references given above:

  1. Create a project, a frontend app, a schema giving details of a User table and a user module
  2. Get the plugin and put it in the plugins folder
  3. Enable the plugin in the ProjectConfiguration.class.php file, as well as the settings.yml file of the application
  4. In the same settings.yml list the login module and action to be used
  5. In the schema.yml, modifications are made to link the User table to the sfGuard model.
  6. In the app.yml of the app, the User table should be set as the Profile class of the sfGuard model
  7. The show action of the module is secured using a config/security.yml file of the module
  8. The forms need to be adapted as well, an sfGuardUserForm is created to extend the PluginsfGuardUserForm, using the username and password fields only (the others don’t need to be input by the user… after that, the newly created form can be embedded in the User form using the embedRelation function… the form template of the module needs to be adapted as well to take into account these changes.
  9. On last little thing: signin and signout links are set in the layout, using the plugin default routes

Tags: , ,
Posted in Symfony | 10 Comments »

Embedded forms with symfony 1.4 and jQuery

Tuesday, April 13th, 2010

How to implement a single interface to insert multiple entries linked by one-to-many relations…

I’ve been looking recently for a way to build a form that would allow the input of data (edition or adding new data) into multiple related objects. Turns out the way to do this in symfony is to use embedded forms and this what this post is about. I am not an expert in symfony nor in jQuery so if find better ways to do some of the things described here I’ll be happy to read your comments.

We’ll build a listing of events which will be editable to the user. Each event has one or more occurrences (a place and a time). Forms shown should allow the user to edit each event and their related occurrences under the same interface plus leaving them the possibility to add new occurrences if needed.

We will do this in 5 steps:

  1. Setting up the project: we’ll create a symfony project and mysql database
  2. Editing Events: we’ll create a form where both events and occurrences can be edited using embedded forms
  3. Adding new occurrence fields: we’ll add the functionality to add more blank occurrence fields using jQuery Ajax functions
  4. Removing new occurrence fields: still using jQuery, we’ll allow the user to remove blank occurrence fields
  5. Creating a new Event: We’ll modify the form template slightly to allow the user to add more events to the list

Ok, this should take a little while so let’s get started!

1. Setting up the project and showing the index page

We start by setting up a symfony project and building a database based on the following schema and fixtures:

The schema:

#config/doctrine/schema.yml
Event
:
  columns
:
    id
:
      type
: integer
      primary
: true
      autoincrement
: true
    title
:
      type
: string(255)
      notnull
: true
  relations
:
    Occurrences
:
      type
: many
      class
: Occurrence
      local
: id
      foreign
: event_id
      onDelete
: CASCADE

Occurrence
:
  columns
:
    id
:
      type
: integer
      primary
: true
      autoincrement
: true
    location
:
      type
: string(255)
      notnull
: true
    date
:
      type
: date
      notnull
: true
    event_id
:
      type
: integer
      notnull
: true
  relations
:
    Event
:
      type
: one
      local
: event_id

… and the fixtures:

#data/fixtures/fixtures.yml
Event
:
  apero_geant
:
    title
: Apero Geant
  rugby_night
:
    title
: Rugby Night

Occurrence
:
  apero_geant1
:
    Event
: apero_geant
    location
: Marseille, France
    date
: '2009-08-29'
  apero_geant2
:
    Event
: apero_geant
    location
: Nantes, France
    date
: '2009-11-10'
  apero_geant3
:
    Event
: apero_geant
    location
: Rennes, France
    date
: '2010-03-25'
  rugby_night1
:
    Event
: rugby_night
    location
: Yvetot, France
    date
: '2010-03-20'

After generating a frontend app, we can create an ‘event’ module by just adding the event/actions and event/templates directories under the modules directory of the app.

In an action.class.php file, we create a first index action that sends a list of events to an indexSuccess.php template.

<?php // apps/frontend/modules/event/actions/actions.class.php

  class eventActions extends sfActions{

    public function executeIndex(sfWebRequest $request){
      $this->events = Doctrine_Core::getTable('Event')->findAll();
    }

  }

To make things simple, we’ll set the index action as default in the routing, removing the default content.

#app/frontend/config/routing.yml
homepage
:
  url
:  /
  param
: { module: event, action: index }

The occurrences are listed under each event in the indexSuccess.php template:

<!--apps/frontend/modules/templates/indexSuccess.php -->
<h2>Events Index</h2>
<?php foreach($events as $event): ?>
<div class="event-item">
  <h3><?php echo $event->getTitle() ?></h3>
  <ul>
    <?php foreach($event->getOccurrences() as $occurrence): ?>
      <li><?php echo $occurrence->getDate()?> - <?php echo $occurrence->getLocation() ?></li>
    <?php endforeach;?>
  </ul>
</div>
<?php endforeach; ?>

There, the first step is done and the project is set up with a default index page showing the events and their occurrences

2 – Editing existing events & their occurrences

Now we have to setup the embedded form structure

We want to be able to edit any of the listed events and their occurrences in the same form. Let’s start by creating an edit action and associated template and link it to the index page. We’ll start simple and setup a standard form that will allow us to update the title field of the event. Once this is running we will start working with embedded forms to add the possibility to edit the related occurrences as well.

To get things working we need to create an edit action and template to launch the edition form, a submit action for updating the database when the form has been filled, and we’ll add some links to the index page to be able to access the edit menu for each event.

  • Let’s start with the executeEdit() action: It simply creates a form and sends it to the editSuccess.php template
  • // apps/frontend/modules/event/actions/actions.class.php

        public function executeEdit(sfWebRequest $request){
          $this->forward404Unless($event = Doctrine::getTable('Event')->find(array($request->getParameter('id'))), sprintf('Event does not exist (%s).', $request->getParameter('id')));
          $this->form = new EventForm($event);
        }
  • The template editSuccess(): It lays out the form and has it ready to send the result to the submit action
  • <!--apps/frontend/modules/templates/editSuccess.php-->
    <h2>Edit Event</h2>

    <form action="<?php echo url_for('@submit') ?>" method="post">
      <?php echo $form->renderHiddenFields() ?>
      <?php echo $form['title']->renderLabel()?> <?php echo $form['title']->renderError()?> <?php echo $form['title'] ?>
      <input type="submit" value="Save" />
    </form>

    <a href="<?php echo url_for('@homepage')?>">Back to index</a>
  • The routing has to be updated with both edit and submit routes:
  • #app/frontend/config/routing.yml
    edit
    :
      url
    : /edit
      param
    : { module: event, action: edit }

    submit
    :
      url
    : /submit
      param
    : { module: event, action: submit }
  • And the submit action, executeSubmit(): it extracts from the request the values passed on by the form, gets the event object based on the extracted id, makes a form from it, binds it with the request data and updates the database. It is important here to focus on what binding a form means: basically, when the form is created from an event object generated from the database, the values stored are the ones of the database, not the ones input by the user in the previous page; these are still stored in the request object. The bind action consists in taking the values of the request and using them to update the freshly created form, checking the validity of the data in the process, as per the form’s rules. If the validity is confirmed, the database is updated by the save method.
  • // apps/frontend/modules/event/actions/actions.class.php

        public function executeSubmit(sfWebRequest $request){
          $tainted_values = $request->getParameter('event');
          $event = Doctrine::getTable('Event')->find($tainted_values['id']);

          $this->form = new EventForm($event);

          if ($request->isMethod('post') && $this->form->bindAndSave($tainted_values))
            $this->redirect('@homepage');

          $this->setTemplate('edit');
        }
  • The index should have link for each event to allow users to show the edit page, add this under the event title:
  • <!--apps/frontend/modules/templates/indexSuccess.php -->

    <a href="<?php echo url_for('event/edit?id='.$event->getId())?>">edit event</a>

    Now you should have a straightforward way of updating event titles. But here comes the tricky part: how to updated the data of the occurrences of the event as well? This can actually be done easily by fiddling with the event form and embedding occurrence forms to it. But we only want to embed the occurrences which are linked to the event. A method serves that purpose and can be used to do just that in one line: embedRelation(). This method basically takes all related objects and generates the corresponding embedded forms. Enough bla bla, lets update the EventForm class with it:

    <?php //lib/form/doctrine/EventForm.class.php

    class EventForm extends BaseEventForm
    {
      public function configure()
      {
        $this->embedRelation('Occurrences');
      }
    }

    Open the OccurrenceForm.class.php and unset the variables that should’nt be in the form:

    <?php //lib/form/doctrine/OccurrenceForm.class.php

    class OccurrenceForm extends BaseOccurrenceForm
    {
      public function configure()
      {
        unset($this['event_id']);
      }
    }

    Now update as well the editSuccess.php template to show the occurrences of an event when they exist… add this bit under the event title fields:

    <!--apps/frontend/modules/templates/editSuccess.php-->
    <ul>
        <?php foreach ($form['Occurrences'] as $occurrence):?>
        <li>
          <?php echo $occurrence['date']->renderLabel() ?>  <?php echo $occurrence['date']->renderError() ?>
          <?php echo $occurrence['date'] ?>
           -
          <?php echo $occurrence['location']->renderLabel() ?>  <?php echo $occurrence['location']->renderError() ?>
          <?php echo $occurrence['location'] ?>
        </li>
        <?php endforeach ?>
      </ul>

    There. Your form allows you to update the occurrences as well.

    3 – Adding new occurrence field sets with jQuery

    But what if you want to add new occurrences to your event? Wouldn’t it be swell to have some neat way to add new occurrence fields as you please now wouldn’t it?

    Sure it would. And we’ll make it happen using some ajax functions with jQuery.

    To do this, we’ll add some javascript mechanisms on the edition page that will consist in querying the server for some bits of forms, and once receive, appending them to the rest of the page without the need for a refresh. On the server side, a new action will handle the ajax request and re-assemble the forms to send the right piece back.

    We start by adding the jquery library (I’m using jquery 1.4.2) to the js folder as well as an empty js file (eventform.js). In the layout.php of the frontend app we add a reference to each file in the header

    <!--app/frontend/template/layout.php-->
    ...
        <?php include_stylesheets() ?>
        <?php use_javascript('jquery-1.4.2.min.js') ?>
        <?php use_javascript('eventform.js') ?>
        <?php include_javascripts() ?>
    ...

    Now in the editSuccess.php templage, we’ll add a button (a link actually) after the occurrence list. We’ll bind it with javascript behavior to add the new fields.

    <!--apps/frontend/modules/templates/editSuccess.php-->
    ...
    </ul>
    <a id="addoccurrence" href="#">Add an occurrence</a>

    In the javascript file (eventform.js), add the following:

    /* web/js/eventform.js */
    newfieldscount = 0;

    function addNewField(num){
      return $.ajax({
        type: 'GET',
        url: '/add?num='+num,
        async: false
      }).responseText;
    }

    $(document).ready(function(){
      $('#addoccurrence').click(function(e){
        e.preventDefault();
        $('ul').append(addNewField(newfieldscount));
        newfieldscount = newfieldscount + 1;
      });
    });

    Everytime the page element with #addoccurrence as id will be clicked, a new field will be fetched through an ajax request and be appended to the occurrence list. The missing piece now is the processing on the server side of the request. First thing is to update the routing by adding the route we describe in the javascript file…

    #app/frontend/config/routing.yml
    add
    :
      url
    : /add
      param
    : { module: event, action: add }

    … and add the corresponding action, which should work only when the request comes from an XmlHttpRequest.

    // apps/frontend/modules/event/actions/actions.class.php

        public function executeAdd(sfWebRequest $request){
          $this->forward404unless($request->isXmlHttpRequest());
          $number = intval($request->getParameter("num"));

          $this->form = new EventForm();

          $this->form->addNewFields($number);

          return $this->renderPartial('addNew',array('form' => $this->form, 'number' => $number));
        }

    The action calls a method of the EventForm class that will add the number of occurrences needed to replicate the current structure of the form displayed.

    //lib/form/doctrine/EventForm.class.php

      public function addNewFields($number){
        $new_occurrences = new BaseForm();

        for($i=0; $i <= $number; $i+=1){
          $occurrence = new Occurrence();
          $occurrence->setEvent($this->getObject());
          $occurrence_form = new OccurrenceForm($occurrence);

          $new_occurrences->embedForm($i,$occurrence_form);
        }

        $this->embedForm('new', $new_occurrences);
      }

    As you can see, Forms behave as arrays. When you need to create a form with multiple embedded forms, you first create an array of form and you embed in it all the forms that you need. Once you’re done, you embedd that form array into your main form.

    Now we need to create the partial that contains the html to send back to the ajax call. It should contain only the last embedded form (the one to be added).

    //apps/frontend/modules/event/templates/_addNew.php
    <li>
      <?php echo $form['new'][$number]['date']->renderLabel() ?>  <?php echo $form['new'][$number]['date']->renderError() ?>
      <?php echo $form['new'][$number]['date'] ?>
       -
      <?php echo $form['new'][$number]['location']->renderLabel() ?>  <?php echo $form['new'][$number]['location']->renderError() ?>
      <?php echo $form['new'][$number]['location'] ?>
    </li>

    One last thing: now, when the event form is submitted and received by the submit action, the action creates a form to which the data in the request will be bound (the data you just submitted). But before this can happen, the structure of the form needs to match the data received: the number of new embedded forms should be the same as the number submitted. The bind method in the EventForm does just that: it recreates the structure of the request data in the created form before the form binding is done.

    //lib/form/doctrine/EventForm.class.php

      public function bind(array $taintedValues = null, array $taintedFiles = null){

        $new_occurrences = new BaseForm();
        foreach($taintedValues['new'] as $key => $new_occurrence){
          $occurrence = new Occurrence();
          $occurrence->setEvent($this->getObject());
          $occurrence_form = new OccurrenceForm($occurrence);

          $new_occurrences->embedForm($key,$occurrence_form);
        }

        $this->embedForm('new',$new_occurrences);

        parent::bind($taintedValues, $taintedFiles);
      }

    4 – Removing new occurrence field sets with jQuery

    What about removing added empty occurrences? This is less tricky as it does not require any server side processing. All we will need to do now is add a remove link for each of the new occurrence fields and add behavior to them.

    First things first, the remove link has to be added in the addNew.php partial:

    <!--apps/frontend/modules/event/templates/_addNew.php-->
    ...
    <a class="removenew" href="#">Remove</a>
    </li>

    Now some behavior needs to be bound to it. One small thing: as this link is loaded through javascript, the behavior needs to be loaded after the item has been loaded.

    We have to update the eventform.js with a removeNew function which will be launched everytime the remove button is pressed.

    /* web/js/eventform.js */

    var removeNew = function(){
      $('.removenew').click(function(e){
        e.preventDefault();
        $(this).parent().remove();
      })
    };

    Still in the javascript file, update the #addoccurrence button behavior:

    /* web/js/eventform.js */

    $(document).ready(function(){
      $('#addoccurrence').click(function(e){
        e.preventDefault();
        $('ul').append(addNewField(newfieldscount));
        newfieldscount = newfieldscount + 1;
        $('.removenew').unbind('click');
        removeNew();
      });
    });

    Et Voila.

    5 – Adding new events

    Now one last thing we want to do: add a link to the index page to display a form for adding new events. When a new event is created, it should at least contain one occurrence. This should be simple: we will re-use the indexSuccess.php template by modifying it slightly and add a new action.

    We can create the link in the index page (at the end):

    <!--apps/frontend/modules/templates/indexSuccess.php -->

    <a href="<?php echo url_for('@new')?>">Add an Event</a>

    Update the routing.

    #app/frontend/config/routing.yml
    new
    :
      url
    : /new
      param
    : { module: event, action: new }

    … and create the executeNew action

        public function executeNew(sfWebRequest $request){
          $event = new Event();
          $this->form = new EventForm($event);

          $this->form->addNewFields(0);

          $this->setTemplate('edit');
        }

    … and as well update the editSuccess.php template so that one new field is readily available (and non removable) when the form is for a new event. Add this just after the ul tag:

    <!--apps/frontend/modules/templates/editSuccess.php-->
        <?php if ($form->getObject()->isNew()): ?>
        <script type="text/javascript">newfieldscount = 1;</script>
          <li>
            <?php echo $form['new'][0]['date']->renderLabel() ?>  <?php echo $form['new'][0]['date']->renderError() ?>
            <?php echo $form['new'][0]['date'] ?>
             -
            <?php echo $form['new'][0]['location']->renderLabel() ?>  <?php echo $form['new'][0]['location']->renderError() ?>
            <?php echo $form['new'][0]['location'] ?>
          </li>
        <?php endif ?>

    I’ll leave you to do something similar with the title to replace “Edit Event” with “New Event”

    And we’re done! This should allow you to edit and add events and their occurrences, using embedded forms and dynamic functions to add more occurrences. I hope this will be useful for you. Again, your input and comments are welcome.

    By the way, you can download the code here.

    Thanks to Nacho and Nicolas, their posts were very useful. You can find find another interesting tutorial on embedded forms here.

    Tags: , ,
    Posted in Symfony | 44 Comments »