Posterous
Daniele is using Posterous to post everything online. Shouldn't you?
Unknown35
 

Daniel’strae

Is cuma cá mhinice a théann tú ar strae; is é is tábhachtaí gurb áil leat do bhealach a aimsiú arís.

Semplici test OOP

##file: lib-doc.php
<?php
class Document{
    private $code;
    private $date;
    private $costumer;
    private $total;
    private $vat;
    private $imp;
    private $i;
    public $items;
    public $template;

       
    public function __construct($code, $date, $costumer){
        $this->i = 0;
        $this->template = 'document.tpl.php';
        $this->code = $code;
        $this->date = $date;
        $this->costumer = $costumer;
        $this->items = array();
    }

        public function addItem($title, $code, $qnt, $price, $nVat){
        $this->i++;
        $item = new Item($code, $title, $qnt, $price, $nVat, $this->i, $this);
        $this->items[$this->i] = $item;

                $this->totaliDocumento();
        return $item;
    }

        public function removeItem($item){
        if(isset($this->items[$item->getKey()])){
            unset($this->items[$item->getKey()]);
            $this->totaliDocumento();
        }
    }

        public function changeQnt($item, $newQnt){
        if(isset($this->items[$item->getKey()])){
            $item->changeQnt($newQnt);
            $this->totaliDocumento();
        }
    }

        public function totaliDocumento(){
        $this->total = 0;
        $this->vat = 0;
        $this->imp = 0;
        foreach($this->items AS $item){
            $this->total += $item->getImporto('totale');
            $this->imp += $item->getImporto('imponibile');
            $this->vat += $item->getImporto('iva');
        }
    }

        public function attr($attr){
        return $this->$attr;
    }

        public function output(){
        $document = $this;
        include($this->template);
    }
    public function outputItem($item){
        include($item->template);
    }
}
class Item Document{
    private $qnt;
    private $prezzo;
    private $cIva;
    public $titolo;
    public $codice;
    public $template;
    /*
     * rayKey e' la chiave dell'array items
     * dell'istanza di ogni Item.
     * Serve per tenerne la tracciabilita'
     * (per rimuovere gli oggetti o modificarli)
    */
    private $rayKey;

        private $documento;
    private $totale;
    private $imponibile;
    private $iva;

        public function __construct($codice, $titolo, $qnt, $prezzo, $cIva, $key, $documento){
        $this->template = 'item.tpl.php';
        $this->documento = $documento;
        $this->rayKey = $key;
        $this->codice = $codice;
        $this->titolo = $titolo;
        $this->qnt = $qnt;
        $this->prezzo = $prezzo;
        $this->cIva = $cIva;
        //calcolo i totali
        $this->calcolaTotali();
    }
    public function getKey(){
        return $this->rayKey;
    }
    /*
     *Diciamo che voglio avere la certezza che
     *aggiornando la quantita' o il prezzo
     *dell'oggetto, i totali sono sempre aggiornati.
     *Quindi qnt e prezzo sono privati, per aggiornarli
     *bisogna utilizzare la relativa funzione che
     *aggiorna anche i totali dell'oggetto.
    */
    public function aggiornaQnt($qnt){
        $this->qnt = $qnt;
        $this->calcolaTotali();
    }

        public function aggiornaPrezzo($prezzo){
        $this->prezzo = $prezzo;
        $this->calcolaTotali();
    }

        private function calcolaTotali(){
        $this->imponibile = $this->qnt * $this->prezzo;
        $this->iva = ($this->imponibile * $this->cIva) / 100;
        $this->totale = $this->imponibile + $this->iva;
        $this->documento->totaliDocumento();
    }
    /*
     * Anche i totali non sono modificabili
     * direttamente ma dipendono da altre
     * proprieta' dell'oggetto.
     * L'unico modo per ottenerli al di fuori
     * della classe, e' quindi questa funzione
    */
    public function getImporto($importo = 'totale'){
        switch($importo){
            case 'totale':
                return $this->totale;
                break;
            case 'imponibile':
                return $this->imponibile;
                break;
            case 'iva':
                return $this->iva;
                break;
        }
    }
    /*
     * questo metodo serve solo per recuperare dall'esterno
     * le variabli protette
    */
    public function attr($attr){
        return $this->$attr;
    }

        public function output(){
        $item = $this;
        include($this->template);
    }
}
?>

##file: index.php
<?php
require_once('lib-doc.php');

$fattura = new Document('00001', '11 November 2009', 'Jhon Doe');

$beer = $fattura->addItem('Beer Bottle', 'F6ASJK8', 6, 3.43, 20);
$chips = $fattura->addItem('Cheesy Chips', 'KBLN32', 2, 1.12, 20);
$popcorn = $fattura->addItem('Pop Corn', 'BCHREUD6', 2, 0.69, 20);
$fattura->removeItem($beer);
$beer_cans = $fattura->addItem('Beer Cans, x6', 'YHEF6DTT', 1, 5.99, 20);
//$fattura->changeQnt($chips, 4);

