odtPHP 1.0.1 Repair Document Warning Bug Solved alongwith Replacing tags in header/footer

Hello..

Recently I was working on odtPHP to generate OpenOffice.org  writer (.odt) file on the fly using PHP. I was using lastest version (1.0.1) of odtPHP. But I found a bug in software. Whenever I try to insert images in the document (specially in a segment), I was getting warning by OpenOffice (3.x) that the resultant file is corrupted and asks to repair document or not. Sometimes this warning can occur if your template is not correctly formated but I verified that this problem also exists with tutorial 5 present in odtPHP package (tested on Ubuntu 10.04 with OpenOffice 3.2).  Although the document repaired by OpenOffice is perfectly fine, but it seems unusual and awkward to people. Also this bug seems to me as a big stone in a smooth path as I can’t be able to convert odt to pdf on the fly using any available tools. The reason is that as the resultant file is corrupted all available tools fail to load/open the document. As said by some great personality “Necessity is the Mother of Invention”, I tried to solve the problem and got success. Below is the reason of problem and solution:

Reason of Problem (bug):-

As I tested the odtPHP software with OpenOffice 3.x, I found that OpenOffice  keeps the record of all files present in .odt archieve file in the manifest.xml file present under META-INF directory. You can open OpenOffice .odt file with any archive manager to see files present under the document. You must find the above said file there.

Now the problem with odtPHP 1.0 is that it only modifies content.xml file and does not edit manifest.xml file. So, when your odt document (generated by odtPHP) contains images, it means you are increasing the number of files in the archive without informing the OpenOffice about their type, path etc. in the manifest.xml file. This has resulted to the corrupted document warning upon opening the file.

Solution of above Bug:-

I have modified odf.php and Segment.php files (present in the library directory of odtPHP package) so that they also modify manifest.xml file to add information about images. You can download these files as zip package from the following link-:

https://docs.google.com/leaf?id=0B0BfaiUk95FTNTJiODk1MTEtYjc4OS00Y2RiLTgyNTktZDE0YTA5OTdlMWZh&hl=en&authkey=CMXv9NgN

Download odtPHP-1.0.1 from odtPHP official website-:

http://www.odtphp.com/

Extract the zip archive and replace the original files (in the library directory) with these files. Now try again the tutorial 5 present in tests directory of odtPHP, you will find that now OpenOffice opens the downloaded file without any warning. If still you are getting corrupt file warning, feel free to ask me.

Replacing tags in header/footer:-

Also, odtPHP version (1.0.1) does not support replacing tags in header or footer sections of document. It requires the editing of styles.xml file of OO template. So, recently I modified odf.php file so that it also replaces tags with text in header or footer sections odt document just it does for body section of the document. Also, now images information is added in manifest.xml file according to extension of image (for compatibility with future releases of OO).🙂

Have Fun..!!

Connecting to remote MySQL Server

Hello to all. Few days back I was asked to connect to remote MySQL Server without actually logging in to shell account at Server i.e without using telnet,ssh etc. If you too face a similar issue then follow simple steps given below-:

Steps:

  • Install MySQL Client on client machine:

You need  MySQL client on client machine to directly connect to MySQL server. For that find appropriate client package according to Operating System of client machine. If you also have MySQL Server installed on client machine then you don’t need to install MySQL client.

  • Open Server configuration file:

Login to the Server using shell or any other means. Then open your MySQL my.cnf file. If you have installed MySQL server binaries then this file is most likely to find at /etc/my.cnf or /etc/mysql/my.cnf. But if you have compiled MySQL from source then find this file under your MySQL install prefix. Also, note that you need root privileges to edit this file.

  • Edit Server configuration file:

Now, under MySql configuratin settings look for line starting at “bind-address” such as:

bind-address        = 127.0.0.1
Change the address value to the IP address of the Server and save the file.
  • Restart MySQL Server:

Now restart your MySQL Server. For example: On many Linux environments this command will do it.

