page_name,page_id,page_title,content,keywords,language,original_page
permissions.ini_file,26,permissions.ini_file,"==The permissions.ini File==

[[toc]]

The permissions.ini file stores custom permissions and roles that can be used by an application.  It is an optional file that should be placed in the application root directory (i.e. the same directory where your conf.ini, and index.php files are located).

The permissions.ini file allows you to define two things:

# Permissions
# Roles (i.e. sets of permissions).

Permissions and roles are used throughout Xataface to limit access to actions, records, fields, and relationships.  For example, each action in your application can specify a permission that is necessary to perform the action.  Your delegate classes may include getPermissions() methods to define what permissions a user gets when interacting with different records.  This file (permissions.ini) simply defines the permissions that can be used by your application.  It doesn't actually assign those permissions.  Assigning permissions is the job of the getPermissions() (or getRoles()) method.

===Defining Permissions===

Permissions are defined by standalone properties in the beginning of the permissions.ini file.  For example, if you were desiging a proof-reading application, you might need permissions for ""submit_for_proof"", or ""approve_text"" to correspond with the submitting a document to be proof-read, and approving a document's proof.  In this case we would have the following at the beginning of our permissions.ini file:

<code>
submit_for_proof = Submit a document to be proofread
approve_text = ""Approve this document's proof""
</code>

The left side of the equals sign is the name of the permission.  The right side contains a human readable description of the permission and what it is for.

===Limiting Access to Actions based on Permissions===

At this point these permissions don't do anything.  In order to be useful we need reference these permissions from an action or a section.  For example, let's create an action called ""submit_for_proof"" which displays a form for a user to submit a document record to be proofread.

Our actions.ini file entry might look something like:

<code>
[submit_for_proof]
    url=""{$this->url('-action=submit_for_proof')}""
    label=""Submit document for proof""
    category=record_actions
    permission=submit_for_proof
    template=submit_for_proof.html
</code>

And for completeness, since this make-believe action specifies th ""submit_for_proof.html"" template, we'll create the ""submit_for_proof.html"" template in the templates directory:

<code>
<html><body>You have permission to perform this action.</body></html>
</code>

===Defining Who Get's Which Permissions===