$fattura->output();
?>

##file: document.tpl.php
<div class="document document-<?php echo $document->attr('code'); ?>">
    <h1>Document <?php echo $document->attr('code'); ?> of <?php echo $document->attr('date'); ?></h1>
    <p>Costumer: <b><?php echo $document->attr('costumer'); ?></b></p>
    <h2>Items Details</h2>
    <p class="item-list">
<?php
foreach($document->items AS $item){
    $document->outputItem($item);
}
?>
    </p>
    <h2>Document Totals:</h2>
    <ul class="totals">
        <li><b>Imponibile:</b> <?php echo $document->attr('imp'); ?>&euro;</li>
        <li><b>VAT:</b> <?php echo $document->attr('vat'); ?>&euro;</li>
        <li><b>Total:</b> <?php echo $document->attr('total'); ?>&euro;</li>
    </ul>
</div>

##file: item.tpl.php
<?php
//questo DEVE dare ERRORE!
$item->aggiornaPrezzo(10.54);
?>
<div class="item item-<?php echo $item->codice; ?>">
    <h3><?php echo $item->titolo; ?></h3>
    <ul>
        <li><b>Quantity:</b> <?php echo $item->attr('qnt'); ?></li>
        <li><b>Cost per Unit:</b> <?php echo $item->attr('prezzo'); ?></li>
        <li><b>VAT Appliable:</b> <?php echo $item->attr('cIva'); ?>%</li>
        <li><b>Imponibile:</b> <?php echo $item->getImporto('imponibile'); ?>&euro;</li>
        <li><b>VAT:</b> <?php echo $item->getImporto('iva'); ?>&euro;</li>
        <li><b>Total:</b> <?php echo $item->getImporto('totale'); ?>&euro;</li>
    </ul>
</div>

Full version: http://pastie.org/705984

Loading mentions Retweet
Posted November 19, 2009
// 0 Comments

Reminder: postgresql 8.4.1 Conditional Expressions

9.16.1. CASE

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages:

CASE WHEN condition THEN result
[WHEN ...]
[ELSE result]
END

CASE clauses can be used wherever an expression is valid. Each condition is an expression that returns a boolean result. If the condition's result is true, the value of the CASE expression is the result that follows the condition, and the remainder of the CASE expression is not processed. If the condition's result is not true, any subsequent WHEN clauses are examined in the same manner. If no WHEN condition yields true, the value of the CASE expression is the result of the ELSE clause. If the ELSE clause is omitted and no condition is true, the result is null.

An example:

SELECT * FROM test;

a
---
1
2
3


SELECT a,
CASE WHEN a=1 THEN 'one'
WHEN a=2 THEN 'two'
ELSE 'other'
END
FROM test;

a | case
---+-------
1 | one
2 | two
3 | other

The data types of all the result expressions must be convertible to a single output type. See Section 10.5 for more details.

There is a "simple" form of CASE expression that is a variant of the general form above:

CASE expression
WHEN value THEN result
[WHEN ...]
[ELSE result]
END

The first expression is computed, then compared to each of the value expressions in the WHEN clauses until one is found that is equal to it. If no match is found, the result of the ELSE clause (or a null value) is returned. This is similar to the switch statement in C.

The example above can be written using the simple CASE syntax:

SELECT a,
CASE a WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'other'
END
FROM test;

a | case
---+-------
1 | one
2 | two
3 | other

A CASE expression does not evaluate any subexpressions that are not needed to determine the result. For example, this is a possible way of avoiding a division-by-zero failure:

SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;

9.16.2. COALESCE

COALESCE(value [, ...])

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display, for example:

SELECT COALESCE(description, short_description, '(none)') ...

Like a CASE expression, COALESCE only evaluates the arguments that are needed to determine the result; that is, arguments to the right of the first non-null argument are not evaluated. This SQL-standard function provides capabilities similar to NVL and IFNULL, which are used in some other database systems.

9.16.3. NULLIF

NULLIF(value1, value2)

The NULLIF function returns a null value if value1 equals value2; otherwise it returns value1. This can be used to perform the inverse operation of the COALESCE example given above:

SELECT NULLIF(value, '(none)') ...

If value1 is (none), return a null, otherwise return value1.

9.16.4. GREATEST and LEAST

GREATEST(value [, ...])
LEAST(value [, ...])

The GREATEST and LEAST functions select the largest or smallest value from a list of any number of expressions. The expressions must all be convertible to a common data type, which will be the type of the result (see Section 10.5 for details). NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL.

Note that GREATEST and LEAST are not in the SQL standard, but are a common extension. Some other databases make them return NULL if any argument is NULL, rather than only when all are NULL.


Source: http://www.postgresql.org/docs/8.4/interactive/functions-conditional.html

Loading mentions Retweet
Posted November 12, 2009
// 0 Comments

Choosing an object-relational mapping tool