$sudo /etc/init.d/mysql restart

MySQL Server now listens requests coming from IP interface so remote clients requests are now received by Server.

  • Edit user settings:

Now edit the settings of user you want to connect to Server as. Easy way is to configure user using Privileges Tab of PhpMyAdmin. Under host field select ANY to bind from any IP address or give particular IP of your client if you don’t want to connect to Server from anywhere of the world except from Server itself and your client pc. It is advised to not remove previous entry of the user (entry for localhost). Also, it is advised to set a different password of good strength to connect to Server from outside for Security reasons. This is big advantage of MySQL that you can choose different passwords for same user depending on the host from which you are connecting.

  • Flush privileges:

Now, flush privileges, if you have edited user from commandline. PhpMyAdmin will automatically do it.

Thats it. Now, try connecting to MySQL Server from client machine with following command:

$mysql -h ServerIP -u username -p

Replace ServerIP and username with yours in above command. If you see MySQL prompt (mysql>) that means you have successfully configured the Server. If you are getting error such as:

ERROR 1045 (28000): Access denied for user 'username'@'hostnamw' (using password: YES)

Then you have not configured/edited the user properly. Other source of Errors is Firewall, be sure that MySQL Port (3306 by default) is opened in Firewall.

Have Fun!!

Configuring Virtual Hosts in Apache 2.x

Hello friends. Today I am going to tell you about configuring Virtual Hosts in Apache. Firstly, you should know that what are Virtual Hosts? If not, below is definition from Wikipedia:

Virtual hosting is a method for hosting multiple domain names on a computer using a single IP address. This allows one machine to share its resources, such as memory and processor cycles, to use its resources more efficiently.

In simple words, If you want to host multiple websites (domains) on a single server then Virtual Hosting is what you need !!. Lets have some discussion about Virtual hosts, if you don’t like theory you can skip directly to configuration part.

Types of Virtual Hosts:

Virtual hosts can be of two types:

  1. Name-based Virtual Hosts
  2. IP based Virtual Hosts.

Name-based Virtual Hosts:

Name-based virtual hosts use multiple host names for the same webserver IP address. Using this method you can host multiple domains (different host names), even if your server has only one Network Interface Card (NIC) i.e one IP. Web server is configured to provide different website based on host name requested by user. If the user requests directly using IP address of server, then default website is provided.

IP-based Virtual Hosts:

In IP-based Virtual Hosts, each site points to a unique IP address. IP-based Virtual Hosting is useful if your server has more than one NIC /IP’s. In that case you can configure your web server to host different site based on the IP address for which request is coming. This type is Virtual hosting is very rarely used.

Name-based Virtual Hosts Configuration:

Here, I am explaining configuration for Apache 2.x. If you are not using Apache as web server then rest of the post is not useful to you. To configure Name-based Virtual Hosts open your server’s httpd.conf file. Search and uncomment the following line is not already uncommented.

NameVirtualHost *:80

If you are unable to find above line in your configuration then it may be possible that Virtual Hosts settings are defined in separate file. Take a look at include directives defined in the httpd.conf file and try to find the right file. For example- In my case, I found the following line in my httpd.conf file:

Include conf/extra/httpd-vhosts.conf

Add or edit rest of configuration at appropriate place according to your httpd.conf. Note that Virtual Hosts in Ubuntu are handled differently, if you install Apache using Ubuntu repositories. I will explain configuration for Ubuntu later in this topic.

For default website, place its contents under Document Root of your web server. You do not need to configure Virtual host for default website. For websites other that default, enter the following lines in appropriate file.

<VirtualHost *:80>
 ServerAdmin root@example.com
 DocumentRoot "/var/www/drupal"
 ServerName example.com
 ErrorLog "logs/example.com-error_log"
 CustomLog "logs/example.com-access_log" common
</VirtualHost>