Finally, in order to benefit from permissions, your application has to decide that it is going to use permissions (unless you define a getPermissions() method, users are granted ALL permissions by default.  Hence if you try to access our submit_for_proof action, we'll see it without any problem.  Regardless of who we are.  So let's create a simple, but restrictive getPermissions() method in our application delegate class:

<code>
<?php
class conf_ApplicationDelegate {
    function getPermissions(&$record){
        return Dataface_PermissionsTool::READ_ONLY();
    }
}
</code>

Now if we try to access our submit_for_proof action it will give us a ""Permission Denied"" message, because we are only granted READ ONLY permissions (which is a role that includes the view permission and some others - but not our custom ""submit_for_proof"" permission.

Now we'll make a small modification to our getPermissions() method to provide us with our submit_for_proof permission:

<code>
<?php
class conf_ApplicationDelegate {
    function getPermissions(&$record){
        $perms =  Dataface_PermissionsTool::READ_ONLY();
        $perms['submit_for_proof'] = 1;
        return $perms;
    }
}
</code>

Now if we try to access our submit_for_proof action, it will show us our template with no error messages (hopefully).


===Roles===

Roles are sets of permissions.  They are defined in the permissions.ini file as sections with lists of included permissions.  It might be handy to create roles such as EDITOR or MANAGER which contain sets of permissions that are meant to be assigned to users of those types.  For example an EDITOR may have the view and edit permissions, but not the delete permission.  A MANAGER might have the view, edit, and delete permissions.  You can define these two roles in the permissions.ini file as follows:

<code>
[EDITOR]
    view=1
    edit=1

[MANAGER]
    view=1
    edit=1
    delete=1
</code>

Then we could assign these roles to users using the Dataface_PermissionsTool::getRolePermissions() method:

<code>
function getPermissions(&$record){
    $user =& Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
    if ( $user and $user->val('role') == 'EDITOR' ){
        return Dataface_PermissionsTool::getRolePermissions('EDITOR');
    } else if ( $user and $user->val('role') == 'MANAGER' ){
        return Dataface_PermissionsTool::getRolePermissions('MANAGER');
    }
    return Dataface_PermissionsTool::READ_ONLY();
}
 </code>

Or equivalently we could use the getRoles() method of our delegate class instead of getPermissions():

<code>
function getRoles(&$record){
    $user =& Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
    if ( $user and $user->val('role') == 'EDITOR' ){
        return 'EDITOR';
    } else if ( $user and $user->val('role') == 'MANAGER' ){
        return 'MANAGER'
    }
    return 'READ ONLY';
}
</code>

===Xataface Core Permissions & Roles===

Xataface is distributed with its own permissions.ini file that defines some core permissions and roles.  You can look at this permissions.ini file (located in the Xataface directory) to see what the format should look like.  Any settings you place in your application's permissions.ini file will augment or override settings in Xataface's file.

Some core permissions include:


{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| view
| Permission to view a record or field.  This permission is required to access the view tab, and several other details tabs.
| 0.6
|-
| list
| Permission to access the list tab.
| 0.6
|-
| calendar
| Permission to access the calendar tab.
| 0.6
|-
| edit
| Permission to edit a record or field.  This also gives access to the edit tab.
| 0.6
|-
| new
| Permission to edit a record or field for the purpose of creating a new record.  This permission is required to access the new record form.
| 0.6
|-
| select_rows
| Permission to select rows in list view to perform actions on them.
| 0.6
|-
| post
| Permission to post a record using HTTP POST
| 0.6
|-
| copy
| Permission to copy a record.
| 0.6
|-
| update_set
| Permission to perform an update on a result set (i.e. access the update set action).
| 0.8
|-
| add new related record
| Permission to add a new record to a relationship.  See [[Relationship Permissions]]
| 0.6
|-
| add existing related record
| Permission to add an existing record to a relationship.  See [[Relationship Permissions]]
| 0.6
|-
| view related records
| Permission to view the records in a relationship. See [[Relationship Permissions]]
| 1.0
|-
| delete
| Permission to delete a record.
| 0.6
|-
| delete found
| Permission to access the delete found set action (to delete multiple records at a time).
| 0.6
|-
| show all
| Permission to access show all records action.
| 0.6
|-
| remove related record
| Permission to remove a record from a relationship.  See [[Relationship Permissions]]
| 0.6
|-
| delete related record
| Permission to delete a record in a relationship.  This is stronger than the remove related record permission in that it allows the user to delete the record from the database.  See [[Relationship permissions]]
| 0.6
|-
| find
| Permission to perform the find action.
| 0.6
|-
| import
| Permission to perform the import action (to import records into the database).
| 0.6
|-
| export_csv
| Permission to perform the Export CSV action (to export the result set in comma-separated-value format).
| 0.6
|-
| export_xml
| Permission to perform the Export XML action (to export the result set as XML).
| 0.8
|-
| translate
| Permission to translate a record into another language.  This permission provides access to the ""translate"" tab.
| 0.8
|-
| history
| Permission to view history information for a record (e.g. the history tab).  This requires that history be enabled.
| 0.8
|-
| edit_history
| Permission to edit history information such as undo/redo support for a record.
| 0.8
|-
| navigate
| Permission to navigate through records of a table.
| 0.6
|-
| reorder_related_records
| Permission to reorder the records of a relationship (this is different than just sorting).  It sets a default order for the records.  Requires the metafields:order directive to be set for the relationship.
| 0.6
|-
| ajax_save
| Permission to save a record through AJAX.
| 0.8
|-
| ajax_load
| Permission to load a record through AJAX.
| 0.8
|-
| ajax_form
| Permission to access the inline editing ajax form for a record.
| 0.8
|-
| find_list
| Permission to search current table.
| 0.6
|-
| find_multi_table
| Permission to perform a site-wide search.
| 0.8
|-
| register
| Permission to register for an account.
| 0.8
|-
| xml_view
| Permission to view a result set as xml.
| 0.8
|-
| view_xml
| View the XML for an individual record.
| 0.8
|-
| manage_output_cache
| Management permission to clear the output cache.
| 0.8
|-
| manage_migrate
| Permission to access the migration tool to migrate between versions.
| 0.8
|-
| manage
| Permission to access the management control panel.
| 0.8
|-
| manage_build_index
| Permission to rebuild the search index.
| 0.8
|-
| expandable
| Whether the record can be expanded in the left nav menu
| N/A
|}

Some core roles include:

{| class=""listing listing2""
|-
! Name
! Permissions Included
! Version
|-
| READ ONLY
| view, list, calendar, view xml, show all, find, navigate, ajax_load, find_list, find_multi_table, rss, export_csv, export_xml, and export_json
| 0.6
|-
| EDIT
| All permissions in READ ONLY, and edit, add new related record, add existing related record, add new record, remove related record, reorder_related_records, import, translate, new, ajax_save, ajax_form, history, edit_history, copy, update_set, and select_rows
| 0.6
|-
| DELETE
| All permissions in EDIT, and delete and delete found.
| 0.6
|-
| OWNER
| All permissions in DELETE except navigate, new, and delete found.
| 0.6
|-
| REVIEWER
| All permissions in READ ONLY, and edit and translate.
| 0.6
|-
| USER
| All permissions in READ ONLY, and add new related record.
| 0.6
|-
| ADMIN
| All permissions in DELETE and xml_view
| 0.6
|-
| MANAGER
| All permissions in ADMIN and manage, manage_output_cache, manage_migrate, manage_build_index, and install.
| 0.6
|}

===Extending and Overriding Roles===

The cleanest and easiest way to define a new role is to extend an existing role.  Xataface allows you to extend roles via the '''extends''' keyword.  For example, if you wanted to create a role '''TEST ROLE''' that contained all of the same permissions as the READ ONLY role, you could define it as follows in your application's permissions.ini file:

<code>
[TEST ROLE extends READ ONLY]
</code>

If we wanted it to contain the same permissions as READ ONLY but to also allow the edit permission we would define it as:
<code>
[TEST ROLE extends READ ONLY]
    edit=1
</code>

If we wanted to disallow the list permission, we would do something like:

<code>
[TEST ROLE extends READ ONLY]
    edit=1
    list=0
</code>

===Overriding Existing Roles===

You can also redefine existing roles:

<code>
[READ ONLY extends READ ONLY]
    my_permission=1
</code>

This is handy if you have added your own custom permissions that you feel should be included in a core role.

Note that there are some caveats regarding the order of how these roles are defined. Please refer to this forum post for more details: 
[http://www.xataface.com/forum/viewtopic.php?t=6187 Overriding Roles / Permissions]

==See Also==

* [[Relationship Permissions]]
* [[getPermissions]] - The getPermissionsMethod
* [[Delegate class methods]] - Delegate class methods.
* [http://xataface.com/documentation/tutorial/getting_started/permissions Getting started with Xataface permissions]","permissions.ini, getPermissions, permissions",en,0
preferences,10,preferences,"==Xataface Preferences==

[[toc]]

Xataface preferences can be defined in 3 ways:

# In the ''[_prefs]'' section of rhe [[conf.ini file]] for global static preferences.
# Implementing the [[getPreferences]] method in the [[Application Delegate Class]]
# In the [[__prefs__]] section of the fields.ini file for a table for static preferences on that table.  (Limited to only certain preferences).

===Example [_prefs] section===
In the conf.ini
<code>
[_prefs]
    hide_updated=1
    hide_posted_by=1
</code>

===Example [[getPreferences]] method===
In the [[Application Delegate Class]]:
<code>
function getPreferences(){
    return array('hide_update'=>1, 'hide_posted_by'=>1);

}
</code>

===Available Preferences===

{| class=""listing listing2""
! Name
! Description
! Default
! Version
|-
| show_result_stats
| Show the result statistics (e.g. found x of y records in table z)
| 1
| 0.6
|-
| show_jump_menu
| Show he drop-down menu that allows you to ""jump"" to any record in the found set.
| 1
| 0.6
|-
| show_result_controller
| Show Next, previous, page number .. links...
| 1
| 0.6
|-
| show_table_tabs
| Show  Details, List, Find, etc... tabs.
| 1
| 0.6
|-
| show_actions_menu
| Show New record, Show all, delete, etc..
| 1
| 0.6
|-
| show_logo
| Show logo at top of app
| 1
| 0.6
|-
| show_tables_menu
| Show the tabs to select a table.
| 1
| 0.6
|-
| show_search
| Show search field in upper right.
| 1
| 0.6
|-
| show_record_actions
| Show actions related to particular record
| 1
| 0.6
|-
| show_bread_crumbs
| Show bread crumbs at top of page to show where you are.
| 1
| 0.6
|-
| show_record_tabs
| View, Edit, Translate, History, etc...
| 1
| 0.6
|-
| show_record_tree
| Show tree to navigate the relationships of this record.
| 1
| 0.6
|-
| list_view_scroll_horizontal
| Whether to scroll list horizontal if it exceeds page width
| 1
| 0.6
|-
| list_view_scroll_vertical
| Whether to scroll list vertical if it exceeds page height.
| 1
| 0.6
|-
| hide_posted_by
| Whether to hide the ''posted by'' text in glance lists (e.g. in the view tab, the related records are shown in the left column.  This hides the ''posted by'' text next to each related record.
| 0
| 1.0b4
|-
| hide_updated
| Whether to hide the ''updated'' text in the glance lists (e.g. in the view tab, the related records are shown in the left column.  This hides the ''updated'' text next to each related record.
| 0
| 1.0b4
|-
| SummaryList_logo_width
| The width of the logo to be used as the preview image in summary lists.
| null
| 0.7
|-
| SummaryList_hideSort
| Hides the sort control for a summary list (the box that allows users to sort by column).
| 0
| 0.7
|-
| hide_user_status
| Hides the user's status (e.g. ""You are logged in as ...""
| 0
| 0.7
|-
| hide_personal_tools
| Hides the personal tool links in upper right.  This includes likes such as ""Control Panel"" and ""My Profile""
| 0
| 0.7
|-
| hide_resultlist_controller
| Hides the controller for a result list (E.g. next/back/results per page etc...).
| 0
| 0.7
|-
| hide_related_sections
| Hides the sections of the view tab that show the related records.  These are the sortable section boxes.  Not the related tabs.
| 0
| 1.3
|-
| hide_record_search
| Hides the record search form that appears in the view tab.  Not to be confused with the find tab.
| 0
| 1.3
|-
| show_resultlist_controller_only_when_needed
| Sets the resultlist controller (e.g. back/next/results per page/etc...) to only show up if paging is required (i.e. if there are more records than can be shown on one page (according to the '-limit' parameter).
| 0
| 1.0
|-
| hide_record_view_logo
| Hides the logo for a record that appears in the upper left of the view tab for each record.
| 0
| 0.7
|-
| horizontal_tables_menu
| Whether to force the tables menu to appear as tabs along the top of the page (alternative is as a menu on the left). If there are 10 or fewer allowed tables, then the default is 1, otherwise the default is set to 0.
| 1
| 0.6
|-
| hide_result_filters
| In list view, setting this value to 1 will cause the column filters to be hidden (the select lists to filter the results).
| 0
| 0.7
|-
| disable_select_rows
| A value of 1 causes the checkboxes in each row of the list view to be hidden.
| 0
| 0.7
|-
| result_list_use_geturl
| Use the getURL() method to link to records in the list view rather than the default (which uses the -cursor parameter).
| 0
| 0.7
|-
| disable_ajax_record_details
| Whether to disable the ajax record details (the '+' sign beside each record in list view that expands to show the record details.
| 1
| 0.7
|-
| use_old_resultlist_controller
| As of Xataface 1.1, a new style result list controller is used that resembles facebook.  It is more slimmed down and is easier to manage.  If you prefer the old controller, set this preference to 1.
| 0
| 1.1
|}

===Inverse Preferences===

The following preferences perform the inverse of some of the options above. When these options are set to 1, their respective option is set to 0.

{| class=""listing listing2""
! Name
! Inverse
|-
| hide_nav_menu
| show_tables_menu
|-
| hide_view_tabs
| show_table_tabs
|-
| hide_result_controller
| show_result_controller
|-
| hide_table_result_stats
| show_result_stats
|-
| hide_search
| show_search
|}
","preferences, prefs, getPreferences",en,0
Relationship_Permissions,111,"Relationship Permissions","[[toc]]

==Synopsis==

As relationships are a core feature of Xataface, it is helpful to understand how to handle permissions on related records.  Even if you apply permissions to every table individually, you need to take into account the relationships that you have defined between tables, because they may open access to actions that you did not intend.

For example, suppose we have two tables: ''people'' and ''publications'', and we have a relationship from ''publications'' table to the ''people'' table called ''publication_authors''.

Suppose you give a user write access to a record of the publications table, but no access to the people table.  If you are allowing the ''add new related record'' permission on the ''publications'' table record, then the user will still be able to add new people, via the ""Add related people record"" function of the database.  This may or may not be desirable.

This article discusses the issues that arise due to relationships and permissions, and how to deal with them.

==Relationship Permissions==

The Xataface [[permissions.ini file]] defines a handful of permissions that are related to the management of related records.  These include:

{| class=""listing listing2""
|-
! Name
! Description
! Included in Roles
|-
| [[add new related record]]
| Permission to add a new related record to a relationship.
| EDIT, DELETE, OWNER, ADMIN, MANAGER
|-
| [[add existing related record]]
| Permission to add an existing record to a relationship.
| EDIT, DELETE, OWNER, ADMIN, MANAGER
|-
| [[remove related record]]
| Permission to remove a record from a relationship.  (This only allows removing a record from the relationship - not deleting the record from the database, so this is only really relevant in a many-to-many relationship).
| EDIT, DELETE, OWNER, ADMIN, MANAGER
|-
| [[delete related record]]
| Permission to delete a related record.  This allows both removing the related record from the relationship, and deleting the record from the database.   This permission is not included in any default roles.  A combination of permission for [[remove related record]] in the source table and [[delete]] in the target table, are equivalent to access to this permission.  Use this permission only when you need to override the ability to delete records from the database based on membership in a relationship.
| -
|-
| [[view related records]]
| Permission to view the records of a relationship.
| READ ONLY, EDIT, DELETE, OWNER, ADMIN, MANAGER
|-
| [[related records feed]]
| Permission to access the RSS feed of a relationship.
| READ ONLY, EDIT, DELETE, OWNER, ADMIN, MANAGER
|}


==Fine-grained, Per-relationship Permissions==

You may often find that defining a flat set of permissions to all relationships on a record is insufficient for your purposes, because some relationships may demand different access levels than others.  You can override the permissions for any particular relationship by implementing the [[rel_relationshipname__permissions]] method in the table's delegate class, where ''relationshipname'' is the name of the relationship.

e.g.  Consider the relationship ''manufacturers'':
<code>
function rel_manufacturers__permissions($record){
	// $record is a Dataface_Record object
	return array(
		'view related records' => 0
	);
}
</code>
This will tell xataface that users should not be able to view related records on the ''manufacturers'' relationship.  This will override any permissions that were defined in the [[getPermissions]] method.


==More Complete Example==

In the following example, we design a products database.  We use 2 relationships on our products table:  One to keep track of the parts that are used in our product.  The other to keep track of the users that are allowed to edit our products.

We want to make it so that only the product owner can manage the editors for a product, but anyone in the product_editors relationship is allowed to edit the product or add/remove parts from the product.

We don't want to give any users access directly to the parts, product_parts, or product_editors tables.  We want all access to go through the relationships on the products table.

===Database/Relationship Design===

Consider a database with 4 tables:

# products (product_id, product_name, owner_username)
# parts (part_id, part_name)
# product_parts (part_id, product_id)
# product_editors (product_id, editor_username)
# users (username, password, role)

And we have the following relationships on the ''products'' table:

<code>
[parts]
    parts.part_id=product_parts.part_id
    product_parts.product_id=""$product_id""

[editors]
    product_editors.product_id=""$product_id""
</code>


===Application Permissions : Very Restrictive===

Like a good boyscout, we define our default permissions in the [[Application Delegate Class]] to be very restrictive: Don't let anyone do anything.

<code>
class conf_ApplicationDelegate {
    function getPermissions($record){
        return Dataface_PermissionsTool::NO_ACCESS();
    }
}
</code>


===Products Table Permissions: Less restrictive===

Now we open it up for our products table in the getPermissions() method of the products delegate class.

In tables/products/products.php:
<code>
class tables_products {
    function getPermissions($record){
        $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
        if ( $user and $record and $record->val('owner_username') == $user->val('username')){
        	// Give the record owner Edit permissions on the product
        	return Dataface_PermissionsTool::getRolePermissions('EDIT');
        }
        
        // Everybody else gets read only access to the products table.
        return Dataface_PermissionsTool::READ_ONLY();
    }
}

</code>

===Checking if the current User is an Editor===

So far we have given the product owner edit permissions and everyone else read only permissions.  We still need to allow editors to edit the product.  In order to do this we need to be able to *efficiently* find out if the current user is an editor of a particular product.  There are a few different ways to do this, but some are better than others.  Some strategies include:

# Perform an SQL query inside the [[getPermissions]] method to see if the user is an editor for the product.  '''THIS IS VERY BAD!!!''' The [[getPermissions]] method should not include any IO or database queries because it is called a large number of times per request... making expensive calls in this method will slow down your app dramatically.
# Create a function to load and cache all of the current user's products so that this can be easily checked at will.  This is fine if the user is expected be able to edit only a few products.  If he could be an editor for thousands of products, this may not be practical as it will cause you to have to load thousands of records into memory on every page request.
# Use the [[__sql__]] method of the delegate class to create a grafted field on the ''products'' table indicating whether the current user is an editor for the product.  This results in a very quick and accessible indicator variable that can be used in the [[getPermissions]] method to check to see if the current user is an editor for the current product.  E.g.  In the tables/products/products.php file (delegate class):<code>
function __sql__(){
    return sprintf(""select p.*, pe.editor_username from products p
                left join product_editors pe on p.product_id=pe.product_id
                where pe.editor_username='%s'"",
                addslashes(
                   Dataface_AuthenticationTool::getInstance()->getLoggedInUsername()
                )
            );
                
}</code>

This will result in a situation where product records will have an additional field ''editor_username'' which will either be blank if the current user is not an editor for the product; or will contain the current user's username if they are an editor for the product.


===Table Permissions for Product Editors===

Now that we have a reliable way to tell, for any given product, whether the current user is, in fact, an editor, we can ammend the [[getPermissions]] method of the products table to include our editor permissions.

<code>
class tables_products {
    function getPermissions($record){
        $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
        if ( $user and $record and $record->val('owner_username') == $user->val('username')){
        	// Give the record owner Edit permissions on the product
        	return Dataface_PermissionsTool::getRolePermissions('EDIT');
        }
        
        if ( $user and $record and $record->val('editor_username') == $user->val('username') ){
            // If the user is an editor, we give them edit permissions
            // also
            return Dataface_PermissionsTool::getRolePermissions('EDIT');
        }
        
        
        if ( $user ){
        // Other logged in users have read only access
            $perms = Dataface_PermissionsTool::READ_ONLY();
            $perms['new'] = 1; // We'll also let them add new products
            return $perms;
	}
	    
	// Regular users just get the default permissions as 
	// defined in the Application Delegate class
	return null;
    }
}

</code>

===Removing Editor Access to the Editor Relationship===

You'll notice that at this point, the product editor has exactly the same permission as the product owner.  They both have permission to add and remove records from all relationships on the product.  However, we don't want them to be able to access the editors relationship at all.  We will use the [[rel_relationshipname__permissions]] method to override the permissions for the ''editors'' relationship.

In the tables/products/products.php delegate class:

<code>

function rel_editors__permissions($record){
    $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
	if ( $user and $record and $record->val('owner_username') == $user->val('username')){
		// Owners should just get their normal permissions
		return null;
	}
	
	if ( $user and $record and $record->val('editor_username') == $user->val('username') ){
		// If the user is an editor, we give them edit permissions
		// also
		return array(
		    'view related records' => 0,
		    'add new related record' => 0,
		    'add existing related record' => 0,
		    'remove related record' => 0,
		    'delete related record' => 0
		    );
	}
	
	// Other users just get their normal permissions
	return null;

}

</code>


===Assigning product owner by default===

With the current permissions, something funny would happen.  Users have permission to add new records, but once the record is added they won't be able to edit it because they are neither an editor nor the owner of the product.  We'll fix this by assigning the current user as the product's owner using the [[beforeSave]] trigger in the products delegate class:

<code>
function beforeSave($record){
	$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
	if ( $user ){
    	$record->setValue('owner_username', $user->val('username'));
    }
}
</code>

===Testing Out Our Solution===

In your testing of the solution, you should find the following:

# Trying to access any table other than the ''products'' table should result in a ''permission denied'' error.
# If you access the ''products'' table, you should be able to see a list of existing products, and the ""Add New Record"" action.
# After you add a new product you should see that you are the product owner.
# As a product owner you should see both the ''parts'' and ''editors'' tabs in your product record.  You should be able to view and add new records to both of these relationships.
# Add another user as an editor to your product, then log in as that user.  You should be able to edit the product, but you shouldn't be able to see the ''editors'' tab for the product.

==See Also==

* [[permissions.ini file]] - Overview of the Xataface permissions.ini file
* [http://xataface.com/documentation/tutorial/getting_started/permissions Getting Started with Xataface Permissions]
* [[How to granulate permissions on each field]] - Brief tutorial on how to set permissions on a field by field basis.
* [[Delegate class methods]] - A list of all of the available delegate class methods that you can implement.  Many of them pertain to permissions and triggers.
* [[Application Delegate Class]] - Overview of the application delegate class.
* [[relationships.ini file]] - The relationships.ini file directives.
","relationships, permissions, rel_relationshipname__permissions, getPermissions, permissions.ini",en,
GettingStarted:relationships,78,Relationships,"==Relationships==

Xataface allows you to define relationships between tables using the relationships.ini file.

Xataface applications without relationships between tables can be quite boring. In our FacultyOfWidgetry application, we have implicitly defined a relationship between the Program table and the Course table by adding a ProgramID field to the Course table. In the previous section we saw how to configure this relationship from the context of a 'Course' by adding a select list to the Course table form to select the Program that the Course belongs to.

From the 'Program' side it is a little bit more complicated. There are no fields in the 'Program' table that can be edited to add a 'Course' to the list of courses in a 'Program', and it would be highly inconvenient to have to edit a 'Course' record in order to add the course to a 'Program'. What we want is a sort of 'Add Course' button to add a course to a 'Program'. 

===Concepts, Definitions, and Terminology===

Before we can delve into examples, it will help to go over some of the concepts and terminology involved in relationships using Xataface. Xataface relationships are always defined in a one-way fashion from the point of view of one table. For example, if you define a one-to-many relationship from the 'Program' table to the 'Course' table, the mirror (many-to-one) relationship from 'Course' to 'Program' is not automatically created. This method of defining relationships allows us to unambiguously refer to the source and destination tables of a relationship.

'''Definition 1:''' The ''source table'' of a relationship is the table on which a relationship is defined. For example if we define a relationship named 'Courses' on the 'Program' table to associate courses in a given program, then the 'Program' table would be considered the source table of the relationship, and the 'Course' table would be a destination table of the relationship.

'''Definition 2:''' The ''destination table'' of a relationship a table from which related records are selected.

There may be multiple destination tables in a given relationship but only one source table. If there are multiple destination tables, then one of these tables is designated as the domain table and the remaining destination tables are called join tables. 

'''Definition 3:''' A ''domain table'' is a destination table which stores the object of the relationship. For example if we define a many-to-many relationship between the 'Program' table and the 'Course' table, (i.e., each program can contain multiple courses and each course can be part of multiple programs), then we would need to add a join table to map 'Course' records to 'Program' records. Let's call this table 'ProgramCourses'. Each record of the 'ProgramCourses' table would contain a 2 fields: a 'ProgramID' field (to reference the program) and a 'CourseID' field to reference the course. If we define the relationship from the point of view of a 'Program' then the 'Program' table would be the source table, the 'ProgramCourses' table would be the join table, and the 'Course' table would be the domain table.

Don't worry if these definitions and terms aren't clear at this point. Use this section as a reference for when you run across the terms later in the tutorial.

===Defining a relationship===

To define a relationship in Xataface, all you need to do is tell Xataface how to select the related records using SQL. Xataface will be able to figure out how to add/remove records to the relationship from this information. This information is defined inside a the 'relationships.ini' file inside the configuration folder for the table.

====Example 1: Adding a 'Courses' relationship to the 'Program' table====

We want to be able to associate multiple courses with each program. We do this by defining a relationship on the 'Program' table as follows:

# Add a file named 'relationships.ini' to the 'Program' table's configuration folder (i.e., tables/Program/relationships.ini). Your application's directory structure should now look like:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/directory-structure-relationships.gif]]<nowiki><br/></nowiki>Notice, in particular the addition of the 'relationships.ini' file in the 'Program' directory.
# Add the following to the 'relationships.ini' file:<code>
[Courses]
	Course.ProgramID = ""$ProgramID""
</code>	

This little snippet defines a relationship named 'Courses' on the 'Program' table. 'Program' is the source table. 'Course' is the destination table. There are no join tables because this is only a one-to-many relationship. You may be wondering what the $ProgramID means. This is a variable that represents the value of the 'ProgramID' field in the source record. This relationship specifies that courses whose 'ProgramID' field matches the value of the 'ProgramID' field in the source record, are related to the source record. The english language makes this seem more difficult and complex than it really is.

Let's check out our changes. Since we have defined the relationship on the 'Program' table, we will click on the 'Program' link in the navigation menu:
[[Image:http://xataface.com/documentation/tutorial/getting_started/course-relationship-defined-1.gif]]

Notice that there is now a 'course' tab at the top of the page. Click on this tab to see the courses that are related to this Program (as defined by our 'Courses' relationship). If it says that ""No records matched the request"" or something to that effect, then you don't have any Course records in the relationship yet. Just click the ""Add New Courses Record"" button in the upper left to add a course. If there are courses in the relationship, then the Courses tab will look something like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/courses-related-records.gif]]

Currently there is only one course in the program, but we can add more. If you click on the ""Add New Courses"" button in the upper left, you will be presented with a new course form that will allow you to add a new course in this Program.

===Example 2: Making the 'Courses' relationship a Many-to-Many relationship===

Example 1 shows how Xataface can handle a one-to-many relationship. Now we will alter the database a little bit and turn this into a many-to-many relationship.

# Add a table named 'ProgramCourses' to the database. The SQL table definition for this table should be something like:<code>
CREATE  TABLE  `ProgramCourses` (
	`ProgramID` INT( 11  )  NOT  NULL ,
	`CourseID` INT( 11  )  NOT  NULL ,
	PRIMARY  KEY (  `ProgramID` ,  `CourseID`  ) 
	) 
</code><nowiki><p>Note that it is important for ALL of your tables to have Primary keys. If a table is missing its primary keys, some strange behavior may occur with relationships involving that table.</p>
<p>
The above defined table will serve as a join table between 'Program' and 'Course'
</p></nowiki>
# Since this is now going to be a many-to-many relationship, we no longer need the 'ProgramID' field in the 'Course' table. (Do not confuse this with the ProgramID field in the 'Program' table. That field is important and needed.). Before removing this field, we will transfer the information across so that the existing relationships are maintained. The following SQL query will effectively all of the old one-to-many relationships into equivalent many-to-many relationships:<code>
INSERT  INTO ProgramCourses( ProgramID, CourseID ) 
	SELECT ProgramID, CourseID
	FROM Course
</code><nowiki><p>	
And now we can remove the 'ProgramID' field from the 'Course' table.
ALTER  TABLE  Course  DROP  ProgramID</p></nowiki>
# Finally, we will need to modify the relationship definition in the relationships.ini file of the 'Program' table:<code>
[Courses]
	Course.CourseID = ProgramCourses.CourseID
	ProgramCourses.ProgramID = ""$ProgramID"" 
</code><nowiki><p>
This means that all courses for which a (ProgramID, CourseID) pair matches the CourseID of the course and the ProgramID of the source Program record are included in the relationship.</p></nowiki>
# Now we can check our application for changes. Go to the 'Program' table in your application (using your web browser) and click on the 'courses' tab once again:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/multi-relationship.gif]]<nowiki>
<p>
This looks almost the same as before. Notice, however that now there is an ""Add Existing Courses Record"" button at the top. This is because with a many-to-many relationship, you are able to add related records in 2 ways:</p></nowiki>
## Adding a completely new record that did not exist before.
## Selecting a record that already exists and adding it to the relationship.

===Example 3: Defining Relationships using SQL===

The previous examples used a simple INI file syntax to define relationships. However, some people may be more comfortable defining their relationships using SQL. This is also possible. Let's look at the relationships.ini file from example 1:<code>
[Courses]
	Course.ProgramID = ""$ProgramID""
</code>

This also could have been defined as follows:<code>
[Courses]
	__sql__ = ""SELECT * FROM Course WHERE ProgramID='$ProgramID'""
</code>

'''Note: Make sure you use two underscores on either side of 'sql' in the above example. It should be '__sql__' not '_sql_'.'''

The two syntaxes are equivalent. In fact, the former will be converted into the later by Xataface behind the scenes.

Now let's look at example 2's relationships.ini file:<code>
[Courses]
	Course.CourseID = ProgramCourses.CourseID
	ProgramCourses.ProgramID = ""$ProgramID"" 
</code>

This could have been written as:<code>
[Courses]
	__sql__ = ""SELECT * 
		FROM ProgramCourses, Course 
		WHERE Course.CourseID = ProgramCourses.CourseID 
		AND ProgramCourses.ProgramID = '$ProgramID'""
</code>

The two are equivalent. This example, however, shows how defining a relationship using SQL can be beneficial. The above SQL query will work but it can be done better using Joins as follows:<code>
[Courses]
	__sql__ = ""SELECT * 
		FROM ProgramCourses pc 
		INNER JOIN Course c ON pc.CourseID = c.CourseID 
		WHERE pc.ProgramID = '$ProgramID'""
</code>

All of these 3 methods will produce the same results, but the last one will probably give a little bit better performance.

===Relationship Restrictions===

Xataface has built-in logic to figure out how to add new and existing records to relationships that you define, as long as your relationships obey a few guidelines.

# All tables must have a Primary key
# The WHERE clause of your SQL definition for the relationship must contain only '=' comparisons, and 'AND' conjunctions. i.e., it cannot receive an 'OR' conjunction, nor can comparisons be done using '>', or '<'. This is because given 'AND' and '=' conjunctions it is easy for Xataface to be able to add records that will satisfy the relationship. If an 'OR' conjunction is used, it makes it ambiguous (though this will probably be corrected in future Xataface releases.

===Download Source Files===

[http://xataface.com/documentation/tutorial/getting_started/facultyofwidgetry-8-tar.gz Download the source files for this application as a tar.gz archive]",relationships,en,
relationships.ini_file,20,relationships.ini_file,"==relationships.ini File Reference==

[[toc]]

===Overview===

The relationship.ini file is a configuration file which is associated with a single table of a database application.  It provides metadata about the table's relationships to other tables to help Xataface dictate how they should be included in the application.  

===Field Directives===

The following directives may be added to a field's section of the relationship.ini file to customize the field's behavior.  Some directives are not applicable to all fields.

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| __sql__
| The SQL query that defines this relationship. 
| all
|-
| [[action:visible]]
| A boolean value (0 or 1) that indicates whether this relationship should be visible in the record tabs.
| all
|-
| [[action:condition]]
| An expression that evaluates to a boolean that determines at runtime whether the relationship's tab should appear in the record tabs.
| all
|-
| [[action:delegate]]
| The name of an alternative action that can be used instead of the standard related records list.  One possible value for this would be ""related_records_checkboxes"" which would provide the user with a checkbox group to select the records that should be part of the relationship rather than the usual related record list.
| 1.0
|-
| [[section:limit]]
| Integer.  The number of records to show in the related record sections (in the view tab).  Default is 5.
| 1.0
|-
| [[section:visible]]
| Boolean value (0 or 1) indicating whether the relationship information should appear as a section on the left side of the table.
| all
|-
| [[actions:addexisting]]
| Boolean value (0 or 1) indicating whether the action to add existing records should exist in this relationship.
| all
|-
| [[actions:addnew]]
| Boolean value (0 or 1) indicating whether the action to add news records should exist in this relationship.
| all
|-
| [[action:label]]
| The label that appears in the relationship tab for this relationship. 
| all
|-
| [[list:type]]
| Optional type of list to use for the related record list.  Possible value: ""treetable""
| 0.8
|-
| [[meta:class]]
| An optional special class to assign to the relationship.  E.g. ""parent"" or ""children"".
| 0.8
|-
| [[metafields:order]]
| If the relationship should have a default order this specifies the field that should be used for this sort. 
| all
|-
| [[visibility:fieldName]]
| If given the value hidden will make that particular fieldName disappear in the relationship.  This will only be applied for that particular relationship.  
| all
|-
| [[visibility:find]]
| If given the value hidden this will cause the related fields to not appear on the find form.  Normally each relationship is provided a section of the find form to enable users to find records that contain at least one match in the related records.  
| 1.3rc4
|-
| [[vocabulary:existing]]
| Specifies a valuelist that can be used to provide the set of records that can be added to this relationship.  If target table has a single column primary key then the valuelist should use the primary key for the value.  If it has a multi-column primary key, then the value should be in the form key1=value1&key2=value2 etc...  See also [[relationshipname__getAddableValues]] delegate class method for a programatic solution.
| 1.0
|}

==Relationship Permissions==

See [[Relationship Permissions]]

==See Also==

* [http://xataface.com/documentation/tutorial/getting_started/relationships Getting started with relationships]","relationships.ini file, relationships",en,0
secure,88,"secure fields.ini directive","[[fields.ini file]] directive used only with [[container fields]].  If this flag is set, then the field contents will be treated in a secure manner and will obey the application permissions.  If this directive is not set, then uploaded files in [[container fields]] are served directly by the web server without considering application permissions.  Setting this directive will cause the application use a special get_blob action to serve the uploaded file, and this obeys application permissions.

==Example==

Given a field to upload a PDF report, your [[fields.ini file]] section for this field might be something like:

<code>
[pdf_report]
    Type=container
    allowed_extensions=""pdf""
    savepath=""uploads""
    url=""uploads""
</code>


Now if we upload a file named ""foo.pdf"" in this field, it will be uploaded to:
 http://www.example.com/path/to/myapp/uploads/foo.pdf

Now we change the field definition to use the secure directive:

<code>
[pdf_report]
    Type=container
    allowed_extensions=""pdf""
    savepath=""uploads""
    url=""uploads""
    secure=1
</code>

In this case it will still upload files to the ''uploads'' directory, but all of the links generated in the Xataface interface (and via the ''display()'' and ''htmlValue()'' methods) will be for a URL like:
  http://www.example.com/path/to/myapp/index.php?-action=getBlob&-table=mytable&-field=pdf_report&record_id=10

Which will serve up the PDF file as an attachment.

===Restricting Direct Access to uploads directory===

Note: You still need to restrict access to the uploads directory or it may be possible for users to still guess the absolute URL to files in it.  You can restrict access by placing an .htaccess file in the uploads directory (if you are using Apache) with the following contents:
<code>
deny from all
</code>

If you are using IIS or another web server you should look into the methods available for you to restrict access to directories.

===HTTP Response Codes===

The [[getBlob action]] will return the following HTTP Response Codes:

* '''404''' - If either the record does not exist, or the record's specified container field is empty.
* '''403''' - If the current user doesn't have permission to access this record.
* '''500''' - If there is another error.  The actual error will be written to the error log.","secure,fields.ini file",en,
Selected_Records_Actions,58,Selected_Records_Actions,"==Creating a Custom ''Selected Records'' Action==

[[toc]]

If you view the ''list'' tab in any of your Xataface applications, you'll notice that there is a checkbox next to each row of the list, and there are a number of actions listed at the bottom of the list that you can perform on the selected records.  Xataface comes pre-built with only a few of these actions:

# Delete selected
# Update selected
# Copy selected

However it is quite easy to add your own actions here that are performed on selected records.  This article describes exactly how to do this.

===What is a ''Selected Record'' action?===

A ''Selected Record'' action is no different than any other action in Xataface, except that it is meant to act on the records that have been selected in the list tab.

==Example Action:  Approve Records==

Consider a news site where news stories are automatically imported into the database en masse, but each news story has a field ''approved'' to indicate whether the store has been approved to appear on the site yet.   The usage pattern of this application involves a lot of looking through lists of news stories and approving them.  Therefore it would be convenient if the user could just select the rows that he wants to approve and click a button to approve them all.

Out of the box Xataface would allow the user to select the records, click ''update selected records'', then update them all via the ''update selected records'' form.  But avoiding this extra step will improve usability greatly.

===Step 1: Design the Action===

First we need to specifically decide how our action will work.  In this case, the flow goes as follows:

# User selects the news items they want to approve.
# User clicks the ''Approve Selected'' button. (to be created)
# Our action approves the selected records.
# User is automatically redirected back to the list tab with a message stating how many records were successfully approved, and whether there were any errors.

===Step 2: Gather Our Tools===

Before we actually create the action, let's look at a few tools that we'll be using from the Xataface framework to make this happen.

# In the [[actions.ini file]], the ''[[selected_result_actions]]'' category is reserved for actions that act on selected records of the list tab.  E.g.<code>
[delete_selected]
    ...
    category=selected_result_actions
    ...
</code>
# The [http://dataface.weblite.ca/df_get_selected_records df_get_selected_records()] function returns an array of [http://dataface.weblite.ca/Dataface_Record Dataface_Record] objects that represent the rows that were selected to initiate the action.  E.g.<code>
$app =& Dataface_Application::getInstance();
$query =& $app->getQuery();
$records = df_get_selected_records($query);
foreach ($records as $record){
    ...
}
</code>
# The [http://dataface.weblite.ca/checkPermission Dataface_Record::checkPermission()] method allows us to see if the current user has access to a specific permission on the given record.  We'll use this method to ensure that the user has permission to approve the news record. E.g.<code>
if ( !$record->checkPermission('edit', array('field'=>'approved')) ){
    return PEAR::raiseError(""You don't have permission to edit the approved field for this record."");
}
</code>
# The Xataface will pass the redirect URL where your action should send the user upon completion of the action as the ''--redirect'' attribute of the ''POST'' variables.  This value is base64_encoded so you'll need to decode it before redirecting.  E.g.:<code>
if ( @$_POST['--redirect'] ) 
    $url = base64_decode($_POST['--redirect']);
$url .= '&--msg='.urlencode($updated.' records were deleted.');
header('Location: '.$url);
exit;
</code>

===Step 3: Create the Action===

We will call our action ''approve_news'' so we'll place it in the ''actions/approve_news.php'' file of our application:
<code>
<?php
class actions_approve_news {
    function handle(&$params){
        // First get the selected records
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        $records =& df_get_selected_records($query);

        $updated = 0;  // Count the number of records we update
        $errs = array();   // Log the errors we encounter

        foreach ($records as $rec){
            if ( !$rec->checkPermission('edit'), array('field'=>'approved')) ){
                $errs[] = Dataface_Error::permissionDenied(
                    ""You do not have permission to approve '"".
                    $rec->getTitle().
                    ""' because you do not have the 'edit' permission."");
                continue;
            }
            $rec->setValue('approved', 1);
 
            $res = $rec->save(true /*secure*/);
            if ( PEAR::isError($res) ) $errs[] = $res->getMessage();
            else $updated++;
            
        }
        
        if ( $errs ){
            // Errors occurred.  Let's let the user know.
            // The $_SESSION['--msg'] content will be displayed to the user as a message
            // in the next page request.
            $_SESSION['--msg'] = 'Errors Occurred:<br/> '.implode('<br/> ', $errs);
        } else {
            $_SESSION['--msg'] = ""No errors occurred"";
        }
        

        $url = $app->url('-action=list');   // A default URL in case no redirect was supplied
        if ( @$_POST['--redirect'] ) $url = base64_decode($_POST['--redirect']);
        $url .= '&--msg='.urlencode($updated.' records were deleted.');

        // Redirect back to the previous page
        header('Location: '.$url);
        exit;
    }
}
</code>

===Step 4: Add the action to your actions.ini file===

The actions.ini file allows us to specify how and where this action is used, and by whom.  We can specify permissions that are required to perform the action, conditions that are required to display the action, confirmation messages that are to be displayed to the user when they are about to perform the action, and more.  Our [[actions.ini file]] entry looks like:

<code>
[approve_news]
    label=""Approve""
    description=""Approve selected records""
    permission = edit
    category=selected_result_actions
    confirm=""Are you sure you want to approve the selected records?""
    icon=""${dataface_site_url}/images/approve.gif""
    condition=""$query['-table'] == 'news'""
</code>

This should be fairly straight forward.  The only special items here are the ''category'' and ''confirm'' directives.  The ''condition'' directive tells Xataface that this action should only be shown for the ''news'' table. 

The ''confirm'' directive defines a confirmation message that should be displayed to the user when they attempt to approve records.

The ''icon'' directive allows you to specify the path to an icon to display for the action.  In our case we have an icon located in the images directory of our application.

===Step 5: Trying it out===

Now when we go to the ''list'' tab of the ''news'' table there is an ''Approve'' button along the bottom where it says ""With Selected"".  You we can click on this button to approve any of the selected rows.


	",,en,0
sendRegistrationActivationEmail,16,sendRegistrationActivationEmail,"==sendRegistrationActivationEmail() Hook==

A hook that can be implemented in the [[Application Delegate Class]] or the [[Table Delegate Class]] to override the sending of an activation email to the user.

===Signature===

function sendRegistrationActivationEmail( Dataface_Record &$record, string $activationURL ) : mixed

====Parameters====

{| class=""listing listing2""
! Name
! Description
|-
| &$record
| A Dataface_Record object encapsulating the record that is being inserted in the users table for this registration.
|-
| $activationURL
| The URL where the user can go to activate their account.
|-
| returns
| Mixed. If this method returns a PEAR_Error object, then registration will fail with an error.
|}

===Example===

<code>
<?php
class conf_ApplicationDelegate {

    function sendRegistrationActivationEmail(&$record, $activationURL){
        // mail the admin to let him know that the registration is occurring.
        $username = $record->val('username');
        $email = $record->val('email');
        
        mail($email, 'Welcome to the team', 
            'Welcome '.$record->val('username').
            '.  You have been successfully registered.  
             Please visit '.$activationURL.' to activate your account'
        );
    }
}
</code>

===See Also===
* [[beforeRegister]]
* [[afterRegister]]
* [[validateRegistrationForm]]
* [[getRegistrationActivationEmailInfo]]
* [[getRegistrationActivationEmailSubject]]
* [[getRegistrationActivationEmailMessage]]
* [[getRegistrationActivationEmailParameters]]
* [[getRegistrationActivationEmailHeaders]]",,en,0
setSecurityFilters,91,"setSecurityFilter() method","== Example ==

In the delegate class for the users table:

<code>
<?php
class tables_users {
    function init(&$table){
        if ( !isAdmin() ){
            $table->setSecurityFilter(array('group_id'=>10));
        }
    }
}
</code>

This will only set the filter on non-admin users (assuming that you have defined a function isAdmin() to tell you if the current user is an admin user.",,en,
registration_form,98,"Setting up User Registration","[[toc]]

===Synopsis===

Xataface optionally enables you to allow users to register for an account in your application.  If your ''users'' table includes a column for email, it will also perform email validation before the account is activated.  Before tackling user registration, it is good to have an understanding of Xataface's [[authentication]] and [http://xataface.com/documentation/tutorial/getting_started/permissions permissions] faculties.

===Enabling Registration===

To enable registration, simply add the following to the ''[[_auth]]'' section of the [[conf.ini file]]:

<code>
allow_register=1
</code>

e.g. after adding this, your ''[[_auth]]'' section might look like:

<code>
[_auth]
     users_table=users
     username_column=username
     password_column=password
     allow_register=1
</code>

After doing this, you'll notice a little ''Register'' link below the login form.  

[[Image:http://media.weblite.ca/files/photos/Picture%2036.png?max_width=640]]

Clicking on this link will produce a registration form for the user which is essentially a ""New Record"" form on your ''users'' table.

[[Image:http://media.weblite.ca/files/photos/Picture%2037.png?max_width=640]]

Some features of this registration form include:

* Checks to ensure that the username is unique
* If the users table contains an ''email'' field, it will use the user-entered address for email validation before activation is complete.

===Setting up Permissions to Support Registration===

'''Xataface <= 1.2.4''':   You must ensure that unlogged-in users have permission to add new records to the ''users'' table.  This means that your getPermissions() method on the users table should, at least, provide the ''new'' permission.  In addition these users must be granted the ''register'' permission in order to be able to register to begin with.

'''Xataface >= 1.2.5''':  You no longer need to provide the ''new'' permission to allow users to register.  You simply need to provide the ''register'' permission.

====Sample Permissions on Users Table====

In the tables/users/users.php file (assuming my ''users'' table is actually named ""users"")

<code>
class tables_users {

    function getPermissions($record){
        if ( isAdmin() ) return null;
        $perms['register'] = 1;
        return $perms;
     
    }
}
</code>

'''Note that this example is only applicable for Xataface 1.2.5 or higher.  In Xataface 1.2.4 you needed to provide users with the ''new'' permission rather than the ''register'' permission, which opens up a small security hole since users could potentially just use the ""new"" action if they new the URL and by-pass the registration and activation email altogether'''.

Some notes on this example:

* The isAdmin() function is not part of Xataface.  It is used as a bit of *magic* here to reduce code.  It is supposed to simply return true if the currently logged in user is an admin.  Hence if the user is an admin, this method defers to the Application Delegate class's permissions (i.e. this method should not affect administrators).
* We are giving all users (logged in or not) the register permission which enables them to register for an account on the system.
* Generally you will want to restrict permissions on some of the fields in the users table.  E.g. users should not be able to set their role or access level when they register.  You can define more fine-grained permissions on these fields using the [[fieldname__permissions]] method of the users table delegate class (per the following example).

====Restricting Permissions on Particular Fields====

You probably don't want users to be able to set their access level when the register for an account, and your ""users"" table will quite often contain some field like ""role"" which stores this information.  So the previous example is not quite realistic.  You will also need to restrict permissions on the ""role"" field (and any other fields that you want to prevent users from setting themselves.

<code>
function role__permissions(&$record){
    if ( isAdmin() ) return null;
    return Dataface_PermissionsTool::NO_ACCESS();
}
</code>

This will cut off the user's ability to set their own role when they register.  You will likely want to set the default role value either in the mysql table definition or in the [[beforeInsert]] trigger.

===Email Validation===

As mentioned above, registration works by sending an activation email to the address specified in the user's registration.  This email contains a link back to the ''activate'' action of your Xataface application, which will create the user account and log the user in.  This implies that your ''users'' table must store an email address for your users.  If you add a field named ''email'' to the ''users'' table, Xataface will assume that you mean to use this field as the user's email address, and thus, for email validation.  However you can override this functionality and use *any* field as an email field by setting the ''email'' directive of the appropriate field in the [[fields.ini file]] for the ''users'' table.

'''Example: Assigning the my_addr field of the users table to be used for email validation''':

In the tables/users/fields.ini file:
<code>
[my_addr]
    email=1
</code>

====Disabling Email Validation====

99% of the time, email validation is the preferred way of ensuring that people who register are who they say they are.  You may, however, prefer to let users register directly without requiring the email activation step.  You can disable email validation by overriding the ''register'' action in the [[actions.ini file]] as follows:

In your application's [[actions.ini file]]:
<code>
[register > register]
    email_validation=0
</code>

After setting this, the user account will automatically be created, and the user logged in upon saving the registration form.

===Triggers: Overriding Registration Workflow===

Xataface provides a number of triggers in the [[Application Delegate Class]] to override and extend the behavior of the user registration and activation process.  For a list of available triggers see [[Application Delegate Class#registration]].


===Preventing Spam with CAPTCHA===

One problem with enabling automatic registration is that it invites SPAM in the form of bots that can learn how to automatically register for user accounts and then leave unwanted input into your application.  The Xataface [[reCAPTCHA module]] allows you to avoid these problems to some extent by forcing users who aren't logged in to fill a CAPTCHA field in order to successfully submit the form.  This is especially helpful for registration forms.

After installing the [[reCAPTCHA module]] the registration form will include a CAPTCHA field like the one depicted below:

[[Image:http://media.weblite.ca/files/photos/Picture%2038.png?max_width=640]]

For more information about the reCAPTCHA module [[reCAPTCHA module|click here]].
    ","registration form, _auth, authentication",en,
ShoppingCart,31,ShoppingCart,"==Xataface Shopping Cart Module==

[[toc]]

Status: Under development
Current Version: 0.2

===Synopsis===

Add a shopping cart to your xataface application.  You can treat any record as a product that can be sold.  Includes Paypal connectivity, shipping calculation, and more.

===Requirements===

* Xataface 1.0 or higher
* PHP 5 or higher
* MySQL 4.1 or higher

===Installation Instructions===

# Download the ShoppingCart module, extract it, and place the ShoppingCart directory in your Xataface modules directory. (i.e. /path/to/xataface/modules/ShoppingCart).
# Add the following line to the [_modules] section of your [[conf.ini file]]:<code>
modules_ShoppingCart=modules/ShoppingCart/ShoppingCart.php
</code>
# Add the following to the beginning of your [[index.php file]]:<code>
function __autoload($class){
    if ( $class == 'ShoppingCart' ) require_once 'modules/ShoppingCart/lib/ShoppingCart/ShoppingCart.class.php';
}
</code>
# In the [[fields.ini file]] for any table whose records you wish to represent items for sale, add the following:<code>
[__implements__]
    InventoryItem=1
</code>
# Specify which fields should be used for the item description, price, width, height, length, and weight in the [[fields.ini file]] for each table whose records you wish to represent items for sale by adding the following directives to the appropriate fields:<code>
ShoppingCart.description=1
ShoppingCart.unitPrice=1
ShoppingCart.weight=1
ShoppingCart.width=1
ShoppingCart.height=1
ShoppingCart.length=1
</code> E.g. if your table has a field named """"price"""" that you want to represent the unit price, you would have something like:<code>
[price]
    ShoppingCart.unitPrice=1
</code>  The shopping cart module will make its best guess on which fields to use for these values if they are not explicitly specified.
# Specify the paypal account where money should be deposited by adding the following to your application's [[actions.ini file]]:<code>
[view_cart]
    paypal.account=""youremail@example.com""
</code>


===Usage Instructions===

Once the Shopping Cart module is installed you can:

# Add items to your shopping cart
# View your cart contents
# Checkout and pay with paypal

====Adding Items to the Cart====

In the View tab of any salable record, you'll notice a little block on the left side of the page with the heading ""Add Item to Cart"".  This includes a field to specify the quantity and a button to add the item to the shopping cart.

====Viewing Cart Contents====

The Shopping Cart module automatically introduces an action to view the cart contents.  This action is named ""view_cart"".  Hence you can always view the cart contents by entering the URL: index.php?-action=view_cart .

====Checking Out====

# View the cart contents.
# Click ""Check out""
# This will take you to a paypal page to pay for your items.


==Actions==

This module adds the following actions to your application.

{| class=""listing listing2""
|-
! Name
! Content-type
! Description
! Version
|-
| checkout
| text/html
| Sends user to paypal to pay for the contents of their cart.
| 0.1
|-
| calculate_shipping
| text/html
| Calculates the shipping charges for the cart.
| 0.1
|-
| add_to_cart
| text/html
| Adds an item to the cart.
| 0.1
|-
| clear_cart
| text/html
| Empties the shopping cart.
| 0.1
|-
| get_shipping_provinces
| text/json
| Returns JSON array of provinces for a given country.
| 0.1
|-
| invoices
| text/html
| Displays the current user's invoices.
| 0.1
|-
| payment_complete
| text/html
| Page that is displayed after a successful payment on paypal.
| 0.1
|-
| paypal_ipn
| none
| Handles paypal events such as successful payments.
| 0.1
|-
| refresh_shipping_methods
| text/html
| Refreshes the shipping methods available to the system.
| 0.1
|-
| set_shipping_method
| text/html
| Sets the selected shipping method to a particular method.
| 0.1
|- 
| view_cart
| text/html
| View the cart contents.
| 0.1
|}

==Blocks and Slots==

This module adds the following blocks and slots to your applications.

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| shipping_method
| A block with a form to select the shipping method.
| 0.1
|-
| add_to_cart
| A block with a form to add a record/item to the shopping cart.
| 0.1 
|}

==Application Delegate Class Hooks==

You can modify the shopping cart behavior by defining the following methods to the application delegate class.

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| isShippingMandatory
| Returns a boolean value indicating whether the user must select a shipping method.
| 0.1
|-
| getDefaultShippingMethod
| Returns a string with the name of the default shipping method to be used.
| 0.1
|}


==Table Delegate Class Hooks==

You can modify the behavior of the shopping cart by defining the following methods to the delegate class of any table that implements the InventoryItem ontology (i.e. any table that is to be used to store products that can be added to the cart).

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| field__taxes
| A calculated field that returns an associative array of all applicable taxes for a product.
| 0.1
|}

==Internal Storage==

This module creates the following tables to store its data:

===dataface__invoices===

The dataface__invoices table stores the actual invoices for purchases made.  An invoice is automatically created as soon as the user ""checks out"".

{| class=""listing listing2""
|-
! Column Name
! Data Type
! Description
! Version
|-
| InvoiceID
| int(11)
| Auto incrementing primary key for the invoice.
| 0.1
|-
| dateCreated
| datetime
| The date that the invoice was created.
| 0.1
|-
| dateModified
| datetime
| The date that the invoice was last modified
| 0.1
|-
| status
| enum
| The status of the invoice (either PENDING, PAID, or APPROVED).
| 0.1
|-
| amount
| decimal(10,2)
| The total amount on the invoice.
| 0.1
|-
| paymentMethod
| varchar(32)
| The name of the payment method used.
| 0.1
|-
| referenceID
| varchar(64)
| ??
| 0.1
|-
| username
| varchar(32)
| The username of the user who owns this invoice.
| 0.1
|-
| firstName
| varchar(32)
| The first name of the payer.
| 0.1
|-
| lastName
| varchar(32)
| The last name of the payer.
| 0.1
|-
| address_name
| varchar(100)
| The name on the shipping address.
| 0.1
|-
| address1
| varchar(100)
| The shipping address line 1.
| 0.1
|-
| address2
| varchar(100)
| The shipping address line 2.
| 0.1
|-
| city
| varchar(40)
| The shipping address city.
| 0.1
|-
| province
| varchar(2)
| The shipping province or state.
| 0.1
|-
| country
| varchar(2)
| The shipping country.
| 0.1
|-
| postalCode
| varchar(32)
| The shipping postal code.
| 0.1
|-
| shipping_method
| varchar(50)
| The name of the shipping method to use.
| 0.1
|-
| phone
| varchar(32)
| The phone number of the payer.
| 0.1
|-
| email
| varchar(127)
| The email address of the buyer.
| 0.1
|-
| data
| text
| Serialize shopping cart data.
| 0.1
|}


===dataface__shipping_methods===

Stores the available shipping methods.

{| class=""listing listing2""
|-
! Column Name
! Data Type
! Description
! Version
|-
| shipping_method_id
| int(11)
| Auto increment ID for a shipping method.
| 0.1
|-
| shipping_method_name
| varchar(50)
| The name of the shipping method.
| 0.1
|-
| shipping_method_label
| varchar(100)
| The label for the shipping method (displayed to the user).
| 0.1
|-
| shipping_method_enabled
| tinyint(1)
| Whether or not this shipping method is currently enabled.
| 0.1
|-
| shipping_method_module
| varchar(32)
| The name of the handler that this shipping method belongs to.
| 0.1
|}

==Payment Handlers==

Information about payment handlers to be added here.

==Shipping Handlers==

The Shopping Cart module is itself modular, allowing you to develop custom shipping handlers for different types of shipping.  A shipping handler is responsible for calculating shipping costs to a destination address.  Currently only a UPS shipping handler has been created, but it is not difficult to create other handlers.

===Shipping Handler Public Interface===

{| class=""listing listing2""
|-
! Method
! Description
! Version
|-
| calculateShipping
| Calculates the shipping cost for the current shopping cart, and adds the shipping cost to the cart as a line item.
| 0.1
|-
| getInfo
| Returns an array of shipping methods that can be handled by this handler.
| 0.1
|}






",,en,0
struct,56,struct,,,en,0
tab,48,tab,"==tab directive of the fields.ini file==

[[toc]]

The ''tab'' directive of the [[fields.ini file]] specifies which tab of the record edit form a field should be displayed on.  Xataface supports multiple tabs on the edit form by way of this ''tab'' directive.  If no fields contain the ''tab'' directive then all fields are displayed in a single tab (named ''__main__'').

==Example 1: Placing address info on separate tab==

Consider the following ''people'' table: 
<code>
CREATE TABLE `people` (
    person_id int(11) not null auto_increment primary key,
    first_name varchar(32) not null,
    last_name varchar(32) not null,
    address varchar(100),
    city varchar(100),
    province varchar(100),
    country varchar(100),
    postal_code varchar(20)
)
</code>

We want to split the fields into two tabs:
* Personal Info
* Address Info

===Splitting form into tabs===
We'll do this in two steps.  We use the ''tab'' directive to assign all address-related fields to the ''address_info'' tab.  In the tables/people/fields.ini file:
<code>
[address]
    tab=address_info

[city]
    tab=address_info

[province]
    tab=address_info

[country]
    tab=address_info

[postal_code]
    tab=address_info
</code>

Now, when we load the edit form of the ''people'' table, we see two tabs:

* __main__
* address_info

<nowiki>
<img src=""http://media.weblite.ca/files/photos/Picture 9.png?max_width=640""/>
<img src=""http://media.weblite.ca/files/photos/Picture 10.png?max_width=640""/>
</nowiki>

''__main__'' is the name assigned to the default tab (for all fields that don't have a tab defined explicitly.


===Customizing the tab labels===

Next we will customize the tab labels by adding the following to the beginning of the [[fields.ini file]]:
<code>
[tab:__main__]
    label=""Personal Information""

[tab:address_info]
    label=""Address Information""
</code>

<nowiki>
<img src=""http://media.weblite.ca/files/photos/Picture 11.png?max_width=640""/>
<img src=""http://media.weblite.ca/files/photos/Picture 12.png?max_width=640""/>
</nowiki>


===Reordering the tabs===

If we want to reorder the tabs so that the ''address_info'' tab comes first, we would just reorder the definitions of the tabs:
<code>
[tab:address_info]
    label=""Address Information""

[tab:__main__]
    label=""Personal Information""
</code>

<nowiki>
<img src=""http://media.weblite.ca/files/photos/Picture 13.png?max_width=640""/>
</nowiki>

===Try This Example App===

You can try this tiny sample application out [http://dev.weblite.ca/tab_test here].",,en,0
table,66,table,"When using widget:type table, it will store the data as XML.

So the field type must be TEXT (or varchar... but text is better). You can decide which columns you want in the table by creating sub-fields in your fields.ini file as follows:

Suppose you want a column called 'name' and a column called 'url'

<code>
[myfield]
widget:type=table
[myfield:name]
[myfield:url]
</code>

Now when you access the stored value using the Dataface API, the value of myfield will be stored as an array of associative arrays. e.g. 

<code>
foreach ( $record->val('myfield') as $vals){ echo $vals['name'].' -- '.$vals['url']; }
</code>",,en,0
templates:tags:use_macro,24,templates:tags:use_macro,"==use_macro Template Tag==

===Synopsis===

The use_macro tag includes another template into the current template with the option to override certain sections.

===Parameters===

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| file
| The path the template to include (within the templates directory).
| 0.6
|}

===Example===

In this example we will create a template for a user profile, but this template will include a slot that can be overridden by other templates to customize the user bio.

====user-profile.html====

<code>
<html>
<head>
    <title>User profile</title>
</head>
<body>
   <h1>User bio</h1>
   <div id=""bio"">
   {define_slot name=""bio""}
        This text will be overridden by other templates to place the correct
        bio information.
   {/define_slot}
</body>
</html>
</code>

====steve-profile.html====

<code>
{use_macro file=""user-profile.html""}
    {fill_slot name=""bio""}
        This is Steve's bio.  It will override the text in the bio slot.
    {/fill_slot}
{/use_macro}
</code>

===See also:===

* [[xataface templates|Xataface templates]]
* [[templates:tags:define_slot|The define_slot tag]]
* [[templates:tags:fill_slot|The fill_slot tag]]
* [http://www.xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing the Look & Feel of Xataface] (From the Getting Started Tutorial)
* [http://www.xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Cusomizing the Xataface Look & Feel] Tutorial
",,en,0
testpage2,2,testpage2,"Another test page
[[testpage]]",,en,0
lookup,61,"The Lookup Widget","Return to [[widget:type]] page to see list of all widget types.
Back to [[fields.ini file]] to see other fields.ini directives.

[[toc]]

===Synopsis===

The lookup widget allows users to look a record from another table to insert into the field.  It is like a select widget except that it doesn't use a vocabulary.  Instead you just specify a table on which it should search using the widget:table directive.  In order to use the lookup widget to edit a field, you should set the [[widget:type]] directive of the [[fields.ini file]] for the field to '''lookup''.  I.e.
<code>
[fieldname]
    widget:type=lookup
    widget:table=mytable
</code>

'''Note that the lookup widget requires the [[widget:table]] directive to be set to the target table of the lookup or it will not work properly.'''

===Required Directives===

The following [[fields.ini file]] directives are required to accompany the field definition if a lookup widget is used:

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| widget:table
| The name of the table in which the lookup widget should look up related records.
| 1.0
|}


===Optional Directives===

The following additional optional directives may be used to customize the behaviour of the lookup widget:

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| widget:filters:-limit
| Sets the number of records that are shown by default in the lookup widget.  Default is 30 if this is omitted. E.g.<code>widget:filters:-limit=100</code> to show 100 records at a time.
| 1.0
|-
| widget:filters:-sort
| Specifies the columns to sort the results on. E.g. <code>widget:filters:-sort=category_name asc, year desc</code>
| 1.0
|-
| widget:filters:*
| Any valid Xataface directive can be used to filter the results by specifying widget:filters:param  (where ""param"" is a valid Xataface GET parameter, which could include a column name to filter results on, or other filter directives). <code>widget:filters:country=Canada</code> To only show results with Country=Canada.
| 1.0
|-
| widget:filters:*=$*
| Dynamic filters.  Causes the options in the record browser to be filtered on the value of another field in the form.  e.g. <code>widget:filters:country_id=""$country_id""</code> would show only results with records having country_id matching the value of the 'country_id' field in the current form.
| 1.3.1
|}

See [[URL Conventions]] for an overview of the types of GET parameters Xataface can take.  Any GET parameters that manipulate a query can be used with the widget:filters:* directive to modify the query results that are shown in the lookup widget.


===Example===

In this example we have a field named appointee that is supposed to reference the contacts table.  So in the [[fields.ini file]] we would have:

<pre>
[appointee]
    widget:type=lookup
    widget:table=contacts
</pre>

Initially we just have a little find icon next to the field. If the user clicks it, a dialog pops up enabling them to search for the contact that they want:

[[Image:http://media.weblite.ca/files/photos/Picture%2023.png?max_width=640]]


===Additional Tips===

Although the lookup widget does not use a vocabulary as indicated in the Synopsis above, it is still useful to define a vocabulary in the fields.ini file for this field. The reason is because the lookup widget is only used with the edit action, where you are inserting or editing data into the field. However, it is not used to the display the data in the view or list actions. Therefore, you must still have a vocabulary defined to properly display these values.

In order to customize the display of the lookup widget's select list, you must edit the delegate class for the table which is referenced by the widget:table directive. There are two important points to note:

# The items in the selection list are formatted based on the getTitle(&$record) delegate class function if it is defined. However, ...
# The Search box will search on text in VARCHAR and TEXT fields. If you need to search for data in numeric fields, you can create a grafted field using a function such as CONCAT() to display numbers as text.

Links:
* [http://xataface.com/forum/viewtopic.php?f=4&t=6723 Lookup widget on view with compound primary key]","lookup widget, widget:filters, widget:-filters:limit, widget:table",en,0
reCAPTCHA_module,99,"The reCAPTCHA module","[[toc]]

===Synopsis===

The Xataface reCAPTCHA module CAPTCHA support to any Xataface form that is rendered to the public (i.e. when users are not logged in).  This is particularly useful for the [[registration form]] as a means of spam prevention.   Below is a screenshot of a registration form with the reCAPTCHA module installed:

[[Image:http://media.weblite.ca/files/photos/Picture%2038.png?max_width=640]]

For more information about reCAPTCHA see [http://recaptcha.net/].


===Installation===

# Download/extract the module directory into your xataface/modules directory.  Currently this module is only available in SVN (http://weblite.ca/svn/dataface/modules/reCAPTCHA/trunk/)
# Add the following to the <nowiki>[_modules]</nowiki> section of your [[conf.ini file]].<code>
[_modules]
    modules_reCAPTCHA=modules/reCAPTCHA/reCAPTCHA.php
</code>
# Add the following section to your conf.ini file.<code>
[reCAPTCHA]
    public_key=""xxxxxxx""
    private_key=""xxxxxxx""
</code> Where public_key, private_key are your keys from your reCAPTCHA account. '''(Note that you need to register for a free reCAPTCHA account at [http://recaptcha.net/] in order for this to work.'''

===Usage===

If you are NOT logged in, you will now see a reCAPTCHA validation image before the submit button for all webforms in your Xataface application.  If you fail to enter the captcha text correctly the form will not validate.  If you are logged in this module has no effect.

===See Also===

* [[registration_form|Enabling User Registration in Xataface]]
* [[modules|Xataface Modules]]
","captcha, registration, validation",en,
relationship,68,"The relationship fields.ini directive","[[fields.ini file|Return to fields.ini file directives]]

[[toc]]

===Synopsis===

Certain types of widgets (e.g. grid (v1.0) and checkbox (v1.2)) support the relationship directive which allows them to effectively add/remove records from a specified relationship.  This directive only works with transient fields.

===Example 1: Checkboxes to add/remove categories===

(Note: This example requires Xataface 1.2 or higher to work)

Suppose we have a database that keeps track of courses and the branch of research that they belong to.  A course can be part of multiple branches.  We want to be able to select the branches that a particular course belongs to on the edit form for that course using checkboxes.

Table Structure:
<code>
courses:
   course_id : int (primary key)
   course_title : varchar

branches:
   branch_id : int (primary key)
   branch_name : varchar
   branch_description: text

course_branches:
   course_id : int
   branch_id : int
</code>

Relationship definition:  (from the tables/courses/[[relationships.ini file]]):
<code>
[branches]
    course_branches.course_id=""$course_id""
    course_branches.branch_id=branches.branch_id
</code>

Field definitions: (from tables/courses/[[fields.ini file]]):
<code>
[branches]
  transient=1
  relationship=branches
  widget:type=checkbox
</code>

Things to notice:
# This is a many-to-many relationship (hence the need for the course_branches join table.
# The [branches] field is a transient field.
# The relationship directive from the [[fields.ini file]] references our branches relationship that was defined in the [[relationships.ini file]].
# You can call the field anything that you like.  There is no need for it to have the same name as the relationship.  It just turned out that way in this example.  

===Example 2: Using a grid widget===

Let's modify example 1 slightly to use a grid widget instead of checkboxes.  The grid widget will allow us edit the records in a relationship using dynamic table.  It automatically uses the correct widget for each column of the table according to the definition in the target table's [[fields.ini file]].  Most of the definition can remain the same.  We only change the [[fields.ini file]] directive:

<code>
[branches]
  transient=1
  relationship=branches
  widget:type=grid
  widget:columns=""branch_name,branch_description""
</code>

In this case we are able to edit the branch name and description in each row of the grid.

===See Also===

* [[grid|The grid widget]]
* [[checkbox|The checkbox widget]]
* [[relationships.ini file|The relationships.ini file]]
* [[fields.ini file|The fields.ini file]]","grid widget, relationship, checkbox",en,0
_output_cache,45,"The Xataface Output Cache","<nowiki><div class=""portalMessage"">Note: There was a bug in the output cache affecting Xataface version 1.0 to 1.3rc1.  If you are using a version of Xataface older than 1.3rc2 then you should either disable the output cache, or replace the Dataface/OutputCache.php file with one from a newer version.</div></nowiki>

[[toc]]

Xataface does quite a bit of heavy lifting on each page request.  If your application is getting a lot of traffic that is slowing your server down, you may want to look at enabling the Xataface output cache.

===Features===

* Improve speed of application dramatically - especially for seldom updated sites.
* Supports multiple languages.
* Supports multiple users (each user has own cache).
* Provides GZIP compression for improved performance.

===How it works?===

When you receive a request, Xataface will return a cached version of the page if the page has been accessed before.  If the page doesn't yet exist in the cache it generates the page, saves it to the cache and outputs it to the user transparently.  The cache is completely transparent to your users.

===Where is the cache stored?===

Xataface creates a table called ''__output_cache'' that stores all of the cached content for your application.  This table stores both a GZIPed and regular version of each page.  If the user's browser supports GZIP compression, Xataface will automatically return the GZIP version.  This results in further performance improvements.

===What if I make changes to the database?===

Xataface records which tables were in use when a page is cached.  If any of those tables are modified after the page is cached, Xataface will mark that cached page as ''out of date'' and regenerate it the next time that it is requested.

===What if I make changes to my configuration files and templates?===

The output cache will have to be manually cleared if you make any changes to your source files (e.g. PHP, templates, and INI files).  Clearing the cache is as easy as deleting or emptying the ''__output_cache'' table.

===How do I enable the Cache?===

Add the following to your [[conf.ini file]]:

<code>
[_output_cache]
    enabled=1
</code>

===How do I disable the Cache?===

Simply comment out or remove the ''[_output_cache]'' section of your [[conf.ini file]].  E.g.
<code>
;[_output_cache]
;   enabled=1
</code>

===Configuration Options===

The following directives can be added to the ''[_output_cache]'' section of your [[conf.ini file]] to customize how your output cache works.

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| lifeTime
| Number of seconds before cached page is considered ''out of date''.
| 0.7
|-
| tableName
| The name of the table to store the cached pages.  Default '__output_cache'.
| 0.7
|-
| ignoredTables
| A comma-delimited list of tables that don't affect the output cache (i.e. these tables can be changed without causing the output cache to be refreshed.
| 0.7
|-
| observedTables
| A comma-delimited list of tables that should affect the status of the output cache for every page (whether the table is explicitly used by the page or not).  This is a useful way to tell Xataface to refresh your cache.
| 0.7
|-
| exemptActions
| A comma-delimited list of actions that are exempt from the output cache (and thus should not be cached).
| 0.7
|}","output cache",en,0
timestamp,44,timestamp,"Return to [[fields.ini file]]

A very simple sample of this could be your table contains the table date_created as a type of date.  In your fields.ini, you would include this:

<code>
[date_created]
timestamp=insert
widget:type=hidden
</code>

The widget:type=hidden will make the field not visible during entry and editing.  And the timestamp=insert causes the field to be filled upon insertion of a new record.

===Possible Values===

* '''update''' - Causes timestamp to be updated whenever the record is modified.
* '''insert''' - Causes the timestamp to be updated only when the record is first inserted.","timestamp, date, datetime",en,0
GettingStarted:triggers,81,Triggers,"==Triggers==

Triggers are methods that can be defined to carry out custom behaviors when certain events occur in the application (e.g., when records are saved, inserted, or deleted).

Triggers are generally regarded as one of the more advanced features of database applications. Despite the ""advanced"" status of triggers, however, they are very simple to use and can be leveraged by Xataface developers to add powerful functionality to their applications.

So what can you do with a trigger?

* Send a confirmation email every time a new record is inserted into a table.
* Delete records related to a record that is being deleted (to maintain the consistency of the database).
* Add custom logging functionality.
* Add extra permissions or validation rules (although these are probably better handled with the validation framework).

You can really do just about anything you want with a trigger. A trigger is essentially just a custom PHP method that is called by Xataface when certain events occur.

===What triggers are available?===

As of version 0.5.3 Xataface supports the following triggers:

* '''beforeSave''' : called just before a record is saved (either inserted or updated).
* '''afterSave''' : called just after a record is saved (either inserted or updated).
* '''beforeInsert''' : called just before a record is inserted.
* '''afterInsert''' : called just after a record is inserted.
* '''beforeUpdate''' : called just before a record is updated.
* '''afterUpdate''' : called just after a record is updated.
* '''beforeDelete''' : called just before a record is deleted.
* '''afterDelete''' : called just after a record is deleted.
* '''beforeAddRelatedRecord''' : called just before a related record (new or existing) is added to a relationship.
* '''afterAddRelatedRecord''' : called just after a related record (new or existing) is added to a relationship.
* '''beforeAddNewRelatedRecord''' : called just before a new related record is added.
* '''afterAddNewRelatedRecord''' : called just after a new related record is added.
* '''beforeAddExistingRelatedRecord''' : called just before an existing related record is added.
* '''afterAddExistingRelatedRecord''' : called just after an existing related record is added.

===How do you define a trigger?===

Triggers are always defined as methods of the delegate class for a table. As an example, suppose we wanted to add a trigger to send a the administrator a notification email every time a new record is inserted into the 'Course' table. The steps would be as follows:

# Create a delegate class for the 'Course' table (if one does not already exist) by creating a file named 'Course.php' inside the 'tables/Course' directory.
# Add the following to the Delegate class file to make it a valid delegate class:<code><?
class tables_Course {}
</code>
# Okay, we want our trigger to be called every time a record is inserted. There are 2 possible triggers that can be defined, then:<nowiki>
<ul>
<li>beforeInsert</li>
<li>afterInsert</li>
</ul>
<p>In this case it is probably more appropriate to define the afterInsert trigger because we really only want to send the notification email after the insert has successfully taken place. Therefore, we will define the afterInsert() method in our delegate class as follows:</p>
</nowiki><code>
<?
class tables_Course {
	....
    /**
     * Trigger that is called after Course record is inserted.
     * @param $record Dataface_Record object that has just been inserted.
     */
    function afterInsert(&$record){
        mail('admin_email@yourdomain.com','Subject Line', 'Message body'); 
    }
}
</code>
# That's all for now. The afterInsert() method defined above will automatically be called every time a record is inserted into the Course table. This method, as we have defined it, will send a notification email to the administrator email.

===Sending feedback to the user===

The above example sends the email without any feedback to the application's user of whether the email succeeded or not. When the user inserts a new Course he will only see that the record was succesfully saved, but no mention is made of the email. The following example does the same thing as the previous one, except that it sends a confirmation to the user when the email has been successfully sent:
<code>
function afterInsert(&$record){
    $response =& Dataface_Application::getResponse();
        // get reference to response array

    if ( mail('shannah@sfu.ca', 'Subject Line', 'Message Body') ){
        $response['--msg'] .= ""\nEmail sent to shannah@sfu.ca successfully."";
    } else {
        $response['--msg'] .= ""\nMail could not be sent at this time."";
    }
}
</code>

Now, when the user inserts a new record he will see a confirmation as follows:

[[Image:http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-after-insert-confirm.gif]]

Notice that we used the Dataface_Application::getResponse() function to obtain a reference to the application's response array. The response array is just a global array that is shared by the entire application that allows you to pass information easily from one part of the application to another. The '--msg' index of array is where you can place text that you wish to have displayed to the user as a confirmation.

'''Note''': It is important to use '=&' to assign the result of Dataface::getResponse() and not just '='. e.g.:
<code>
$response =& Dataface_Application::getResponse(); // correct!
$response = Dataface_Application::getResponse(); // WRONG!!
</code>

This is because we need a reference to the response array, not a copy. That way when we assign a value to the '--msg' index it is applied to the actual response array and not a copy of it.

===Handling Errors===

The above method of sending messages to the user is useful for notifications and confirmations. However, in some cases you want to inform the user that an error occurred and cancel further operations. For example you may want to disallow a record to be inserted if a confirmation email cannot be sent. In this case we define the beforeInsert() trigger and return a PEAR_Error object if the email fails as follows:
<code>
<?
class tables_Course {
    function beforeInsert(&$record){
        $response =& Dataface_Application::getResponse();
        if ( mail('shannah@sfu.ca', 'Notification', 'Your record was created')){
            $response['--msg'] .= ""\nEmail sent successfully to shannah@sfu.ca"";
        } else {
            return PEAR::raiseError(
                ""Errors occurred while sending email.  Record could not be inserted"",
                 DATAFACE_E_NOTICE
            );
        }
    }
     
}
</code>

This trigger is called just before a course record is inserted into the database. If the mail succeeds, then the user sees a success message. If it fails, on the other hand, the insert is cancelled, and the user will see a message as follows:

[[Image:http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-error.gif]]


'''Note''': Notice the use of the DATAFACE_E_NOTICE constant as a second parameter for PEAR::raiseError(). This is important as without it Xataface will display a less user-friendly error message complete with stack trace. If the error is such that you want a complete stack trace, you can use the DATAFACE_E_ERROR constant instead.","triggers, beforeSave, afterSave, beforeInsert, afterInsert,sending email",en,
Troubleshooting,49,Troubleshooting,"==Xataface Troubleshooting==

This document is intended to help Xataface developers through some of the most common issues.

[[toc]]

==All I get is a blank white screen!==

The most common issue mentioned in the forums is that an application comes up with a blank white screen in the web browser.  This can happen for a number of reasons but the most common reason is because PHP has encountered a fatal error and your PHP installation is not set up to display errors.  

The first step to troubleshooting this problem must be to find out what the error is.  You can do that in one of the following ways:

# Check your Apache error log if you know where it is.  One common location on many linux installations is <code>
/var/log/httpd/error_log
</code> but your system may have it located elsewhere.  If you cannot find your error log, continue to the next option.
# Turn on the ''display_errors'' flag in your ''php.ini'' file.  I.e., in your ''php.ini'' file, find where it says <code>
display_errors Off
</code> and change it to <code>
display_errors On
</code>.  After this is done, restart your apache webserver.  If you don't know where your ''php.ini'' file is located see the section later in this document on locating your ''php.ini'' file.  If you don't have access to your php.ini file, move on to the next option.
# In your application's ''.htaccess'' file, add the following directives to enable displaying errors:<code>
php_flag display_errors on
</code> .  Note that this method will only work if your apache config file allows you to override these values at the directory level.  If you still get a blank white screen after this, continue to the next option.
# At the beginning of your application's index.php file, add the following:<code>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
</code> .  Note that if the error occurs in the parsing or compiling of your PHP files you will still get a blank screen.  But this will at least display runtime errors on the page.

Once you can see the error messages that caused the blank white screen you are in a much better position to solve the problem.

==Locating your php.ini file==

Locating your ''php.ini'' file is actually quite easy.  The quickest way is to create a php script with the following contents:
<code>
<?php
phpinfo();
</code>
then navigate to this page in your web browser.  This look at the line where it says the ''php.ini file''.  It will list the path there.",,en,0
URL_Conventions,37,URL_Conventions,"==Xataface URL Conventions==

[[toc]]

Xataface adheres to a few simple URL conventions for all of its actions.  When you understand how Xataface URLs work you begin to get far more out of your applications.  By specifying the appropriate query parameters to can jump directly to any point in your application, or produce a specific result set.

For example, the URL ''index.php?-table=people'' will take you to the ''people'' table (and since the default action for a Xataface application is ''list'', it will take you to the ''list'' view.

You could be more explicit by specifying the action in the URL directly: ''index.php?-table=people&-action=list''.  This would take you to the same screen.  From this example, you see that you can specify such things as the table and action via GET parameters.  Xataface accepts many more GET parameters also, as you'll see in the next section.

===Available GET Parameters===


{| class=""listing listing2""
|-
! Name
! Description
! Default
! Version
|-
| -action
| Specifies the action to perform.  E.g. ''browse'', ''list'', ''find'', ''edit'', ''new'', ... etc..
| list
| all
|-
| -table
| The name of the table to use as the context table.
| The first table in the [_tables] section of your [[conf.ini file]]
| all
|-
| -skip
| Skip a certain number of results in the current found set to display.  E.g. If there are 100 records in the table and you want to start browsing from the 30th record, you would set ''-skip=29''.

Not to be confused with the ''-cursor'' parameter which is used to specify which record to view in the ''details'' tab.
| 0
| all
|-
| -limit
| The maximum number of records in the found set to display.
| 30
| all
|-
| -cursor
| The index of the record in the current found set that is treated as the ""current"" record.  This is used in the ''details'' tab to identify which record to act on.  E.g. which record to view or edit.
| 0
| all
|-
| -sort
| A comma-delimited list of columns to sort the result set on.
| null
| all
|-
| -relationship
| If we are browsing related records, this specifies the name of the relationship.
| null
| all
|-
| -related:start
| If we are browsing related records, this is the first record in the relationship to show.
| 0
| all
|-
| -related:limit
| If we are browsing related records, this is the number of records to show per page.
| 30
| all
|-
| -search
| A keyword search term to filter the found set on.  Any row containing any field that matches the query will be returned.
| null
| all
|-
| --no-query=1
| A flag to indicate that xataface should not query the database by default.  This flag is used in the new record form to prevent the form parameters from being interpreted as query parameters to search in the database.  If you set this flag, it likely result in a message saying ""No records found"".  Generally you would only use this in a custom action where you are not relying on Xataface's default found set.
| 0
| 1.3
|}

There are many other GET parameters that are used in various contexts but the above parameters are available throughout the entire application.

===Finding Records using the URL===

Notice that all of the GET parameters mentioned in the previous section begin with a hyphen (i.e. '-').  This is a convention Xataface uses to distinguish directives from search queries.  All parameters that do not begin with '-' are treated as a query to filter the found set.

For example, ''first_name=bob'' used as a GET parameter would cause the found set to be filtered so that only records where the ''first_name'' column contains the phrase ""bob"" are returned.  Putting this all together, suppose we wanted to show the list tab for the ''people'' table, but only wanted to show the people with first names containing ""bob"":

index.php?-action=list&-table=people&first_name=bob

====Exact, Range, and Pattern Matching====

By default, queries on text columns look for partial matches.  I.e. if you search for ""bob"" it will match ""bob"", ""bobby"", ""rubob"", and any other text that contains ""bob"".  If you are only interested in finding records that match ''exactly'' ""bob"", then you can prepend an ""="" to the query.  E.g. ''first_name==bob'', or the full URL:

index.php?-action=list&-table=people&first_name==bob

This should show the ''list'' tab for the ''people'' table with only records with first name exactly ""bob"".

There are a number of modifiers that you can prepend to your query to modify how it is executed.  They are as follows:

=====Search Operators=====

{| class=""listing listing2""
|-
! Prefix
! Usage Example
! Description
|- 
| >
| age=>10
| Match records greater than search parameter.
|-
| <
| age=<10
| Match records less than search parameter.
|-
| >=
| age=>=10
| Match records greater than or equal to the search parameter.
|-
| <=
| age=<=10
| Match records less than or equal to the search parameter.
|-
| ..
| age=10..20
| Match records in a given range.
|-
| =
| first_name==bob
| Match records that exactly match the search parameter (if there is no prefix then it will search for partial matches on text/varchar/char fields.).
|-
| ~
| first_name=~a%
| Exact match, but you can include wildcards such as '%' and '?' in your search.
|}


=====Search Examples=====

Given the following data set:

{| class=""listing listing2""
|-
! first_name
! age
|-
| Bob
| 10
|-
| Cindy
| 12
|-
| Julie
| 6
|-
| Jake
| 8
|-
| Kabob
| 16
|}

Here are some example queries on this data set and their results:

{| class=""listing listing2""
|-
! Query
! Matches
|- 
| age=>10 
| match records where ''age'' is greater than 10.  This includes ''Cindy'' and ''Kabob''.
|-
| age=<10 
| match records where ''age'' is less than 10.  This includes ''Julie'' and ''Jake''
|-
| age=>=10 
| match records where ''age'' is greater or equal to 10.  This includes ''Bob'', ''Cindy'', and ''Kabob''.
|-
| age=<=10
| match records where ''age'' is less than or equal to 10. This includes ''Bob'', ''Julie'', and ''Jake''.
|-
| age=8..10
| match records where ''age'' is between 8 and 10.  This includes ''Bob'' and ''Jake''.
|-
| first_name=bob
| Matches records where ''first_name'' contains ""bob"".  This includes ''Bob'' and ''Kabob''.
|-
| first_name==bob
| Matches records where ''first_name'' is exactly ""bob"".  This includes ''Bob'' only.
|-
| first_name=~J%
| Matches records that begin with ""J"".  This includes ''Jake'' and ''Julie''
|}

====Matching on Related Records====

It is also possible to match records based on their related data (i.e. data that is not physically stored in the record itself, but in related records via a relationship).  For example if we want to find authors who have written about a particular topic, we would normally have to first find all of the articles that contain a topic, and then cross-reference that result against the ''authors'' table.  With Xataface we can perform this query directly from the ''authors'' table using something like the following query:
 index.php?-table=authors&articles/title=sports
This assumes that the ''authors'' table has a relationship named ''articles'' that contains all of the articles that an author has written.  So the above query returns precisely those authors who have written at least one article whose ''title'' field contains the phrase ""sports"".


=====Anatomy of a Related Query=====

 %relationship%/%field%=%query%
This matches all records in the current table such that at least one record in its ''<relationship>'' relationship matches the query: ''%field%=%query%''.


====Using the ''OR'' Operator====

Xataface allows you to search for more than one value at a time using the ''OR'' operator.  E.g.
 first_name=bob+OR+steve
Would match all records with ''first_name'' containing ""bob"" or ""steve"".
 first_name=bob+OR+=steve
Would match all records with ''first_name'' containing ""bob"" or exactly matching ""steve""
 age=<10+OR+>20
Would match all records with age less than 10 or greater than 20.

====Combining Multiple Queries in One Request====

Xataface allows you to filter on more than one field at a time.  If you combine multiple queries in the same request it has the effect of strengthening the filter, matching only those rows that match ''both'' queries.  E.g.
 age=>10&first_name=bob
would match all records where ''age'' is greater than 10 '''AND''' that have ''first_name'' containing ""bob"".

=====Examples of Combined Queries=====

Given the same data set as the previous set of examples:

{| class=""listing listing2""
|-
! first_name
! age
|-
| Bob
| 10
|-
| Cindy
| 12
|-
| Julie
| 6
|-
| Jake
| 8
|-
| Kabob
| 16
|}

 first_name=bob&age=11
would return no matches because there are no records that contain both ''first_name'' ""bob"" and ''age'' 11.  However
 first_name=bob&age=10
would return only ''Bob'' and
 first_name=bob&age=16
would return only ''Kabob''.

====Special Common Queries====

=====Search For Null or Blank Value=====

Searching for a null value or a blank value is an exact match for """".  Therefore you can simply search for ""="".  E.g. To find records with a null or blank first_name you would use the query ''first_name==''.  Or the full query:
 index.php?-table=people&first_name==

=====Search for Non-blank Value=====

Searching for a non-blank value is the same as searching for a value greater than """".  Therefore you can simply search for "">"".  E.g. if you wanted to find records with a first_name, you would use the query ''first_name=>''.  Or the full query:
 index.php?-table=people&first_name=>

==Preserved vs Non-preserved Parameters==

As mentioned above any parameters that are prefixed by a hyphen (i.e. ""="") are treated as directives rather than search filters.  Hence if you want to use your own GET parameters you should always prefix them with a ""-"" to ensure that Xataface does not attempt to apply it as a search filter.  In order to keep a consistent context for users, all browsing within the same table preserves both search queries and directives.  Hence if you go to the URL:
 index.php?-table=people&-action=list&first_name=bob
It will show you the ''list'' tab of the ''people'' table with only those records with ''first_name'' ""bob"".  Now if you click on the ''details'' tab it will preserve your query ''first_name''.  The query will become something like:
 index.php?-table=people&-action=details&first_name=bob&...etc... more parameters
(Although the parameters may appear in a different order).  This allows you to navigate forward and back to previous and next records and stay within the same found set.  It also ensures that if you click on the ''list'' tab to return to the list view, it will retain your place in the list.

Note that navigating within the same table it will also preserve your directives.  E.g. If you specify the ''-limit'' directive to show 100 records per page:
 index.php?-table=people&-action=list&-limit=100
And then you click on the ''details'' tab, it will retain your ''-limit'' parameter.  Of course the ''-limit'' parameter is not actually used by the ''details'' action because it works on only one record at a time (it uses the ''-cursor'' parameter instead), when you click back on the ''list'' tab it will still show you 100 records per page.

Because of this, we call the ''-limit'' parameter a preserved parameter.  It is retained when navigating within the same table.  '''Note:''' parameters are retained in the HTTP Query string, not in sessions or cookies.  This ensures that there are no surprises when you enter a URL to your Xataface application.

===Unpreserved Parameters===

If you ''don't'' want Xataface to preserve one of your parameters, you should prefix two hyphens to the parameter name.  I.e. ""--"".  One example of an unpreserved parameters throughout Xataface applications is the ''--msg'' parameter.  The value of this parameter will be displayed on the page as an info message to the user.  Clearly you don't want this parameter preserved across requests, as you only want the user to see a message once.  E.g.
 index.php?--msg=Record+Successfully+saved.
Would didsplay the mesage ""Record Successfully Saved"" at the top of the page.  If you click on any link in the application, it will not retain the ''--msg'' parameter so you will not see the message on subsequent requests.

This parameter is useful if you want to give feedback to the user about an action that has been carried out.

===Summary===

{| class=""listing listing2""
|-
! Parameter Type
! Prefix
! Examples
! Description
|-
| Preserved
| -
| -limit, -skip, -cursor, -action, -table
| Parameter value is preserved when user navigates away from the page (within the same table).
|-
| Unpreserved Parameters
| --
| --msg
| Parameter is ''NOT'' retrained with the user navigates away from the page.
|}





","URL Conventions, GET Parameters, POST parameters, Request Parameters",en,0
Using_RecordGrid,115,"Using RecordGrid","==Xataface RecordGrid Class and Template==

Also see [http://lamp.weblite.ca/dataface-0.6/docs/index.php?-table=Classes&-action=browse&ClassID=30| RecordGrid in the API Doc].


[[toc collapse=0]]

===Introduction===
As we learned in '''[http://xataface.com/documentation/tutorial/getting_started/dataface_actions Actions I: The Basics]''', we can retrieve custom data from the DB in action via queries. This site deals with showing data in tabular form, like it could be received from even such a query. It is done by using Dataface_RecordGrid.


===First Example===
<code>
class actions_testTableAction {

	// Will be called from Xataface, if this action is called
	function handle(&$params){
		$this->app =& Dataface_Application::getInstance();  // reference to Dataface_Application object

		// Custom query
		$result = mysql_query(""select * from testTable"", $this->app->db());
		$body = ""<br /><br />"";
		
		if(!$result)
		{
			// Error handling
			$body .= ""MySQL Error ..."";
		}else
		{
			while($row = mysql_fetch_assoc($result))	// Fetch all rows
			{
				// Maybe do something with the single rows
				$data[] = $row;	// Add singe row to the data
			}
			mysql_free_result($result); // Frees the result after finnished using it

			$grid = new Dataface_RecordGrid($data);	// Create new RecordGrid with the data
			
			$body .= $grid->toHTML();	// Get the HTML of the RecordGrid
		}

		// Shows the content (RecordGrid or error message) in the Main Template
		df_display(array('body' => $body), 'Dataface_Main_Template.html');
	}
}
</code>

You get your data from the query, fetch it into an associative array, create with it an RecordGrid and use the toHTML function. This is sure better than manually create the html tags around the data.

=====Screenshot: Blank RecordGrid=====
<nowiki>
<img src=""http://i89.photobucket.com/albums/k234/horchr/xataface/RecordGrid_blank.png?max_width=610""/>
</nowiki>

=====Screenshot: ResultList=====

<nowiki>
<img src=""http://i89.photobucket.com/albums/k234/horchr/xataface/RecordList.png?max_width=713""/>
</nowiki>


===Colored Example===

As you see above, the resultlist has colored rows, our First Example not. But you can easily change this, when you override the Dataface_RecordGrid.html template:

<code>
<table id=""{$id}"" class=""listing {$class}"">
	<thead>
		<tr>
		{foreach from=$labels item=label}
		<th>{$label}</th>
		{/foreach}
		</tr>
	</thead>
	<tbody>
		{section name=row loop=$data}
		<tr class=""listing {cycle values=""odd,even""}"">
			{foreach from=$columns item=col}
			<td>{$data[row][$col]}</td>
			{/foreach}
		</tr>
		{/section}
	</tbody>
</table>
</code>

The magic happens in <tr class=""listing {cycle values=""odd,even""}"">
The {cycle values=""odd,even""} value cycles these two values and creates so the alternating row classes, like they are in the RecordList. By the way, {cycle ...} is a Smarty Function, see [http://www.smarty.net/docsv2/en/language.custom.functions.tpl| Smarty Doc].

(Find fruther information to template overriding in the tutorial and its links: [http://xataface.com/documentation/tutorial/getting_started/changing-look-and-feel| Changing the Look and Feel])

=====Screenshot: colored RecordGrid=====

<nowiki>
<img src=""http://i89.photobucket.com/albums/k234/horchr/xataface/RecordGrid_colored.png?max_width=610""/>
</nowiki>


===Example completly imitating ResultList===

The Colored Example doesn't look like the ResulList? Its rows aren't as high as theres? That's a styling matter or rather in this case a cause of the checkboxes. Here an example with checkboxes and added (empty) links, so it looks completly like the ResultList:

Change the part in action.php
<code>
			while($row = mysql_fetch_assoc($result))	// Fetch all rows
			{
				// Maybe do something with the single rows
				$row['<input type=""checkbox"">'] = '<input type=""checkbox"">';
				$data[] = $row;	// Add singe row to the data
			}
			mysql_free_result($result); // Frees the result after finnished using it

			$grid = new Dataface_RecordGrid($data,	// Create new RecordGrid with the data
				  array('<input type=""checkbox"">', 'testID', 'name', 'description', 'number'),	
				//Order and selection of the colums
				  null);	// No other labels defined -> it uses keys of the associative array
			
			$body .= $grid->toHTML();	// Get the HTML of the RecordGrid
</code>

Dataface_RecordGrid.html template
<code>
<table id=""{$id}"" class=""listing {$class}"">
	<thead>
		<tr>
		{foreach from=$labels item=label}
		<th><a class=""unmarked_link"">{$label}</a></th>
		{/foreach}
		</tr>
	</thead>
	<tbody>
		{section name=row loop=$data}
		<tr class=""listing {cycle values=""odd,even""}"">
			{foreach from=$columns item=col}
			<td><a class=""unmarked_link"">{$data[row][$col]}</a></td>
			{/foreach}
		</tr>
		{/section}
	</tbody>
</table>
</code>

=====Screenshot: RecordGrid completly imitating ResultList=====

<nowiki>
<img src=""http://i89.photobucket.com/albums/k234/horchr/xataface/RecordGrid_colored_checkboxes_links.png?max_width=610""/>
</nowiki>

=====Screenshot: ResultList=====

<nowiki>
<img src=""http://i89.photobucket.com/albums/k234/horchr/xataface/RecordList.png?max_width=713""/>
</nowiki>

===Try it out===

Use the following code with static test data and any template in this article (or even without overriding it) to try it out.

<code>
class actions_testTableAction {

	// Will be called from Xataface, if this action is called
	function handle(&$params){
		$this->app =& Dataface_Application::getInstance();  // reference to Dataface_Application object

		$result_dummy = array(
			array('testID' => '1', 'name' => 'testname', 
				'description' => 'a short description', 'number' => '258'),
			array('testID' => '2', 'name' => 'another name', 
				'description' => 'a bit longer description to this data set', 'number' => '946'),
			array('testID' => '3', 'name' => 'dummy name', 
				'description' => 'yea, a dummy data set!', 'number' => '1342'),
			array('testID' => '4', 'name' => 'not empty', 
				'description' => 'this data set isn\'t empty ...', 'number' => '282'),
			array('testID' => '5', 'name' => 'your entry', 
				'description' => 'this entry is only for you', 'number' => '79'),
			array('testID' => '6', 'name' => 'no idea', 
				'description' => 'running out of ideas ...', 'number' => '203'),
			array('testID' => '7', 'name' => 'the last one', 
				'description' => 'the end', 'number' => '26841')
		);
		$body = ""<br /><br />"";
		
		foreach($result_dummy as $row)	// Fetch all rows
		{
			// Maybe do something with the singe rows
			$row['<input type=""checkbox"">'] = '<input type=""checkbox"">';
			$data[] = $row;	// Add singe row to the data
		}

		$grid = new Dataface_RecordGrid($data,	// Create new RecordGrid with the data
			array('<input type=""checkbox"">', 'testID', 'name', 'description', 'number'),	
			//Order and selection of the colums
			  null);	// No other labels defined -> it uses keys of the associative array

		$body .= $grid->toHTML();	// Get the HTML of the RecordGrid

		// Shows the content (RecordGrid or error message) in the Main Template
		df_display(array('body' => $body), 'Dataface_Main_Template.html');
	}
}
</code>
","RecordGrid, Dataface_RecordGrid, data in tabular form",en,
GettingStarted:valuelists,77,"Using Valuelists","==Using Value-lists==

Value-lists serve as vocabularies that can be used for fields such as select lists, checkbox groups, and auto-complete fields.

So far we have not used any enumerated fields such as select lists, checkbox groups, or auto-completion fields in our examples. This is because we are missing a key ingredient that is required by all of these widget types: a vocabulary. We need a way to define options for these fields.

This is where 'valuelists' come into play. A valuelists is essentially a list of key-value pairs that can be used as a vocabulary in enumerated fields like checkbox groups, select lists, and auto-completion fields. Valuelists are defined in the valuelists.ini file in each table's configuration directory.

===Example 1: Use a select list for the Subject field in the Course table===

The ""Subject"" field in the ""Course"" table really shouldn't be a free-form field that will accept any value. The user should just be able to pick from a finite list of subjects in a select list. To make these changes we will follow these steps:

# Create the configuration directory for the ""Course"" table if it does not exist yet.
# Create a file named 'fields.ini' inside the Course table's configuration directory (i.e., tables/Course/fields.ini), if it does not already exist.
# Create a file named 'valuelists.ini' inside the Course table's configuration directory (i.e., tables/Course/valuelists.ini) if it does not already exist.
Your application directory structure should now look like:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/application-structure-valuelists.gif]]
# Edit the valuelists.ini file so that it looks like:<code>
[Subjects]
	ENGL = English
	MATH = Math
	PHYS = Physics
	CHEM = Chemistry
</code> This defines a valuelist named 'Subjects' with values {ENGL, MATH, PHYS, CHEM} and associated labels {English, Math, Physics, Chemistry}. The values (i.e., ENGL, MATH, etc..) represent what will be stored in the database, and the values is a user-friendly representation that will be displayed on the screen.
# Now we edit the fields.ini file so that it looks like:<code>
[Subject]
	widget:type = select
	vocabulary = Subjects
</code> This tells Xataface that we want to use a select widget to edit the ""Subject"" field, and its values should be drawn from the ""Subjects"" valuelist.
#Navigate to the ""Course"" table in our application and select ""new record"" from the ""Actions to be performed menu"" in the top left.<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/actions-menu-1.gif]]<nowiki><br/><br/></nowiki>This will bring up a form to create a new Course record, so that we can see what the form looks like. It should look like:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/new-course-form-1.gif]]<nowiki><br/></nowiki>Notice that the ""Subject"" field is represented by a select widget, its options are as follows:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/course-subject-pulldown-1.gif]]<nowiki><br/></nowiki> And if you look at the HTML source code for this select list, it would look like:<code>
<select class=""default"" id=""Subject"" name=""Subject"">
	<option value="""">Please Select...</option>
	<option value=""ENGL"">English</option>
	<option value=""MATH"">Math</option>
	<option value=""PHYS"">Physics</option>
	<option value=""CHEM"">Chemistry</option>
</select>
</code>

===Example 2: Using a checkbox group for the 'Subject' field===

In Example 1, we showed how to use a select list for the 'Subject' field in the 'Course' table. This is great if each course can only be one subject. But what if a course can be categorized in 2 subject areas. Then we will need a widget the allows you to select multiple items. Checkbox groups work well for this.
Make a change to the 'fields.ini' file for the 'Course' table to change the widget:type attribute of the 'Subject' field to 'checkbox' as follows:<code>
[Subject]
widget:type = checkbox
vocabulary = Subjects
</code>

Now load the form again and notice that the 'Subject' field is now represented by checkboxes.

[[Image:http://xataface.com/documentation/tutorial/getting_started/checkbox-group-1.gif]]

You may be wondering how we store multiple values in a single field. In this case Subject is treated as a 'repeat' field where each value is on a separate line. I.e., with the form above, if we clicked 'save' and checked the values stored in the database we would see:<code>
PHYS
CHEM
</code>

As the value in the 'Subject' field. Please note that if you are going to use a repeating field like this, you should make sure that the field is 'big' enough to store all of the values. E.g., I think my Subject field was a VARCHAR(64) (64 characters long), so the sum of the lengths of all of the values 'checked' for 'Subject' should be less than 64.

===Example 3: Dynamic Valuelists based on the results of SQL queries===

Example 1 & 2 demonstrated the basic idea of valuelists and how they can be used as values for select lists and checkbox groups. However defining valuelists ""statically"" inside the valuelists.ini file doesn't really seem to offer anything over using and ENUM or SET field in the MySQL database. In many cases we want the user to be able to choose from a number of options that are pulled from the database. For example, we may want the user to be able to specify the Program that a Course belongs to, using a pull-down list.

Recall that when we created the 'Course' table we included a field named 'ProgramID' to store the ID number of the Program that this course belongs to. It would be unreasonable to expect the users of your application to remember the ID number of the Program to which the course belongs when they are filling in the 'Course' form. It would be much better if the user could choose the program from a list of available programs. Fortunately, this functionality is simple to add:

# Add a valuelist named 'Programs' to the valuelists.ini file for the 'Course' table as follows:<code>
[Programs]
	__sql__ = ""SELECT ProgramID, ProgramName FROM Program ORDER BY ProgramName""
</code> '''Note: Make sure you use two underscores on either side of 'sql' in the above example. It should be '__sql__' not '_sql_'.'''<nowiki><p></nowiki>This valuelist will be a list of the records in the 'Program' table in alphabetical order on the program name. Note that this query selects 2 columns. The first column is always taken to be the ID column of the value-list and the 2nd column (if specified) is the Name column of the valuelist. The ID column is what will actually be stored in the database, and the Name column is what will be shown to the user in place of the ID.<nowiki></p></nowiki>
# Add a field definition for the ProgramID field in the fields.ini file of the 'Course' table as follows:<code>
[ProgramID]
	widget:type = select
	vocabulary = Programs
</code>

Now we can load up our form and see what it looks like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/programid-select-list.gif]]

We can see that the ProgramID field now appears with a select list of all of the programs in the database. The HTML code for the select list is:<code>
<select class=""default"" id=""ProgramID"" name=""ProgramID"">
	<option value="""">Please Select...</option>
	<option value=""2"">Advanced Widgetry</option>
	<option value=""1"">Basic Widgetry</option>
	<option value=""3"">International Widgetry</option>
</select></code>

===Download Source Files===

[http://xataface.com/documentation/tutorial/getting_started/facultyofwidgetry-7-tar.gz Download application source files as tar.gz archive]

These source files reflect the application's state at this point in the tutorial. As changes are made to the application in later sections, modified source archives will be available to be downloaded.

===Summary===

In this section, we have learned how to use valuelists to add selection lists and checkbox groups to our web forms. We also shows how valuelists can be dynamically defined using SQL. Using valuelists in this way is like defining a many-to-one relationship to our database (in example 3, it was many 'Course' records to one 'Program' record). In the next section we will learn how to add many-to-many and one-to-many relationships to our database in such a way that records can be easily added and removed from relationships using Xataface.","valuelists, __sql__, select lists, checkbox options,checkbox groups,vocabularies",en,
GettingStarted:using_first_app,75,"Using Your First Application","==Using Your First Application==

A Web Lite application, at its core, provides 4 standard operations: Add new records, edit existing records, delete records, and find records. This section gives a brief overview of how to use your first Dataface application.
When you first create your Xataface application and there are no records in the database, the application will look quite plain. If you point your web browser to your newly created application it will look something like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/basic-application-1.gif]]

You may be wondering why it says ""No records matched your request"" when you haven't even really made a request. This is because the 'default' request that is performed if no other request is specified is to show the first record from the first table in the navigation menu. Since there are no records, it is true that there are NO records matching the default request.
So what can you do with this application anyways? Essentially there are 4 operations you will want to perform:

# Create new records
# Edit Existing records
# Find records
# Delete records

==Basic Navigation==

The navigation tabs (aka Navigation menu) at the top left represent the tables in your database. You can navigate to any of the tables in this list by clicking on that table:

[[Image:http://xataface.com/documentation/tutorial/getting_started/navmenu-1.gif]]

There are 3 ""views"" associated with tables in the database:

* '''Details''' - Shows the details of a single record in the table
* '''List''' - Shows the records in the current ""found set"" as a list. (in a table).
* '''Find''' - Allows users to find records matching certain criteria.

You can toggle between these 3 views using the tabs at the top of the page:

[[Image:http://xataface.com/documentation/tutorial/getting_started/basic-tabs-1.gif]]

===The ""Found Set""===

Throughout this tutorial you will see the phrase ""found set"" an awful lot, so it is important to understand just what this means. A ""found set"" is the set of all records in the current table that match the current ""find criteria"". This begs the question, ""what is 'find criteria'?"". By default there is no find criteria. When you perform a search or a find on the current table, you add ""find criteria"" so that only the records satisfying these criteria will be included in the ""found set"".

For example, if you click on the ""find"" tab, you will get a search form that allows you to search for records that match certain criteria. The ""find"" tab for the ""Course"" table in our application looks like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/find-form-1.gif]]

If you type in ""English"" in the ""Subject"" field and click ""Find"", then the ""found set"" will consist of only records that contain the word ""English"" in their subject fields.

On the top left of the application window there will always be a ""Found"" line that indicates how many records are currently in the found set. e.g., 

This indicates that there are 256 records in the current table (which is the 'Groups' table). There are currently only 225 records in the current ""found set"" (meaning that we have performed a ""find"" operation and it matched 225 of the records). It also indicates that the currently displayed record is record number 1 out of the 225 found records.

===The Actions Menu===

Just below the view tabs ('details', 'list', and 'find') there are a few buttons that allow you to perform actions such as create new records, clear find parameters (i.e. Show All), and delete records.

[[Image:http://xataface.com/documentation/tutorial/getting_started/actions-menu-1.gif]]

'''Descriptions:'''

* '''new record''' - Creates a new record in the current table.
* '''show all''' - Clears all find criteria on current table so that all records are shown.
* '''delete''' - Deletes the current record in the table.
* '''delete found records''' - Deletes all records in the current ""found set"". If no find criteria is specified this will delete all records in the table. 

===Creating new records===

The basic FacultyOfWidgetry application that we created in the previous section isn't very interesting when it doesn't contain any records, so let's create some Program records.

# Select the ""Program"" table by clicking on the ""Program"" option of the navigation menu.
# Click ""new record"" in the actions menu (top left).
# This will bring up a form to insert a new record that looks like: <nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/new-record-1.gif]]
# Fill in the form and click ""Save"". If everything went OK, you will see the same form again, but with a ""success"" message at the top of the page: <nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/successfully-saved-1.gif]]

===Editing an existing record===

The ""details"" view allows you to view details or edit the current record. There should be at least 2 sub-tabs: 'View' and 'Edit'. If you click on the 'Edit' tab, you will be presented with a form to edit the record. The form is identical to the ""create new record"" form.

===Deleting records===

If the 'list' tab is selected, then you will see a button called 'delete found records' in the actions menu (just below the view tabs). Alternatively if the 'details' tab is selected, you will see a button called simply 'delete'. 

[[Image:http://xataface.com/documentation/tutorial/getting_started/actions-menu-1.gif]]

Select ""delete"" to delete only the current record you are viewing in the ""details"" view.

Select ""delete found records"" to delete all of the records in the current found set. 

In either case, you will be prompted to confirm your decision before the records are actually deleted.

===Interface Overview===

Xataface applications provide an intuitive and consistent interface throughout. The following screenshot contains a map of some comment interface components along with some explanations:

[[Image:http://xataface.com/documentation/tutorial/getting_started/interface-schematic.png]]


Other topics
This short section is only intended to get you acquainted with the basics of Xataface applications. As your application becomes more complex with relationships and value-lists, there will be other usage scenarios of interest.","""find form"",""edit form"",""delete record"",""user interface"",ui,template,look and feel",en,
validateRegistrationForm,15,validateRegistrationForm,"==validateRegistrationForm() hook==

A hook that validates the input into the user registration form to make sure that the input is valid.

===Signature===

function validateRegistrationForm( array $values ) : mixed

====Parameters====

{| class=""listing listing2""
! Name
! Description
|-
| $values
| An associative array of the input values of the registration form.
|-
| returns
| Mixed. If this method returns a PEAR_Error object then the validation will fail - and the user will be asked to correct his input.
|}

===Example===

<code>
<?php
class conf_ApplicationDelegate {
    function validateRegistrationForm($values){
        if ( $values['age'] < 18 ){
            return PEAR::raiseError(""Sorry you must be at least 18 years old to join this site."");
        }
        return true;
    }
}
</code>

===Validation via the Users table Delegate class===

Note that since the registration form is just a ""new record form"" for the users table, it is also possible (and preferred) to do validation through the users [[table delegate class]].

===See Also===

* [[afterRegister]]
* [[beforeRegister]]
* [[sendRegistrationActivationEmail]]
* [[getRegistrationActivationEmailInfo]]
* [[getRegistrationActivationEmailSubject]]
* [[getRegistrationActivationEmailMessage]]
* [[getRegistrationActivationEmailParameters]]
* [[getRegistrationActivationEmailHeaders]]",,en,0
validators,95,"validators:NAME fields.ini directive","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

In the fields.ini file you can specify validation rules to be applied to any field by adding the validators:NAME directive in that field's section of the [[fields.ini file]].

===Available Validators===

{| class=""listing listing2""
|-
! Name
! Description
! Value
! Version
|-
| required
| Field is required
| 1
| All
|-
| maxlength
| Maximum number of characters allowed.
| $length
| All
|-
| minlength
| Minimum number of characters allowed.
| $length
| All
|-
| rangelength
| Range (min and max) characters allows
| $min,$max
| All
|-
| email
| Input must be syntactically correct email address.
| 1
| All
|-
| emailorblank
| Accepts an email address or a blank field.
| 1
| All
|-
| regex
| Input must match the provided regular expression.
| A regular expression
| All
|-
| lettersonly
| Input must contain only letters (i.e. [a-zA-Z]
| 1
| All
|-
| numeric
| The input must contain a valid positive or negative integer or decimal number.
| 1
| All
|-
| nopunctuation
| The input must not contain any of these characters: <nowiki>( ) . / * ^ ? # ! @ $ % + = , "" ' &gt; &lt; ~ [ ] { }.</nowiki>
| 1
| All
|-
| nonzero
| The input must not begin with zero.
| 1
| All
|-
| uploadedfile
| The element must contain a successfully uploaded file.
| 1
| All
|-
| maxfilesize
| The uploaded file must be no more than $size bytes.
| $size
| All
|-
|filename
| The uploaded file must have a filename that matches the regular expression $file_rx.
| $file_rx
| All
|}


===Examples===

To make a the first_name field required we add the following to the [[fields.ini file]]:
<code>
[first_name]
    validators:required=1
</code>

'''Note that fields that are declared NOT NULL in the database are required by default.'''.  If you wanted to remove the ''required'' validator from a field that is NOT NULL in the database you would add the following to the [[fields.ini file]]:
<code>
[first_name]
    validators:required=0
</code>

===See Also===

* [[fieldname__validate]] - For more complex validation you can define the [[fieldname__validate]] method in the [[Delegate class methods|Table Delegate Class]].
* [http://www.devarticles.com/c/a/Web-Graphic-Design/Using-HTML-Quickform-for-Form-Processing/12/ HTML_QuickForm article] going over HTML_Quickform validation.  Dataface's forms are built on HTML_QuickForm.
* [http://xataface.com/documentation/tutorial/getting_started/validation Form Validation] - Section from getting started tutorial introducing form validation in a tutorial format.

","validation, form validation, validators,validator:name",en,
validators:VALIDATOR_NAME:message,96,"validators:VALIDATOR_NAME:message directive for the fields.ini file","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

If you want to customize the error message associated with a particular [[validator|validation rule]] you can use the validators:VALIDATOR_NAME:message directive in the fields.ini file.

===Format===

<code>
[myfield]
    validators:VALIDATOR_NAME:message = MESSAGE
</code>

===Examples===

If you don't like the default error message that is displayed when you make the first_name field required, you can customize it with your own message.  E.g.
<code>
[first_name]
    validators:required=1
    validators:required:message = ""Please enter your first name""
</code>

===See Also===

* [[validators]] - The [[fields.ini file]] directive for adding a validation rule to a field.  This directive must be used in conjunction with [[validators]].
* [[fieldname__validate]] - For more complex validation rules you can define them in the table delegate class.
* [http://xataface.com/documentation/tutorial/getting_started/validation Form Validation] - Section in the Getting Started tutorial on form validation.","validation messages,error messages,form validation rules",en,
valuelists.ini_file,5,valuelists.ini_file,"==valuelists.ini file Reference==

[[toc]]

The valuelists.ini file stores value lists that can be used as [[vocabulary|vocabularies]] for select lists, checkbox groups, and other widgets the provide the user with options to choose from.

Each table can have an associated valuelists.ini file located in its [[table configuration directory]]. E.g. for a table named ""people"" its valuelists.ini file will be stored in ""tables/people/valuelists.ini"".

In addition you can define an application-wide valuelists.ini file in the root of your application's directory, whose valuelists can be used by any table.

===Syntax===

The valuelists.ini file uses [[INI file syntax]], where a valuelist is defined by a single section of the INI file.  E.g.

<code>
[colors]
    r=Red
    b=Blue
    g=Green
</code>

This example would define a single valuelist named ""colors"" with 3 values: r,g, and b (with corresponding labels ""Red"", ""Green"", and ""Blue).  The values (the left of the equals sign) are stored in the database, while the labels are rendered on screen for the user's convenience.

===Dynamic Valuelists===

It is often advantageous to load valuelists from the database rather than store them directly in the valuelists.ini file.  The __sql__ directive allows you to specify an SQL query which selects up to 2 columns (the first is the id and the second, the label).

E.g.

<code>
[colors]
    __sql__ = ""select colorCode, colorName from colors""
</code>


===Defining Valuelists in a Delegate Class===

If you require more flexibility with the definition of your valuelists than can be gained from the valuelists.ini file, you can define your valuelist using PHP inside a delegate class.  Essentially you just create a method that returns an associative array, where the keys are the IDs that are stored in the database, and the values are the values that are visible in the select list.

e.g.  In either the application delegate class or a table delegate class:

<code>
function valuelist__colors(){
    return array(
        'r'=>'Red',
        'g'=>'Green',
        'b'=>'Blue'
    );
}
</code>

This method is called each time the valuelist is about to be used, so if your method performs any sort of intensive processing, it is a good idea to use a caching scheme so that it only runs the critical code once per request.  For example, you could use a static variable as follows:

<code>
function valuelist__colors(){
    static $colors = -1;
    if ( !is_array($colors) ){
        $colors = array();
        $res = mysql_query(""select colorCode, colorName from colors"", df_db());
        if ( !$res ) throw new Exception(mysql_error(df_db()));
        while ($row = mysql_fetch_row($res) ) $colors[$row[0]] = $row[1];
    }
    return $colors;
}
</code>

In this example the database query is only executed once per request to load the $colors variable.  The rest of the time it simply loads the cached value from $colors.","valuelists, dynamic valuelists, programmatically defined valuelists",en,0
visibility:fieldName,47,visibility:fieldName,"==Example==

<code>visibility:ConferenceID = hidden</code>

This will make the ConferenceID in the relationship list view disappear.",,en,0
GettingStarted:Why_Use_Xataface,72,"Why Use Xataface","==Why Use Xataface?==

Some simple examples similar to those that are frequently encountered by web developers, and how dataface can be used to acheive a solution.
As a web services developer in the Faculty of Applied Sciences at Simon Fraser University, I am frequently getting requests to build websites that are manageable by the site owner. Most of these requests also specify certain types of content that must be stored on the website, and much of this content needs to be n-ary (i.e., there will be multiple instances of each type of content). Let me give you an example.

===Example 1: Website for Faculty of Widgetry===

The Faculty of Widgetry needs a website to publish information about its undergraduate programs. It is important for them to be able to publish admission requirements, and program overviews for each program. It is also important to have course outlines and timetables for each course. The Faculty of Widgetry has 12 undergraduate programs and over 100 courses offered.

====Solution 1: Static HTML====

To build this web site using only static HTML pages using Dreamweaver or some other HTML editor would require at least 112 pages to be created (one for each course and program). However, once we recognize that there are only 2 types of pages required (one for courses and one for programs), we can reduce the task down to creating 2 templates and filling in the main content for each program and course individually. Most HTML editors have some templating ability so you can make changes to the template and have the changes propogated to all pages that use that template with the click of a button.

This works great, but courses are added frequently, and outlines are changed. Do you really want to receive requests to update all of these pages every time there are changes to make? (If your answer is 'yes', then you probably won't be interested in reading the rest of this tutorial). Whether the Dean of the faculty knows it or not, it is very important for the program assistants to be able to update these web pages on their own. To acheive these goals you can:

* Install Dreamweaver on the Program Assistants' computers, teach them how to use it, and allow them to perform updates.
* Install Contribute, which is a scaled down version of Dreamweaver to make it easier for the Program Assistants to edit the content.
* Use another solution that is equivalent to one of the above 2 solutions.

Installing Dreamweaver for each Program Assistant is a little overkill, and since it has the ability to do much more than just update content. In addition, Dreamweaver is really a developer's tool - not a secretary's tool, so it can be difficult to learn at first. The best reason NOT to install Dreamweaver on the Program Assistant's computer, however, is that it enables him/her to muck things up by accident (believe me, I has happened to me more times than I care to count).

Admittedly, Contribute is a viable option as it controls access to only certain portions of web pages to be edited, and it is targetted at secretaries (not developers) so it is easier to use. In fact, given the requirements for this web site (as stated above), this is a perfectly good solution. However you better hope that none of the following requirements are added:

* Each program web page should contain an up-to-date list of all of the courses required for the program, along with a link to the course outline for that course.
* Course outlines should be available in PDF format as well as HTML format.
* An index page showing all of the courses available should be added. This page must allow courses to be organized by program, course subject, or course number.
* Any other requirement that would have information formatted in more than one way.

If any of these requirements are likely to be added (EVER) then you would be well-advised to look into solutions that use a database back-end.

====Solution 2: Use a Content Management System (CMS)====

There are hundreds of content management systems available that will allow you to store and update content through the web (TTW). Some of them even have an assortment of add-ons that will allow you to store more specific types of information. Some good CMS's include Plone, Drupal, and Xoops. Suppose we want to develop the Faculty of Widgetry website using one of these CMS's. Any good CMS will allow you to create and edit HTML documents easily (without having to write any custom products). However, it is often the case that our documents require the content to be structured. For example, each program has some common data associated with it: Program Name, Admission Deadline, Program Description, Outline, Courses, etc... If we want to properly separate data from presentation, we would need to build a special content-type to store our programs. Most CMS's allow you to develop custom content-types using the underlying programming language and an API (Application Programming Interface). Some API's are easier to use than others and some are documented better than others. The common element is that each has its own proprietary interface for writing these add-ons.

If you are using a CMS and you are proficient in the creation of add-on content-types, then you will be able to build the Faculty of Widgetry website without great difficulty. However there are a number of reasons why you may choose NOT to use a CMS:

* Steep learning curve: Depending on the CMS it can be very time consuming and difficult to learn how to use and modify the CMS to suit you purposes.
* It is over-kill: Most CMS's are filled with features and modules that you will never need. In fact it can even be a pain to turn them off if you don't want them.
* You can get tied into the CMS: When you are using a CMS, you will start developing for the CMS. With all of your content in the CMS it may be difficult to migrate to a different solution later on. (The truth of this statement will vary for different CMS's). Choose your CMS carefully.

====Solution 3: Use an existing Application====

OK, OK, let's not get too carried away with trying to develop the website until we have checked the market to see if someone else has already done it better. Maybe there is already a PHP application that makes websites for Faculties easy. I mean, I can't be the first person that needed to build a website for a Faculty. In fact if you do a search or go to Hotscripts.com, you will probably find a handful of applications or scripts that almost do what you need. If you're lucky, maybe you can find an application that does exactly what you need (but frankly, I've never been that lucky). If you find one, maybe it's worth taking it for a test drive. But beware. Using a system that almost does what you need but is difficult to modify to your needs can be worse than building it by scratch. Make sure that you are able to modify the application to suit your needs exactly.

====Solution 4: Use PHP and MySQL====

If all we want to do is separate the data from the presentation and allow the Program Assistants to update data on the website, why not just design a MySQL database with the appropriate tables and fields to store the required data. In our case we will need 2 tables:

'''Programs''': 

* Fields:
** ProgramID : int
** ProgramName : varchar
** ProgramDescription: text
** AdmissionDeadline: date
** Outline_HTML : text
** Outline_PDF : blob


'''Courses''':
* Fields:
** CourseID : int
** CourseSubject : varchar
** CourseTitle : varchar
** CourseNumber : int
** ProgramID : int
** CourseDescription : text
** Outline_HTML : text
** Outline_PDF : blob


Now it's easy to create a few web pages that extract data from the database and displays it as HTML. In fact if there is an existing page template that you can use for the header and footer, you can develop the entire Faculty website in under an hour (you just have to create 3 pages).

'''Question''': How will the Program Assistants update the information in the database?

'''Answer''': OK, let's assume that you're not going to teach them SQL and that a DB Admin tool will also be too difficult to learn. Then you have to create HTML forms to update records in the database.

Ouch! What was easy just became hard. Making HTML forms is a real pain, because you have to validate the input, deal with file uploads, and also make sure that everything is stored to the database OK without losing any information. Such a basic task, but it can be very difficult. This is when it is time to use Xataface.

====Solution 5: Use Xataface====

OK, this isn't really its own solution. It is more like ""Solution 4 Part II"", because Xataface is intended to complement your custom application you built with solution 4, by providing an easy-to-use, configurable user interface that is targeted at secretaries and normal users (as opposed to database administrators). A Xataface application takes only seconds to set up and it will provide you with a full user interface for your users to edit information in the database.","introduction motivation why",en,
widget:atts,46,widget:atts,"==widget:atts Directive Reference==

The widget:atts directive in the fields.ini file allows any arbitrary HTML attributes to be added to any of the fields.  It may also be used to specify javascript event handler functions that the widget should call upon the specified event.  In particular, here are some examples of possible widget:atts directives:

===Available Widget Event Handlers===

{| class=""listing listing2""
|-
! name
! description
! version
|-
| [[field_size|widget:atts:size]]
| This directive sets the length of the input area a text box field, but it does not limit the number of characters that can be entered.  For example: <nowiki><br/>widget:atts:size = 50</nowiki>
| ?
|-
| [[field_maxlength|widget:atts:maxlength]]
| This directive limits the maximum number of characters that can be entered into a text box field.  For example: <nowiki><br/>widget:atts:maxlength = 25</nowiki>
| ?
|-
| [[field_style|widget:atts:style]]
| This directive specifies the style (font-size, font-family, etc.) for the field.  For example: <nowiki><br/>widget:atts:style = ""font-size: 24pt; font-family: Apple Chancery""</nowiki>
| ?
|-
| [[field_rows|widget:atts:rows]]
| This directive specifies the number of rows for a text area field to display.  For example: <nowiki><br/>widget:atts:rows = 10</nowiki>
| ?
|-
| [[field_cols|widget:atts:cols]]
| This directive specifies the number of columns for a text area input field (1 character = 1 column).  For example: <nowiki><br/>widget:atts:cols = 10</nowiki>
| ?
|-
| [[field_javascript_onchange|widget:atts:onchange]]
| This directive will cause the specified javascript function to be called with the value of the field whenever its value is changed (i.e. when you change the field and tab out of it).  For example: <nowiki><br/>widget:atts:onchange = ""doJsFunction();""</nowiki>
| ?
|-
| [[field_javascript_onclick|widget:atts:onclick]]
| This directive will cause the specified javascript function to be called with the value of the field whenever it is clicked.  For example: <nowiki><br/>widget:atts:onclick = ""doJsFunction();""</nowiki>
| ?
|}

===Helpful tutorials===

See the bottom of this page in the Getting Started tutorial for more details on the basic directives above:

[http://xataface.com/documentation/tutorial/getting_started/customizing Customizing Field labels, descriptions, and widgets]

This tutorial talks about how to use the javascript directives:

[http://xataface.com/documentation/how-to/custom_javascripts]",,en,0
widget:editor,35,widget:editor,"==widget:editor fields.ini directive==

Return to [[fields.ini file]]

[[toc]]

The widget:editor directive is applicable in the [[fields.ini file]].  It specifies the type of HTML editor that should be used.  This directive is only used when [[widget:type]] is set to [[widget:type htmlarea|htmlarea]].  Xataface currently supports FCKEditor, TinyMCE, and NicEdit.

===Allowed Values===

{| class=""listing listing2""
|-
! Value
! Description
! Version
|-
| fckeditor
| Use [http://www.fckeditor.net/ FCKEditor].  This is the default value.
| all
|-
| tinymce 
| Use [http://tinymce.moxiecode.com/ TinyMCE editor].
| 0.6
|-
| nicedit
| Use [http://www.nicedit.com/ NicEdit].
| 1.0.5
|}

===Examples===

====Example 1: Using FCKEditor====

Given a field 'content' that you wish to be able to edit with FCKEditor, you would have the following section in your [[fields.ini file]]:

<code>
[content]
    widget:type=htmlarea
    widget:editor=fckeditor
</code>

Note that since FCKEditor is the default editor, the above would give the same result as:

<code>
[content]
    widget:type=htmlarea
</code>

====Example 2: Using TinyMCE====

Further from example 1, if we wanted to use TinyMCE editor, we would change our directive to:

<code>
[content]
    widget:type=htmlarea
    widget:editor=tinymce
</code>

====Example 3: Using NicEdit====

Further from example 1:

<code>
[content]
    widget:type=htmlarea
    widget:editor=nicedit
</code>

==Enabling Image Uploads==

By default image uploads are disabled in these WYSIWYG editors.

===Enabling Image Uploads in FCKEditor===

# Create a directory named ''uploads'' inside your application directory. e.g.<code>
cd /path/to/myapp/uploads
</code>
# Make the ''uploads'' directory writable by the webserver. e.g. <code>
chmod 777 /path/to/myapp/uploads
</code>
# Edit the ''lib/FCKeditor/editor/filemanager/connectors/php/config.php'' file inside your ''xataface'' directory so that:<code>
$Config['Enabled'] = true ;
$Config['UserFilesPath'] = '/url/to/myapp/uploads/' ;
    // The path portion of the URL to your uploads directory.
    // e.g. if your uploads directory is accessible at
    // http://example.com/myapp/uploads, then this value should
    // be /myapp/uploads/
$Config['UserFilesAbsolutePath'] = '/path/to/myapp/uploads/' ;
    // The absolute file system path to your uploads directory.
    // e.g. if your uploads directory is located at
    // /home/myhome/www/myapp/uploads, then this value should be
    // /home/myhome/www/myapp/uploads
</code>
# Now when you click on the ""Add Image"" link in your HTML editor, it will allow you to upload images and browse existing uploaded images.

",,en,0
widget:type,4,widget:type,"==widget:type Directive Reference==

The widget:type directive in the [[fields.ini file]] specifies the type of widget that should be used to edit a particular field in HTML forms.  Xataface uses [http://pear.php.net/package/HTML_QuickForm/ HTML_QuickForm] for its form generation so theoretically any widget supported by HTML_QuickForm should work with Xataface.

===Available Widget Types===

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| [[advmultiselect]]
| Two select lists with add/remove buttons.  Selected items appear in the right select list.  Options may be selected from the left select list.
| 1.0
|-
| [[autocomplete]]
| An autocomplete. text field.  This is not to be confused with the [[yui_autocomplete]] widget.  The main difference is that this widget does not provide a drop-down list of possibilities, it just tries to complete what the user is typing inside the text field based on a valuelist.
| all
|-
| [[calendar]]
| A DHTML pop-up calendar to select the date.  [[Image:http://media.weblite.ca/files/photos/calendar_widget.png?max_width=400]]
| 0.5.3
|-
| [[checkbox]]
| A checkbox or checkbox group. 

Example 1: Checkbox as boolean on Tinyint field.

[[Image:http://media.weblite.ca/files/photos/checkbox_widget.png?max_width=400]]

Example 2: Checkbox group to allow multiple selections.

[[Image:http://media.weblite.ca/files/photos/checkbox-group_widget.png?max_width=500]]
| all
|-
| [[date]]
| Select lists for month, year, day, hour, etc...
| all
|-
| [[file]]
| A file widget (default type for [[container]] fields and [[blob]] fields.  [[Image:http://media.weblite.ca/files/photos/file_widget.png?max_width=400]]

| all
|-
| [[grid]]
| A grid widget for editing multiple rows of related records inside the edit form.  Supports adding/removing/reordering. As of version 1.2.5, file uploads are not supported in the grid widget.

[[Image: http://media.weblite.ca/files/photos/grid_widget.png?max_width=500]]
| 1.0
|-
| [[group]]
| A compound widget for editing multiple fields but storing the data in a single XML field.
[[Image:http://media.weblite.ca/files/photos/group_widget.png?max_width=400]]
| all
|-
| [[hidden]]
| A hidden field 
| all
|-
| [[htmlarea]]
| A WYSIWYG (What you see is what you get) HTML editor.  This defaults to [http://www.fckeditor.net/ FCKeditor], but [http://tinymce.moxiecode.com/ TinyMCE] is also supported.  [[Image:http://media.weblite.ca/files/photos/htmlarea_widget.png?max_width=400]]
| all
|-
| [[lookup]]
| A field that allows users to look-up a record from another table.  THis is a good alternative to a select list.  It doesn't use a vocabulary, so this is appropriate when vocabularies would be unpractical (for large vocabularies).  You do, however need to specify the widget:table directive for the field so that the lookup knows from which table to load the records.
[[Image:http://media.weblite.ca/files/photos/Picture%2023.png?max_width=640]]

| 1.2
|-
| [[password]]
| A password field.

[[Image:http://media.weblite.ca/files/photos/password_widget.png?max_width=400]]
| all
|-
| [[select]]
| A select list.

Example 1: A single select.

[[Image:http://media.weblite.ca/files/photos/select_widget.png?max_width=400]]

Example 2: A multi-select.  To use a multi-select, add repeat=1 to your fields.ini.

[[Image:http://media.weblite.ca/files/photos/multi-select_widget.png?max_width=500]]
| all
|-
| [[table]]
| A compound widget for editing tabular data.  This widget dictates the storage format as XML.

[[Image:http://media.weblite.ca/files/photos/table_widget.png?max_width=400]]
| all
|-
| [[text]]
| A text field

[[Image:http://media.weblite.ca/files/photos/text_widget.png?max_width=400]]
| all
|-
| [[textarea]]
| A text area (multi-line text field)

[[Image:http://media.weblite.ca/files/photos/textarea_widget.png?max_width=400]]
| all
|-
| [[time]]
| A select list of times separated by a specified interval (default 30 minutes).
| 0.7
|-
| [[yui_autocomplete]]
| An autocomplete widget ported from the [http://developer.yahoo.com/yui/autocomplete/ Yahoo UI Library].

[[Image:http://media.weblite.ca/files/photos/yui_autocomplete.png?max_width=400]]
| 1.0
|}",,en,0
widget:type_textarea,60,widget:type_textarea,,,en,0
Writing_Custom_Authentication_Plugins,22,Writing_Custom_Authentication_Plugins,"==Writing a Custom Authentication Plugin for Xataface==

[[toc]]

Xataface has a pluggable [[authentication]] framework that allows you to easily write your own custom [[authentication]] modules to tie in with other systems.  Several plugins have already been created including:

* [[CAS Authentication Module|Yale CAS]]
* [[LDAP Authentication Module|LDAP]]
* [[Facebook Authentication Module|Facebook]]
* [[HTTP Authentication Module|HTTP]]

===Example: Creating a custom authentication plugin===

Before we begin, a couple of conventions:

# '''%XATAFACE_ROOT%''' refers to your Xataface installation directory.  This is where all of the Xataface files are located includeing dataface-public-api.php
# '''%SITE_ROOT%''' refers to your Xataface application's installation directory.  This is where your conf.ini file, index.php, and other application files are stored.

====About our plugin====

Our plugin will be the simplest, most useless authentication plugin you can imagine.  It simply checks an array of usernames and passwords to see if the password that the user supplied is valid.

====Creating our plugin====

# Create the '''%XATAFACE_ROOT%/modules/Auth''' directory if it doesn't exist already.  This directory will store all of our Xataface authentication plugins.
#Create the '''%XATAFACE_ROOT%/modules/Auth/XDB''' directory if it doesn't exist already. This directory will house all of the scripts and files associated with our custom plugin.
#Create a new PHP file named '''XDB.php''' inside our '''XDB''' directory that we just created, with the following contents:<code>
class dataface_modules_XDB {
    var $passwords = array(
        'steve' => 'stevespass',
        'mike' => 'foo'
    );
    function checkCredentials(){
        $auth =& Dataface_AuthenticationTool::getInstance();
        $creds = $auth->getCredentials();
        if ( @$this->passwords[$creds['UserName']] == $creds['Password'] ){
            return true;
        } else {
            return false;
        }
    }
}
</code>
# Now, change the '''[_auth]''' section of the conf.ini file to let Xataface know that we want to use our custom module:<code>
[_auth]
    auth_type=XDB
</code>
# Try to log into your application.  You'll notice that the only username/password combinations that are accepted are the ones that we specified in our '''$passwords''' array in our module.

This is just a simple example, but you can see how this can be expanded to provide more complex modules.

===checkCredentials() not enough?===

Some authentication plugins will need more control than simply checking credentials.  Some plugins may want to make use if their own login forms, or redirect to other sites to handle the authentication.  Xataface's [http://dataface.weblite.ca/Dataface_AuthenticationTool authentication tool] is up to the task, as virtually all parts of the login/logout process can be overridden and customized in your module.  The previous example shows how the getCredentials() method can be overridden, but there are other methods that can be implemented to customize the login process as well.

e.g.

* showLoginPrompt() - This method is called when it is time to display the login prompt for the user.  It could also be made to redirect to another site that has a login prompt.
* logout() - This is called when the user tries to log out.  If there are any special cookies of variables that need to be cleaned up to facilitate a successful logout, you could implement this method.
* [http://dataface.weblite.ca/getLoggedInUser getLoggedInUser()]
* [http://dataface.weblite.ca/getLoggedInUsername getLoggedInUsername()]
* getCredentials() - Handles the obtaining of credentials from the request or from the environment.
* authenticate() - Handles the whole login process

===See Also:===

* [[Application Delegate Class]] for before/after login/logout triggers that may be more appropriate in some circumstances than creating a custom authentication plugin.
* [[authentication|Xataface Authentication]]",,en,0
modules,30,"Xataface Modules","[[toc]]

Xataface provides a number of hooks that allow developers to create modules to extend its functionality.  This page lists a handful of the currently available modules.

* [[ShoppingCart|Shopping Cart]] - Converts your application into a shopping cart.
* [[Filemaker]] - Export record sets as Filemaker XML.
* [[DataGrid|Data Grid]] - Editable Datagrid.
* [[Email]] - Convert your database into a email list.  Send email to any found set.
* [[reCAPTCHA module]] - A reCAPTCHA module to add CAPTCHA support to your Xataface forms.
* [[XataJax]] - Platform for building Web 2.0 AJAX applications with Xataface.  Will be a standard component for Xataface starting with version 1.3.

==Module Installation==

You can add modules in either:

# DATAFACE_PATH/modules directory (since 1.0)
# DATAFACE_SITE_PATH/modules directory (since 1.3)

Modules in the DATAFACE_SITE_PATH directory will supersede modules in the DATAFACE_PATH/modules directory (since 1.3).

To activate a module for your application you also need to add an entry to the [[_modules]] section of your [[conf.ini file]].  Each module will come with its own installation instructions.

==Authentication Modules==

Modules to add alternative authentication methods are added to the modules/Auth directory.

==Developing Your Own Modules==

See [[Module Developers Guide]].","modules, captcha",en,0
xataface_templates,23,xataface_templates,"==Xataface Templates==

[[toc]]

Xataface uses the [http://smarty.php.net Smarty Template Engine] to power all of its templates.  Templates are stored in the one of the following locations:

* %XATAFACE_ROOT%/Dataface/templates
* %SITE_ROOT%/templates

Where %XATAFACE_ROOT% is the Xataface directory (includes files such as dataface-public-api.php), and %SITE_ROOT% is the path to your application.

You may also have subdirectories within these templates directories.

===Cascading Templates===

Xataface uses a simple cascading technique for deciding which template to use.  If there are templates in the %SITE_ROOT%/templates and %XATAFACE_ROOT%/Dataface/templates directories with the same name, then Xataface will use the one in the %SITE_ROOT%/templates directory.  In this way, you are able to override any of Xataface's core templates by adding one of the same name to your %SITE_ROOT%/templates directory.

The most common template to override is the Dataface_Main_Template.html template which defines the look and feel for the entire application (e.g. header, footer, etc...).  Hence, if you wanted to customize the look & feel of your application, you would likely start by copying %XATAFACE_ROOT%/Dataface/templates/Dataface_Main_Template.html into the %SITE_ROOT%/templates directory and make modifications to it as desired.

===Useful Smarty Tags introduced by Xataface===

In addition to the standard set of Smarty tags, Xataface templates provide some of its own.

==Xataface Templates==

Xataface uses the [http://smarty.php.net Smarty Template Engine] to power all of its templates.  Templates are stored in the one of the following locations:

* %XATAFACE_ROOT%/Dataface/templates
* %SITE_ROOT%/templates

Where %XATAFACE_ROOT% is the Xataface directory (includes files such as dataface-public-api.php), and %SITE_ROOT% is the path to your application.

You may also have subdirectories within these templates directories.

===Cascading Templates===

Xataface uses a simple cascading technique for deciding which template to use.  If there are templates in the %SITE_ROOT%/templates and %XATAFACE_ROOT%/Dataface/templates directories with the same name, then Xataface will use the one in the %SITE_ROOT%/templates directory.  In this way, you are able to override any of Xataface's core templates by adding one of the same name to your %SITE_ROOT%/templates directory.

The most common template to override is the Dataface_Main_Template.html template which defines the look and feel for the entire application (e.g. header, footer, etc...).  Hence, if you wanted to customize the look & feel of your application, you would likely start by copying %XATAFACE_ROOT%/Dataface/templates/Dataface_Main_Template.html into the %SITE_ROOT%/templates directory and make modifications to it as desired.

===Useful Smarty Tags introduced by Xataface===

In addition to the standard set of Smarty tags, Xataface templates provide some of its own.

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| [[templates:tags:use_macro|use_macro]]
| Include another template with the option to override certain sections.
| 0.6
|-
| define_slot
| Marks a section that can be overridden by other templates that include this one via the use_macro tag.
| 0.6
|-
| fill_slot
| Overrides content in a template that has been included via the use_macro tag.
| 0.6
|-
| block
| Marks an insertion point where content can be inserted by delegate classes and modules.
| 0.6
|-
| load_record
| Loads a [http://dataface.weblite.ca Dataface_Record] object from the database to be used in the template.
| 0.6
|-
| group
| Groups an array of records together based on a field value.
| 0.6
|-
| img
| Displays a thumbnail of an image.
| 0.6
|-
| actions
| Loads an associative array of actions defined in the actions.ini file, based on certain criteria.
| 0.6
|-
| actions_menu
| Displays a menu of actions based on certain criteria.
| 0.6
|-
| record_actions
| A specialization of the actions_menu tag.  This displays a menu of actions only in the record_actions category.
| 0.6
|-
| record_tabs
| A specialization of the actions_menu tag.  This displays a menu of actions only in the record_tabs category.
| 0.6
|-
| result_controller
| Displays the paging controls for the current table's records.   Use this for any listing of records.
| 0.6
|-
| result_list
| Displays the result list (from the list tab) for the current request.
| 0.6
|-
| related_list
| Displays the related records list for the current request.
| 0.6
|-
| bread_crumbs
| Displays the bread crumbs for the current request.
| 0.6
|-
| search_form
| Displays the find form for the current table.
| 0.6
|-
| language_selector
| Displays a menu to select the user's preferred language.
| 0.6
|-
| next_link
| Displays a link to the next XXX records.
| 0.6
|-
| prev_link
| Displays a link to the previous XXX records.
| 0.6
|-
| jump_menu
| Displays the select list of the records found in this found-set so that the user can jump directly to any record.
| 0.6
|-
| limit_field
| Displays a text field for the user to select the number of records to display per page.
| 0.6
|-
| result_index
| Displays the index of pages (1 to XXX) for this query.
| 0.6
|-
| summary_list
| Displays a list of records in the current found set using a summary format rather than the regular table format.
| 0.6
|-
| sort_controller
| Displays a control to sort the results on any column.
| 0.6
|-
| glance_list
| Displays a simple, brief list of records matching certain criteria.
| 0.6
|-
| record_view
| Loads structured data for a record as required for the view tab.
| 0.6
|-
| feed
| Generates a link to an RSS feed based on certain criteria.
| 0.6
|-
| translate
| Display a section of text in the user's selected language. (i18n).
| 0.6
|-
| if_allowed
| The contents of this block are shown only if the user has certain permissions.
| 0.6
|-
| editable
| Make a section of the page editable using AJAX.
| 0.6
|-
| abs
| Convert a URL into an absolute URL.
| 0.6
|}


===Useful Template Variables===

Xataface makes certain variables available to every template:

{| class=""listing listing2""
|-
! Name
! Description
! Version
|-
| $ENV.REQUEST
| Reference to the $_REQUEST array (HTTP Request parameters, both GET and POST)
| 0.6
|-
| $ENV.SESSION
| Reference to the $_SESSION array (the session variables)
| 0.6
|-
| $ENV.DATAFACE_PATH
| The file system path to the Xataface directory (i.e. the directory containing all of the Xataface files such as dataface-public-api.php).
| 0.6
|-
| $ENV.DATAFACE_URL
| The URL to the Xataface directory.
| 0.6
|-
| $ENV.DATAFACE_SITE_PATH
| The file system path to your application directory. (i.e. the directory containing your conf.ini and index.php files).
| 0.6
|-
| $ENV.DATAFACE_SITE_URL
| The URL to your application directory.
| 0.6
|-
| $ENV.DATAFACE_SITE_HREF
| The URL to your application's script.  This differs from the $ENV.DATAFACE_SITE_URL variable in that this also includes the script name.
| 0.6
|-
| $ENV.SCRIPT_NAME
| Same as $ENV.DATAFACE_SITE_HREF
| 0.6
|-
| $ENV.APPLICATION
| A reference to the application's conf array (i.e. the parsed contents of the conf.ini file).
| 0.6
|-
| $ENV.APPLICATION_OBJECT
| A reference to the Dataface_Application object for the application.
| 0.6
|-
| $ENV.SERVER
| A reference to the $_SERVER array.
| 0.6
|-
| $ENV.QUERY
| A reference to the current query (i.e.  Dataface_Application::getInstance()->getQuery())
| 0.6
|-
| $ENV.action
| The name of the current action as specified by the -action REQUEST parameter.
| 0.6
|-
| $ENV.table
| The name of the current table as specified by the -table REQUEST parameter.
| 0.6
|-
| $ENV.table_object
| A reference to the current table.
| 0.6
|-
| $ENV.relationship
| The name of the current relationship as specified by the -relationship REQUEST parameter.
| 0.6
|-
| $ENV.limit
| The value of the -limit REQUEST parameter.  This is the number of records to show per page.
| 0.6
|-
| $ENV.start
| The value of the -start REQUEST parmeter.  This is the starting point in the result set which is currently being displayed.
| 0.6
|-
| $ENV.resultSet
| A reference to the [http://dataface.weblite.ca/Dataface_QueryTool Dataface_QueryTool] object for this result set.
| 0.6
|-
| $ENV.record
| A reference to the [http://dataface.weblite.ca/Dataface_Record Dataface_Record] object that is matched by the current query.
| 0.6
|-
| $ENV.mode
| The name of the current mode.  e.g. find, list, browse
| 0.6
|-
| $ENV.language
| The 2-digit ISO language code that is currently selected as the user's preferred language.
| 0.6
|-
| $ENV.prefs
| A reference to the preferences array ($conf['_prefs'])
| 0.6
|-
| $ENV.search
| The value of the current full-text search (i.e. the search that was entered into the upper right search field.
| 0.6
|}


==Smarty Plugins==

One of the most powerful features of [http://www.smarty.net Smarty] is its pluggable architecture.  You can easily add your own custom plugins to a registered ""plugins"" directory to add functions, modifiers, blocks, and other features to your templates.

Prior to Xataface 2.0, you Smarty plugins could only be placed in the  ''lib/Smarty/plugins'' directory of the Xataface distribution folder.  This is not very conducive to Xataface updates, though.  In general it is best practice to not change anything inside the xataface directory.  Most other configuration and extensions can be handled by making changes to your application's directory which override corresponding functionality in Xataface.

As of Xataface 2.0, you can create a directory named ''plugins'' to your application directory, Smarty knows to look in this directory for plugins.

For versions of Xataface prior to 2.0, you can make a small modification to the SkinTool to also add support as desribed in [http://xataface.com/forum/viewtopic.php?f=4&t=6722 this post].

===Example Plugin===

The following is an example Smarty plugin adapted from [http://www.smarty.net/docs/en/plugins.functions.tpl this page] but modified slightly to work in Xataface.  It is a simple ""eightball"" plugin that adds a tag {eightball} to Xataface that you can use in any of your templates.  Whenever this tag is rendered it outputs one of a set of predefined strings randomly.

# Add a ''plugins'' directory to your application directory.  i.e.  ''path/to/app/plugins''
# Add a file inside this ''plugins'' directory called ''<nowiki>function.eightball.php</nowiki>'' with the following content:<code>
<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.eightball.php
 * Type:     function
 * Name:     eightball
 * Purpose:  outputs a random magic answer
 * -------------------------------------------------------------
 */
function smarty_function_eightball($params, Dataface_SkinTool $template)
{
    $answers = array('Yes',
                     'No',
                     'No way',
                     'Outlook not so good',
                     'Ask again soon',
                     'Maybe in your reality');

    $result = array_rand($answers);
    return $answers[$result];
}
</code>
# If you compare this function to the original example in [http://www.smarty.net/docs/en/plugins.functions.tpl the smarty tutorial] you'll notice that the 2nd parameter has been changed to type ''Dataface_SkinTool'' from ''Smarty_Internal_Template''. If you don't make this change, you will get a fatal error when you try to use the tag.  This function defines an ''{eightball}'' tag that can be added to any Smarty template in Xataface.
# Next we'll create a template that uses this tag.  If your application doesn't have a ''templates'' directory, create one now (i.e. path/to/app/templates).
# Add a file inside your templates directory called ''testing.html'' with the following content:<code>
The eight ball says {eightball}
</code>
# Now we need to display this template somewhere in our interface.  In this case, we'll choose the ''before_record_content'' block.  (This will render the template before the main section of the view tab).  Add the following method to your [[Application_Delegate_Class]]:<code>
function block__before_record_content(){
    df_display(array(), 'testing.html');
}
</code>
# Now if you load your application in a web browser and navigate to the details view for a record, you should see something like the following:
<nowiki><img src=""http://media.weblite.ca/files/photos/Screen_Shot_2012-04-16_at_12.33.01_PM.png?max_width=640""/></nowiki>

===See also:===

* [http://www.xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing the Look & Feel of Xataface] (From the Getting Started Tutorial)
* [http://www.xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Cusomizing the Xataface Look & Feel] Tutorial","templates, plugins, smarty",en,0
_auth,97,"_auth section of the conf.ini file","[[conf.ini file|Return to conf.ini file]]

[[toc]]

===Synopsis===

The ''_auth'' section of the conf.ini file includes configuration directives to enable authentication in a Xataface application.  For more information about authentication and registration see [[authentication]].  This section may include the following directives:

===Directives===

{| class=""listing listing2""
|-
! Directive
! Description
! Required
! Default
! Version
|-
| users_table
| The name of the table that contains your user accounts.
| Yes
| None
| 0.6
|-
| username_column
| The name of the column that stores the username.
| Yes
| None
| 0.6
|-
| password_column
| The name of the column that stores the password.
| Required if using basic authentication.
| None
| 0.6
|-
| auth_type
| Specifies the authentication module that is being used.  E.g. basic, cas, ldap, http, facebook, etc...
| No
| basic
| 0.6
|-
| allow_register
| Flag to enable user registration.  If this is set to 1, then a ''register'' link will appear below the login form.
| No
| 0
| 0.8
|-
| session_timeout
| Number of seconds of inactivity after which the user will be logged out. Note: Arithmetic don't work in the conf.ini, use seconds.
| No
| 86400 (=> 24*60*60 (24 hours))
| 1.3rc4
|}

===See Also===

* [[authentication]] - Overview of Xataface Authentication
* [[conf.ini file]] - Directives available in the conf.ini file.","_auth,authentication,conf.ini file,allow_register",en,
__field__permissions,50,__field__permissions,"This method can be used to set the default permissions for all fields in a designated table, when specified in that table's delegate class. It comes in handy in situations when you want to deny access to all fields except for those designated, rather then specifying each field to deny individually. For example, to revoke edit permissions from all fields but one, the user must first have edit permissions to the table overall, otherwise the Edit tab/action will not appear. Then, use this __field_permissions method to revoke edit permissions from all fields. Finally, use the fieldname__permissions method (see below) to allow access to only those fields needed.

=== Also See: ===

* [[How_to_granulate_permissions_on_each_field]]
* [[fieldname__permissions]]",,en,0
__global__,106,"__global__ section for the fields.ini file","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

The fields.ini file supports a __global__ section that applies to all fields in the current table.  This is particularly useful for setting up default functionality that you wish to see on all fields except a few.  For example you may wish to have all fields hidden from list view by default, and only explicitly enable a few.  Same for CSV export or the details form.

===Example 1: Hiding All Fields from List View===

In the fields.ini file:
<code>
[__global__]
    ;; hide all of the fields from list view
    visibility:list=hidden

[first_name]
    ;; show the first name in list view 
    visibility:list=visible

[last_name]
    visibility:list=visible

;;.... etc....
</code>

In the above example we used the __global__ section to declare that we want all fields to be hidden from list view by default.  Then we explicitly showed first_name and last_name in list view. In this case only first_name and last_name will appear in the list view.

==See Also==

*[[fields.ini file]]
*[[visibility:list]]","__global__, fields.ini, visibility:list",en,
__prefs__,9,__prefs__,"==__prefs__ fields.ini Section==

A global section of the [[fields.ini file]] that sets the preferences for the given table and its records.

E.g.
<code>
[__prefs__]
    hide_posted_by=1 ; Hides the ""Posted by"" text in glance lists (e.g. related records in the view tab).
    hide_updated=1 ; Hides the ""Updated"" text in glance lists (e.g. the related records in the view tab).
</code>


===Available Preferences===

Ultimately, all of the preferences available at a global level should be available here, however currently this is not the case and only selected preferences are available at the table level.

{| class=""listing listing2""
! Name
! Description
! Version
|-
| [[hide_posted_by]]
| HIdes the ''posted_by'' text in glance lists.  E.g. In the view tab of a record, the related records are shown in the left column.  This will hide the ''posted_by'' text next to each related record.
| 1.0b4
|-
| [[hide_updated]]
| Hides the ''updated'' text in glance lists.  E.g. In the view tab of a record, the related records are shown in the left column.  This will hide the ''updated'' text next to each related record.
| 1.0b4
|-
|}",,en,0
sql_delegate_method,87,"__sql__ Delegate Method","return to [[Delegate class methods]]

===Synopsis===

The __sql__ delegate class method can be defined in any delegate class to specify the SQL query that should be used to fetch records for a given table.  This method overrides the [[__sql__]] directive of the fields.ini file.  This strategy is primarily used to graft columns from another table onto the base table.

=====Use Caution=====

This is an advanced feature and, if used incorrectly, can muck up your application. Make sure that your SQL query includes a superset of the columns in the base table, and is a row-for-row match for the rows in the base table.  I.e. you should never use an internal join.  Always use a left join so that all of the rows of the base table are returned even if the join table doesn't have a corresponding row.

If you want to simply filter a table's records, and don't need to graft any additional columns onto the table, you should use the [[setSecurityFilters]] method.

===Example===

Given the table foo, its delegate class:

<code>
class tables_foo {
    function __sql__(){
        return ""select f.*, c.category_name from foo f left join categories c on f.category_id=c.category_id"";
    }
}
</code>

This effectively grafts a column ""category_name"" onto the foo table based on a join with the categories table.

","__sql__, SQL queries, delegate class",en,