Whether you are developing a small or a big application, you always have to deal with data. It's even a critical part of an application. Problem is this is tedious, repetitive work, which consumes a lot of the time we would prefer to spend on other parts of the application. Without forgetting that the less interesting the work is, the higher the risks of errors.
To solve these problems, multiple solutions exist. Their goal is to simplify the creation of data access layers, automate data access, or generate data access code.
We will focus on one of these solutions: object-relational mapping tools (O/RM).

The principle of object-relational mapping is to delegate to tools the management of persistence, and to work at code-level with objects representing a domain model, and not with data structures in the same format as the relational database (.NET's DataSet class). Object-relational mapping tools establish a bidirectional link with data in a relational database and objects in code, based on a configuration and by executing SQL queries (dynamic most of the time) on the database.
We won't get here into the details of how mapping tools work and their principles. You can refer to the links at the end of this article to learn more about that.
We should not forget that other solutions exist, such as those based on code generation. They all have their pros and cons, just as it's the case for mapping tools themselves of course. The perfect tool for all situations does not exist, or someone has to tell me about it :-)
We won't talk about these other approaches here; it's not the subject for today.

In terms of tools, the offer is huge. This is true for .NET as well as for Java, even if the offer for Java is more advanced for historical reasons. There is anyway an impressive quantity of tools for both sides! (see the list of tools for .NET at the end of this article)
Is quality always there? Are the tools suitable to your needs? These are the main questions.
The most important when searching for the right tool is to define precisely which criteria are essential for you. This is why I will present in this article the criteria for selecting an object-relational mapping tool.
The .NET and Java/J2EE platforms being so close, the needs being the same, these criteria can be considered universal.
Criteria specific to object-relational mapping
Basic features

* Be able to use inheritance, create hierarchies between entities, and use polymorphism (we are using objects!). The tools can support a variety of combinations for tables and classes to allow these mechanisms.
* Handle any type of relations (1-1, 1-n, n-n)
* Support for transactions
* Aggregates (equivalent to SQL's SUM, AVG, MIN, MAX, COUNT)
* Support for grouping (SQL's GROUP BY)

Useful extended features

* Supported databases. A big advantage of mapping tools is that they provide an abstraction of the underlying database engine. Most of them allow switching easily between RDBMSs (Relational Database Management Systems).
* Query language (OQL - Object Query Language, OPath). We very frequently have to execute dynamic queries. It's the case at least with searches based on filters. It is important to be able to use a powerful query language.
* Support for DataBinding (to be able to bind data objects to visual components). Note some specificity exists with Windows Forms.

Flexibility

* Customization of queries. We often need to go beyond what is possible with the provided query language. In these cases, we need to be able to provide custom SQL queries. HQL, which is a strong point of Hibernate/NHibernate, allows for this. We could also wish a dynamic mapping to be possible from developer provided SQL queries.
* Support any type of SQL joins (inner join, outer join)
* Concurrency management (support for optimistic and pessimistic approaches)
* Support for the data types specific to the database management system (identity columns, sequences, GUIDs, autoincrements)
* Be able to map a single object to data coming from multiple tables (joins, views). Most of the tools handle a direct mapping of a class to one table. We often need more.
* Be able to dispatch the data from a single table to multiple objects.

Assistance, ease of use

* GUI to set up the mapping. Such a graphical tool presents the relational data model and lets you specify the objects to be created or at least the links between the objects and the tables.
* Generation of the classes. This can speed up the development, even if in a lot of cases we prefer to map the database to hand-coded classes or to classes generated from UML for example. Check which scenarios are supported by the tools.
* Generation of the database schema. Some tools work only with a database they generated. This can be a big constraint, especially if you have to work with a legacy database of course! Otherwise, it all depends on whether you are an expert in database modeling, or if you prefer not to have to deal with the database schema. If you have a DBA who takes care of your databases, or if you prefer to design them by yourself, be sure to select a mapping tool that doesn't require its own data model.

Optimizations, performance, design

* Global performance (good implementation of the object-relational mapping concept)
* Lazy loading (the loading of some data is deferred until it's needed)
o for the data through relations
o for some columns. When we want to display just a list of names, we don't need all the columns of a table to be loaded. We may need the blob fields only at certain point, under certain conditions, and so it's better to load them only at that time.
* Cache dynamically generated queries, so that they don't get rebuilt at each call.
* Cache some data to avoid too many calls to the data source.
* Optimized queries (update only the modified columns; detect situations where the number of executed queries can be reduced; ...)
* Handle circular references without duplication of objects ("account == account.Client.Account")
* Handle cascade updates. Deleting a master record should delete the linked details if wished so.
* Bulk updates or deletions. When we want to update or delete thousands of records at a time, it's not possible to load all the objects in memory, while this can be easily and quickly done with a SQL query (DELETE FROM Customer WHERE Balance < 0). Support from the tool is welcome to handle such massive operations without having to deal with SQL. Hibernate is not very good on this point for example.

Evolution, compatibility

* Maintainability (what happens if the database schema changes? If I need to add a new collection?)
* Possibility to move to a new mapping tool (what would it imply? At what cost?)
* Serialization. Serialization can be used to persist data outside of the database. Serialization can be done into a binary format, or more important, in XML (see the section on SOA below)
* Distributed objects (remoting; web services; requires support for serialization)

Welcome additional features

* Freedom in the design of the classes (no base class for the entities; no mandatory interface; no specific class for collections). Think POJO (Plain Old Java Object).
* Less constraints as possible on the database schema (eg. support for composite data keys)
* State information on data. It can be useful to know by looking at an object if the entity has been added, modified, deleted.
* External mapping file or not? Attributes (annotations) in code or not?
o Advantages of external files: mapping entirely externalized; no intrusion in the classes; can be generated
o Disadvantages of external files: one or multiple additional files to deal with; a syntax to learn if no GUI is provided; understanding the links between the code and the database requires some effort; can become out of sync with the code
o Advantages of attributes/annotations: everything at hand at code-level; the mapping is obvious since directly present on classes and class members; can be used to generate external mapping files using reflection if needed; if the mapping tool isn't used anymore, they are ignored
o Disadvantages of attributes/annotations: the code is "polluted"; the code depends on a specific mapping framework
* Advanced compatibility with the development platform. For example, compatibility with .NET's DataSets can be useful. It can be important to be able to convert object graphs into DataSets to interact with components that require them (reporting tools for example).
* Support for disconnected mode (fill objects from a database, close the connection, the session, create/update/delete some objects, and apply this modifications back to the database later)
* Interceptors and delegation mechanisms to be able to react when the handling of the persistence happens (eg. to be able to log what happens)
* Support for stored procedures. The advantages of stored procedures compared to dynamic SQL queries make for a hot debate, but it is better to have the choice.
* One advantage of some tools for .NET could be their popularity in the Java world. This is the case for iBatis.NET or NHibernate. NHibernate is a port of Hibernate, a tool widely used in Java, and so can benefit from a large community of developers and existing documentation.
* Ability to specify constraints between objects and on properties (OCL - Object Constraint Language). This can avoid having to wait for the data to reach the database before being validated.
* Filtering objects in memory (without having new queries executed on the database)
* Be able to defer the updates on the database, and apply them at a given time using a specific method call, instead of having them systematically applied immediately.

Non O/RM specific criteria

A lot of criteria are common to the selection of any piece of software, and so are to be included in your checklist:

* Price
* Performance
* Resource consumption (memory)
* Scalability
* Complexity (or simplicity...)
* Ease of use, time to be up and running
* Flexibility
* Documentation. Using a mapping tool is not always a snap. Check the quality of the documentation and the provided samples.
* Maturity. Many tools are relatively new, at least for .NET, and are still not mature. Some are still at the beta level, or even alpha.
* Frequency of the updates, bug fixes, evolutions
* Support, forums, community
* Vendor's reputation and stability. This is a big problem today. There are a lot of tools, but natural selection is constantly at work. Which products will still be there tomorrow? Some have already fallen. Time will probably continue to eliminate some actors in this very competitive market.
* Source code provided or not (important in case the vendor disappears in a black hole or in the Cayman Islands)
* Support for multiple platforms (Java and .NET? Windows and Linux? .NET Framework and Mono?)

Specific case of a Service-Oriented Architecture (SOA)

Some criteria should particularly be taken into account when considering service-oriented architectures.

Object-relational mapping tools often base the development of your applications on the fact that the entities you handle are linked to a data source with which they communicate directly to reflect updates you perform on them. With SOA, the handling of persistence is delegated to a dedicated layer; the code for persistence is not in the entities themselves.

When considering a tool, you will ask yourself the following questions:

* Can my objects be serialized in XML?
* Can I persist my data objects into different formats?
* Am I the one who decides when the calls to handle persistence are performed? Are these calls frequent? Are the moments when they happen well-defined?
* Can I use my data objects from another platform? (eg. client in .NET, server in Java) Without the object-relational mapping tool?
* Am I sure my business objects won't call directly the database from the presentation layer, by any chance?
* What happens if I decide to move my presentation layer or my service's clients to a remote location?

The design of your applications will tell you what tool you should use, not the opposite...
Other tools

Mapping tools are not the only solution to handle persistence. The second big category of tools consists in code generators.
To keep it simple, the main differences between these two categories of tools can be as follow:

* Dynamic queries (filters) are handled only by mapping tools
* Mapping tools use reflection, which is slower than the compiled code produced by code generators

Code generation tools are numerous for .NET. See the links at the bottom of this article.

Depending on the situation, it can be code generation tools or mapping tools that are best fitted. An interesting point is that some tools combine code generation and object-relational techniques to offer the best of both worlds.
Some final words

As you can see, the criteria are numerous! You should start by defining which are critical for you (MUST HAVE) and which are less important (NICE TO HAVE).

You have to make your own opinion. As with any tool, don't hesitate to test extensively. Download evaluation versions. Do more than simply taking a look at the provided demos, use the tools on a prototype in your own application domain.
Evaluate, compare, use, criticize and comment so we too know what you think about the different tools...


Source: http://madgeek.com/Articles/ORMapping/EN/mapping.htm

Loading mentions Retweet
Posted November 3, 2009
// 0 Comments

Postgresql equivalent of Mysql 'SHOW PROCESSLIST'

SELECT * FROM PG_STAT_ACTIVITY;

Loading mentions Retweet
Posted October 29, 2009
// 0 Comments

Tar for newbie tooltip

Compressing a folder, with all subfolders keeping the folder's tree:

tar -cvzpf /yourfile/path/archive.tgz /path/of/the/main/folder/to/compress

Uncompressing the previous created file, NOT overwriting the original folders ( /path/of/the/main/folder/to/compress) but extracting in a folder of your choice:

tar -xvzf /path/to/the/archive/file.tgz -C /path/of/your/choice/

Loading mentions Retweet
Posted October 21, 2009
// 0 Comments

Preventing Browser Cache

Preventing Browser Cache

Multiple Platform Solutions

Bill Volk wrote on the websandiego.org mailing list:
> On a similar subject ... what's the best way to force a Browser to do a
> refresh on a page when the user uses the "Back Arrow" to get to it? I need
> to referesh the session objects.

This is a persistent problem, particularly with sites whose content updates frequently. The most common answer I see answering this question is to use <meta> tags in the <head> of the document.


<meta http-equiv="Expires" content="Tue, 01 Jan 2000 12:12:12 GMT">
<meta http-equiv="Pragma" content="no-cache">

...although this works inconsistently or not at all in Internet Explorer.

The way to do it according to the HTTP spec (RFC 2187) is to generate raw HTTP headers. Below are some different code snippets for some different server-side languages.

In ASP/IIS:
http://support.microsoft.com/support/kb/articles/Q234/0/67.asp
<% Response.CacheControl = "no-cache" %>
<% Response.AddHeader "Pragma", "no-cache" %>
<% Response.Expires = -1 %>

In PHP:
http://www.php.net/manual/en/function.header.php
<?
Header('Cache-Control: no-cache');
Header('Pragma: no-cache');
?>

In COLD FUSION:
<cfheader name="Expires" value="#Now()#">
<cfheader name="Pragma" value="no-cache">

In JSP:
http://www.jguru.com/faq/view.jsp?EID=377&page=2
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>

If you want to view the raw headers of
your web page - you can use this service:
http://www.delorie.com/web/headers.html

Sample HTTP Headers: (for this page)
HTTP/1.1 200 OK
Date: Tue, 29 Oct 2002 19:50:44 GMT
Server: Apache/1.3.27
X-Powered-By: PHP/4.2.2
Cache-Control: no-cache
Pragma: no-cache
Connection: close
Content-Type: text/html

Loading mentions Retweet
Posted October 15, 2009
// 0 Comments

Mycd si rinnova: Nuovo logo, Nuovo sito | Mycd Stampa e Duplicazione Cd e Dvd

Oggi 6 ottobre 2009 sono orgoglioso di presentarvi il nostro nuovo logo e il nostro nuovo sito internet. A causa del troppo lavoro il nostro sito aveva subito una drastica diminuzione di aggiornamenti, tuttavia per noi il web ha sempre rappresentato una priorità e una grande fonte di comunicazione con clienti e fornitori. In questi ultimi mesi abbiamo cercato di concentrare le forze per far si il sito internet diventi parte integrante dell'azienda e fornisca un reale aggiornamento in su tutto ciò che stiamo facendo. Questa soluzione, ad alcuni, potrebbe sembrare un azzardo ma personalmente la ritengo un punto cruciale per far si che il sito Mycd possa realmente diventare un punto di riferimento sulla stampa e duplicazione cd e dvd per il web.

In breve su Mycd da oggi potrete trovare:

  • Tutte le lavorazioni prodotte con i possibilità di commentarle
  • Tutorial, guide e novità sul mondo della stampa e duplicazione cd e dvd
  • Un layout semplice per una navigazione veloce e immediata

Questo sito internet è stato realizzato soprattutto per offrire un valido servizio a tutti i nostri clienti come già accadeva precedentemente avrete la possibilità di richiedere il preventivo e ottenere la risposta in tempo reale sulla vostra posta elettronica.

Il sito è stato arricchito da una fotogallery completamente nuova da cui avrete la possibilità di vedere fotografie chiare e dettagliate di tutti i nostri prodotti. Ci auguriamo che il nuovo sito vi piaccia, ci farebbe piacere ricevere qualche commento a questo primo post con le vostre opinioni.

Un saluto Luca Colli

01 logo-mycd.jpg
Bookmark and Share

Loading mentions Retweet
Posted October 12, 2009
// 0 Comments

.HTACCESS files useful tips and tricks

By Garnet R. Chaney

This page is mentioned in my searches at Fun with .htaccess files.
The .htaccess file is a very powerful configuration tool for users of the Apache web server. Here are some quick tips and tricks about how an .HTACCESS file can be placed in the various directories of your web server to provide specific handling of various Apache web server options for that directory.

Apache Configuration

  • Apache web servers have two main places for configuration information:
    • httpd Config files (typically located somewhere like /etc/httpd/)
    • Per-directory .htaccess files
  • Usually only the administrators of a server have access to the httpd config files. Individual users are able to place .htaccess files in their individual directories in order to override the options in the httpd config files.
  • .htaccess files are reread upon every hit within that directory. In fact, the web server will look for these .htaccess files on every access to the web server.

What can web hosting users do with .htaccess?

  • Specify custom error documents
  • Add special document handlers and MIME types
  • Set environment variables
  • Redirect URLs from one to another
  • Rewrite one URL into another
  • Restrict documents to specific people

.htaccess Format

  • The dot in .htaccess makes it a 'hidden' Unix file. It is not listed in a normal directory listing. If default directory indexes are enabled on the web server, this file will be hidden in those lists also.
  • It is a plain ASCII text file. It should be editted with an ASCII text editor like notepad.
  • Comments are marked with a hash (#) at the start of the line.
    # this is a commented-out line
  • It needs to be readable by the server ('world' readable), which can be a security problem.

Custom Error Documents

  • Some sites establish site wide 404 error pages. For example: There is a Characterology Default 404 error page.
  • 404 handlers can be created by every web hosting user. They can even be put in every indivdual directory. For example: Psychology Department's Error Page
  • Usage:
    ErrorDocument 404 errors/404.html
    Note: It's probably better to start with a leading / so that this directive has a complete path specification to make sure that the 404 handler page can always be found.
  • You can also have error documents created by CGI:
    ErrorDocument 404 /psych/cgi-bin/error/error?404
  • An example of the power of customized error documents is for telling people why their authentication failed

Enabling server-side includes

  • Server-side includes are macros within HTML expanded on the fly
    • Dynamically
    • Conditionally
  • Usage:
    AddType text/html .shtml
    AddHandler server-parsed .shtml
  • See Apache's Handler Use and mod_include documentation for more information.
  • ITS has documentation on Server Side Includes at Monash

Modifying the Environment

  • Environment variables contain information used by server-side includes and CGI.
    • For instance, an SSI statement: <--#echo SITE_WEBMASTER -->
  • Setting, unsetting:
    SetEnv SITE_WEBMASTER "Jack Sprat"
    SetEnv SITE_WEBMASTER_URI mailto:Jack.Sprat@characterology.com

    UnSetEnv REMOTE_ADDR

Adding new MIME types

  • The type of file depends on the filename extension.
    • Unrecognized file extensions are treated as text data, and corrupted on download.
  • Examples:
    AddType application/x-endnote-connection enz
    AddType application/x-endnote-filter enf
    AddType application/x-spss-savefile sav

Restricting documents

  • .htaccess files provide a number of different ways to restrict documents:
    • by accessor host address
    • by browser type
    • by accessor HTTP Basic credentials
    • by phase of moon...
  • Characterology campus-only access:
    order deny,allow
    deny from all
    allow from 130.194 characterology.com

Authcate Restricted Documents

  • Characterology Authcate credentials:
    order deny,allow
    deny from all
    AuthType Basic
    AuthName "Characterology Directory Service"
    AuthLDAP on
    AuthLDAPServer ldap://directory.characterology.com/
    AuthLDAPBase "o=Characterology University, c=au"
    require valid-user
  • It is possible to restrict who can access it even further
    • Staff only
    • Students only
    • By Subject enrolment
    • Specific individuals
  • See the ITS documentation on MDS HTTP Authentication
  • For restricting access so that non-Monash people can access it, consider AuthUserFile.

Protecting a single file

  • Normally .htaccess applies to the entire directory
  • With the <Files> directive you can restrict it to specific files:
    <Files quiz.html>
    order deny,allow
    deny from all
    AuthType Basic
    AuthName "Characterology Student Authcate"
    AuthLDAP on
    AuthLDAPServer ldap://directory.characterology.com/
    AuthLDAPBase "ou=Student, o=Characterology University, c=au"
    require valid-user
    satisfy any
    </Files>
  • Another example - protecting the .htaccess file itself:
    <Files .htaccess>
    order deny,allow
    deny from all
    </Files>
  • <FilesMatch> does the same except using a regular expression wildcard.

Redirecting the client

  • The server can be instructed to send a redirection back to the client whenever a particular URL is requested
  • Several different types of redirection:
    • permanent - the resource has moved permanently
    • temp - it has temporarily moved elsewhere
    • seeother - the resource has been replaced
    • gone - it has been permanently removed
  • Usage:
    Redirect permanent /psych/subject/timetable http://www.characterology.com/psych/subject/ttable

    Redirect gone /psych/subject/1998
    Redirect seeother /psych/subject/1999/ /psych/subject/2000/

  • The redirection applies to all documents under that URI path (eg., /psych/subject/1999/psy1011/books.html will be redirected to /psych/subject/2000/psy1011/books.html).
  • See the Apache documentation on the Redirect statement for detailed information.

Rewriting the URL

  • Unlike Redirect, the client is unaware of any server-side rewriting of the URL.
  • Rewrite rules are applied repeatedly to the URL to change it into another URL.
  • Example:
    RewriteEngine on
    RewriteBase /psych

    RewriteRule test/printenv(.*) cgi-bin/printenv$1

  • The bracket-dot-star-bracket has special meaning: it is a regular expression

Aside: Regular Expressions

  • Patterns ("wildcards") are matched against a string
  • Normal alphanumeric characters are treated as normal
  • Special characters:
    • . (full stop) - match any character
    • * (asterix) - match zero or more of the previous symbol
    • + (plus) - match one or more of the previous symbol
    • ? (question) - match zero or one of the previous symbol
    • \? (backslash-something) - match special characters
    • ^ (caret) - match the start of a string
    • $ (dollar) - match the end of a string
    • [set] - match any one of the symbols inside the square braces.
    • (pattern) - grouping, remember what the pattern matched as a special variable
  • Examples:
    • a+ matches "a", "aaaa", "aaaaaaaaaaaa", but not "bbb"
    • [ab]+ matches, "a", "b", or any length combination of the two
    • \.s?html? matches ".htm", ".shtm", ".html" or ".shtml"
    • (.+)/1999/(.+) matches "subject/1999/psy1011/", and also stores "subject" in $1 and "psy1011/" in $2.
  • Regular expressions are very extensive.
    • Documentation on silas: man regex
    • Friedl (1997). Mastering Regular Expressions. O'Reilly.

More Rewrite voodoo

  • Rewrites can be conditional, for example, rewrite only if the file could not be found:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)errata\.html?$ cgi-bin/errata/errata-html/$1

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule images/barcode/(.*).gif cgi-bin/barcode/mkgif?$1

  • RewriteCond is very powerful. You can test on environment variable values:
    RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
    RewriteRule ^/$ /homepage.max.html [L]

    RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
    RewriteRule ^/$ /homepage.min.html [L]

    RewriteRule ^/$ /homepage.std.html [L]

  • Full information on RewriteCond can be found within the Apache documentation on mod_rewrite
  • The Apache URL Rewriting Guide is strongly recommended. Typical problems are presented along with their solution.

Want More Info About Apache Directives?

Source: Liberal borrowing from http://www.its.monash.edu.au/web/slideshows/htaccess/all.htm

Loading mentions Retweet
Posted October 6, 2009
// 0 Comments

.htaccess Error Documents

In Apache, you can set up each directory on your server individually, giving them different properties or requirements for access. And while you can do this through normal Apache configuration, some hosts may wish to give users the ability to set up their own virtual server how they like. And so we have .htaccess files, a way to set Apache directives on a directory by directory basis without the need for direct server access, and without being able to affect other directories on the same server.

One up-side of this (amongst many) is that with a few short lines in an .htaccess file, you can tell your server that, for example, when a user asks for a page that doesn't exist, they are shown a customized error page instead of the bog-standard error page they've seen a million times before. If you visit http://www.addedbytes.com/random_made_up_address then you'll see this in action - instead of your browser's default error page, you see an error page sent by my server to you, telling you that the page you asked for doesn't exist.

This has a fair few uses. For example, my 404 (page not found) error page also sends me an email whenever somebody ends up there, telling me which page they were trying to find, and where they came from to find it - hopefully, this will help me to fix broken links without needing to trawl through mind-numbing error logs.

[Aside: If you set up your custom error page to email you whenever a page isn't found, remember that "/favicon.ico" requests failing doesn't mean that a page is missing. Internet Explorer 5 assumes everyone has a "favicon" and so asks the server for it. It's best to filter error messages about missing "/favicon.ico" files from your error logging, if you plan to do any.]

Setting up your htaccess file is a piece of cake. First things first, open notepad (or better yet, EditPlus2), and add the following to a new document:

  1. ErrorDocument 404 /404.html

Next you need to save the file. You need to save it as ".htaccess". Not ".htaccess.txt", or "mysite.htaccess" - just ".htaccess". I know it sounds strange, but that is what these files are - just .htaccess files. Nothing else. Happy? If not, take a look at this .htaccess guide, which also explains the naming convention of .htaccess in a little more depth. If you do use Notepad, you may need to rename the file after saving it, and you can do this before or after uploading the file to your server.

Now, create a page called 404.html, containing whatever you want a visitor to your site to see when they try to visit a page that doesn't exist. Now, upload both to your website, and type in a random, made-up address. You should, with any luck, see your custom error page instead of the traditional "Page Not Found" error message. If you do not see that, then there is a good chance your server does not support .htaccess, or it has been disabled. I suggest the next thing you do is check quickly with your server administrator that you are allowed to use .htaccess to serve custom error pages.

If all went well, and you are now viewing a custom 404 (page not found) error page, then you are well on your way to a complete set of error documents to match your web site. There are more errors out there, you know, not just missing pages. Of course, you can also use PHP, ASP or CFML pages as error documents - very useful for keeping track of errors.

You can customize these directives a great deal. For example, you can add directives for any of the status codes below, to show custom pages for any error the server may report. You can also, if you want, specify a full URL instead of a relative one. And if you are truly adventurous, you could even use pure HTML in the .htaccess file to be displayed in case of an error, as below. Note that if you want to use HTML, you must start the HTML with a quotation mark, however you should not put one at the other end of the HTML (you can include quotation marks within the HTML itself as normal).

  1. ErrorDocument 404 "Ooops, that page was <b>not found</b>. Please try a different one or <a href="mailto:owner@site.com">email the site owner</a> for assistance.

Server response codes

A server reponse code is a three digit number sent by a server to a user in response to a request for a web page or document. They tell the user whether the request can be completed, or if the server needs more information, or if the server cannot complete the request. Usually, these codes are sent 'silently' - so you never see them, as a user - however, there are some common ones that you may wish to set up error pages for, and they are listed below. Most people will only ever need to set up error pages for server codes 400, 401, 403, 404 and 500, and you would be wise to always have an error document for 404 errors at the very least.

It is also relatively important to ensure that any error page is over 512 bytes in size. Internet Explorer 5, when sent an error page of less than 512 bytes, will display its own default error document instead of your one. Feel free to use padding if this is an issue - personally, I'm not going to increase the size of a page because Internet Explorer 5 doesn't behave well.

In order to set up an error page for any other error codes, you simply add more lines to your .htaccess file. If you wanted to have error pages for the above five errors, your .htaccess file might look something like this:

  1. ErrorDocument 400 /400.html
  2. ErrorDocument 401 /401.html
  3. ErrorDocument 403 /403.html
  4. ErrorDocument 404 /404.html
  5. ErrorDocument 500 /500.html

Informational

  • 100 - Continue
  • 101 - Switching Protocols
Successful
  • 200 - OK
  • 201 - Created
  • 202 - Accepted
  • 203 - Non-Authoritative Information
  • 204 - No Content
  • 205 - Reset Content
  • 206 - Partial Content
Redirection
  • 300 - Multiple Choices
  • 301 - Moved Permanently
  • 302 - Found
  • 303 - See Other
  • 304 - Not Modified
  • 305 - Use Proxy
  • 307 - Temporary Redirect
Client Error
  • 400 - Bad Request
  • 401 - Unauthorized
  • 402 - Payment Required
  • 403 - Forbidden
  • 404 - Not Found
  • 405 - Method Not Allowed
  • 406 - Not Acceptable
  • 407 - Proxy Authentication Required
  • 408 - Request Timeout
  • 409 - Conflict
  • 410 - Gone
  • 411 - Length Required
  • 412 - Precondition Failed
  • 413 - Request Entity Too Large
  • 414 - Request-URI Too Long
  • 415 - Unsupported Media Type
  • 416 - Requested Range Not Satisfiable
  • 417 - Expectation Failed
Server Error
  • 500 - Internal Server Error
  • 501 - Not Implemented
  • 502 - Bad Gateway
  • 503 - Service Unavailable
  • 504 - Gateway Timeout
  • 505 - HTTP Version Not Supported

If you are interested, I have also put together a more thorough explanation of the meaning of the HTTP Status Response Codes.

Loading mentions Retweet
Posted October 6, 2009
// 0 Comments

BERE è come praticare YOGA

 


    
 
STUDI  SCIENTIFICI CONFERMANO CHE BERE ALCOOL  
ADDUCE AGLI STESSI BENEFICI DEL  PRATICARE LO YOGA:
Savasana
posizione di relax  totale



Balasana
posizione che dona una  sensazione di pace e tranquillità


Setu Bandha  Sarvangasana
questa posizione calma il cervello e ristora la  stanchezza delle gambe


Marjayasana
posizione che  regale un leggero massaggio al sedere ed alla spina  dorsale


Halasana
eccellente per il  dolore di spalle e per curare l'insonnia


Dolphin
perfetta per gli  omeri, irrobustisce il torace, gambe e braccia


Salambhasana
posizione adatta  a rinforzare i muscoli lombari, gambe e braccia


Ananda Balasana
posizione che  provoca un buon massaggio ai polpacci e piedi


Malasana
questa posizione stende i polpacci ed i  muscoli delle spalle

Pigeon
tonifica il corpo, aumenta  l'elasticità e sveglia la mente


Loading mentions Retweet
Posted September 18, 2009
// 0 Comments