Here, I am using example.com as host name. Change it to your host name. Also, change the value of DocumentRoot to the path of your Virtual Host web directory i.e directory which you want to server when request comes from the name defined as ServerName. Restart Apache for the configuration to take effect.

IP-based Virtual Hosts Configuration:

For IP-based Virtual Hosts, add following lines in the appropriate file (see above section for selecting file).

<VirtualHost example1.com>
ServerAdmin root@example1.com
DocumentRoot "/var/www/example1"
ServerName example1.com
ErrorLog "logs/example1.com-error_log"
CustomLog "logs/example1.com-access_log" common
</Virtualhost>

Do not forget to replace host name and DocumentRoot with your own host name. You can also use IP address in <VirtualHost > directive here. Then restart Apache.

Virtual Hosts configuration in Ubuntu:

If you are using Ubuntu Linux distribution and Apache is installed using Ubuntu repositories. Then to configure Virtual Hosts you have to follow following steps:

  • Open /etc/apache2/apache2.conf file. Be sure that following line is uncommented under Virtual Hosts section.
Include /etc/apache2/sites-enabled/
  • Then create a separate file for each Virtual Host you want to configure in the /etc/apache2/sites-enabled/ folder.
  • Write Virtual Host configurations for each Virtual Hosts in their respective files. Configuration is same as discussed in above sections.
  • Restart your webserver. Following command can do it.
$sudo /etc/init.d/apache2 restart

 

Installing FreeCAD 0.10 in Ubuntu Lucid

Hello to all. Today I am going to explain the procedure to install FreeCAD 0.10 on Ubuntu Lucid.

Firstly, What is FreeCAD?

FreeCAD is a general purpose Open Source 3D CAD/MCAD/CAx/CAE/PLM modeler, aimed directly at mechanical engineering and product design but also fits in a wider range of uses around engineering, such as architecture or other engineering specialties. It is a feature-based parametric modeler with a modular software architecture which makes it easy to provide additional functionality without modifying the core system.

FreeCAD is based on OpenCasCade, a powerful geometry kernel, features an Open Inventor-compliant 3D scene representation model provided by the Coin 3D library, and a broad python API. The interface is built with Qt. FreeCAD runs exactly the same way on Windows, Mac OSX and Linux platforms.

Simple steps to successfully install and run FreeCAD 0.10-:

  • Install FreeCAD 0.9 using ubuntu repositories.

To do that type the following command on terminal.

$sudo apt-get install freecad

As currently Ubuntu repositories provide FreeCAD 0.9, so above command install FreeCAD 0.9 on your system. You can also use Ubuntu package manager instead of above command.

  • Verify the installation.

To verify the installation run FreeCAD from Applications -> Graphics ->FreeCAD or by giving following command on terminal-:

$freecad

Note-: Bug in python-pivy package provided by Ubuntu repositories.

If you are unable to draw any 2-D component such as line, circle, rectangle etc. and FreeCAD is giving your errors much likely as shown bolow-:

Error: Draft_line command not found

This means there is a bug in python-pivy package which is used by FreeCAD to draw all 2-D figures. Next step will explain how to remove this bug. If you are not facing this type of error may be Ubuntu has resolved this issue then you can skip the next step.

  • Resolving buggy python-pivy error

Firstly, remove existing python-pivy package with this command.

$ sudo apt-get remove python-pivy

Now, download the latest python-pivy package from debian. Download the package appropriate for your CPU architecture from the link below-:

Download python-pivy

Install this .deb package by double clicking on it or by this command-:

$ dpkg -i python-pivy*.deb

  • Install FreeCAD 0.10

I have experienced some problems with FreeCAD 0.9, one is the shape of circle is not perfectly round. So it would be better to use FreeCAD 0.10 and stay updated. For that, download FreeCAD 0.10 (.deb package) from following link-:

FreeCAD from sourceforge.net


Be sure to download .deb package available under FreeCAD Linux.

Now remove existing FreeCAD 0.9 package with this command-:

$ sudo apt-get remove freecad

At last, install the downloaded FreeCAD 0.10 .deb package by double clicking on it or via following command-:

$sudo dbpkg -i freecad_*.deb

Now run the new FreeCAD installation and Enjoy.

Have Fun !!.

Inserting and displaying images in MySQL using PHP

Well working with images is quite easy task in MySQL  using php code. Some years back managing images in relational database is quite complex task as at those times relational databases are able to store only textual data so file path to the images are stored in database and images are stored and retrieved externally. Also special  file functions are necessary for retrieving  images this way and this approach is system dependent (because of path names used). Nowadays, almost all major DBMS support storing of images directly in database by storing images in the form of binary data. Here, I am explaining the method of storing and retrieving images in MySQL database using PHP code.

Inserting images in mysql-:

MySQL has a blob data type which can used to store binary data. A blob is a collection of binary data stored as a single entity in a database management system. Blobs are typically images, audio or other multimedia blob objects. MySQL has four BLOB types:

  • TINYBLOB
  • BLOB
  • MEDIUMBLOB
  • LONGBLOB

All these types differ only in their sizes.

For my demonstration, lets us create a test table named test_image in MySQL having 3 columns show below-:

  • Id (INT) -Act as primary key for table.
  • Name (VARCHAR) – Used to store image name.
  • Image (BLOB) – Used to store actual image data.

You can use phpMyAdmin tool to create the above table else use the following MySQL query-:

create table test_image (
id              int(10)  not null AUTO_INCREMENT PRIMARY KEY,
name            varchar(25) not null default '',
image           blob        not null
 );

PHP code to upload image and store in database-:

To upload the image file from client to server and then store image in MySQL database on server, I am posting here the PHP code for our test/sample table (test_image).

Please change the values of variables in file_constants.php file according to your system. Save the following scripts with names as shown in your web directory.

file_constants.php

<?php
$host="your_hostname";
$user="your_databaseuser";
$pass="your_database_password";
$db="database_name_to_use";
?>

file_insert.php

<html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>

<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>

<?php

// check if a file was submitted
if(!isset($_FILES['userfile']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try {
    $msg= upload();  //this will upload your image
    echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';
    }
}

// the upload function

function upload() {
    include "file_constants.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {    

            //checks size of uploaded image on server side
            if( $_FILES['userfile']['size'] < $maxsize) {  
  
               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {    

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    mysql_connect($host, $user, $pass) OR DIE (mysql_error());

                    // select the db
                    mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO test_image
                    (image, name)
                    VALUES
                    ('{$imgData}', '{$_FILES['userfile']['name']}');";

                    // insert the image
                    mysql_query($sql) or die("Error in Query: " . mysql_error());
                    $msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
                }
                else
                    $msg="<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg="File not uploaded successfully.";

    }
    else {
        $msg= file_upload_error_message($_FILES['userfile']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>
</body>
</html>

Below is screenshot of above web page when executed by browser-:

With this you will be able to upload and store images in MySQL database. Also check for the presence of file in the database using phpMyAdmin or any other tool.

Displaying images stored in MySQL-:

Now we are in a position to write PHP code to see images stored by the above script. For that firstly save the script below with name file_display.php in your web directory.

file_display.php

<?php
 include "file_constants.php";
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $link = mysql_connect("$host", "$user", "$pass")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("$db") or die(mysql_error());

     // get the image from the db
     $sql = "SELECT image FROM test_image WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

     // set the header for the image
     header("Content-type: image/jpeg");
     echo mysql_result($result, 0);

     // close the db link
     mysql_close($link);
 }
 else {
     echo 'Please use a real id number';
 }
?>

Now you can see the images stored in the database using the following query string-:

http://{path_to_your_web_directory}/file_display.php?id=1

You will see image which is stored  in database corresponding to id having value  “1” . You can use different numbers to see different images. Below is a sample screenshot-:

Migrating from MS SQL to PostgreSQL or from MySQL to PostgreSQL

PostgreSQL  is another strong widely used companion in addition to MySQL in the field of free and open source softwares (FOSS). PostgreSQL also has extension names PostGIS which is specially designed to handle Map data efficiently. If you have your existing data in MS SQL or MySQL and want to migrate it to PostgreSQL then follow the following steps-:

  • Firstly, if you are migrating from MS SQL , then migrate your database to MySQL . You can follow my previous post for details. Here is the link of the post Migrating from MS SQL to MySQL.
  • After migrating to MySQL download and install PostgreSQL if not already in your pc from the PostgreSQL website. Ready to install (.bin) files for Linux and .exe files for Windows are available to download.
  • When installation of PostgreSQL is completed it will ask you for adding additional components. Continue on this window by clicking on Next button. If you already have PostgreSQL installed on your pc then start PostgreSQL Application Stack Builder from Start Menu in case of Windows or from Applications Menu in case of Linux. You can also use following command under Linux

#{PostgreSQL installation path}/scripts/launchstackbuilder.sh

Select your server on first Screen and click on Next.

  • Now select EnterpriseDB MySQL migration wizard under Registration required add-ons as shown in following screenshot-:
  • You have to register on PostgreSQL website for installing the above add-on . Then follow on screen options to complete installation.
  • Now run the Migration Wizard from  Linux (Applications–>PostgreSQL Plus Add-ons –>Migration Wizard) or from Windows (Start Menu –>PostgreSQL Plus Add-ons –> Migration Wizard). Below is Screenshot of Migration Wizard-:
  • Now fill in the various fields according to your configuration and then follow on screen instructions to complete the migration process
  • After migrating data you can use phpPgAdmin or pgAdmin graphical tools to log in to your database and verify the transfer process.

Where Linux is lagging behind Windows?

As we know today Linux OS have become much user friendly comparing to the scene some years back. Also now graphics of Linux distributions are really nice. Even Linux comes with such features which windows can’t such as virus free environment, free softwares  and OS, robust,  great environment for servers, free mailing and community lists etc. Its advantages are endless and I too recommend to explore the power of Linux OS. Despite of  these great advantages,today  the market share of Linux OS is less than Windows OS due to some reasons such as support for proprietary drivers, dependencies required by softwares etc. I am discussing here the later issue.

Now a days there are a lot of package managers like yum for rpm, apt-get for debian etc. Despite of these package managers , sometimes when you are trying to install something you have to do a lot of hard work such as searching and downloading dependencies packages, if not resolved automatically by package manager. A normal user or newbabies to Linux may feel awkward  and if you installing from source, then the game is much more complex in the sense that you have to compile and install individual dependency and dependencies of dependency and so on. So it may be possible that you wont get anything i.e wont be able to install required software after a lot of hard work due to unavailability or incompatibility  of some nested dependencies. This way you may got angry and may do some stupid things such as shut down pc directly by removing power cable as i experienced this  sometimes.

Suggested Solution-:

There is no doubt that the concept of dependencies has its own advantages, the major one is this helps the software developers to reduce the size of their softwares by great extent. But according to me its limitations can be decreased to great extent by the following these solutions -:

  • Firstly, like Linux Filesystem Standard, the Linux Library Standard or Linux Utility Standard should be made and be followed worldwide by all major vendors of Linux distributions. This way software developers know what libraries and utilities will be present on  the machines so they can include libraries/utilities other than  specified by the standard in their package. At the most dependencies upto one level should be allowed (to reduce the size of software).  This step would be in great advancement towards making Linux easy to use and user friendly and also helps to save a lot of time of users in installing software packages like windows.
  • The software developers should provide legacy backward compatibility to their softwares so that their packages doesn’t behave differently based on libraries, utilities or dependencies version. This way users will be able to install new software packages on their old versions of OS.