diff options
Diffstat (limited to 'user_guide_src/source/libraries')
29 files changed, 7268 insertions, 0 deletions
diff --git a/user_guide_src/source/libraries/benchmark.rst b/user_guide_src/source/libraries/benchmark.rst new file mode 100644 index 000000000..5b86142dd --- /dev/null +++ b/user_guide_src/source/libraries/benchmark.rst @@ -0,0 +1,122 @@ +################## +Benchmarking Class +################## + +CodeIgniter has a Benchmarking class that is always active, enabling the +time difference between any two marked points to be calculated. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +In addition, the benchmark is always started the moment the framework is +invoked, and ended by the output class right before sending the final +view to the browser, enabling a very accurate timing of the entire +system execution to be shown. + +.. contents:: Table of Contents + +Using the Benchmark Class +========================= + +The Benchmark class can be used within your +:doc:`controllers </general/controllers>`, +:doc:`views </general/views>`, or your :doc:`models </general/models>`. +The process for usage is this: + +#. Mark a start point +#. Mark an end point +#. Run the "elapsed time" function to view the results + +Here's an example using real code:: + + $this->benchmark->mark('code_start'); + + // Some code happens here + + $this->benchmark->mark('code_end'); + + echo $this->benchmark->elapsed_time('code_start', 'code_end'); + +.. note:: The words "code_start" and "code_end" are arbitrary. They + are simply words used to set two markers. You can use any words you + want, and you can set multiple sets of markers. Consider this example:: + + $this->benchmark->mark('dog'); + + // Some code happens here + + $this->benchmark->mark('cat'); + + // More code happens here + + $this->benchmark->mark('bird'); + + echo $this->benchmark->elapsed_time('dog', 'cat'); + echo $this->benchmark->elapsed_time('cat', 'bird'); + echo $this->benchmark->elapsed_time('dog', 'bird'); + + +Profiling Your Benchmark Points +=============================== + +If you want your benchmark data to be available to the +:doc:`Profiler </general/profiling>` all of your marked points must +be set up in pairs, and each mark point name must end with _start and +_end. Each pair of points must otherwise be named identically. Example:: + + $this->benchmark->mark('my_mark_start'); + + // Some code happens here... + + $this->benchmark->mark('my_mark_end'); + + $this->benchmark->mark('another_mark_start'); + + // Some more code happens here... + + $this->benchmark->mark('another_mark_end'); + +Please read the :doc:`Profiler page </general/profiling>` for more +information. + +Displaying Total Execution Time +=============================== + +If you would like to display the total elapsed time from the moment +CodeIgniter starts to the moment the final output is sent to the +browser, simply place this in one of your view templates:: + + <?php echo $this->benchmark->elapsed_time();?> + +You'll notice that it's the same function used in the examples above to +calculate the time between two point, except you are **not** using any +parameters. When the parameters are absent, CodeIgniter does not stop +the benchmark until right before the final output is sent to the +browser. It doesn't matter where you use the function call, the timer +will continue to run until the very end. + +An alternate way to show your elapsed time in your view files is to use +this pseudo-variable, if you prefer not to use the pure PHP:: + + {elapsed_time} + +.. note:: If you want to benchmark anything within your controller + functions you must set your own start/end points. + +Displaying Memory Consumption +============================= + +If your PHP installation is configured with --enable-memory-limit, you +can display the amount of memory consumed by the entire system using the +following code in one of your view file:: + + <?php echo $this->benchmark->memory_usage();?> + +.. note:: This function can only be used in your view files. The consumption + will reflect the total memory used by the entire app. + +An alternate way to show your memory usage in your view files is to use +this pseudo-variable, if you prefer not to use the pure PHP:: + + {memory_usage} + diff --git a/user_guide_src/source/libraries/caching.rst b/user_guide_src/source/libraries/caching.rst new file mode 100644 index 000000000..2f06d29f9 --- /dev/null +++ b/user_guide_src/source/libraries/caching.rst @@ -0,0 +1,220 @@ +############## +Caching Driver +############## + +CodeIgniter features wrappers around some of the most popular forms of +fast and dynamic caching. All but file-based caching require specific +server requirements, and a Fatal Exception will be thrown if server +requirements are not met. + +.. contents:: Table of Contents + +************* +Example Usage +************* + +The following example will load the cache driver, specify `APC <#apc>`_ +as the driver to use, and fall back to file-based caching if APC is not +available in the hosting environment. + +:: + + $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file')); + + if ( ! $foo = $this->cache->get('foo')) + { + echo 'Saving to the cache!<br />'; + $foo = 'foobarbaz!'; + + // Save into the cache for 5 minutes + $this->cache->save('foo', $foo, 300); + } + + echo $foo; + +****************** +Function Reference +****************** + +.. php:class:: CI_Cache + +is_supported() +=============== + + .. php:method:: is_supported ( $driver ) + + This function is automatically called when accessing drivers via + $this->cache->get(). However, if the individual drivers are used, make + sure to call this function to ensure the driver is supported in the + hosting environment. + + :param string $driver: the name of the caching driver + :returns: TRUE if supported, FALSE if not + :rtype: Boolean + + :: + + if ($this->cache->apc->is_supported() + { + if ($data = $this->cache->apc->get('my_cache')) + { + // do things. + } + } + + +get() +===== + + .. php:method:: get ( $id ) + + This function will attempt to fetch an item from the cache store. If the + item does not exist, the function will return FALSE. + + :param string $id: name of cached item + :returns: The item if it exists, FALSE if it does not + :rtype: Mixed + + :: + + $foo = $this->cache->get('my_cached_item'); + + +save() +====== + + .. php:method:: save ( $id , $data [, $ttl]) + + This function will save an item to the cache store. If saving fails, the + function will return FALSE. + + :param string $id: name of the cached item + :param mixed $data: the data to save + :param int $ttl: Time To Live, in seconds (default 60) + :returns: TRUE on success, FALSE on failure + :rtype: Boolean + + :: + + $this->cache->save('cache_item_id', 'data_to_cache'); + +delete() +======== + + .. php:method:: delete ( $id ) + + This function will delete a specific item from the cache store. If item + deletion fails, the function will return FALSE. + + :param string $id: name of cached item + :returns: TRUE if deleted, FALSE if the deletion fails + :rtype: Boolean + + :: + + $this->cache->delete('cache_item_id'); + +clean() +======= + + .. php:method:: clean ( ) + + This function will 'clean' the entire cache. If the deletion of the + cache files fails, the function will return FALSE. + + :returns: TRUE if deleted, FALSE if the deletion fails + :rtype: Boolean + + :: + + $this->cache->clean(); + +cache_info() +============= + + .. php:method:: cache_info ( ) + + This function will return information on the entire cache. + + :returns: information on the entire cache + :rtype: Mixed + + :: + + var_dump($this->cache->cache_info()); + + .. note:: The information returned and the structure of the data is dependent + on which adapter is being used. + + +get_metadata() +=============== + + .. php:method:: get_metadata ( $id ) + + This function will return detailed information on a specific item in the + cache. + + :param string $id: name of cached item + :returns: metadadta for the cached item + :rtype: Mixed + + :: + + var_dump($this->cache->get_metadata('my_cached_item')); + + .. note:: The information returned and the structure of the data is dependent + on which adapter is being used. + + +******* +Drivers +******* + +Alternative PHP Cache (APC) Caching +=================================== + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->apc->save('foo', 'bar', 10); + +For more information on APC, please see +`http://php.net/apc <http://php.net/apc>`_ + +File-based Caching +================== + +Unlike caching from the Output Class, the driver file-based caching +allows for pieces of view files to be cached. Use this with care, and +make sure to benchmark your application, as a point can come where disk +I/O will negate positive gains by caching. + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->file->save('foo', 'bar', 10); + +Memcached Caching +================= + +Multiple Memcached servers can be specified in the memcached.php +configuration file, located in the application/config/ directory. + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->memcached->save('foo', 'bar', 10); + +For more information on Memcached, please see +`http://php.net/memcached <http://php.net/memcached>`_ + +Dummy Cache +=========== + +This is a caching backend that will always 'miss.' It stores no data, +but lets you keep your caching code in place in environments that don't +support your chosen cache. diff --git a/user_guide_src/source/libraries/calendar.rst b/user_guide_src/source/libraries/calendar.rst new file mode 100644 index 000000000..471fd64f9 --- /dev/null +++ b/user_guide_src/source/libraries/calendar.rst @@ -0,0 +1,181 @@ +################# +Calendaring Class +################# + +The Calendar class enables you to dynamically create calendars. Your +calendars can be formatted through the use of a calendar template, +allowing 100% control over every aspect of its design. In addition, you +can pass data to your calendar cells. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Calendar class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('calendar'); + +Once loaded, the Calendar object will be available using:: + + $this->calendar + +Displaying a Calendar +===================== + +Here is a very simple example showing how you can display a calendar:: + + $this->load->library('calendar'); + echo $this->calendar->generate(); + +The above code will generate a calendar for the current month/year based +on your server time. To show a calendar for a specific month and year +you will pass this information to the calendar generating function:: + + $this->load->library('calendar'); + echo $this->calendar->generate(2006, 6); + +The above code will generate a calendar showing the month of June in +2006. The first parameter specifies the year, the second parameter +specifies the month. + +Passing Data to your Calendar Cells +=================================== + +To add data to your calendar cells involves creating an associative +array in which the keys correspond to the days you wish to populate and +the array value contains the data. The array is passed to the third +parameter of the calendar generating function. Consider this example:: + + $this->load->library('calendar'); + + $data = array( + 3 => 'http://example.com/news/article/2006/03/', + 7 => 'http://example.com/news/article/2006/07/', + 13 => 'http://example.com/news/article/2006/13/', + 26 => 'http://example.com/news/article/2006/26/' + ); + + echo $this->calendar->generate(2006, 6, $data); + +Using the above example, day numbers 3, 7, 13, and 26 will become links +pointing to the URLs you've provided. + +.. note:: By default it is assumed that your array will contain links. + In the section that explains the calendar template below you'll see how + you can customize how data passed to your cells is handled so you can + pass different types of information. + +Setting Display Preferences +=========================== + +There are seven preferences you can set to control various aspects of +the calendar. Preferences are set by passing an array of preferences in +the second parameter of the loading function. Here is an example:: + + $prefs = array ( + 'start_day' => 'saturday', + 'month_type' => 'long', + 'day_type' => 'short' + ); + + $this->load->library('calendar', $prefs); + + echo $this->calendar->generate(); + +The above code would start the calendar on saturday, use the "long" +month heading, and the "short" day names. More information regarding +preferences below. + ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| Preference | Default | Options | Description | ++=======================+===========+===============================================+===================================================================+ +| **template** | None | None | A string containing your calendar template. | +| | | | See the template section below. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **local_time** | time() | None | A Unix timestamp corresponding to the current time. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **start_day** | sunday | Any week day (sunday, monday, tuesday, etc.) | Sets the day of the week the calendar should start on. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **month_type** | long | long, short | Determines what version of the month name to use in the header. | +| | | | long = January, short = Jan. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **day_type** | abr | long, short, abr | Determines what version of the weekday names to use in | +| | | | the column headers. | +| | | | long = Sunday, short = Sun, abr = Su. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **show_next_prev** | FALSE | TRUE/FALSE (boolean) | Determines whether to display links allowing you to toggle | +| | | | to next/previous months. See information on this feature below. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +| **next_prev_url** | None | A URL | Sets the basepath used in the next/previous calendar links. | ++-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ + + +Showing Next/Previous Month Links +================================= + +To allow your calendar to dynamically increment/decrement via the +next/previous links requires that you set up your calendar code similar +to this example:: + + $prefs = array ( + 'show_next_prev' => TRUE, + 'next_prev_url' => 'http://example.com/index.php/calendar/show/' + ); + + $this->load->library('calendar', $prefs); + + echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4)); + +You'll notice a few things about the above example: + +- You must set the "show_next_prev" to TRUE. +- You must supply the URL to the controller containing your calendar in + the "next_prev_url" preference. +- You must supply the "year" and "month" to the calendar generating + function via the URI segments where they appear (Note: The calendar + class automatically adds the year/month to the base URL you + provide.). + +Creating a Calendar Template +============================ + +By creating a calendar template you have 100% control over the design of +your calendar. Each component of your calendar will be placed within a +pair of pseudo-variables as shown here:: + + $prefs['template'] = ' + + {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open} + + {heading_row_start}<tr>{/heading_row_start} + + {heading_previous_cell}<th><a href="{previous_url}"><<</a></th>{/heading_previous_cell} + {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell} + {heading_next_cell}<th><a href="{next_url}">>></a></th>{/heading_next_cell} + + {heading_row_end}</tr>{/heading_row_end} + + {week_row_start}<tr>{/week_row_start} + {week_day_cell}<td>{week_day}</td>{/week_day_cell} + {week_row_end}</tr>{/week_row_end} + + {cal_row_start}<tr>{/cal_row_start} + {cal_cell_start}<td>{/cal_cell_start} + + {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content} + {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today} + + {cal_cell_no_content}{day}{/cal_cell_no_content} + {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today} + + {cal_cell_blank} {/cal_cell_blank} + + {cal_cell_end}</td>{/cal_cell_end} + {cal_row_end}</tr>{/cal_row_end} + + {table_close}</table>{/table_close} + '; + + $this->load->library('calendar', $prefs); + + echo $this->calendar->generate();
\ No newline at end of file diff --git a/user_guide_src/source/libraries/cart.rst b/user_guide_src/source/libraries/cart.rst new file mode 100644 index 000000000..850d7e9a8 --- /dev/null +++ b/user_guide_src/source/libraries/cart.rst @@ -0,0 +1,294 @@ +################### +Shopping Cart Class +################### + +The Cart Class permits items to be added to a session that stays active +while a user is browsing your site. These items can be retrieved and +displayed in a standard "shopping cart" format, allowing the user to +update the quantity or remove items from the cart. + +Please note that the Cart Class ONLY provides the core "cart" +functionality. It does not provide shipping, credit card authorization, +or other processing components. + +.. contents:: Page Contents + +Initializing the Shopping Cart Class +==================================== + +.. important:: The Cart class utilizes CodeIgniter's :doc:`Session + Class <sessions>` to save the cart information to a database, so + before using the Cart class you must set up a database table as + indicated in the :doc:`Session Documentation <sessions>`, and set the + session preferences in your application/config/config.php file to + utilize a database. + +To initialize the Shopping Cart Class in your controller constructor, +use the $this->load->library function:: + + $this->load->library('cart'); + +Once loaded, the Cart object will be available using:: + + $this->cart + +.. note:: The Cart Class will load and initialize the Session Class + automatically, so unless you are using sessions elsewhere in your + application, you do not need to load the Session class. + +Adding an Item to The Cart +========================== + +To add an item to the shopping cart, simply pass an array with the +product information to the $this->cart->insert() function, as shown +below:: + + $data = array( + 'id' => 'sku_123ABC', + 'qty' => 1, + 'price' => 39.95, + 'name' => 'T-Shirt', + 'options' => array('Size' => 'L', 'Color' => 'Red') + ); + + $this->cart->insert($data); + +.. important:: The first four array indexes above (id, qty, price, and + name) are **required**. If you omit any of them the data will not be + saved to the cart. The fifth index (options) is optional. It is intended + to be used in cases where your product has options associated with it. + Use an array for options, as shown above. + +The five reserved indexes are: + +- **id** - Each product in your store must have a unique identifier. + Typically this will be an "sku" or other such identifier. +- **qty** - The quantity being purchased. +- **price** - The price of the item. +- **name** - The name of the item. +- **options** - Any additional attributes that are needed to identify + the product. These must be passed via an array. + +In addition to the five indexes above, there are two reserved words: +rowid and subtotal. These are used internally by the Cart class, so +please do NOT use those words as index names when inserting data into +the cart. + +Your array may contain additional data. Anything you include in your +array will be stored in the session. However, it is best to standardize +your data among all your products in order to make displaying the +information in a table easier. + +The insert() method will return the $rowid if you successfully insert a +single item. + +Adding Multiple Items to The Cart +================================= + +By using a multi-dimensional array, as shown below, it is possible to +add multiple products to the cart in one action. This is useful in cases +where you wish to allow people to select from among several items on the +same page. + +:: + + $data = array( + array( + 'id' => 'sku_123ABC', + 'qty' => 1, + 'price' => 39.95, + 'name' => 'T-Shirt', + 'options' => array('Size' => 'L', 'Color' => 'Red') + ), + array( + 'id' => 'sku_567ZYX', + 'qty' => 1, + 'price' => 9.95, + 'name' => 'Coffee Mug' + ), + array( + 'id' => 'sku_965QRS', + 'qty' => 1, + 'price' => 29.95, + 'name' => 'Shot Glass' + ) + ); + + $this->cart->insert($data); + +Displaying the Cart +=================== + +To display the cart you will create a :doc:`view +file </general/views>` with code similar to the one shown below. + +Please note that this example uses the :doc:`form +helper </helpers/form_helper>`. + +:: + + <?php echo form_open('path/to/controller/update/function'); ?> + + <table cellpadding="6" cellspacing="1" style="width:100%" border="0"> + + <tr> + <th>QTY</th> + <th>Item Description</th> + <th style="text-align:right">Item Price</th> + <th style="text-align:right">Sub-Total</th> + </tr> + + <?php $i = 1; ?> + + <?php foreach ($this->cart->contents() as $items): ?> + + <?php echo form_hidden($i.'[rowid]', $items['rowid']); ?> + + <tr> + <td><?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td> + <td> + <?php echo $items['name']; ?> + + <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?> + + <p> + <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?> + + <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br /> + + <?php endforeach; ?> + </p> + + <?php endif; ?> + + </td> + <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td> + <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td> + </tr> + + <?php $i++; ?> + + <?php endforeach; ?> + + <tr> + <td colspan="2"> </td> + <td class="right"><strong>Total</strong></td> + <td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td> + </tr> + + </table> + + <p><?php echo form_submit('', 'Update your Cart'); ?></p> + +Updating The Cart +================= + +To update the information in your cart, you must pass an array +containing the Row ID and quantity to the $this->cart->update() +function: + +.. note:: If the quantity is set to zero, the item will be removed from + the cart. + +:: + + $data = array( + 'rowid' => 'b99ccdf16028f015540f341130b6d8ec', + 'qty' => 3 + ); + + $this->cart->update($data); + + // Or a multi-dimensional array + + $data = array( + array( + 'rowid' => 'b99ccdf16028f015540f341130b6d8ec', + 'qty' => 3 + ), + array( + 'rowid' => 'xw82g9q3r495893iajdh473990rikw23', + 'qty' => 4 + ), + array( + 'rowid' => 'fh4kdkkkaoe30njgoe92rkdkkobec333', + 'qty' => 2 + ) + ); + + $this->cart->update($data); + +What is a Row ID? +***************** + +The row ID is a unique identifier that is +generated by the cart code when an item is added to the cart. The reason +a unique ID is created is so that identical products with different +options can be managed by the cart. + +For example, let's say someone buys two identical t-shirts (same product +ID), but in different sizes. The product ID (and other attributes) will +be identical for both sizes because it's the same shirt. The only +difference will be the size. The cart must therefore have a means of +identifying this difference so that the two sizes of shirts can be +managed independently. It does so by creating a unique "row ID" based on +the product ID and any options associated with it. + +In nearly all cases, updating the cart will be something the user does +via the "view cart" page, so as a developer, it is unlikely that you +will ever have to concern yourself with the "row ID", other then making +sure your "view cart" page contains this information in a hidden form +field, and making sure it gets passed to the update function when the +update form is submitted. Please examine the construction of the "view +cart" page above for more information. + + +Function Reference +================== + +$this->cart->insert(); +********************** + +Permits you to add items to the shopping cart, as outlined above. + +$this->cart->update(); +********************** + +Permits you to update items in the shopping cart, as outlined above. + +$this->cart->total(); +********************* + +Displays the total amount in the cart. + +$this->cart->total_items(); +**************************** + +Displays the total number of items in the cart. + +$this->cart->contents(); +************************ + +Returns an array containing everything in the cart. + +$this->cart->has_options(rowid); +********************************* + +Returns TRUE (boolean) if a particular row in the cart contains options. +This function is designed to be used in a loop with +$this->cart->contents(), since you must pass the rowid to this function, +as shown in the Displaying the Cart example above. + +$this->cart->product_options(rowid); +************************************* + +Returns an array of options for a particular product. This function is +designed to be used in a loop with $this->cart->contents(), since you +must pass the rowid to this function, as shown in the Displaying the +Cart example above. + +$this->cart->destroy(); +*********************** + +Permits you to destroy the cart. This function will likely be called +when you are finished processing the customer's order. diff --git a/user_guide_src/source/libraries/config.rst b/user_guide_src/source/libraries/config.rst new file mode 100644 index 000000000..c81cad7b3 --- /dev/null +++ b/user_guide_src/source/libraries/config.rst @@ -0,0 +1,181 @@ +############ +Config Class +############ + +The Config class provides a means to retrieve configuration preferences. +These preferences can come from the default config file +(application/config/config.php) or from your own custom config files. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +.. contents:: Page Contents + +Anatomy of a Config File +======================== + +By default, CodeIgniter has one primary config file, located at +application/config/config.php. If you open the file using your text +editor you'll see that config items are stored in an array called +$config. + +You can add your own config items to this file, or if you prefer to keep +your configuration items separate (assuming you even need config items), +simply create your own file and save it in config folder. + +.. note:: If you do create your own config files use the same format as + the primary one, storing your items in an array called $config. + CodeIgniter will intelligently manage these files so there will be no + conflict even though the array has the same name (assuming an array + index is not named the same as another). + +Loading a Config File +===================== + +.. note:: + CodeIgniter automatically loads the primary config file + (application/config/config.php), so you will only need to load a config + file if you have created your own. + +There are two ways to load a config file: + +Manual Loading +************** + +To load one of your custom config files you will use the following +function within the :doc:`controller </general/controllers>` that +needs it:: + + $this->config->load('filename'); + +Where filename is the name of your config file, without the .php file +extension. + +If you need to load multiple config files normally they will be +merged into one master config array. Name collisions can occur, +however, if you have identically named array indexes in different +config files. To avoid collisions you can set the second parameter to +TRUE and each config file will be stored in an array index +corresponding to the name of the config file. Example:: + + // Stored in an array with this prototype: $this->config['blog_settings'] = $config + $this->config->load('blog_settings', TRUE); + +Please see the section entitled Fetching Config Items below to learn +how to retrieve config items set this way. + +The third parameter allows you to suppress errors in the event that a +config file does not exist:: + + $this->config->load('blog_settings', FALSE, TRUE); + +Auto-loading +************ + +If you find that you need a particular config file globally, you can +have it loaded automatically by the system. To do this, open the +**autoload.php** file, located at application/config/autoload.php, +and add your config file as indicated in the file. + + +Fetching Config Items +===================== + +To retrieve an item from your config file, use the following function:: + + $this->config->item('item name'); + +Where item name is the $config array index you want to retrieve. For +example, to fetch your language choice you'll do this:: + + $lang = $this->config->item('language'); + +The function returns FALSE (boolean) if the item you are trying to fetch +does not exist. + +If you are using the second parameter of the $this->config->load +function in order to assign your config items to a specific index you +can retrieve it by specifying the index name in the second parameter of +the $this->config->item() function. Example:: + + // Loads a config file named blog_settings.php and assigns it to an index named "blog_settings" + $this->config->load('blog_settings', TRUE); + + // Retrieve a config item named site_name contained within the blog_settings array + $site_name = $this->config->item('site_name', 'blog_settings'); + + // An alternate way to specify the same item: + $blog_config = $this->config->item('blog_settings'); + $site_name = $blog_config['site_name']; + +Setting a Config Item +===================== + +If you would like to dynamically set a config item or change an existing +one, you can do so using:: + + $this->config->set_item('item_name', 'item_value'); + +Where item_name is the $config array index you want to change, and +item_value is its value. + +.. _config-environments: + +Environments +============ + +You may load different configuration files depending on the current +environment. The ENVIRONMENT constant is defined in index.php, and is +described in detail in the :doc:`Handling +Environments </general/environments>` section. + +To create an environment-specific configuration file, create or copy a +configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php + +For example, to create a production-only config.php, you would: + +#. Create the directory application/config/production/ +#. Copy your existing config.php into the above directory +#. Edit application/config/production/config.php so it contains your + production settings + +When you set the ENVIRONMENT constant to 'production', the settings for +your new production-only config.php will be loaded. + +You can place the following configuration files in environment-specific +folders: + +- Default CodeIgniter configuration files +- Your own custom configuration files + +.. note:: + CodeIgniter always tries to load the configuration files for + the current environment first. If the file does not exist, the global + config file (i.e., the one in application/config/) is loaded. This means + you are not obligated to place **all** of your configuration files in an + environment folder − only the files that change per environment. + +Helper Functions +================ + +The config class has the following helper functions: + +$this->config->site_url(); +*************************** + +This function retrieves the URL to your site, along with the "index" +value you've specified in the config file. + +$this->config->base_url(); +*************************** + +This function retrieves the URL to your site, plus an optional path such +as to a stylesheet or image. + +The two functions above are normally accessed via the corresponding +functions in the :doc:`URL Helper </helpers/url_helper>`. + +$this->config->system_url(); +***************************** + +This function retrieves the URL to your system folder. diff --git a/user_guide_src/source/libraries/email.rst b/user_guide_src/source/libraries/email.rst new file mode 100644 index 000000000..759899242 --- /dev/null +++ b/user_guide_src/source/libraries/email.rst @@ -0,0 +1,257 @@ +########### +Email Class +########### + +CodeIgniter's robust Email Class supports the following features: + +- Multiple Protocols: Mail, Sendmail, and SMTP +- TLS and SSL Encryption for SMTP +- Multiple recipients +- CC and BCCs +- HTML or Plaintext email +- Attachments +- Word wrapping +- Priorities +- BCC Batch Mode, enabling large email lists to be broken into small + BCC batches. +- Email Debugging tools + +Sending Email +============= + +Sending email is not only simple, but you can configure it on the fly or +set your preferences in a config file. + +Here is a basic example demonstrating how you might send email. Note: +This example assumes you are sending the email from one of your +:doc:`controllers <../general/controllers>`. + +:: + + $this->load->library('email'); + + $this->email->from('your@example.com', 'Your Name'); + $this->email->to('someone@example.com'); + $this->email->cc('another@another-example.com'); + $this->email->bcc('them@their-example.com'); + + $this->email->subject('Email Test'); + $this->email->message('Testing the email class.'); + + $this->email->send(); + + echo $this->email->print_debugger(); + +Setting Email Preferences +========================= + +There are 17 different preferences available to tailor how your email +messages are sent. You can either set them manually as described here, +or automatically via preferences stored in your config file, described +below: + +Preferences are set by passing an array of preference values to the +email initialize function. Here is an example of how you might set some +preferences:: + + $config['protocol'] = 'sendmail'; + $config['mailpath'] = '/usr/sbin/sendmail'; + $config['charset'] = 'iso-8859-1'; + $config['wordwrap'] = TRUE; + + $this->email->initialize($config); + +.. note:: Most of the preferences have default values that will be used + if you do not set them. + +Setting Email Preferences in a Config File +------------------------------------------ + +If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called the +email.php, add the $config array in that file. Then save the file at +config/email.php and it will be used automatically. You will NOT need to +use the $this->email->initialize() function if you save your preferences +in a config file. + +Email Preferences +================= + +The following is a list of all the preferences that can be set when +sending email. + +=================== ====================== ============================ ======================================================================= +Preference Default Value Options Description +=================== ====================== ============================ ======================================================================= +**useragent** CodeIgniter None The "user agent". +**protocol** mail mail, sendmail, or smtp The mail sending protocol. +**mailpath** /usr/sbin/sendmail None The server path to Sendmail. +**smtp_host** No Default None SMTP Server Address. +**smtp_user** No Default None SMTP Username. +**smtp_pass** No Default None SMTP Password. +**smtp_port** 25 None SMTP Port. +**smtp_timeout** 5 None SMTP Timeout (in seconds). +**smtp_crypto** No Default tls or ssl SMTP Encryption +**wordwrap** TRUE TRUE or FALSE (boolean) Enable word-wrap. +**wrapchars** 76 Character count to wrap at. +**mailtype** text text or html Type of mail. If you send HTML email you must send it as a complete web + page. Make sure you don't have any relative links or relative image + paths otherwise they will not work. +**charset** utf-8 Character set (utf-8, iso-8859-1, etc.). +**validate** FALSE TRUE or FALSE (boolean) Whether to validate the email address. +**priority** 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal. +**crlf** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822). +**newline** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822). +**bcc_batch_mode** FALSE TRUE or FALSE (boolean) Enable BCC Batch Mode. +**bcc_batch_size** 200 None Number of emails in each BCC batch. +=================== ====================== ============================ ======================================================================= + +Email Function Reference +======================== + +$this->email->from() +-------------------- + +Sets the email address and name of the person sending the email:: + + $this->email->from('you@example.com', 'Your Name'); + +$this->email->reply_to() +------------------------- + +Sets the reply-to address. If the information is not provided the +information in the "from" function is used. Example:: + + $this->email->reply_to('you@example.com', 'Your Name'); + +$this->email->to() +------------------ + +Sets the email address(s) of the recipient(s). Can be a single email, a +comma-delimited list or an array:: + + $this->email->to('someone@example.com'); + +:: + + $this->email->to('one@example.com, two@example.com, three@example.com'); + +:: + + $list = array('one@example.com', 'two@example.com', 'three@example.com'); + + $this->email->to($list); + +$this->email->cc() +------------------ + +Sets the CC email address(s). Just like the "to", can be a single email, +a comma-delimited list or an array. + +$this->email->bcc() +------------------- + +Sets the BCC email address(s). Just like the "to", can be a single +email, a comma-delimited list or an array. + +$this->email->subject() +----------------------- + +Sets the email subject:: + + $this->email->subject('This is my subject'); + +$this->email->message() +----------------------- + +Sets the email message body:: + + $this->email->message('This is my message'); + +$this->email->set_alt_message() +--------------------------------- + +Sets the alternative email message body:: + + $this->email->set_alt_message('This is the alternative message'); + +This is an optional message string which can be used if you send HTML +formatted email. It lets you specify an alternative message with no HTML +formatting which is added to the header string for people who do not +accept HTML email. If you do not set your own message CodeIgniter will +extract the message from your HTML email and strip the tags. + +$this->email->clear() +--------------------- + +Initializes all the email variables to an empty state. This function is +intended for use if you run the email sending function in a loop, +permitting the data to be reset between cycles. + +:: + + foreach ($list as $name => $address) + { + $this->email->clear(); + + $this->email->to($address); + $this->email->from('your@example.com'); + $this->email->subject('Here is your info '.$name); + $this->email->message('Hi '.$name.' Here is the info you requested.'); + $this->email->send(); + } + +If you set the parameter to TRUE any attachments will be cleared as +well:: + + $this->email->clear(TRUE); + +$this->email->send() +-------------------- + +The Email sending function. Returns boolean TRUE or FALSE based on +success or failure, enabling it to be used conditionally:: + + if ( ! $this->email->send()) + { + // Generate error + } + +$this->email->attach() +---------------------- + +Enables you to send an attachment. Put the file path/name in the first +parameter. Note: Use a file path, not a URL. For multiple attachments +use the function multiple times. For example:: + + $this->email->attach('/path/to/photo1.jpg'); + $this->email->attach('/path/to/photo2.jpg'); + $this->email->attach('/path/to/photo3.jpg'); + + $this->email->send(); + +$this->email->print_debugger() +------------------------------- + +Returns a string containing any server messages, the email headers, and +the email messsage. Useful for debugging. + +Overriding Word Wrapping +======================== + +If you have word wrapping enabled (recommended to comply with RFC 822) +and you have a very long link in your email it can get wrapped too, +causing it to become un-clickable by the person receiving it. +CodeIgniter lets you manually override word wrapping within part of your +message like this:: + + The text of your email that + gets wrapped normally. + + {unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap} + + More text that will be + wrapped normally. + + +Place the item you do not want word-wrapped between: {unwrap} {/unwrap} diff --git a/user_guide_src/source/libraries/encryption.rst b/user_guide_src/source/libraries/encryption.rst new file mode 100644 index 000000000..356465b21 --- /dev/null +++ b/user_guide_src/source/libraries/encryption.rst @@ -0,0 +1,183 @@ +################ +Encryption Class +################ + +The Encryption Class provides two-way data encryption. It uses a scheme +that either compiles the message using a randomly hashed bitwise XOR +encoding scheme, or is encrypted using the Mcrypt library. If Mcrypt is +not available on your server the encoded message will still provide a +reasonable degree of security for encrypted sessions or other such +"light" purposes. If Mcrypt is available, you'll be provided with a high +degree of security appropriate for storage. + +Setting your Key +================ + +A *key* is a piece of information that controls the cryptographic +process and permits an encrypted string to be decoded. In fact, the key +you chose will provide the **only** means to decode data that was +encrypted with that key, so not only must you choose the key carefully, +you must never change it if you intend use it for persistent data. + +It goes without saying that you should guard your key carefully. Should +someone gain access to your key, the data will be easily decoded. If +your server is not totally under your control it's impossible to ensure +key security so you may want to think carefully before using it for +anything that requires high security, like storing credit card numbers. + +To take maximum advantage of the encryption algorithm, your key should +be 32 characters in length (128 bits). The key should be as random a +string as you can concoct, with numbers and uppercase and lowercase +letters. Your key should **not** be a simple text string. In order to be +cryptographically secure it needs to be as random as possible. + +Your key can be either stored in your application/config/config.php, or +you can design your own storage mechanism and pass the key dynamically +when encoding/decoding. + +To save your key to your application/config/config.php, open the file +and set:: + + $config['encryption_key'] = "YOUR KEY"; + +Message Length +============== + +It's important for you to know that the encoded messages the encryption +function generates will be approximately 2.6 times longer than the +original message. For example, if you encrypt the string "my super +secret data", which is 21 characters in length, you'll end up with an +encoded string that is roughly 55 characters (we say "roughly" because +the encoded string length increments in 64 bit clusters, so it's not +exactly linear). Keep this information in mind when selecting your data +storage mechanism. Cookies, for example, can only hold 4K of +information. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Encryption class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('encrypt'); + +Once loaded, the Encrypt library object will be available using: +$this->encrypt + +$this->encrypt->encode() +======================== + +Performs the data encryption and returns it as a string. Example:: + + $msg = 'My secret message'; + + $encrypted_string = $this->encrypt->encode($msg); + + +You can optionally pass your encryption key via the second parameter if +you don't want to use the one in your config file:: + + $msg = 'My secret message'; + $key = 'super-secret-key'; + + $encrypted_string = $this->encrypt->encode($msg, $key); + +$this->encrypt->decode() +======================== + +Decrypts an encoded string. Example:: + + $encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84'; + + $plaintext_string = $this->encrypt->decode($encrypted_string); + +You can optionally pass your encryption key via the second parameter if +you don't want to use the one in your config file:: + + $msg = 'My secret message'; + $key = 'super-secret-key'; + + $encrypted_string = $this->encrypt->decode($msg, $key); + +$this->encrypt->set_cipher(); +============================== + +Permits you to set an Mcrypt cipher. By default it uses +MCRYPT_RIJNDAEL_256. Example:: + + $this->encrypt->set_cipher(MCRYPT_BLOWFISH); + +Please visit php.net for a list of `available +ciphers <http://php.net/mcrypt>`_. + +If you'd like to manually test whether your server supports Mcrypt you +can use:: + + echo ( ! function_exists('mcrypt_encrypt')) ? 'Nope' : 'Yup'; + +$this->encrypt->set_mode(); +============================ + +Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. +Example:: + + $this->encrypt->set_mode(MCRYPT_MODE_CFB); + +Please visit php.net for a list of `available +modes <http://php.net/mcrypt>`_. + +$this->encrypt->sha1(); +======================= + +SHA1 encoding function. Provide a string and it will return a 160 bit +one way hash. Note: SHA1, just like MD5 is non-decodable. Example:: + + $hash = $this->encrypt->sha1('Some string'); + +Many PHP installations have SHA1 support by default so if all you need +is to encode a hash it's simpler to use the native function:: + + $hash = sha1('Some string'); + +If your server does not support SHA1 you can use the provided function. + +$this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = ''); +========================================================================================== + +Enables you to re-encode data that was originally encrypted with +CodeIgniter 1.x to be compatible with the Encryption library in +CodeIgniter 2.x. It is only necessary to use this method if you have +encrypted data stored permanently such as in a file or database and are +on a server that supports Mcrypt. "Light" use encryption such as +encrypted session data or transitory encrypted flashdata require no +intervention on your part. However, existing encrypted Sessions will be +destroyed since data encrypted prior to 2.x will not be decoded. + +..important:: **Why only a method to re-encode the data instead of maintaining legacy +methods for both encoding and decoding?** The algorithms in the +Encryption library have improved in CodeIgniter 2.x both for performance +and security, and we do not wish to encourage continued use of the older +methods. You can of course extend the Encryption library if you wish and +replace the new methods with the old and retain seamless compatibility +with CodeIgniter 1.x encrypted data, but this a decision that a +developer should make cautiously and deliberately, if at all. + +:: + + $new_data = $this->encrypt->encode_from_legacy($old_encrypted_string); + +Parameter +Default +Description +**$orig_data** +n/a +The original encrypted data from CodeIgniter 1.x's Encryption library +**$legacy_mode** +MCRYPT_MODE_ECB +The Mcrypt mode that was used to generate the original encrypted data. +CodeIgniter 1.x's default was MCRYPT_MODE_ECB, and it will assume that +to be the case unless overridden by this parameter. +**$key** +n/a +The encryption key. This it typically specified in your config file as +outlined above. diff --git a/user_guide_src/source/libraries/file_uploading.rst b/user_guide_src/source/libraries/file_uploading.rst new file mode 100644 index 000000000..90efca95d --- /dev/null +++ b/user_guide_src/source/libraries/file_uploading.rst @@ -0,0 +1,327 @@ +#################### +File Uploading Class +#################### + +CodeIgniter's File Uploading Class permits files to be uploaded. You can +set various preferences, restricting the type and size of the files. + +*********** +The Process +*********** + +Uploading a file involves the following general process: + +- An upload form is displayed, allowing a user to select a file and + upload it. +- When the form is submitted, the file is uploaded to the destination + you specify. +- Along the way, the file is validated to make sure it is allowed to be + uploaded based on the preferences you set. +- Once uploaded, the user will be shown a success message. + +To demonstrate this process here is brief tutorial. Afterward you'll +find reference information. + +Creating the Upload Form +======================== + +Using a text editor, create a form called upload_form.php. In it, place +this code and save it to your applications/views/ folder:: + + <html> + <head> + <title>Upload Form</title> + </head> + <body> + + <?php echo $error;?> + + <?php echo form_open_multipart('upload/do_upload');?> + + <input type="file" name="userfile" size="20" /> + + <br /><br /> + + <input type="submit" value="upload" /> + + </form> + + </body> + </html> + +You'll notice we are using a form helper to create the opening form tag. +File uploads require a multipart form, so the helper creates the proper +syntax for you. You'll also notice we have an $error variable. This is +so we can show error messages in the event the user does something +wrong. + +The Success Page +================ + +Using a text editor, create a form called upload_success.php. In it, +place this code and save it to your applications/views/ folder:: + + <html> + <head> + <title>Upload Form</title> + </head> + <body> + + <h3>Your file was successfully uploaded!</h3> + + <ul> + <?php foreach ($upload_data as $item => $value):?> + <li><?php echo $item;?>: <?php echo $value;?></li> + <?php endforeach; ?> + </ul> + + <p><?php echo anchor('upload', 'Upload Another File!'); ?></p> + + </body> + </html> + +The Controller +============== + +Using a text editor, create a controller called upload.php. In it, place +this code and save it to your applications/controllers/ folder:: + + <?php + + class Upload extends CI_Controller { + + function __construct() + { + parent::__construct(); + $this->load->helper(array('form', 'url')); + } + + function index() + { + $this->load->view('upload_form', array('error' => ' ' )); + } + + function do_upload() + { + $config['upload_path'] = './uploads/'; + $config['allowed_types'] = 'gif|jpg|png'; + $config['max_size'] = '100'; + $config['max_width'] = '1024'; + $config['max_height'] = '768'; + + $this->load->library('upload', $config); + + if ( ! $this->upload->do_upload()) + { + $error = array('error' => $this->upload->display_errors()); + + $this->load->view('upload_form', $error); + } + else + { + $data = array('upload_data' => $this->upload->data()); + + $this->load->view('upload_success', $data); + } + } + } + ?> + +The Upload Folder +================= + +You'll need a destination folder for your uploaded images. Create a +folder at the root of your CodeIgniter installation called uploads and +set its file permissions to 777. + +Try it! +======= + +To try your form, visit your site using a URL similar to this one:: + + example.com/index.php/upload/ + +You should see an upload form. Try uploading an image file (either a +jpg, gif, or png). If the path in your controller is correct it should +work. + +*************** +Reference Guide +*************** + +Initializing the Upload Class +============================= + +Like most other classes in CodeIgniter, the Upload class is initialized +in your controller using the $this->load->library function:: + + $this->load->library('upload'); + +Once the Upload class is loaded, the object will be available using: +$this->upload + +Setting Preferences +=================== + +Similar to other libraries, you'll control what is allowed to be upload +based on your preferences. In the controller you built above you set the +following preferences:: + + $config['upload_path'] = './uploads/'; + $config['allowed_types'] = 'gif|jpg|png'; + $config['max_size'] = '100'; + $config['max_width'] = '1024'; + $config['max_height'] = '768'; + + $this->load->library('upload', $config); + + // Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class: + $this->upload->initialize($config); + +The above preferences should be fairly self-explanatory. Below is a +table describing all available preferences. + +Preferences +=========== + +The following preferences are available. The default value indicates +what will be used if you do not specify that preference. + +============================ ================= ======================= ====================================================================== +Preference Default Value Options Description +============================ ================= ======================= ====================================================================== +**upload_path** None None The path to the folder where the upload should be placed. The folder + must be writable and the path can be absolute or relative. +**allowed_types** None None The mime types corresponding to the types of files you allow to be + uploaded. Usually the file extension can be used as the mime type. + Separate multiple types with a pipe. +**file_name** None Desired file name If set CodeIgniter will rename the uploaded file to this name. The + extension provided in the file name must also be an allowed file type. +**overwrite** FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are + uploading exists, it will be overwritten. If set to false, a number will + be appended to the filename if another with the same name exists. +**max_size** 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no + limit. Note: Most PHP installations have their own limit, as specified + in the php.ini file. Usually 2 MB (or 2048 KB) by default. +**max_width** 0 None The maximum width (in pixels) that the file can be. Set to zero for no + limit. +**max_height** 0 None The maximum height (in pixels) that the file can be. Set to zero for no + limit. +**max_filename** 0 None The maximum length that a file name can be. Set to zero for no limit. +**max_filename_increment** 100 None When overwrite is set to FALSE, use this to set the maximum filename + increment for CodeIgniter to append to the filename. +**encrypt_name** FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted + string. This can be useful if you would like the file saved with a name + that can not be discerned by the person uploading it. +**remove_spaces** TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to + underscores. This is recommended. +============================ ================= ======================= ====================================================================== + +Setting preferences in a config file +==================================== + +If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called the +upload.php, add the $config array in that file. Then save the file in: +config/upload.php and it will be used automatically. You will NOT need +to use the $this->upload->initialize function if you save your +preferences in a config file. + +****************** +Function Reference +****************** + +The following functions are available + +$this->upload->do_upload() +=========================== + +Performs the upload based on the preferences you've set. Note: By +default the upload routine expects the file to come from a form field +called userfile, and the form must be a "multipart type:: + + <form method="post" action="some_action" enctype="multipart/form-data" /> + +If you would like to set your own field name simply pass its value to +the do_upload function:: + + $field_name = "some_field_name"; + $this->upload->do_upload($field_name); + +$this->upload->display_errors() +================================ + +Retrieves any error messages if the do_upload() function returned +false. The function does not echo automatically, it returns the data so +you can assign it however you need. + +Formatting Errors +***************** + +By default the above function wraps any errors within <p> tags. You can +set your own delimiters like this:: + + $this->upload->display_errors('<p>', '</p>'); + +$this->upload->data() +===================== + +This is a helper function that returns an array containing all of the +data related to the file you uploaded. Here is the array prototype:: + + Array + ( + [file_name] => mypic.jpg + [file_type] => image/jpeg + [file_path] => /path/to/your/upload/ + [full_path] => /path/to/your/upload/jpg.jpg + [raw_name] => mypic + [orig_name] => mypic.jpg + [client_name] => mypic.jpg + [file_ext] => .jpg + [file_size] => 22.2 + [is_image] => 1 + [image_width] => 800 + [image_height] => 600 + [image_type] => jpeg + [image_size_str] => width="800" height="200" + ) + +Explanation +*********** + +Here is an explanation of the above array items. + +Item +Description +**file_name** +The name of the file that was uploaded including the file extension. +**file_type** +The file's Mime type +**file_path** +The absolute server path to the file +**full_path** +The absolute server path including the file name +**raw_name** +The file name without the extension +**orig_name** +The original file name. This is only useful if you use the encrypted +name option. +**client_name** +The file name as supplied by the client user agent, prior to any file +name preparation or incrementing. +**file_ext** +The file extension with period +**file_size** +The file size in kilobytes +**is_image** +Whether the file is an image or not. 1 = image. 0 = not. +**image_width** +Image width. +**image_height** +Image height +**image_type** +Image type. Typically the file extension without the period. +**image_size_str** +A string containing the width and height. Useful to put into an image +tag. diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst new file mode 100644 index 000000000..7f5ba8653 --- /dev/null +++ b/user_guide_src/source/libraries/form_validation.rst @@ -0,0 +1,1009 @@ +############### +Form Validation +############### + +CodeIgniter provides a comprehensive form validation and data prepping +class that helps minimize the amount of code you'll write. + +- `Overview <#overview>`_ +- `Form Validation Tutorial <#tutorial>`_ + + - `The Form <#theform>`_ + - `The Success Page <#thesuccesspage>`_ + - `The Controller <#thecontroller>`_ + - `Setting Validation Rules <#validationrules>`_ + - `Setting Validation Rules Using an + Array <#validationrulesasarray>`_ + - `Cascading Rules <#cascadingrules>`_ + - `Prepping Data <#preppingdata>`_ + - `Re-populating the Form <#repopulatingform>`_ + - `Callbacks <#callbacks>`_ + - `Setting Error Messages <#settingerrors>`_ + - `Changing the Error Delimiters <#errordelimiters>`_ + - `Translating Field Names <#translatingfn>`_ + - `Showing Errors Individually <#individualerrors>`_ + - `Saving Sets of Validation Rules to a Config + File <#savingtoconfig>`_ + - `Using Arrays as Field Names <#arraysasfields>`_ + +- `Rule Reference <#rulereference>`_ +- `Prepping Reference <#preppingreference>`_ +- `Function Reference <#functionreference>`_ +- `Helper Reference <#helperreference>`_ + +******** +Overview +******** + +Before explaining CodeIgniter's approach to data validation, let's +describe the ideal scenario: + +#. A form is displayed. +#. You fill it in and submit it. +#. If you submitted something invalid, or perhaps missed a required + item, the form is redisplayed containing your data along with an + error message describing the problem. +#. This process continues until you have submitted a valid form. + +On the receiving end, the script must: + +#. Check for required data. +#. Verify that the data is of the correct type, and meets the correct + criteria. For example, if a username is submitted it must be + validated to contain only permitted characters. It must be of a + minimum length, and not exceed a maximum length. The username can't + be someone else's existing username, or perhaps even a reserved word. + Etc. +#. Sanitize the data for security. +#. Pre-format the data if needed (Does the data need to be trimmed? HTML + encoded? Etc.) +#. Prep the data for insertion in the database. + +Although there is nothing terribly complex about the above process, it +usually requires a significant amount of code, and to display error +messages, various control structures are usually placed within the form +HTML. Form validation, while simple to create, is generally very messy +and tedious to implement. + +************************ +Form Validation Tutorial +************************ + +What follows is a "hands on" tutorial for implementing CodeIgniters Form +Validation. + +In order to implement form validation you'll need three things: + +#. A :doc:`View <../general/views>` file containing a form. +#. A View file containing a "success" message to be displayed upon + successful submission. +#. A :doc:`controller <../general/controllers>` function to receive and + process the submitted data. + +Let's create those three things, using a member sign-up form as the +example. + +The Form +======== + +Using a text editor, create a form called myform.php. In it, place this +code and save it to your applications/views/ folder:: + + <html> + <head> + <title>My Form</title> + </head> + <body> + + <?php echo validation_errors(); ?> + + <?php echo form_open('form'); ?> + + <h5>Username</h5> + <input type="text" name="username" value="" size="50" /> + + <h5>Password</h5> + <input type="text" name="password" value="" size="50" /> + + <h5>Password Confirm</h5> + <input type="text" name="passconf" value="" size="50" /> + + <h5>Email Address</h5> + <input type="text" name="email" value="" size="50" /> + + <div><input type="submit" value="Submit" /></div> + + </form> + + </body> + </html> + +The Success Page +================ + +Using a text editor, create a form called formsuccess.php. In it, place +this code and save it to your applications/views/ folder:: + + <html> + <head> + <title>My Form</title> + </head> + <body> + + <h3>Your form was successfully submitted!</h3> + + <p><?php echo anchor('form', 'Try it again!'); ?></p> + + </body> + </html> + +The Controller +============== + +Using a text editor, create a controller called form.php. In it, place +this code and save it to your applications/controllers/ folder:: + + <?php + + class Form extends CI_Controller { + + function index() + { + $this->load->helper(array('form', 'url')); + + $this->load->library('form_validation'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } + } + ?> + +Try it! +======= + +To try your form, visit your site using a URL similar to this one:: + + example.com/index.php/form/ + +If you submit the form you should simply see the form reload. That's +because you haven't set up any validation rules yet. + +**Since you haven't told the Form Validation class to validate anything +yet, it returns FALSE (boolean false) by default. The run() function +only returns TRUE if it has successfully applied your rules without any +of them failing.** + +Explanation +=========== + +You'll notice several things about the above pages: + +The form (myform.php) is a standard web form with a couple exceptions: + +#. It uses a form helper to create the form opening. Technically, this + isn't necessary. You could create the form using standard HTML. + However, the benefit of using the helper is that it generates the + action URL for you, based on the URL in your config file. This makes + your application more portable in the event your URLs change. +#. At the top of the form you'll notice the following function call: + :: + + <?php echo validation_errors(); ?> + + This function will return any error messages sent back by the + validator. If there are no messages it returns an empty string. + +The controller (form.php) has one function: index(). This function +initializes the validation class and loads the form helper and URL +helper used by your view files. It also runs the validation routine. +Based on whether the validation was successful it either presents the +form or the success page. + +Setting Validation Rules +======================== + +CodeIgniter lets you set as many validation rules as you need for a +given field, cascading them in order, and it even lets you prep and +pre-process the field data at the same time. To set validation rules you +will use the set_rules() function:: + + $this->form_validation->set_rules(); + +The above function takes **three** parameters as input: + +#. The field name - the exact name you've given the form field. +#. A "human" name for this field, which will be inserted into the error + message. For example, if your field is named "user" you might give it + a human name of "Username". +#. The validation rules for this form field. + +.. note:: If you would like the field + name to be stored in a language file, please see `Translating Field + Names <#translatingfn>`_. + +Here is an example. In your controller (form.php), add this code just +below the validation initialization function:: + + $this->form_validation->set_rules('username', 'Username', 'required'); + $this->form_validation->set_rules('password', 'Password', 'required'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); + $this->form_validation->set_rules('email', 'Email', 'required'); + +Your controller should now look like this:: + + <?php + + class Form extends CI_Controller { + + function index() + { + $this->load->helper(array('form', 'url')); + + $this->load->library('form_validation'); + + $this->form_validation->set_rules('username', 'Username', 'required'); + $this->form_validation->set_rules('password', 'Password', 'required'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); + $this->form_validation->set_rules('email', 'Email', 'required'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } + } + ?> + +Now submit the form with the fields blank and you should see the error +messages. If you submit the form with all the fields populated you'll +see your success page. + +.. note:: The form fields are not yet being re-populated with the data + when there is an error. We'll get to that shortly. + +Setting Rules Using an Array +============================ + +Before moving on it should be noted that the rule setting function can +be passed an array if you prefer to set all your rules in one action. If +you use this approach you must name your array keys as indicated:: + + $config = array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); + + $this->form_validation->set_rules($config); + +Cascading Rules +=============== + +CodeIgniter lets you pipe multiple rules together. Let's try it. Change +your rules in the third parameter of rule setting function, like this:: + + $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]'); + $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); + $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); + + +The above code sets the following rules: + +#. The username field be no shorter than 5 characters and no longer than + 12. +#. The password field must match the password confirmation field. +#. The email field must contain a valid email address. + +Give it a try! Submit your form without the proper data and you'll see +new error messages that correspond to your new rules. There are numerous +rules available which you can read about in the validation reference. + +Prepping Data +============= + +In addition to the validation functions like the ones we used above, you +can also prep your data in various ways. For example, you can set up +rules like this:: + + $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean'); + $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required'); + $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); + +In the above example, we are "trimming" the fields, converting the +password to MD5, and running the username through the "xss_clean" +function, which removes malicious data. + +**Any native PHP function that accepts one parameter can be used as a +rule, like htmlspecialchars, trim, MD5, etc.** + +.. note:: You will generally want to use the prepping functions + **after** the validation rules so if there is an error, the original + data will be shown in the form. + +Re-populating the form +====================== + +Thus far we have only been dealing with errors. It's time to repopulate +the form field with the submitted data. CodeIgniter offers several +helper functions that permit you to do this. The one you will use most +commonly is:: + + set_value('field name') + +Open your myform.php view file and update the **value** in each field +using the set_value() function: + +**Don't forget to include each field name in the set_value() +functions!** + +:: + + <html> + <head> + <title>My Form</title> + </head> + <body> + + <?php echo validation_errors(); ?> + + <?php echo form_open('form'); ?> + + <h5>Username</h5> + <input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> + + <h5>Password</h5> + <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> + + <h5>Password Confirm</h5> + <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> + + <h5>Email Address</h5> + <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> + + <div><input type="submit" value="Submit" /></div> + + </form> + + </body> + </html> + +Now reload your page and submit the form so that it triggers an error. +Your form fields should now be re-populated + +.. note:: The `Function Reference <#functionreference>`_ section below + contains functions that permit you to re-populate <select> menus, radio + buttons, and checkboxes. + +**Important Note:** If you use an array as the name of a form field, you +must supply it as an array to the function. Example:: + + <input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" /> + +For more info please see the `Using Arrays as Field +Names <#arraysasfields>`_ section below. + +Callbacks: Your own Validation Functions +======================================== + +The validation system supports callbacks to your own validation +functions. This permits you to extend the validation class to meet your +needs. For example, if you need to run a database query to see if the +user is choosing a unique username, you can create a callback function +that does that. Let's create a example of this. + +In your controller, change the "username" rule to this:: + + $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); + +Then add a new function called username_check to your controller. +Here's how your controller should now look:: + + <?php + + class Form extends CI_Controller { + + public function index() + { + $this->load->helper(array('form', 'url')); + + $this->load->library('form_validation'); + + $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); + $this->form_validation->set_rules('password', 'Password', 'required'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); + $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } + + public function username_check($str) + { + if ($str == 'test') + { + $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); + return FALSE; + } + else + { + return TRUE; + } + } + + } + ?> + +Reload your form and submit it with the word "test" as the username. You +can see that the form field data was passed to your callback function +for you to process. + +To invoke a callback just put the function name in a rule, with +"callback\_" as the rule **prefix**. If you need to receive an extra +parameter in your callback function, just add it normally after the +function name between square brackets, as in: "callback_foo**[bar]**", +then it will be passed as the second argument of your callback function. + +.. note:: You can also process the form data that is passed to your + callback and return it. If your callback returns anything other than a + boolean TRUE/FALSE it is assumed that the data is your newly processed + form data. + +Setting Error Messages +====================== + +All of the native error messages are located in the following language +file: language/english/form_validation_lang.php + +To set your own custom message you can either edit that file, or use the +following function:: + + $this->form_validation->set_message('rule', 'Error Message'); + +Where rule corresponds to the name of a particular rule, and Error +Message is the text you would like displayed. + +If you include %s in your error string, it will be replaced with the +"human" name you used for your field when you set your rules. + +In the "callback" example above, the error message was set by passing +the name of the function:: + + $this->form_validation->set_message('username_check') + +You can also override any error message found in the language file. For +example, to change the message for the "required" rule you will do this:: + + $this->form_validation->set_message('required', 'Your custom message here'); + +Translating Field Names +======================= + +If you would like to store the "human" name you passed to the +set_rules() function in a language file, and therefore make the name +able to be translated, here's how: + +First, prefix your "human" name with lang:, as in this example:: + + $this->form_validation->set_rules('first_name', 'lang:first_name', 'required'); + +Then, store the name in one of your language file arrays (without the +prefix):: + + $lang['first_name'] = 'First Name'; + +.. note:: If you store your array item in a language file that is not + loaded automatically by CI, you'll need to remember to load it in your + controller using:: + + $this->lang->load('file_name'); + +See the :doc:`Language Class <language>` page for more info regarding +language files. + +Changing the Error Delimiters +============================= + +By default, the Form Validation class adds a paragraph tag (<p>) around +each error message shown. You can either change these delimiters +globally or individually. + +#. **Changing delimiters Globally** + To globally change the error delimiters, in your controller function, + just after loading the Form Validation class, add this:: + + $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); + + In this example, we've switched to using div tags. + +#. **Changing delimiters Individually** + Each of the two error generating functions shown in this tutorial can + be supplied their own delimiters as follows:: + + <?php echo form_error('field name', '<div class="error">', '</div>'); ?> + + Or:: + + <?php echo validation_errors('<div class="error">', '</div>'); ?> + + +Showing Errors Individually +=========================== + +If you prefer to show an error message next to each form field, rather +than as a list, you can use the form_error() function. + +Try it! Change your form so that it looks like this:: + + <h5>Username</h5> + <?php echo form_error('username'); ?> + <input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> + + <h5>Password</h5> + <?php echo form_error('password'); ?> + <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> + + <h5>Password Confirm</h5> + <?php echo form_error('passconf'); ?> + <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> + + <h5>Email Address</h5> + <?php echo form_error('email'); ?> + <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> + +If there are no errors, nothing will be shown. If there is an error, the +message will appear. + +**Important Note:** If you use an array as the name of a form field, you +must supply it as an array to the function. Example:: + + <?php echo form_error('options[size]'); ?> + <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> + +For more info please see the `Using Arrays as Field +Names <#arraysasfields>`_ section below. + +************************************************ +Saving Sets of Validation Rules to a Config File +************************************************ + +A nice feature of the Form Validation class is that it permits you to +store all your validation rules for your entire application in a config +file. You can organize these rules into "groups". These groups can +either be loaded automatically when a matching controller/function is +called, or you can manually call each set as needed. + +How to save your rules +====================== + +To store your validation rules, simply create a file named +form_validation.php in your application/config/ folder. In that file +you will place an array named $config with your rules. As shown earlier, +the validation array will have this prototype:: + + $config = array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); + +Your validation rule file will be loaded automatically and used when you +call the run() function. + +Please note that you MUST name your array $config. + +Creating Sets of Rules +====================== + +In order to organize your rules into "sets" requires that you place them +into "sub arrays". Consider the following example, showing two sets of +rules. We've arbitrarily called these two rules "signup" and "email". +You can name your rules anything you want:: + + $config = array( + 'signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'PasswordConfirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ), + 'email' => array( + array( + 'field' => 'emailaddress', + 'label' => 'EmailAddress', + 'rules' => 'required|valid_email' + ), + array( + 'field' => 'name', + 'label' => 'Name', + 'rules' => 'required|alpha' + ), + array( + 'field' => 'title', + 'label' => 'Title', + 'rules' => 'required' + ), + array( + 'field' => 'message', + 'label' => 'MessageBody', + 'rules' => 'required' + ) + ) + ); + +Calling a Specific Rule Group +============================= + +In order to call a specific group you will pass its name to the run() +function. For example, to call the signup rule you will do this:: + + if ($this->form_validation->run('signup') == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + +Associating a Controller Function with a Rule Group +=================================================== + +An alternate (and more automatic) method of calling a rule group is to +name it according to the controller class/function you intend to use it +with. For example, let's say you have a controller named Member and a +function named signup. Here's what your class might look like:: + + <?php + + class Member extends CI_Controller { + + function signup() + { + $this->load->library('form_validation'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } + } + ?> + +In your validation config file, you will name your rule group +member/signup:: + + $config = array( + 'member/signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'PasswordConfirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ) + ); + +When a rule group is named identically to a controller class/function it +will be used automatically when the run() function is invoked from that +class/function. + +*************************** +Using Arrays as Field Names +*************************** + +The Form Validation class supports the use of arrays as field names. +Consider this example:: + + <input type="text" name="options[]" value="" size="50" /> + +If you do use an array as a field name, you must use the EXACT array +name in the `Helper Functions <#helperreference>`_ that require the +field name, and as your Validation Rule field name. + +For example, to set a rule for the above field you would use:: + + $this->form_validation->set_rules('options[]', 'Options', 'required'); + +Or, to show an error for the above field you would use:: + + <?php echo form_error('options[]'); ?> + +Or to re-populate the field you would use:: + + <input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" /> + +You can use multidimensional arrays as field names as well. For example:: + + <input type="text" name="options[size]" value="" size="50" /> + +Or even:: + + <input type="text" name="sports[nba][basketball]" value="" size="50" /> + +As with our first example, you must use the exact array name in the +helper functions:: + + <?php echo form_error('sports[nba][basketball]'); ?> + +If you are using checkboxes (or other fields) that have multiple +options, don't forget to leave an empty bracket after each option, so +that all selections will be added to the POST array:: + + <input type="checkbox" name="options[]" value="red" /> + <input type="checkbox" name="options[]" value="blue" /> + <input type="checkbox" name="options[]" value="green" /> + +Or if you use a multidimensional array:: + + <input type="checkbox" name="options[color][]" value="red" /> + <input type="checkbox" name="options[color][]" value="blue" /> + <input type="checkbox" name="options[color][]" value="green" /> + +When you use a helper function you'll include the bracket as well:: + + <?php echo form_error('options[color][]'); ?> + + +************** +Rule Reference +************** + +The following is a list of all the native rules that are available to +use: + +.. table:: +======================= ========== ============================================================================================= ======================= +Rule Parameter Description Example +======================= ========== ============================================================================================= ======================= +**required** No Returns FALSE if the form element is empty. +**matches** Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item] +**is_unique** Yes Returns FALSE if the form element is not unique to the is_unique[table.field] + table and field name in the parameter. is_unique[table.field] +**max_length** Yes Returns FALSE if the form element is longer then the parameter value. max_length[12] +**exact_length** Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8] +**greater_than** Yes Returns FALSE if the form element is less than the parameter value or not numeric. greater_than[8] +**less_than** Yes Returns FALSE if the form element is greater than the parameter value or not numeric. less_than[8] +**alpha** No Returns FALSE if the form element contains anything other than alphabetical characters. +**alpha_numeric** No Returns FALSE if the form element contains anything other than alpha-numeric characters. +**alpha_dash** No Returns FALSE if the form element contains anything other than alpha-numeric characters, + underscores or dashes. +**numeric** No Returns FALSE if the form element contains anything other than numeric characters. +**integer** No Returns FALSE if the form element contains anything other than an integer. +**decimal** Yes Returns FALSE if the form element is not exactly the parameter value. +**is_natural** No Returns FALSE if the form element contains anything other than a natural number: + 0, 1, 2, 3, etc. +**is_natural_no_zero** No Returns FALSE if the form element contains anything other than a natural + number, but not zero: 1, 2, 3, etc. +**is_unique** Yes Returns FALSE if the form element is not unique in a database table. is_unique[table.field] +**valid_email** No Returns FALSE if the form element does not contain a valid email address. +**valid_emails** No Returns FALSE if any value provided in a comma separated list is not a valid email. +**valid_ip** No Returns FALSE if the supplied IP is not valid. +**valid_base64** No Returns FALSE if the supplied string contains anything other than valid Base64 characters. +======================= ========== ============================================================================================= ======================= + +.. note:: These rules can also be called as discrete functions. For + example:: + + $this->form_validation->required($string); + +.. note:: You can also use any native PHP functions that permit one + parameter. + +****************** +Prepping Reference +****************** + +The following is a list of all the prepping functions that are available +to use: + +==================== ========= =================================================================================================== +Name Parameter Description +==================== ========= =================================================================================================== +**xss_clean** No Runs the data through the XSS filtering function, described in the :doc:`Input Class <input>` page. +**prep_for_form** No Converts special characters so that HTML data can be shown in a form field without breaking it. +**prep_url** No Adds "http://" to URLs if missing. +**strip_image_tags** No Strips the HTML from image tags leaving the raw URL. +**encode_php_tags** No Converts PHP tags to entities. +==================== ========= =================================================================================================== + +.. note:: You can also use any native PHP functions that permit one + parameter, like trim, htmlspecialchars, urldecode, etc. + +****************** +Function Reference +****************** + +The following functions are intended for use in your controller +functions. + +$this->form_validation->set_rules(); +====================================== + +Permits you to set validation rules, as described in the tutorial +sections above: + +- `Setting Validation Rules <#validationrules>`_ +- `Saving Groups of Validation Rules to a Config + File <#savingtoconfig>`_ + +$this->form_validation->run(); +=============================== + +Runs the validation routines. Returns boolean TRUE on success and FALSE +on failure. You can optionally pass the name of the validation group via +the function, as described in: `Saving Groups of Validation Rules to a +Config File <#savingtoconfig>`_. + +$this->form_validation->set_message(); +======================================== + +Permits you to set custom error messages. See `Setting Error +Messages <#settingerrors>`_ above. + +**************** +Helper Reference +**************** + +The following helper functions are available for use in the view files +containing your forms. Note that these are procedural functions, so they +**do not** require you to prepend them with $this->form_validation. + +form_error() +============= + +Shows an individual error message associated with the field name +supplied to the function. Example:: + + <?php echo form_error('username'); ?> + +The error delimiters can be optionally specified. See the `Changing the +Error Delimiters <#errordelimiters>`_ section above. + +validation_errors() +==================== + +Shows all error messages as a string: Example:: + + <?php echo validation_errors(); ?> + +The error delimiters can be optionally specified. See the `Changing the +Error Delimiters <#errordelimiters>`_ section above. + +set_value() +============ + +Permits you to set the value of an input form or textarea. You must +supply the field name via the first parameter of the function. The +second (optional) parameter allows you to set a default value for the +form. Example:: + + <input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" /> + +The above form will show "0" when loaded for the first time. + +set_select() +============= + +If you use a <select> menu, this function permits you to display the +menu item that was selected. The first parameter must contain the name +of the select menu, the second parameter must contain the value of each +item, and the third (optional) parameter lets you set an item as the +default (use boolean TRUE/FALSE). + +Example:: + + <select name="myselect"> + <option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option> + <option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option> + <option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option> + </select> + +set_checkbox() +=============== + +Permits you to display a checkbox in the state it was submitted. The +first parameter must contain the name of the checkbox, the second +parameter must contain its value, and the third (optional) parameter +lets you set an item as the default (use boolean TRUE/FALSE). Example:: + + <input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox('mycheck[]', '1'); ?> /> + <input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> /> + +set_radio() +============ + +Permits you to display radio buttons in the state they were submitted. +This function is identical to the **set_checkbox()** function above. + +:: + + <input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> /> + <input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> /> + diff --git a/user_guide_src/source/libraries/ftp.rst b/user_guide_src/source/libraries/ftp.rst new file mode 100644 index 000000000..20b11a5c8 --- /dev/null +++ b/user_guide_src/source/libraries/ftp.rst @@ -0,0 +1,250 @@ +######### +FTP Class +######### + +CodeIgniter's FTP Class permits files to be transfered to a remote +server. Remote files can also be moved, renamed, and deleted. The FTP +class also includes a "mirroring" function that permits an entire local +directory to be recreated remotely via FTP. + +.. note:: SFTP and SSL FTP protocols are not supported, only standard + FTP. + +********************** +Initializing the Class +********************** + +Like most other classes in CodeIgniter, the FTP class is initialized in +your controller using the $this->load->library function:: + + $this->load->library('ftp'); + +Once loaded, the FTP object will be available using: $this->ftp + +Usage Examples +============== + +In this example a connection is opened to the FTP server, and a local +file is read and uploaded in ASCII mode. The file permissions are set to +755. Note: Setting permissions requires PHP 5. + +:: + + $this->load->library('ftp'); + + $config['hostname'] = 'ftp.example.com'; + $config['username'] = 'your-username'; + $config['password'] = 'your-password'; + $config['debug'] = TRUE; + + $this->ftp->connect($config); + + $this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775); + + $this->ftp->close(); + +In this example a list of files is retrieved from the server. + +:: + + $this->load->library('ftp'); + + $config['hostname'] = 'ftp.example.com'; + $config['username'] = 'your-username'; + $config['password'] = 'your-password'; + $config['debug'] = TRUE; + + $this->ftp->connect($config); + + $list = $this->ftp->list_files('/public_html/'); + + print_r($list); + + $this->ftp->close(); + +In this example a local directory is mirrored on the server. + +:: + + $this->load->library('ftp'); + + $config['hostname'] = 'ftp.example.com'; + $config['username'] = 'your-username'; + $config['password'] = 'your-password'; + $config['debug'] = TRUE; + + $this->ftp->connect($config); + + $this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/'); + + $this->ftp->close(); + +****************** +Function Reference +****************** + +$this->ftp->connect() +===================== + +Connects and logs into to the FTP server. Connection preferences are set +by passing an array to the function, or you can store them in a config +file. + +Here is an example showing how you set preferences manually:: + + $this->load->library('ftp'); + + $config['hostname'] = 'ftp.example.com'; + $config['username'] = 'your-username'; + $config['password'] = 'your-password'; + $config['port'] = 21; + $config['passive'] = FALSE; + $config['debug'] = TRUE; + + $this->ftp->connect($config); + +Setting FTP Preferences in a Config File +**************************************** + +If you prefer you can store your FTP preferences in a config file. +Simply create a new file called the ftp.php, add the $config array in +that file. Then save the file at config/ftp.php and it will be used +automatically. + +Available connection options +**************************** + +- **hostname** - the FTP hostname. Usually something like: + ftp.example.com +- **username** - the FTP username. +- **password** - the FTP password. +- **port** - The port number. Set to 21 by default. +- **debug** - TRUE/FALSE (boolean). Whether to enable debugging to + display error messages. +- **passive** - TRUE/FALSE (boolean). Whether to use passive mode. + Passive is set automatically by default. + +$this->ftp->upload() +==================== + +Uploads a file to your server. You must supply the local path and the +remote path, and you can optionally set the mode and permissions. +Example:: + + $this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775); + +**Mode options are:** ascii, binary, and auto (the default). If auto is +used it will base the mode on the file extension of the source file. + +Permissions are available if you are running PHP 5 and can be passed as +an octal value in the fourth parameter. + +$this->ftp->download() +====================== + +Downloads a file from your server. You must supply the remote path and +the local path, and you can optionally set the mode. Example:: + + $this->ftp->download('/public_html/myfile.html', '/local/path/to/myfile.html', 'ascii'); + +**Mode options are:** ascii, binary, and auto (the default). If auto is +used it will base the mode on the file extension of the source file. + +Returns FALSE if the download does not execute successfully (including +if PHP does not have permission to write the local file) + +$this->ftp->rename() +==================== + +Permits you to rename a file. Supply the source file name/path and the +new file name/path. + +:: + + // Renames green.html to blue.html + $this->ftp->rename('/public_html/foo/green.html', '/public_html/foo/blue.html'); + +$this->ftp->move() +================== + +Lets you move a file. Supply the source and destination paths:: + + // Moves blog.html from "joe" to "fred" + $this->ftp->move('/public_html/joe/blog.html', '/public_html/fred/blog.html'); + +Note: if the destination file name is different the file will be +renamed. + +$this->ftp->delete_file() +========================== + +Lets you delete a file. Supply the source path with the file name. + +:: + + $this->ftp->delete_file('/public_html/joe/blog.html'); + +$this->ftp->delete_dir() +========================= + +Lets you delete a directory and everything it contains. Supply the +source path to the directory with a trailing slash. + +**Important** Be VERY careful with this function. It will recursively +delete **everything** within the supplied path, including sub-folders +and all files. Make absolutely sure your path is correct. Try using the +list_files() function first to verify that your path is correct. + +:: + + $this->ftp->delete_dir('/public_html/path/to/folder/'); + +$this->ftp->list_files() +========================= + +Permits you to retrieve a list of files on your server returned as an +array. You must supply the path to the desired directory. + +:: + + $list = $this->ftp->list_files('/public_html/'); + + print_r($list); + +$this->ftp->mirror() +==================== + +Recursively reads a local folder and everything it contains (including +sub-folders) and creates a mirror via FTP based on it. Whatever the +directory structure of the original file path will be recreated on the +server. You must supply a source path and a destination path:: + + $this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/'); + +$this->ftp->mkdir() +=================== + +Lets you create a directory on your server. Supply the path ending in +the folder name you wish to create, with a trailing slash. Permissions +can be set by passed an octal value in the second parameter (if you are +running PHP 5). + +:: + + // Creates a folder named "bar" + $this->ftp->mkdir('/public_html/foo/bar/', DIR_WRITE_MODE); + +$this->ftp->chmod() +=================== + +Permits you to set file permissions. Supply the path to the file or +folder you wish to alter permissions on:: + + // Chmod "bar" to 777 + $this->ftp->chmod('/public_html/foo/bar/', DIR_WRITE_MODE); + +$this->ftp->close(); +==================== + +Closes the connection to your server. It's recommended that you use this +when you are finished uploading. diff --git a/user_guide_src/source/libraries/image_lib.rst b/user_guide_src/source/libraries/image_lib.rst new file mode 100644 index 000000000..300cbef31 --- /dev/null +++ b/user_guide_src/source/libraries/image_lib.rst @@ -0,0 +1,428 @@ +######################## +Image Manipulation Class +######################## + +CodeIgniter's Image Manipulation class lets you perform the following +actions: + +- Image Resizing +- Thumbnail Creation +- Image Cropping +- Image Rotating +- Image Watermarking + +All three major image libraries are supported: GD/GD2, NetPBM, and +ImageMagick + +.. note:: Watermarking is only available using the GD/GD2 library. In + addition, even though other libraries are supported, GD is required in + order for the script to calculate the image properties. The image + processing, however, will be performed with the library you specify. + +********************** +Initializing the Class +********************** + +Like most other classes in CodeIgniter, the image class is initialized +in your controller using the $this->load->library function:: + + $this->load->library('image_lib'); + +Once the library is loaded it will be ready for use. The image library +object you will use to call all functions is: $this->image_lib + +Processing an Image +=================== + +Regardless of the type of processing you would like to perform +(resizing, cropping, rotation, or watermarking), the general process is +identical. You will set some preferences corresponding to the action you +intend to perform, then call one of four available processing functions. +For example, to create an image thumbnail you'll do this:: + + $config['image_library'] = 'gd2'; + $config['source_image'] = '/path/to/image/mypic.jpg'; + $config['create_thumb'] = TRUE; + $config['maintain_ratio'] = TRUE; + $config['width'] = 75; + $config['height'] = 50; + + $this->load->library('image_lib', $config); + + $this->image_lib->resize(); + +The above code tells the image_resize function to look for an image +called *mypic.jpg* located in the source_image folder, then create a +thumbnail that is 75 X 50 pixels using the GD2 image_library. Since the +maintain_ratio option is enabled, the thumb will be as close to the +target width and height as possible while preserving the original aspect +ratio. The thumbnail will be called *mypic_thumb.jpg* + +.. note:: In order for the image class to be allowed to do any + processing, the folder containing the image files must have write + permissions. + +.. note:: Image processing can require a considerable amount of server + memory for some operations. If you are experiencing out of memory errors + while processing images you may need to limit their maximum size, and/or + adjust PHP memory limits. + +Processing Functions +==================== + +There are four available processing functions: + +- $this->image_lib->resize() +- $this->image_lib->crop() +- $this->image_lib->rotate() +- $this->image_lib->watermark() +- $this->image_lib->clear() + +These functions return boolean TRUE upon success and FALSE for failure. +If they fail you can retrieve the error message using this function:: + + echo $this->image_lib->display_errors(); + +A good practice is use the processing function conditionally, showing an +error upon failure, like this:: + + if ( ! $this->image_lib->resize()) + { + echo $this->image_lib->display_errors(); + } + +Note: You can optionally specify the HTML formatting to be applied to +the errors, by submitting the opening/closing tags in the function, like +this:: + + $this->image_lib->display_errors('<p>', '</p>'); + +Preferences +=========== + +The preferences described below allow you to tailor the image processing +to suit your needs. + +Note that not all preferences are available for every function. For +example, the x/y axis preferences are only available for image cropping. +Likewise, the width and height preferences have no effect on cropping. +The "availability" column indicates which functions support a given +preference. + +Availability Legend: + +- R - Image Resizing +- C - Image Cropping +- X - Image Rotation +- W - Image Watermarking + +======================= ======================= =============================== =========================================================================== ============= +Preference Default Value Options Description Availability +======================= ======================= =============================== =========================================================================== ============= +**image_library** GD2 GD, GD2, ImageMagick, NetPBM Sets the image library to be used. R, C, X, W +**library_path** None None Sets the server path to your ImageMagick or NetPBM library. If you use R, C, X + either of those libraries you must supply the path. R, C, S, W +**source_image** None None Sets the source image name/path. The path must be a relative or absolute + server path, not a URL. +**dynamic_output** FALSE TRUE/FALSE (boolean) Determines whether the new image file should be written to disk or R, C, X, W + generated dynamically. Note: If you choose the dynamic setting, only one + image can be shown at a time, and it can't be positioned on the page. It + simply outputs the raw image dynamically to your browser, along with + image headers. +**quality** 90% 1 - 100% Sets the quality of the image. The higher the quality the larger the R, C, X, W + file size. +**new_image** None None Sets the destination image name/path. You'll use this preference when R, C, X, W + creating an image copy. The path must be a relative or absolute server + path, not a URL. +**width** None None Sets the width you would like the image set to. R, C +**height** None None Sets the height you would like the image set to. R, C +**create_thumb** FALSE TRUE/FALSE (boolean) Tells the image processing function to create a thumb. R +**thumb_marker** _thumb None Specifies the thumbnail indicator. It will be inserted just before the R + file extension, so mypic.jpg would become mypic_thumb.jpg +**maintain_ratio** TRUE TRUE/FALSE (boolean) Specifies whether to maintain the original aspect ratio when resizing or R, C + use hard values. +**master_dim** auto auto, width, height Specifies what to use as the master axis when resizing or creating R + thumbs. For example, let's say you want to resize an image to 100 X 75 + pixels. If the source image size does not allow perfect resizing to + those dimensions, this setting determines which axis should be used as + the hard value. "auto" sets the axis automatically based on whether the + image is taller then wider, or vice versa. +**rotation_angle** None 90, 180, 270, vrt, hor Specifies the angle of rotation when rotating images. Note that PHP X + rotates counter-clockwise, so a 90 degree rotation to the right must be + specified as 270. +**x_axis** None None Sets the X coordinate in pixels for image cropping. For example, a C + setting of 30 will crop an image 30 pixels from the left. +**y_axis** None None Sets the Y coordinate in pixels for image cropping. For example, a C + setting of 30 will crop an image 30 pixels from the top. +======================= ======================= =============================== =========================================================================== ============= + +Setting preferences in a config file +==================================== + +If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called +image_lib.php, add the $config array in that file. Then save the file +in: config/image_lib.php and it will be used automatically. You will +NOT need to use the $this->image_lib->initialize function if you save +your preferences in a config file. + +$this->image_lib->resize() +=========================== + +The image resizing function lets you resize the original image, create a +copy (with or without resizing), or create a thumbnail image. + +For practical purposes there is no difference between creating a copy +and creating a thumbnail except a thumb will have the thumbnail marker +as part of the name (ie, mypic_thumb.jpg). + +All preferences listed in the table above are available for this +function except these three: rotation_angle, x_axis, and y_axis. + +Creating a Thumbnail +-------------------- + +The resizing function will create a thumbnail file (and preserve the +original) if you set this preference to TRUE:: + + $config['create_thumb'] = TRUE; + +This single preference determines whether a thumbnail is created or not. + +Creating a Copy +--------------- + +The resizing function will create a copy of the image file (and preserve +the original) if you set a path and/or a new filename using this +preference:: + + $config['new_image'] = '/path/to/new_image.jpg'; + +Notes regarding this preference: + +- If only the new image name is specified it will be placed in the same + folder as the original +- If only the path is specified, the new image will be placed in the + destination with the same name as the original. +- If both the path and image name are specified it will placed in its + own destination and given the new name. + +Resizing the Original Image +--------------------------- + +If neither of the two preferences listed above (create_thumb, and +new_image) are used, the resizing function will instead target the +original image for processing. + +$this->image_lib->crop() +========================= + +The cropping function works nearly identically to the resizing function +except it requires that you set preferences for the X and Y axis (in +pixels) specifying where to crop, like this:: + + $config['x_axis'] = '100'; + $config['y_axis'] = '40'; + +All preferences listed in the table above are available for this +function except these: rotation_angle, width, height, create_thumb, +new_image. + +Here's an example showing how you might crop an image:: + + $config['image_library'] = 'imagemagick'; + $config['library_path'] = '/usr/X11R6/bin/'; + $config['source_image'] = '/path/to/image/mypic.jpg'; + $config['x_axis'] = '100'; + $config['y_axis'] = '60'; + + $this->image_lib->initialize($config); + + if ( ! $this->image_lib->crop()) + { + echo $this->image_lib->display_errors(); + } + +Note: Without a visual interface it is difficult to crop images, so this +function is not very useful unless you intend to build such an +interface. That's exactly what we did using for the photo gallery module +in ExpressionEngine, the CMS we develop. We added a JavaScript UI that +lets the cropping area be selected. + +$this->image_lib->rotate() +=========================== + +The image rotation function requires that the angle of rotation be set +via its preference:: + + $config['rotation_angle'] = '90'; + +There are 5 rotation options: + +#. 90 - rotates counter-clockwise by 90 degrees. +#. 180 - rotates counter-clockwise by 180 degrees. +#. 270 - rotates counter-clockwise by 270 degrees. +#. hor - flips the image horizontally. +#. vrt - flips the image vertically. + +Here's an example showing how you might rotate an image:: + + $config['image_library'] = 'netpbm'; + $config['library_path'] = '/usr/bin/'; + $config['source_image'] = '/path/to/image/mypic.jpg'; + $config['rotation_angle'] = 'hor'; + + $this->image_lib->initialize($config); + + if ( ! $this->image_lib->rotate()) + { + echo $this->image_lib->display_errors(); + } + +$this->image_lib->clear() +========================== + +The clear function resets all of the values used when processing an +image. You will want to call this if you are processing images in a +loop. + +:: + + $this->image_lib->clear(); + + +****************** +Image Watermarking +****************** + +The Watermarking feature requires the GD/GD2 library. + +Two Types of Watermarking +========================= + +There are two types of watermarking that you can use: + +- **Text**: The watermark message will be generating using text, either + with a True Type font that you specify, or using the native text + output that the GD library supports. If you use the True Type version + your GD installation must be compiled with True Type support (most + are, but not all). +- **Overlay**: The watermark message will be generated by overlaying an + image (usually a transparent PNG or GIF) containing your watermark + over the source image. + +Watermarking an Image +===================== + +Just as with the other functions (resizing, cropping, and rotating) the +general process for watermarking involves setting the preferences +corresponding to the action you intend to perform, then calling the +watermark function. Here is an example:: + + $config['source_image'] = '/path/to/image/mypic.jpg'; + $config['wm_text'] = 'Copyright 2006 - John Doe'; + $config['wm_type'] = 'text'; + $config['wm_font_path'] = './system/fonts/texb.ttf'; + $config['wm_font_size'] = '16'; + $config['wm_font_color'] = 'ffffff'; + $config['wm_vrt_alignment'] = 'bottom'; + $config['wm_hor_alignment'] = 'center'; + $config['wm_padding'] = '20'; + + $this->image_lib->initialize($config); + + $this->image_lib->watermark(); + +The above example will use a 16 pixel True Type font to create the text +"Copyright 2006 - John Doe". The watermark will be positioned at the +bottom/center of the image, 20 pixels from the bottom of the image. + +.. note:: In order for the image class to be allowed to do any + processing, the image file must have "write" file permissions. For + example, 777. + +Watermarking Preferences +======================== + +This table shown the preferences that are available for both types of +watermarking (text or overlay) + +======================= =================== ======================= ========================================================================== +Preference Default Value Options Description +======================= =================== ======================= ========================================================================== +**wm_type** text text, overlay Sets the type of watermarking that should be used. +**source_image** None None Sets the source image name/path. The path must be a relative or absolute + server path, not a URL. +**dynamic_output** FALSE TRUE/FALSE (boolean) Determines whether the new image file should be written to disk or + generated dynamically. Note: If you choose the dynamic setting, only one + image can be shown at a time, and it can't be positioned on the page. It + simply outputs the raw image dynamically to your browser, along with + image headers. +**quality** 90% 1 - 100% Sets the quality of the image. The higher the quality the larger the + file size. +**padding** None A number The amount of padding, set in pixels, that will be applied to the + watermark to set it away from the edge of your images. +**wm_vrt_alignment** bottom top, middle, bottom Sets the vertical alignment for the watermark image. +**wm_hor_alignment** center left, center, right Sets the horizontal alignment for the watermark image. +**wm_hor_offset** None None You may specify a horizontal offset (in pixels) to apply to the + watermark position. The offset normally moves the watermark to the + right, except if you have your alignment set to "right" then your offset + value will move the watermark toward the left of the image. +**wm_vrt_offset** None None You may specify a vertical offset (in pixels) to apply to the watermark + position. The offset normally moves the watermark down, except if you + have your alignment set to "bottom" then your offset value will move the + watermark toward the top of the image. +======================= =================== ======================= ========================================================================== + +Text Preferences +---------------- + +This table shown the preferences that are available for the text type of +watermarking. + +======================= =================== =================== ========================================================================== +Preference Default Value Options Description +======================= =================== =================== ========================================================================== +**wm_text** None None The text you would like shown as the watermark. Typically this will be a + copyright notice. +**wm_font_path** None None The server path to the True Type Font you would like to use. If you do + not use this option, the native GD font will be used. +**wm_font_size** 16 None The size of the text. Note: If you are not using the True Type option + above, the number is set using a range of 1 - 5. Otherwise, you can use + any valid pixel size for the font you're using. +**wm_font_color** ffffff None The font color, specified in hex. Note, you must use the full 6 + character hex value (ie, 993300), rather than the three character + abbreviated version (ie fff). +**wm_shadow_color** None None The color of the drop shadow, specified in hex. If you leave this blank + a drop shadow will not be used. Note, you must use the full 6 character + hex value (ie, 993300), rather than the three character abbreviated + version (ie fff). +**wm_shadow_distance** 3 None The distance (in pixels) from the font that the drop shadow should + appear. +======================= =================== =================== ========================================================================== + +Overlay Preferences +------------------- + +This table shown the preferences that are available for the overlay type +of watermarking. + +======================= =================== =================== ========================================================================== +Preference Default Value Options Description +======================= =================== =================== ========================================================================== +**wm_overlay_path** None None The server path to the image you wish to use as your watermark. Required + only if you are using the overlay method. +**wm_opacity** 50 1 - 100 Image opacity. You may specify the opacity (i.e. transparency) of your + watermark image. This allows the watermark to be faint and not + completely obscure the details from the original image behind it. A 50% + opacity is typical. +**wm_x_transp** 4 A number If your watermark image is a PNG or GIF image, you may specify a color + on the image to be "transparent". This setting (along with the next) + will allow you to specify that color. This works by specifying the "X" + and "Y" coordinate pixel (measured from the upper left) within the image + that corresponds to a pixel representative of the color you want to be + transparent. +**wm_y_transp** 4 A number Along with the previous setting, this allows you to specify the + coordinate to a pixel representative of the color you want to be + transparent. +======================= =================== =================== ========================================================================== diff --git a/user_guide_src/source/libraries/index.rst b/user_guide_src/source/libraries/index.rst new file mode 100644 index 000000000..678b633dd --- /dev/null +++ b/user_guide_src/source/libraries/index.rst @@ -0,0 +1,9 @@ +######### +Libraries +######### + +.. toctree:: + :glob: + :titlesonly: + + *
\ No newline at end of file diff --git a/user_guide_src/source/libraries/input.rst b/user_guide_src/source/libraries/input.rst new file mode 100644 index 000000000..bcf117358 --- /dev/null +++ b/user_guide_src/source/libraries/input.rst @@ -0,0 +1,300 @@ +########### +Input Class +########### + +The Input Class serves two purposes: + +#. It pre-processes global input data for security. +#. It provides some helper functions for fetching input data and + pre-processing it. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +Security Filtering +================== + +The security filtering function is called automatically when a new +:doc:`controller <../general/controllers>` is invoked. It does the +following: + +- If $config['allow_get_array'] is FALSE(default is TRUE), destroys + the global GET array. +- Destroys all global variables in the event register_globals is + turned on. +- Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric + (and a few other) characters. +- Provides XSS (Cross-site Scripting Hacks) filtering. This can be + enabled globally, or upon request. +- Standardizes newline characters to \\n(In Windows \\r\\n) + +XSS Filtering +============= + +The Input class has the ability to filter input automatically to prevent +cross-site scripting attacks. If you want the filter to run +automatically every time it encounters POST or COOKIE data you can +enable it by opening your application/config/config.php file and setting +this:: + + $config['global_xss_filtering'] = TRUE; + +Please refer to the :doc:`Security class <security>` documentation for +information on using XSS Filtering in your application. + +Using POST, COOKIE, or SERVER Data +================================== + +CodeIgniter comes with three helper functions that let you fetch POST, +COOKIE or SERVER items. The main advantage of using the provided +functions rather than fetching an item directly ($_POST['something']) +is that the functions will check to see if the item is set and return +false (boolean) if not. This lets you conveniently use data without +having to test whether an item exists first. In other words, normally +you might do something like this:: + + if ( ! isset($_POST['something'])) + { + $something = FALSE; + } + else + { + $something = $_POST['something']; + } + +With CodeIgniter's built in functions you can simply do this:: + + $something = $this->input->post('something'); + +The three functions are: + +- $this->input->post() +- $this->input->cookie() +- $this->input->server() + +$this->input->post() +==================== + +The first parameter will contain the name of the POST item you are +looking for:: + + $this->input->post('some_data'); + +The function returns FALSE (boolean) if the item you are attempting to +retrieve does not exist. + +The second optional parameter lets you run the data through the XSS +filter. It's enabled by setting the second parameter to boolean TRUE; + +:: + + $this->input->post('some_data', TRUE); + +To return an array of all POST items call without any parameters. + +To return all POST items and pass them through the XSS filter set the +first parameter NULL while setting the second parameter to boolean; + +The function returns FALSE (boolean) if there are no items in the POST. + +:: + + $this->input->post(NULL, TRUE); // returns all POST items with XSS filter + $this->input->post(); // returns all POST items without XSS filter + +$this->input->get() +=================== + +This function is identical to the post function, only it fetches get +data:: + + $this->input->get('some_data', TRUE); + +To return an array of all GET items call without any parameters. + +To return all GET items and pass them through the XSS filter set the +first parameter NULL while setting the second parameter to boolean; + +The function returns FALSE (boolean) if there are no items in the GET. + +:: + + $this->input->get(NULL, TRUE); // returns all GET items with XSS filter + $this->input->get(); // returns all GET items without XSS filtering + + +$this->input->get_post() +========================= + +This function will search through both the post and get streams for +data, looking first in post, and then in get:: + + $this->input->get_post('some_data', TRUE); + +$this->input->cookie() +====================== + +This function is identical to the post function, only it fetches cookie +data:: + + $this->input->cookie('some_data', TRUE); + +$this->input->server() +====================== + +This function is identical to the above functions, only it fetches +server data:: + + $this->input->server('some_data'); + +$this->input->set_cookie() +=========================== + +Sets a cookie containing the values you specify. There are two ways to +pass information to this function so that a cookie can be set: Array +Method, and Discrete Parameters: + +Array Method +^^^^^^^^^^^^ + +Using this method, an associative array is passed to the first +parameter:: + + $cookie = array( + 'name' => 'The Cookie Name', + 'value' => 'The Value', + 'expire' => '86500', + 'domain' => '.some-domain.com', + 'path' => '/', + 'prefix' => 'myprefix_', + 'secure' => TRUE + ); + + $this->input->set_cookie($cookie); + +**Notes:** + +Only the name and value are required. To delete a cookie set it with the +expiration blank. + +The expiration is set in **seconds**, which will be added to the current +time. Do not include the time, but rather only the number of seconds +from *now* that you wish the cookie to be valid. If the expiration is +set to zero the cookie will only last as long as the browser is open. + +For site-wide cookies regardless of how your site is requested, add your +URL to the **domain** starting with a period, like this: +.your-domain.com + +The path is usually not needed since the function sets a root path. + +The prefix is only needed if you need to avoid name collisions with +other identically named cookies for your server. + +The secure boolean is only needed if you want to make it a secure cookie +by setting it to TRUE. + +Discrete Parameters +^^^^^^^^^^^^^^^^^^^ + +If you prefer, you can set the cookie by passing data using individual +parameters:: + + $this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); + +$this->input->cookie() +====================== + +Lets you fetch a cookie. The first parameter will contain the name of +the cookie you are looking for (including any prefixes):: + + cookie('some_cookie'); + +The function returns FALSE (boolean) if the item you are attempting to +retrieve does not exist. + +The second optional parameter lets you run the data through the XSS +filter. It's enabled by setting the second parameter to boolean TRUE; + +:: + + cookie('some_cookie', TRUE); + + +$this->input->ip_address() +=========================== + +Returns the IP address for the current user. If the IP address is not +valid, the function will return an IP of: 0.0.0.0 + +:: + + echo $this->input->ip_address(); + +$this->input->valid_ip($ip) +============================ + +Takes an IP address as input and returns TRUE or FALSE (boolean) if it +is valid or not. Note: The $this->input->ip_address() function above +validates the IP automatically. + +:: + + if ( ! $this->input->valid_ip($ip)) + { + echo 'Not Valid'; + } + else + { + echo 'Valid'; + } + +$this->input->user_agent() +=========================== + +Returns the user agent (web browser) being used by the current user. +Returns FALSE if it's not available. + +:: + + echo $this->input->user_agent(); + +See the :doc:`User Agent Class <user_agent>` for methods which extract +information from the user agent string. + +$this->input->request_headers() +================================ + +Useful if running in a non-Apache environment where +`apache_request_headers() <http://php.net/apache_request_headers>`_ +will not be supported. Returns an array of headers. + +:: + + $headers = $this->input->request_headers(); + +$this->input->get_request_header(); +===================================== + +Returns a single member of the request headers array. + +:: + + $this->input->get_request_header('some-header', TRUE); + +$this->input->is_ajax_request() +================================= + +Checks to see if the HTTP_X_REQUESTED_WITH server header has been +set, and returns a boolean response. + +$this->input->is_cli_request() +================================ + +Checks to see if the STDIN constant is set, which is a failsafe way to +see if PHP is being run on the command line. + +:: + + $this->input->is_cli_request() + diff --git a/user_guide_src/source/libraries/javascript.rst b/user_guide_src/source/libraries/javascript.rst new file mode 100644 index 000000000..5e80fb998 --- /dev/null +++ b/user_guide_src/source/libraries/javascript.rst @@ -0,0 +1,301 @@ +.. note:: This driver is experimental. Its feature set and + implementation may change in future releases. + +################ +Javascript Class +################ + +CodeIgniter provides a library to help you with certain common functions +that you may want to use with Javascript. Please note that CodeIgniter +does not require the jQuery library to run, and that any scripting +library will work equally well. The jQuery library is simply presented +as a convenience if you choose to use it. + +Initializing the Class +====================== + +To initialize the Javascript class manually in your controller +constructor, use the $this->load->library function. Currently, the only +available library is jQuery, which will automatically be loaded like +this:: + + $this->load->library('javascript'); + +The Javascript class also accepts parameters, js_library_driver +(string) default 'jquery' and autoload (bool) default TRUE. You may +override the defaults if you wish by sending an associative array:: + + $this->load->library('javascript', array('js_library_driver' => 'scripto', 'autoload' => FALSE)); + +Again, presently only 'jquery' is available. You may wish to set +autoload to FALSE, though, if you do not want the jQuery library to +automatically include a script tag for the main jQuery script file. This +is useful if you are loading it from a location outside of CodeIgniter, +or already have the script tag in your markup. + +Once loaded, the jQuery library object will be available using: +$this->javascript + +Setup and Configuration +======================= + +Set these variables in your view +-------------------------------- + +As a Javascript library, your files must be available to your +application. + +As Javascript is a client side language, the library must be able to +write content into your final output. This generally means a view. +You'll need to include the following variables in the <head> sections of +your output. + +:: + + <?php echo $library_src;?> + <?php echo $script_head;?> + + +$library_src, is where the actual library file will be loaded, as well +as any subsequent plugin script calls; $script_head is where specific +events, functions and other commands will be rendered. + +Set the path to the librarys with config items +---------------------------------------------- + +There are some configuration items in Javascript library. These can +either be set in application/config.php, within its own +config/javascript.php file, or within any controller usings the +set_item() function. + +An image to be used as an "ajax loader", or progress indicator. Without +one, the simple text message of "loading" will appear when Ajax calls +need to be made. + +:: + + $config['javascript_location'] = 'http://localhost/codeigniter/themes/js/jquery/'; + $config['javascript_ajax_img'] = 'images/ajax-loader.gif'; + +If you keep your files in the same directories they were downloaded +from, then you need not set this configuration items. + +The jQuery Class +================ + +To initialize the jQuery class manually in your controller constructor, +use the $this->load->library function:: + + $this->load->library('jquery'); + +You may send an optional parameter to determine whether or not a script +tag for the main jQuery file will be automatically included when loading +the library. It will be created by default. To prevent this, load the +library as follows:: + + $this->load->library('jquery', FALSE); + +Once loaded, the jQuery library object will be available using: +$this->jquery + +jQuery Events +============= + +Events are set using the following syntax. + +:: + + $this->jquery->event('element_path', code_to_run()); + + +In the above example: + +- "event" is any of blur, change, click, dblclick, error, focus, hover, + keydown, keyup, load, mousedown, mouseup, mouseover, mouseup, resize, + scroll, or unload. +- "element_path" is any valid `jQuery + selector <http://docs.jquery.com/Selectors>`_. Due to jQuery's unique + selector syntax, this is usually an element id, or CSS selector. For + example "#notice_area" would effect <div id="notice_area">, and + "#content a.notice" would effect all anchors with a class of "notice" + in the div with id "content". +- "code_to_run()" is script your write yourself, or an action such as + an effect from the jQuery library below. + +Effects +======= + +The query library supports a powerful +`Effects <http://docs.jquery.com/Effects>`_ repertoire. Before an effect +can be used, it must be loaded:: + + $this->jquery->effect([optional path] plugin name); // for example $this->jquery->effect('bounce'); + + +hide() / show() +--------------- + +Each of this functions will affect the visibility of an item on your +page. hide() will set an item invisible, show() will reveal it. + +:: + + $this->jquery->hide(target, optional speed, optional extra information); + $this->jquery->show(target, optional speed, optional extra information); + + +- "target" will be any valid jQuery selector or selectors. +- "speed" is optional, and is set to either slow, normal, fast, or + alternatively a number of milliseconds. +- "extra information" is optional, and could include a callback, or + other additional information. + +toggle() +-------- + +toggle() will change the visibility of an item to the opposite of its +current state, hiding visible elements, and revealing hidden ones. + +:: + + $this->jquery->toggle(target); + + +- "target" will be any valid jQuery selector or selectors. + +animate() +--------- + +:: + + $this->jquery->animate(target, parameters, optional speed, optional extra information); + + +- "target" will be any valid jQuery selector or selectors. +- "parameters" in jQuery would generally include a series of CSS + properties that you wish to change. +- "speed" is optional, and is set to either slow, normal, fast, or + alternatively a number of milliseconds. +- "extra information" is optional, and could include a callback, or + other additional information. + +For a full summary, see +`http://docs.jquery.com/Effects/animate <http://docs.jquery.com/Effects/animate>`_ + +Here is an example of an animate() called on a div with an id of "note", +and triggered by a click using the jQuery library's click() event. + +:: + + $params = array( + 'height' => 80, + 'width' => '50%', + 'marginLeft' => 125 + ); + $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, normal)); + +fadeIn() / fadeOut() +-------------------- + +:: + + $this->jquery->fadeIn(target, optional speed, optional extra information); + $this->jquery->fadeOut(target, optional speed, optional extra information); + + +- "target" will be any valid jQuery selector or selectors. +- "speed" is optional, and is set to either slow, normal, fast, or + alternatively a number of milliseconds. +- "extra information" is optional, and could include a callback, or + other additional information. + +toggleClass() +------------- + +This function will add or remove a CSS class to its target. + +:: + + $this->jquery->toggleClass(target, class) + + +- "target" will be any valid jQuery selector or selectors. +- "class" is any CSS classname. Note that this class must be defined + and available in a CSS that is already loaded. + +fadeIn() / fadeOut() +-------------------- + +These effects cause an element(s) to disappear or reappear over time. + +:: + + $this->jquery->fadeIn(target, optional speed, optional extra information); + $this->jquery->fadeOut(target, optional speed, optional extra information); + + +- "target" will be any valid jQuery selector or selectors. +- "speed" is optional, and is set to either slow, normal, fast, or + alternatively a number of milliseconds. +- "extra information" is optional, and could include a callback, or + other additional information. + +slideUp() / slideDown() / slideToggle() +--------------------------------------- + +These effects cause an element(s) to slide. + +:: + + $this->jquery->slideUp(target, optional speed, optional extra information); + $this->jquery->slideDown(target, optional speed, optional extra information); + $this->jquery->slideToggle(target, optional speed, optional extra information); + + +- "target" will be any valid jQuery selector or selectors. +- "speed" is optional, and is set to either slow, normal, fast, or + alternatively a number of milliseconds. +- "extra information" is optional, and could include a callback, or + other additional information. + +Plugins +======= + +Some select jQuery plugins are made available using this library. + +corner() +-------- + +Used to add distinct corners to page elements. For full details see +`http://www.malsup.com/jquery/corner/ <http://www.malsup.com/jquery/corner/>`_ + +:: + + $this->jquery->corner(target, corner_style); + + +- "target" will be any valid jQuery selector or selectors. +- "corner_style" is optional, and can be set to any valid style such + as round, sharp, bevel, bite, dog, etc. Individual corners can be set + by following the style with a space and using "tl" (top left), "tr" + (top right), "bl" (bottom left), or "br" (bottom right). + +:: + + $this->jquery->corner("#note", "cool tl br"); + + +tablesorter() +------------- + +description to come + +modal() +------- + +description to come + +calendar() +---------- + +description to come diff --git a/user_guide_src/source/libraries/language.rst b/user_guide_src/source/libraries/language.rst new file mode 100644 index 000000000..ec678cd21 --- /dev/null +++ b/user_guide_src/source/libraries/language.rst @@ -0,0 +1,90 @@ +############## +Language Class +############## + +The Language Class provides functions to retrieve language files and +lines of text for purposes of internationalization. + +In your CodeIgniter system folder you'll find one called language +containing sets of language files. You can create your own language +files as needed in order to display error and other messages in other +languages. + +Language files are typically stored in your system/language directory. +Alternately you can create a folder called language inside your +application folder and store them there. CodeIgniter will look first in +your application/language directory. If the directory does not exist or +the specified language is not located there CI will instead look in your +global system/language folder. + +.. note:: Each language should be stored in its own folder. For example, + the English files are located at: system/language/english + +Creating Language Files +======================= + +Language files must be named with _lang.php as the file extension. For +example, let's say you want to create a file containing error messages. +You might name it: error_lang.php + +Within the file you will assign each line of text to an array called +$lang with this prototype:: + + $lang['language_key'] = "The actual message to be shown"; + +.. note:: It's a good practice to use a common prefix for all messages + in a given file to avoid collisions with similarly named items in other + files. For example, if you are creating error messages you might prefix + them with error\_ + +:: + + $lang['error_email_missing'] = "You must submit an email address"; + $lang['error_url_missing'] = "You must submit a URL"; + $lang['error_username_missing'] = "You must submit a username"; + +Loading A Language File +======================= + +In order to fetch a line from a particular file you must load the file +first. Loading a language file is done with the following code:: + + $this->lang->load('filename', 'language'); + +Where filename is the name of the file you wish to load (without the +file extension), and language is the language set containing it (ie, +english). If the second parameter is missing, the default language set +in your application/config/config.php file will be used. + +Fetching a Line of Text +======================= + +Once your desired language file is loaded you can access any line of +text using this function:: + + $this->lang->line('language_key'); + +Where language_key is the array key corresponding to the line you wish +to show. + +Note: This function simply returns the line. It does not echo it for +you. + +Using language lines as form labels +----------------------------------- + +This feature has been deprecated from the language library and moved to +the lang() function of the :doc:`Language +helper <../helpers/language_helper>`. + +Auto-loading Languages +====================== + +If you find that you need a particular language globally throughout your +application, you can tell CodeIgniter to +:doc:`auto-load <../general/autoloader>` it during system +initialization. This is done by opening the +application/config/autoload.php file and adding the language(s) to the +autoload array. + + diff --git a/user_guide_src/source/libraries/loader.rst b/user_guide_src/source/libraries/loader.rst new file mode 100644 index 000000000..bbe2ed530 --- /dev/null +++ b/user_guide_src/source/libraries/loader.rst @@ -0,0 +1,278 @@ +############ +Loader Class +############ + +Loader, as the name suggests, is used to load elements. These elements +can be libraries (classes) :doc:`View files <../general/views>`, +:doc:`Helpers <../general/helpers>`, +:doc:`Models <../general/models>`, or your own files. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +The following functions are available in this class: + +$this->load->library('class_name', $config, 'object name') +=========================================================== + +This function is used to load core classes. Where class_name is the +name of the class you want to load. Note: We use the terms "class" and +"library" interchangeably. + +For example, if you would like to send email with CodeIgniter, the first +step is to load the email class within your controller:: + + $this->load->library('email'); + +Once loaded, the library will be ready for use, using +$this->email->*some_function*(). + +Library files can be stored in subdirectories within the main +"libraries" folder, or within your personal application/libraries +folder. To load a file located in a subdirectory, simply include the +path, relative to the "libraries" folder. For example, if you have file +located at:: + + libraries/flavors/chocolate.php + +You will load it using:: + + $this->load->library('flavors/chocolate'); + +You may nest the file in as many subdirectories as you want. + +Additionally, multiple libraries can be loaded at the same time by +passing an array of libraries to the load function. + +:: + + $this->load->library(array('email', 'table')); + +Setting options +--------------- + +The second (optional) parameter allows you to optionally pass +configuration setting. You will typically pass these as an array:: + + $config = array ( + 'mailtype' => 'html', + 'charset' => 'utf-8, + 'priority' => '1' + ); + + $this->load->library('email', $config); + +Config options can usually also be set via a config file. Each library +is explained in detail in its own page, so please read the information +regarding each one you would like to use. + +Please take note, when multiple libraries are supplied in an array for +the first parameter, each will receive the same parameter information. + +Assigning a Library to a different object name +---------------------------------------------- + +If the third (optional) parameter is blank, the library will usually be +assigned to an object with the same name as the library. For example, if +the library is named Session, it will be assigned to a variable named +$this->session. + +If you prefer to set your own class names you can pass its value to the +third parameter:: + + $this->load->library('session', '', 'my_session'); + + // Session class is now accessed using: + + $this->my_session + +Please take note, when multiple libraries are supplied in an array for +the first parameter, this parameter is discarded. + +$this->load->view('file_name', $data, true/false) +================================================== + +This function is used to load your View files. If you haven't read the +:doc:`Views <../general/views>` section of the user guide it is +recommended that you do since it shows you how this function is +typically used. + +The first parameter is required. It is the name of the view file you +would like to load. Note: The .php file extension does not need to be +specified unless you use something other than .php. + +The second **optional** parameter can take an associative array or an +object as input, which it runs through the PHP +`extract <http://www.php.net/extract>`_ function to convert to variables +that can be used in your view files. Again, read the +:doc:`Views <../general/views>` page to learn how this might be useful. + +The third **optional** parameter lets you change the behavior of the +function so that it returns data as a string rather than sending it to +your browser. This can be useful if you want to process the data in some +way. If you set the parameter to true (boolean) it will return data. The +default behavior is false, which sends it to your browser. Remember to +assign it to a variable if you want the data returned:: + + $string = $this->load->view('myfile', '', true); + +$this->load->model('Model_name'); +================================== + +:: + + $this->load->model('Model_name'); + + +If your model is located in a sub-folder, include the relative path from +your models folder. For example, if you have a model located at +application/models/blog/queries.php you'll load it using:: + + $this->load->model('blog/queries'); + + +If you would like your model assigned to a different object name you can +specify it via the second parameter of the loading function:: + + $this->load->model('Model_name', 'fubar'); + + $this->fubar->function(); + +$this->load->database('options', true/false) +============================================ + +This function lets you load the database class. The two parameters are +**optional**. Please see the :doc:`database <../database/index>` +section for more info. + +$this->load->vars($array) +========================= + +This function takes an associative array as input and generates +variables using the PHP `extract <http://www.php.net/extract>`_ +function. This function produces the same result as using the second +parameter of the $this->load->view() function above. The reason you +might want to use this function independently is if you would like to +set some global variables in the constructor of your controller and have +them become available in any view file loaded from any function. You can +have multiple calls to this function. The data get cached and merged +into one array for conversion to variables. + +$this->load->get_var($key) +=========================== + +This function checks the associative array of variables available to +your views. This is useful if for any reason a var is set in a library +or another controller method using $this->load->vars(). + +$this->load->helper('file_name') +================================= + +This function loads helper files, where file_name is the name of the +file, without the _helper.php extension. + +$this->load->file('filepath/filename', true/false) +================================================== + +This is a generic file loading function. Supply the filepath and name in +the first parameter and it will open and read the file. By default the +data is sent to your browser, just like a View file, but if you set the +second parameter to true (boolean) it will instead return the data as a +string. + +$this->load->language('file_name') +=================================== + +This function is an alias of the :doc:`language loading +function <language>`: $this->lang->load() + +$this->load->config('file_name') +================================= + +This function is an alias of the :doc:`config file loading +function <config>`: $this->config->load() + +Application "Packages" +====================== + +An application package allows for the easy distribution of complete sets +of resources in a single directory, complete with its own libraries, +models, helpers, config, and language files. It is recommended that +these packages be placed in the application/third_party folder. Below +is a sample map of an package directory + +Sample Package "Foo Bar" Directory Map +====================================== + +The following is an example of a directory for an application package +named "Foo Bar". + +:: + + /application/third_party/foo_bar + + config/ + helpers/ + language/ + libraries/ + models/ + +Whatever the purpose of the "Foo Bar" application package, it has its +own config files, helpers, language files, libraries, and models. To use +these resources in your controllers, you first need to tell the Loader +that you are going to be loading resources from a package, by adding the +package path. + +$this->load->add_package_path() +--------------------------------- + +Adding a package path instructs the Loader class to prepend a given path +for subsequent requests for resources. As an example, the "Foo Bar" +application package above has a library named Foo_bar.php. In our +controller, we'd do the following:: + + $this->load->add_package_path(APPPATH.'third_party/foo_bar/'); + $this->load->library('foo_bar'); + +$this->load->remove_package_path() +------------------------------------ + +When your controller is finished using resources from an application +package, and particularly if you have other application packages you +want to work with, you may wish to remove the package path so the Loader +no longer looks in that folder for resources. To remove the last path +added, simply call the method with no parameters. + +$this->load->remove_package_path() +------------------------------------ + +Or to remove a specific package path, specify the same path previously +given to add_package_path() for a package.:: + + $this->load->remove_package_path(APPPATH.'third_party/foo_bar/'); + +Package view files +------------------ + +By Default, package view files paths are set when add_package_path() +is called. View paths are looped through, and once a match is +encountered that view is loaded. + +In this instance, it is possible for view naming collisions within +packages to occur, and possibly the incorrect package being loaded. To +ensure against this, set an optional second parameter of FALSE when +calling add_package_path(). + +:: + + $this->load->add_package_path(APPPATH.'my_app', FALSE); + $this->load->view('my_app_index'); // Loads + $this->load->view('welcome_message'); // Will not load the default welcome_message b/c the second param to add_package_path is FALSE + + // Reset things + $this->load->remove_package_path(APPPATH.'my_app'); + + // Again without the second parameter: + $this->load->add_package_path(APPPATH.'my_app', TRUE); + $this->load->view('my_app_index'); // Loads + $this->load->view('welcome_message'); // Loads
\ No newline at end of file diff --git a/user_guide_src/source/libraries/output.rst b/user_guide_src/source/libraries/output.rst new file mode 100644 index 000000000..2cf7c0854 --- /dev/null +++ b/user_guide_src/source/libraries/output.rst @@ -0,0 +1,138 @@ +############ +Output Class +############ + +The Output class is a small class with one main function: To send the +finalized web page to the requesting browser. It is also responsible for +:doc:`caching <../general/caching>` your web pages, if you use that +feature. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +Under normal circumstances you won't even notice the Output class since +it works transparently without your intervention. For example, when you +use the :doc:`Loader <../libraries/loader>` class to load a view file, +it's automatically passed to the Output class, which will be called +automatically by CodeIgniter at the end of system execution. It is +possible, however, for you to manually intervene with the output if you +need to, using either of the two following functions: + +$this->output->set_output(); +============================= + +Permits you to manually set the final output string. Usage example:: + + $this->output->set_output($data); + +.. important:: If you do set your output manually, it must be the last + thing done in the function you call it from. For example, if you build a + page in one of your controller functions, don't set the output until the + end. + +$this->output->set_content_type(); +==================================== + +Permits you to set the mime-type of your page so you can serve JSON +data, JPEG's, XML, etc easily. + +:: + + $this->output + ->set_content_type('application/json') + ->set_output(json_encode(array('foo' => 'bar'))); + + $this->output + ->set_content_type('jpeg') // You could also use ".jpeg" which will have the full stop removed before looking in config/mimes.php + ->set_output(file_get_contents('files/something.jpg')); + +.. important:: Make sure any non-mime string you pass to this method + exists in config/mimes.php or it will have no effect. + +$this->output->get_output(); +============================= + +Permits you to manually retrieve any output that has been sent for +storage in the output class. Usage example:: + + $string = $this->output->get_output(); + +Note that data will only be retrievable from this function if it has +been previously sent to the output class by one of the CodeIgniter +functions like $this->load->view(). + +$this->output->append_output(); +================================ + +Appends data onto the output string. Usage example:: + + $this->output->append_output($data); + +$this->output->set_header(); +============================= + +Permits you to manually set server headers, which the output class will +send for you when outputting the final rendered display. Example:: + + $this->output->set_header("HTTP/1.0 200 OK"); + $this->output->set_header("HTTP/1.1 200 OK"); + $this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT'); + $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate"); + $this->output->set_header("Cache-Control: post-check=0, pre-check=0"); + $this->output->set_header("Pragma: no-cache"); + +$this->output->set_status_header(code, 'text'); +================================================= + +Permits you to manually set a server status header. Example:: + + $this->output->set_status_header('401'); + // Sets the header as: Unauthorized + +`See here <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>`_ for +a full list of headers. + +$this->output->enable_profiler(); +================================== + +Permits you to enable/disable the +:doc:`Profiler <../general/profiling>`, which will display benchmark +and other data at the bottom of your pages for debugging and +optimization purposes. + +To enable the profiler place the following function anywhere within your +:doc:`Controller <../general/controllers>` functions:: + + $this->output->enable_profiler(TRUE); + +When enabled a report will be generated and inserted at the bottom of +your pages. + +To disable the profiler you will use:: + + $this->output->enable_profiler(FALSE); + +$this->output->set_profiler_sections(); +========================================= + +Permits you to enable/disable specific sections of the Profiler when +enabled. Please refer to the :doc:`Profiler <../general/profiling>` +documentation for further information. + +$this->output->cache(); +======================= + +The CodeIgniter output library also controls caching. For more +information, please see the :doc:`caching +documentation <../general/caching>`. + +Parsing Execution Variables +=========================== + +CodeIgniter will parse the pseudo-variables {elapsed_time} and +{memory_usage} in your output by default. To disable this, set the +$parse_exec_vars class property to FALSE in your controller. +:: + + $this->output->parse_exec_vars = FALSE; + diff --git a/user_guide_src/source/libraries/pagination.rst b/user_guide_src/source/libraries/pagination.rst new file mode 100644 index 000000000..f1653c913 --- /dev/null +++ b/user_guide_src/source/libraries/pagination.rst @@ -0,0 +1,256 @@ +################ +Pagination Class +################ + +CodeIgniter's Pagination class is very easy to use, and it is 100% +customizable, either dynamically or via stored preferences. + +If you are not familiar with the term "pagination", it refers to links +that allows you to navigate from page to page, like this:: + + « First < 1 2 3 4 5 > Last » + +******* +Example +******* + +Here is a simple example showing how to create pagination in one of your +:doc:`controller <../general/controllers>` functions:: + + $this->load->library('pagination'); + + $config['base_url'] = 'http://example.com/index.php/test/page/'; + $config['total_rows'] = 200; + $config['per_page'] = 20; + + $this->pagination->initialize($config); + + echo $this->pagination->create_links(); + +Notes +===== + +The $config array contains your configuration variables. It is passed to +the $this->pagination->initialize function as shown above. Although +there are some twenty items you can configure, at minimum you need the +three shown. Here is a description of what those items represent: + +- **base_url** This is the full URL to the controller class/function + containing your pagination. In the example above, it is pointing to a + controller called "Test" and a function called "page". Keep in mind + that you can :doc:`re-route your URI <../general/routing>` if you + need a different structure. +- **total_rows** This number represents the total rows in the result + set you are creating pagination for. Typically this number will be + the total rows that your database query returned. +- **per_page** The number of items you intend to show per page. In the + above example, you would be showing 20 items per page. + +The create_links() function returns an empty string when there is no +pagination to show. + +Setting preferences in a config file +==================================== + +If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called +pagination.php, add the $config array in that file. Then save the file +in: config/pagination.php and it will be used automatically. You will +NOT need to use the $this->pagination->initialize function if you save +your preferences in a config file. + +************************** +Customizing the Pagination +************************** + +The following is a list of all the preferences you can pass to the +initialization function to tailor the display. + +$config['uri_segment'] = 3; +============================ + +The pagination function automatically determines which segment of your +URI contains the page number. If you need something different you can +specify it. + +$config['num_links'] = 2; +========================== + +The number of "digit" links you would like before and after the selected +page number. For example, the number 2 will place two digits on either +side, as in the example links at the very top of this page. + +$config['use_page_number'] = TRUE; +================================== + +By default, the URI segment will use the starting index for the items +you are paginating. If you prefer to show the the actual page number, +set this to TRUE. + +$config['page_query_string'] = TRUE; +==================================== + +By default, the pagination library assume you are using :doc:`URI +Segments <../general/urls>`, and constructs your links something +like + +:: + + http://example.com/index.php/test/page/20 + + +If you have $config['enable_query_strings'] set to TRUE your links +will automatically be re-written using Query Strings. This option can +also be explictly set. Using $config['page_query_string'] set to TRUE, +the pagination link will become. + +:: + + http://example.com/index.php?c=test&m=page&per_page=20 + + +Note that "per_page" is the default query string passed, however can be +configured using $config['query_string_segment'] = 'your_string' + +*********************** +Adding Enclosing Markup +*********************** + +If you would like to surround the entire pagination with some markup you +can do it with these two prefs: + +$config['full_tag_open'] = '<p>'; +=================================== + +The opening tag placed on the left side of the entire result. + +$config['full_tag_close'] = '</p>'; +===================================== + +The closing tag placed on the right side of the entire result. + +************************** +Customizing the First Link +************************** + +$config['first_link'] = 'First'; +================================= + +The text you would like shown in the "first" link on the left. If you do +not want this link rendered, you can set its value to FALSE. + +$config['first_tag_open'] = '<div>'; +====================================== + +The opening tag for the "first" link. + +$config['first_tag_close'] = '</div>'; +======================================== + +The closing tag for the "first" link. + +************************* +Customizing the Last Link +************************* + +$config['last_link'] = 'Last'; +=============================== + +The text you would like shown in the "last" link on the right. If you do +not want this link rendered, you can set its value to FALSE. + +$config['last_tag_open'] = '<div>'; +===================================== + +The opening tag for the "last" link. + +$config['last_tag_close'] = '</div>'; +======================================= + +The closing tag for the "last" link. + +*************************** +Customizing the "Next" Link +*************************** + +$config['next_link'] = '>'; +=============================== + +The text you would like shown in the "next" page link. If you do not +want this link rendered, you can set its value to FALSE. + +$config['next_tag_open'] = '<div>'; +===================================== + +The opening tag for the "next" link. + +$config['next_tag_close'] = '</div>'; +======================================= + +The closing tag for the "next" link. + +******************************* +Customizing the "Previous" Link +******************************* + +$config['prev_link'] = '<'; +=============================== + +The text you would like shown in the "previous" page link. If you do not +want this link rendered, you can set its value to FALSE. + +$config['prev_tag_open'] = '<div>'; +===================================== + +The opening tag for the "previous" link. + +$config['prev_tag_close'] = '</div>'; +======================================= + +The closing tag for the "previous" link. + +*********************************** +Customizing the "Current Page" Link +*********************************** + +$config['cur_tag_open'] = '<b>'; +================================== + +The opening tag for the "current" link. + +$config['cur_tag_close'] = '</b>'; +==================================== + +The closing tag for the "current" link. + +**************************** +Customizing the "Digit" Link +**************************** + +$config['num_tag_open'] = '<div>'; +==================================== + +The opening tag for the "digit" link. + +$config['num_tag_close'] = '</div>'; +====================================== + +The closing tag for the "digit" link. + +**************** +Hiding the Pages +**************** + +If you wanted to not list the specific pages (for example, you only want +"next" and "previous" links), you can suppress their rendering by +adding:: + + $config['display_pages'] = FALSE; + +****************************** +Adding a class to every anchor +****************************** + +If you want to add a class attribute to every link rendered by the +pagination class, you can set the config "anchor_class" equal to the +classname you want. diff --git a/user_guide_src/source/libraries/parser.rst b/user_guide_src/source/libraries/parser.rst new file mode 100644 index 000000000..0b77ae4b9 --- /dev/null +++ b/user_guide_src/source/libraries/parser.rst @@ -0,0 +1,149 @@ +##################### +Template Parser Class +##################### + +The Template Parser Class enables you to parse pseudo-variables +contained within your view files. It can parse simple variables or +variable tag pairs. If you've never used a template engine, +pseudo-variables look like this:: + + <html> + <head> + <title>{blog_title}</title> + </head> + <body> + + <h3>{blog_heading}</h3> + + {blog_entries} + <h5>{title}</h5> + <p>{body}</p> + {/blog_entries} + </body> + </html> + +These variables are not actual PHP variables, but rather plain text +representations that allow you to eliminate PHP from your templates +(view files). + +.. note:: CodeIgniter does **not** require you to use this class since + using pure PHP in your view pages lets them run a little faster. + However, some developers prefer to use a template engine if they work + with designers who they feel would find some confusion working with PHP. + +.. important:: The Template Parser Class is **not** a full-blown + template parsing solution. We've kept it very lean on purpose in order + to maintain maximum performance. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Parser class is initialized +in your controller using the $this->load->library function:: + + $this->load->library('parser'); + +Once loaded, the Parser library object will be available using: +$this->parser + +The following functions are available in this library: + +$this->parser->parse() +====================== + +This method accepts a template name and data array as input, and it +generates a parsed version. Example:: + + $this->load->library('parser'); + + $data = array( + 'blog_title' => 'My Blog Title', + 'blog_heading' => 'My Blog Heading' + ); + + $this->parser->parse('blog_template', $data); + +The first parameter contains the name of the :doc:`view +file <../general/views>` (in this example the file would be called +blog_template.php), and the second parameter contains an associative +array of data to be replaced in the template. In the above example, the +template would contain two variables: {blog_title} and {blog_heading} + +There is no need to "echo" or do something with the data returned by +$this->parser->parse(). It is automatically passed to the output class +to be sent to the browser. However, if you do want the data returned +instead of sent to the output class you can pass TRUE (boolean) to the +third parameter:: + + $string = $this->parser->parse('blog_template', $data, TRUE); + +$this->parser->parse_string() +============================== + +This method works exactly like parse(), only accepts a string as the +first parameter in place of a view file. + +Variable Pairs +============== + +The above example code allows simple variables to be replaced. What if +you would like an entire block of variables to be repeated, with each +iteration containing new values? Consider the template example we showed +at the top of the page:: + + <html> + <head> + <title>{blog_title}</title> + </head> + <body> + + <h3>{blog_heading}</h3> + + {blog_entries} + <h5>{title}</h5> + <p>{body}</p> + {/blog_entries} + </body> + </html> + +In the above code you'll notice a pair of variables: {blog_entries} +data... {/blog_entries}. In a case like this, the entire chunk of data +between these pairs would be repeated multiple times, corresponding to +the number of rows in a result. + +Parsing variable pairs is done using the identical code shown above to +parse single variables, except, you will add a multi-dimensional array +corresponding to your variable pair data. Consider this example:: + + $this->load->library('parser'); + + $data = array( + 'blog_title' => 'My Blog Title', + 'blog_heading' => 'My Blog Heading', + 'blog_entries' => array( + array('title' => 'Title 1', 'body' => 'Body 1'), + array('title' => 'Title 2', 'body' => 'Body 2'), + array('title' => 'Title 3', 'body' => 'Body 3'), + array('title' => 'Title 4', 'body' => 'Body 4'), + array('title' => 'Title 5', 'body' => 'Body 5') + ) + ); + + $this->parser->parse('blog_template', $data); + +If your "pair" data is coming from a database result, which is already a +multi-dimensional array, you can simply use the database result_array() +function:: + + $query = $this->db->query("SELECT * FROM blog"); + + $this->load->library('parser'); + + $data = array( + 'blog_title' => 'My Blog Title', + 'blog_heading' => 'My Blog Heading', + 'blog_entries' => $query->result_array() + ); + + $this->parser->parse('blog_template', $data); + diff --git a/user_guide_src/source/libraries/security.rst b/user_guide_src/source/libraries/security.rst new file mode 100644 index 000000000..8ee0c6e77 --- /dev/null +++ b/user_guide_src/source/libraries/security.rst @@ -0,0 +1,93 @@ +############## +Security Class +############## + +The Security Class contains methods that help you create a secure +application, processing input data for security. + +XSS Filtering +============= + +CodeIgniter comes with a Cross Site Scripting Hack prevention filter +which can either run automatically to filter all POST and COOKIE data +that is encountered, or you can run it on a per item basis. By default +it does **not** run globally since it requires a bit of processing +overhead, and since you may not need it in all cases. + +The XSS filter looks for commonly used techniques to trigger Javascript +or other types of code that attempt to hijack cookies or do other +malicious things. If anything disallowed is encountered it is rendered +safe by converting the data to character entities. + +Note: This function should only be used to deal with data upon +submission. It's not something that should be used for general runtime +processing since it requires a fair amount of processing overhead. + +To filter data through the XSS filter use this function: + +$this->security->xss_clean() +============================= + +Here is an usage example:: + + $data = $this->security->xss_clean($data); + +If you want the filter to run automatically every time it encounters +POST or COOKIE data you can enable it by opening your +application/config/config.php file and setting this:: + + $config['global_xss_filtering'] = TRUE; + +Note: If you use the form validation class, it gives you the option of +XSS filtering as well. + +An optional second parameter, is_image, allows this function to be used +to test images for potential XSS attacks, useful for file upload +security. When this second parameter is set to TRUE, instead of +returning an altered string, the function returns TRUE if the image is +safe, and FALSE if it contained potentially malicious information that a +browser may attempt to execute. + +:: + + if ($this->security->xss_clean($file, TRUE) === FALSE) + { + // file failed the XSS test + } + +$this->security->sanitize_filename() +===================================== + +When accepting filenames from user input, it is best to sanitize them to +prevent directory traversal and other security related issues. To do so, +use the sanitize_filename() method of the Security class. Here is an +example:: + + $filename = $this->security->sanitize_filename($this->input->post('filename')); + +If it is acceptable for the user input to include relative paths, e.g. +file/in/some/approved/folder.txt, you can set the second optional +parameter, $relative_path to TRUE. + +:: + + $filename = $this->security->sanitize_filename($this->input->post('filename'), TRUE); + +Cross-site request forgery (CSRF) +================================= + +You can enable csrf protection by opening your +application/config/config.php file and setting this:: + + $config['csrf_protection'] = TRUE; + +If you use the :doc:`form helper <../helpers/form_helper>` the +form_open() function will automatically insert a hidden csrf field in +your forms. + +Select URIs can be whitelisted from csrf protection (for example API +endpoints expecting externally POSTed content). You can add these URIs +by editing the 'csrf_exclude_uris' config parameter:: + + $config['csrf_exclude_uris'] = array('api/person/add'); + diff --git a/user_guide_src/source/libraries/sessions.rst b/user_guide_src/source/libraries/sessions.rst new file mode 100644 index 000000000..af9dd49c9 --- /dev/null +++ b/user_guide_src/source/libraries/sessions.rst @@ -0,0 +1,333 @@ +############# +Session Class +############# + +The Session class permits you maintain a user's "state" and track their +activity while they browse your site. The Session class stores session +information for each user as serialized (and optionally encrypted) data +in a cookie. It can also store the session data in a database table for +added security, as this permits the session ID in the user's cookie to +be matched against the stored session ID. By default only the cookie is +saved. If you choose to use the database option you'll need to create +the session table as indicated below. + +.. note:: The Session class does **not** utilize native PHP sessions. It + generates its own session data, offering more flexibility for + developers. + +.. note:: Even if you are not using encrypted sessions, you must set + an :doc:`encryption key <./encryption>` in your config file which is used + to aid in preventing session data manipulation. + +Initializing a Session +====================== + +Sessions will typically run globally with each page load, so the session +class must either be :doc:`initialized <../general/libraries>` in your +:doc:`controller <../general/controllers>` constructors, or it can be +:doc:`auto-loaded <../general/autoloader>` by the system. For the most +part the session class will run unattended in the background, so simply +initializing the class will cause it to read, create, and update +sessions. + +To initialize the Session class manually in your controller constructor, +use the $this->load->library function:: + + $this->load->library('session'); + +Once loaded, the Sessions library object will be available using: +$this->session + +How do Sessions work? +===================== + +When a page is loaded, the session class will check to see if valid +session data exists in the user's session cookie. If sessions data does +**not** exist (or if it has expired) a new session will be created and +saved in the cookie. If a session does exist, its information will be +updated and the cookie will be updated. With each update, the +session_id will be regenerated. + +It's important for you to understand that once initialized, the Session +class runs automatically. There is nothing you need to do to cause the +above behavior to happen. You can, as you'll see below, work with +session data or even add your own data to a user's session, but the +process of reading, writing, and updating a session is automatic. + +What is Session Data? +===================== + +A *session*, as far as CodeIgniter is concerned, is simply an array +containing the following information: + +- The user's unique Session ID (this is a statistically random string + with very strong entropy, hashed with MD5 for portability, and + regenerated (by default) every five minutes) +- The user's IP Address +- The user's User Agent data (the first 120 characters of the browser + data string) +- The "last activity" time stamp. + +The above data is stored in a cookie as a serialized array with this +prototype:: + + [array] + ( + 'session_id' => random hash, + 'ip_address' => 'string - user IP address', + 'user_agent' => 'string - user agent data', + 'last_activity' => timestamp + ) + +If you have the encryption option enabled, the serialized array will be +encrypted before being stored in the cookie, making the data highly +secure and impervious to being read or altered by someone. More info +regarding encryption can be :doc:`found here <encryption>`, although +the Session class will take care of initializing and encrypting the data +automatically. + +Note: Session cookies are only updated every five minutes by default to +reduce processor load. If you repeatedly reload a page you'll notice +that the "last activity" time only updates if five minutes or more has +passed since the last time the cookie was written. This time is +configurable by changing the $config['sess_time_to_update'] line in +your system/config/config.php file. + +Retrieving Session Data +======================= + +Any piece of information from the session array is available using the +following function:: + + $this->session->userdata('item'); + +Where item is the array index corresponding to the item you wish to +fetch. For example, to fetch the session ID you will do this:: + + $session_id = $this->session->userdata('session_id'); + +.. note:: The function returns FALSE (boolean) if the item you are + trying to access does not exist. + +Adding Custom Session Data +========================== + +A useful aspect of the session array is that you can add your own data +to it and it will be stored in the user's cookie. Why would you want to +do this? Here's one example: + +Let's say a particular user logs into your site. Once authenticated, you +could add their username and email address to the session cookie, making +that data globally available to you without having to run a database +query when you need it. + +To add your data to the session array involves passing an array +containing your new data to this function:: + + $this->session->set_userdata($array); + +Where $array is an associative array containing your new data. Here's an +example:: + + $newdata = array( + 'username' => 'johndoe', + 'email' => 'johndoe@some-site.com', + 'logged_in' => TRUE + ); + + $this->session->set_userdata($newdata); + +If you want to add userdata one value at a time, set_userdata() also +supports this syntax. + +:: + + $this->session->set_userdata('some_name', 'some_value'); + + +.. note:: Cookies can only hold 4KB of data, so be careful not to exceed + the capacity. The encryption process in particular produces a longer + data string than the original so keep careful track of how much data you + are storing. + +Retrieving All Session Data +=========================== + +An array of all userdata can be retrieved as follows:: + + $this->session->all_userdata() + +And returns an associative array like the following:: + + Array + ( + [session_id] => 4a5a5dca22728fb0a84364eeb405b601 + [ip_address] => 127.0.0.1 + [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; + [last_activity] => 1303142623 + ) + +Removing Session Data +===================== + +Just as set_userdata() can be used to add information into a session, +unset_userdata() can be used to remove it, by passing the session key. +For example, if you wanted to remove 'some_name' from your session +information:: + + $this->session->unset_userdata('some_name'); + + +This function can also be passed an associative array of items to unset. + +:: + + $array_items = array('username' => '', 'email' => ''); + + $this->session->unset_userdata($array_items); + + +Flashdata +========= + +CodeIgniter supports "flashdata", or session data that will only be +available for the next server request, and are then automatically +cleared. These can be very useful, and are typically used for +informational or status messages (for example: "record 2 deleted"). + +Note: Flash variables are prefaced with "flash\_" so avoid this prefix +in your own session names. + +To add flashdata:: + + $this->session->set_flashdata('item', 'value'); + + +You can also pass an array to set_flashdata(), in the same manner as +set_userdata(). + +To read a flashdata variable:: + + $this->session->flashdata('item'); + + +If you find that you need to preserve a flashdata variable through an +additional request, you can do so using the keep_flashdata() function. + +:: + + $this->session->keep_flashdata('item'); + + +Saving Session Data to a Database +================================= + +While the session data array stored in the user's cookie contains a +Session ID, unless you store session data in a database there is no way +to validate it. For some applications that require little or no +security, session ID validation may not be needed, but if your +application requires security, validation is mandatory. Otherwise, an +old session could be restored by a user modifying their cookies. + +When session data is available in a database, every time a valid session +is found in the user's cookie, a database query is performed to match +it. If the session ID does not match, the session is destroyed. Session +IDs can never be updated, they can only be generated when a new session +is created. + +In order to store sessions, you must first create a database table for +this purpose. Here is the basic prototype (for MySQL) required by the +session class:: + + CREATE TABLE IF NOT EXISTS `ci_sessions` ( + session_id varchar(40) DEFAULT '0' NOT NULL, + ip_address varchar(16) DEFAULT '0' NOT NULL, + user_agent varchar(120) NOT NULL, + last_activity int(10) unsigned DEFAULT 0 NOT NULL, + user_data text NOT NULL, + PRIMARY KEY (session_id), + KEY `last_activity_idx` (`last_activity`) + ); + +.. note:: By default the table is called ci_sessions, but you can name + it anything you want as long as you update the + application/config/config.php file so that it contains the name you have + chosen. Once you have created your database table you can enable the + database option in your config.php file as follows:: + + $config['sess_use_database'] = TRUE; + + Once enabled, the Session class will store session data in the DB. + + Make sure you've specified the table name in your config file as well:: + + $config['sess_table_name'] = 'ci_sessions'; + +.. note:: The Session class has built-in garbage collection which clears + out expired sessions so you do not need to write your own routine to do + it. + +Destroying a Session +==================== + +To clear the current session:: + + $this->session->sess_destroy(); + +.. note:: This function should be the last one called, and even flash + variables will no longer be available. If you only want some items + destroyed and not all, use unset_userdata(). + +Session Preferences +=================== + +You'll find the following Session related preferences in your +application/config/config.php file: + +Preference +Default +Options +Description +**sess_cookie_name** +ci_session +None +The name you want the session cookie saved as. +**sess_expiration** +7200 +None +The number of seconds you would like the session to last. The default +value is 2 hours (7200 seconds). If you would like a non-expiring +session set the value to zero: 0 +**sess_expire_on_close** +FALSE +TRUE/FALSE (boolean) +Whether to cause the session to expire automatically when the browser +window is closed. +**sess_encrypt_cookie** +FALSE +TRUE/FALSE (boolean) +Whether to encrypt the session data. +**sess_use_database** +FALSE +TRUE/FALSE (boolean) +Whether to save the session data to a database. You must create the +table before enabling this option. +**sess_table_name** +ci_sessions +Any valid SQL table name +The name of the session database table. +**sess_time_to_update** +300 +Time in seconds +This options controls how often the session class will regenerate itself +and create a new session id. +**sess_match_ip** +FALSE +TRUE/FALSE (boolean) +Whether to match the user's IP address when reading the session data. +Note that some ISPs dynamically changes the IP, so if you want a +non-expiring session you will likely set this to FALSE. +**sess_match_useragent** +TRUE +TRUE/FALSE (boolean) +Whether to match the User Agent when reading the session data. diff --git a/user_guide_src/source/libraries/table.rst b/user_guide_src/source/libraries/table.rst new file mode 100644 index 000000000..9bc3f3423 --- /dev/null +++ b/user_guide_src/source/libraries/table.rst @@ -0,0 +1,267 @@ +################ +HTML Table Class +################ + +The Table Class provides functions that enable you to auto-generate HTML +tables from arrays or database result sets. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Table class is initialized +in your controller using the $this->load->library function:: + + $this->load->library('table'); + +Once loaded, the Table library object will be available using: +$this->table + +Examples +======== + +Here is an example showing how you can create a table from a +multi-dimensional array. Note that the first array index will become the +table heading (or you can set your own headings using the set_heading() +function described in the function reference below). + +:: + + $this->load->library('table'); + + $data = array( + array('Name', 'Color', 'Size'), + array('Fred', 'Blue', 'Small'), + array('Mary', 'Red', 'Large'), + array('John', 'Green', 'Medium') + ); + + echo $this->table->generate($data); + +Here is an example of a table created from a database query result. The +table class will automatically generate the headings based on the table +names (or you can set your own headings using the set_heading() +function described in the function reference below). + +:: + + $this->load->library('table'); + + $query = $this->db->query("SELECT * FROM my_table"); + + echo $this->table->generate($query); + +Here is an example showing how you might create a table using discrete +parameters:: + + $this->load->library('table'); + + $this->table->set_heading('Name', 'Color', 'Size'); + + $this->table->add_row('Fred', 'Blue', 'Small'); + $this->table->add_row('Mary', 'Red', 'Large'); + $this->table->add_row('John', 'Green', 'Medium'); + + echo $this->table->generate(); + +Here is the same example, except instead of individual parameters, +arrays are used:: + + $this->load->library('table'); + + $this->table->set_heading(array('Name', 'Color', 'Size')); + + $this->table->add_row(array('Fred', 'Blue', 'Small')); + $this->table->add_row(array('Mary', 'Red', 'Large')); + $this->table->add_row(array('John', 'Green', 'Medium')); + + echo $this->table->generate(); + +Changing the Look of Your Table +=============================== + +The Table Class permits you to set a table template with which you can +specify the design of your layout. Here is the template prototype:: + + $tmpl = array ( + 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', + + 'heading_row_start' => '<tr>', + 'heading_row_end' => '</tr>', + 'heading_cell_start' => '<th>', + 'heading_cell_end' => '</th>', + + 'row_start' => '<tr>', + 'row_end' => '</tr>', + 'cell_start' => '<td>', + 'cell_end' => '</td>', + + 'row_alt_start' => '<tr>', + 'row_alt_end' => '</tr>', + 'cell_alt_start' => '<td>', + 'cell_alt_end' => '</td>', + + 'table_close' => '</table>' + ); + + $this->table->set_template($tmpl); + +.. note:: You'll notice there are two sets of "row" blocks in the + template. These permit you to create alternating row colors or design + elements that alternate with each iteration of the row data. + +You are NOT required to submit a complete template. If you only need to +change parts of the layout you can simply submit those elements. In this +example, only the table opening tag is being changed:: + + $tmpl = array ( 'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' ); + + $this->table->set_template($tmpl); + +****************** +Function Reference +****************** + +$this->table->generate() +======================== + +Returns a string containing the generated table. Accepts an optional +parameter which can be an array or a database result object. + +$this->table->set_caption() +============================ + +Permits you to add a caption to the table. + +:: + + $this->table->set_caption('Colors'); + +$this->table->set_heading() +============================ + +Permits you to set the table heading. You can submit an array or +discrete params:: + + $this->table->set_heading('Name', 'Color', 'Size'); + +:: + + $this->table->set_heading(array('Name', 'Color', 'Size')); + +$this->table->add_row() +======================== + +Permits you to add a row to your table. You can submit an array or +discrete params:: + + $this->table->add_row('Blue', 'Red', 'Green'); + +:: + + $this->table->add_row(array('Blue', 'Red', 'Green')); + +If you would like to set an individual cell's tag attributes, you can +use an associative array for that cell. The associative key 'data' +defines the cell's data. Any other key => val pairs are added as +key='val' attributes to the tag:: + + $cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2); + $this->table->add_row($cell, 'Red', 'Green'); + + // generates + // <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td> + +$this->table->make_columns() +============================= + +This function takes a one-dimensional array as input and creates a +multi-dimensional array with a depth equal to the number of columns +desired. This allows a single array with many elements to be displayed +in a table that has a fixed column count. Consider this example:: + + $list = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'); + + $new_list = $this->table->make_columns($list, 3); + + $this->table->generate($new_list); + + // Generates a table with this prototype + + <table border="0" cellpadding="4" cellspacing="0"> + <tr> + <td>one</td><td>two</td><td>three</td> + </tr><tr> + <td>four</td><td>five</td><td>six</td> + </tr><tr> + <td>seven</td><td>eight</td><td>nine</td> + </tr><tr> + <td>ten</td><td>eleven</td><td>twelve</td></tr> + </table> + +$this->table->set_template() +============================= + +Permits you to set your template. You can submit a full or partial +template. + +:: + + $tmpl = array ( 'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' ); + + $this->table->set_template($tmpl); + +$this->table->set_empty() +========================== + +Let's you set a default value for use in any table cells that are empty. +You might, for example, set a non-breaking space:: + + $this->table->set_empty(" "); + +$this->table->clear() +===================== + +Lets you clear the table heading and row data. If you need to show +multiple tables with different data you should to call this function +after each table has been generated to empty the previous table +information. Example:: + + $this->load->library('table'); + + $this->table->set_heading('Name', 'Color', 'Size'); + $this->table->add_row('Fred', 'Blue', 'Small'); + $this->table->add_row('Mary', 'Red', 'Large'); + $this->table->add_row('John', 'Green', 'Medium'); + + echo $this->table->generate(); + + $this->table->clear(); + + $this->table->set_heading('Name', 'Day', 'Delivery'); + $this->table->add_row('Fred', 'Wednesday', 'Express'); + $this->table->add_row('Mary', 'Monday', 'Air'); + $this->table->add_row('John', 'Saturday', 'Overnight'); + + echo $this->table->generate(); + +$this->table->function +====================== + +Allows you to specify a native PHP function or a valid function array +object to be applied to all cell data. + +:: + + $this->load->library('table'); + + $this->table->set_heading('Name', 'Color', 'Size'); + $this->table->add_row('Fred', '<strong>Blue</strong>', 'Small'); + + $this->table->function = 'htmlspecialchars'; + echo $this->table->generate(); + +In the above example, all cell data would be ran through PHP's +htmlspecialchars() function, resulting in:: + + <td>Fred</td><td><strong>Blue</strong></td><td>Small</td> + diff --git a/user_guide_src/source/libraries/trackback.rst b/user_guide_src/source/libraries/trackback.rst new file mode 100644 index 000000000..07b2b2177 --- /dev/null +++ b/user_guide_src/source/libraries/trackback.rst @@ -0,0 +1,201 @@ +############### +Trackback Class +############### + +The Trackback Class provides functions that enable you to send and +receive Trackback data. + +If you are not familiar with Trackbacks you'll find more information +`here <http://en.wikipedia.org/wiki/Trackback>`_. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Trackback class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('trackback'); + +Once loaded, the Trackback library object will be available using: +$this->trackback + +Sending Trackbacks +================== + +A Trackback can be sent from any of your controller functions using code +similar to this example:: + + $this->load->library('trackback'); + + $tb_data = array( + 'ping_url' => 'http://example.com/trackback/456', + 'url' => 'http://www.my-example.com/blog/entry/123', + 'title' => 'The Title of My Entry', + 'excerpt' => 'The entry content.', + 'blog_name' => 'My Blog Name', + 'charset' => 'utf-8' + ); + + if ( ! $this->trackback->send($tb_data)) + { + echo $this->trackback->display_errors(); + } + else + { + echo 'Trackback was sent!'; + } + +Description of array data: + +- **ping_url** - The URL of the site you are sending the Trackback to. + You can send Trackbacks to multiple URLs by separating each URL with + a comma. +- **url** - The URL to YOUR site where the weblog entry can be seen. +- **title** - The title of your weblog entry. +- **excerpt** - The content of your weblog entry. Note: the Trackback + class will automatically send only the first 500 characters of your + entry. It will also strip all HTML. +- **blog_name** - The name of your weblog. +- **charset** - The character encoding your weblog is written in. If + omitted, UTF-8 will be used. + +The Trackback sending function returns TRUE/FALSE (boolean) on success +or failure. If it fails, you can retrieve the error message using:: + + $this->trackback->display_errors(); + +Receiving Trackbacks +==================== + +Before you can receive Trackbacks you must create a weblog. If you don't +have a blog yet there's no point in continuing. + +Receiving Trackbacks is a little more complex than sending them, only +because you will need a database table in which to store them, and you +will need to validate the incoming trackback data. You are encouraged to +implement a thorough validation process to guard against spam and +duplicate data. You may also want to limit the number of Trackbacks you +allow from a particular IP within a given span of time to further +curtail spam. The process of receiving a Trackback is quite simple; the +validation is what takes most of the effort. + +Your Ping URL +============= + +In order to accept Trackbacks you must display a Trackback URL next to +each one of your weblog entries. This will be the URL that people will +use to send you Trackbacks (we will refer to this as your "Ping URL"). + +Your Ping URL must point to a controller function where your Trackback +receiving code is located, and the URL must contain the ID number for +each particular entry, so that when the Trackback is received you'll be +able to associate it with a particular entry. + +For example, if your controller class is called Trackback, and the +receiving function is called receive, your Ping URLs will look something +like this:: + + http://example.com/index.php/trackback/receive/entry_id + +Where entry_id represents the individual ID number for each of your +entries. + +Creating a Trackback Table +========================== + +Before you can receive Trackbacks you must create a table in which to +store them. Here is a basic prototype for such a table:: + + CREATE TABLE trackbacks ( + tb_id int(10) unsigned NOT NULL auto_increment, + entry_id int(10) unsigned NOT NULL default 0, + url varchar(200) NOT NULL, + title varchar(100) NOT NULL, + excerpt text NOT NULL, + blog_name varchar(100) NOT NULL, + tb_date int(10) NOT NULL, + ip_address varchar(16) NOT NULL, + PRIMARY KEY `tb_id` (`tb_id`), + KEY `entry_id` (`entry_id`) + ); + +The Trackback specification only requires four pieces of information to +be sent in a Trackback (url, title, excerpt, blog_name), but to make +the data more useful we've added a few more fields in the above table +schema (date, IP address, etc.). + +Processing a Trackback +====================== + +Here is an example showing how you will receive and process a Trackback. +The following code is intended for use within the controller function +where you expect to receive Trackbacks. + +:: + + $this->load->library('trackback'); + $this->load->database(); + + if ($this->uri->segment(3) == FALSE) + { + $this->trackback->send_error("Unable to determine the entry ID"); + } + + if ( ! $this->trackback->receive()) + { + $this->trackback->send_error("The Trackback did not contain valid data"); + } + + $data = array( + 'tb_id' => '', + 'entry_id' => $this->uri->segment(3), + 'url' => $this->trackback->data('url'), + 'title' => $this->trackback->data('title'), + 'excerpt' => $this->trackback->data('excerpt'), + 'blog_name' => $this->trackback->data('blog_name'), + 'tb_date' => time(), + 'ip_address' => $this->input->ip_address() + ); + + $sql = $this->db->insert_string('trackbacks', $data); + $this->db->query($sql); + + $this->trackback->send_success(); + +Notes: +^^^^^^ + +The entry ID number is expected in the third segment of your URL. This +is based on the URI example we gave earlier:: + + http://example.com/index.php/trackback/receive/entry_id + +Notice the entry_id is in the third URI segment, which you can retrieve +using:: + + $this->uri->segment(3); + +In our Trackback receiving code above, if the third segment is missing, +we will issue an error. Without a valid entry ID, there's no reason to +continue. + +The $this->trackback->receive() function is simply a validation function +that looks at the incoming data and makes sure it contains the four +pieces of data that are required (url, title, excerpt, blog_name). It +returns TRUE on success and FALSE on failure. If it fails you will issue +an error message. + +The incoming Trackback data can be retrieved using this function:: + + $this->trackback->data('item') + +Where item represents one of these four pieces of info: url, title, +excerpt, or blog_name + +If the Trackback data is successfully received, you will issue a success +message using:: + + $this->trackback->send_success(); + +.. note:: The above code contains no data validation, which you are + encouraged to add. diff --git a/user_guide_src/source/libraries/typography.rst b/user_guide_src/source/libraries/typography.rst new file mode 100644 index 000000000..db3f227be --- /dev/null +++ b/user_guide_src/source/libraries/typography.rst @@ -0,0 +1,105 @@ +################ +Typography Class +################ + +The Typography Class provides functions that help you format text. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Typography class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('typography'); + +Once loaded, the Typography library object will be available using: +$this->typography + +auto_typography() +================== + +Formats text so that it is semantically and typographically correct +HTML. Takes a string as input and returns it with the following +formatting: + +- Surrounds paragraphs within <p></p> (looks for double line breaks to + identify paragraphs). +- Single line breaks are converted to <br />, except those that appear + within <pre> tags. +- Block level elements, like <div> tags, are not wrapped within + paragraphs, but their contained text is if it contains paragraphs. +- Quotes are converted to correctly facing curly quote entities, except + those that appear within tags. +- Apostrophes are converted to curly apostrophe entities. +- Double dashes (either like -- this or like--this) are converted to + em—dashes. +- Three consecutive periods either preceding or following a word are + converted to ellipsis… +- Double spaces following sentences are converted to non-breaking + spaces to mimic double spacing. + +Usage example:: + + $string = $this->typography->auto_typography($string); + +Parameters +---------- + +There is one optional parameters that determines whether the parser +should reduce more then two consecutive line breaks down to two. Use +boolean TRUE or FALSE. + +By default the parser does not reduce line breaks. In other words, if no +parameters are submitted, it is the same as doing this:: + + $string = $this->typography->auto_typography($string, FALSE); + +.. note:: Typographic formatting can be processor intensive, + particularly if you have a lot of content being formatted. If you choose + to use this function you may want to consider :doc:`caching <../general/caching>` + your pages. + +format_characters() +==================== + +This function is similar to the auto_typography function above, except +that it only does character conversion: + +- Quotes are converted to correctly facing curly quote entities, except + those that appear within tags. +- Apostrophes are converted to curly apostrophe entities. +- Double dashes (either like -- this or like--this) are converted to + em—dashes. +- Three consecutive periods either preceding or following a word are + converted to ellipsis… +- Double spaces following sentences are converted to non-breaking + spaces to mimic double spacing. + +Usage example:: + + $string = $this->typography->format_characters($string); + +nl2br_except_pre() +==================== + +Converts newlines to <br /> tags unless they appear within <pre> tags. +This function is identical to the native PHP nl2br() function, except +that it ignores <pre> tags. + +Usage example:: + + $string = $this->typography->nl2br_except_pre($string); + +protect_braced_quotes +======================= + +When using the Typography library in conjunction with the Template +Parser library it can often be desirable to protect single and double +quotes within curly braces. To enable this, set the +protect_braced_quotes class property to TRUE. + +Usage example:: + + $this->load->library('typography'); + $this->typography->protect_braced_quotes = TRUE; + diff --git a/user_guide_src/source/libraries/unit_testing.rst b/user_guide_src/source/libraries/unit_testing.rst new file mode 100644 index 000000000..03819b27c --- /dev/null +++ b/user_guide_src/source/libraries/unit_testing.rst @@ -0,0 +1,164 @@ +################## +Unit Testing Class +################## + +Unit testing is an approach to software development in which tests are +written for each function in your application. If you are not familiar +with the concept you might do a little googling on the subject. + +CodeIgniter's Unit Test class is quite simple, consisting of an +evaluation function and two result functions. It's not intended to be a +full-blown test suite but rather a simple mechanism to evaluate your +code to determine if it is producing the correct data type and result. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Unit Test class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('unit_test'); + +Once loaded, the Unit Test object will be available using: $this->unit + +Running Tests +============= + +Running a test involves supplying a test and an expected result to the +following function: + +$this->unit->run( test, expected result, 'test name', 'notes'); +=============================================================== + +Where test is the result of the code you wish to test, expected result +is the data type you expect, test name is an optional name you can give +your test, and notes are optional notes. Example:: + + $test = 1 + 1; + + $expected_result = 2; + + $test_name = 'Adds one plus one'; + + $this->unit->run($test, $expected_result, $test_name); + +The expected result you supply can either be a literal match, or a data +type match. Here's an example of a literal:: + + $this->unit->run('Foo', 'Foo'); + +Here is an example of a data type match:: + + $this->unit->run('Foo', 'is_string'); + +Notice the use of "is_string" in the second parameter? This tells the +function to evaluate whether your test is producing a string as the +result. Here is a list of allowed comparison types: + +- is_object +- is_string +- is_bool +- is_true +- is_false +- is_int +- is_numeric +- is_float +- is_double +- is_array +- is_null + +Generating Reports +================== + +You can either display results after each test, or your can run several +tests and generate a report at the end. To show a report directly simply +echo or return the run function:: + + echo $this->unit->run($test, $expected_result); + +To run a full report of all tests, use this:: + + echo $this->unit->report(); + +The report will be formatted in an HTML table for viewing. If you prefer +the raw data you can retrieve an array using:: + + echo $this->unit->result(); + +Strict Mode +=========== + +By default the unit test class evaluates literal matches loosely. +Consider this example:: + + $this->unit->run(1, TRUE); + +The test is evaluating an integer, but the expected result is a boolean. +PHP, however, due to it's loose data-typing will evaluate the above code +as TRUE using a normal equality test:: + + if (1 == TRUE) echo 'This evaluates as true'; + +If you prefer, you can put the unit test class in to strict mode, which +will compare the data type as well as the value:: + + if (1 === TRUE) echo 'This evaluates as FALSE'; + +To enable strict mode use this:: + + $this->unit->use_strict(TRUE); + +Enabling/Disabling Unit Testing +=============================== + +If you would like to leave some testing in place in your scripts, but +not have it run unless you need it, you can disable unit testing using:: + + $this->unit->active(FALSE) + +Unit Test Display +================= + +When your unit test results display, the following items show by +default: + +- Test Name (test_name) +- Test Datatype (test_datatype) +- Expected Datatype (res_datatype) +- Result (result) +- File Name (file) +- Line Number (line) +- Any notes you entered for the test (notes) + +You can customize which of these items get displayed by using +$this->unit->set_items(). For example, if you only wanted the test name +and the result displayed: + +Customizing displayed tests +--------------------------- + +:: + + $this->unit->set_test_items(array('test_name', 'result')); + +Creating a Template +------------------- + +If you would like your test results formatted differently then the +default you can set your own template. Here is an example of a simple +template. Note the required pseudo-variables:: + + $str = ' + <table border="0" cellpadding="4" cellspacing="1"> + {rows} + <tr> + <td>{item}</td> + <td>{result}</td> + </tr> + {/rows} + </table>'; + + $this->unit->set_template($str); + +.. note:: Your template must be declared **before** running the unit + test process. diff --git a/user_guide_src/source/libraries/uri.rst b/user_guide_src/source/libraries/uri.rst new file mode 100644 index 000000000..ee60b77d7 --- /dev/null +++ b/user_guide_src/source/libraries/uri.rst @@ -0,0 +1,188 @@ +######### +URI Class +######### + +The URI Class provides functions that help you retrieve information from +your URI strings. If you use URI routing, you can also retrieve +information about the re-routed segments. + +.. note:: This class is initialized automatically by the system so there + is no need to do it manually. + +$this->uri->segment(n) +====================== + +Permits you to retrieve a specific segment. Where n is the segment +number you wish to retrieve. Segments are numbered from left to right. +For example, if your full URL is this:: + + http://example.com/index.php/news/local/metro/crime_is_up + +The segment numbers would be this: + +#. news +#. local +#. metro +#. crime_is_up + +By default the function returns FALSE (boolean) if the segment does not +exist. There is an optional second parameter that permits you to set +your own default value if the segment is missing. For example, this +would tell the function to return the number zero in the event of +failure:: + + $product_id = $this->uri->segment(3, 0); + +It helps avoid having to write code like this:: + + if ($this->uri->segment(3) === FALSE) + { + $product_id = 0; + } + else + { + $product_id = $this->uri->segment(3); + } + +$this->uri->rsegment(n) +======================= + +This function is identical to the previous one, except that it lets you +retrieve a specific segment from your re-routed URI in the event you are +using CodeIgniter's :doc:`URI Routing <../general/routing>` feature. + +$this->uri->slash_segment(n) +============================= + +This function is almost identical to $this->uri->segment(), except it +adds a trailing and/or leading slash based on the second parameter. If +the parameter is not used, a trailing slash added. Examples:: + + $this->uri->slash_segment(3); + $this->uri->slash_segment(3, 'leading'); + $this->uri->slash_segment(3, 'both'); + +Returns: + +#. segment/ +#. /segment +#. /segment/ + +$this->uri->slash_rsegment(n) +============================== + +This function is identical to the previous one, except that it lets you +add slashes a specific segment from your re-routed URI in the event you +are using CodeIgniter's :doc:`URI Routing <../general/routing>` +feature. + +$this->uri->uri_to_assoc(n) +============================= + +This function lets you turn URI segments into and associative array of +key/value pairs. Consider this URI:: + + index.php/user/search/name/joe/location/UK/gender/male + +Using this function you can turn the URI into an associative array with +this prototype:: + + [array] + ( + 'name' => 'joe' + 'location' => 'UK' + 'gender' => 'male' + ) + +The first parameter of the function lets you set an offset. By default +it is set to 3 since your URI will normally contain a +controller/function in the first and second segments. Example:: + + $array = $this->uri->uri_to_assoc(3); + + echo $array['name']; + +The second parameter lets you set default key names, so that the array +returned by the function will always contain expected indexes, even if +missing from the URI. Example:: + + $default = array('name', 'gender', 'location', 'type', 'sort'); + + $array = $this->uri->uri_to_assoc(3, $default); + +If the URI does not contain a value in your default, an array index will +be set to that name, with a value of FALSE. + +Lastly, if a corresponding value is not found for a given key (if there +is an odd number of URI segments) the value will be set to FALSE +(boolean). + +$this->uri->ruri_to_assoc(n) +============================== + +This function is identical to the previous one, except that it creates +an associative array using the re-routed URI in the event you are using +CodeIgniter's :doc:`URI Routing <../general/routing>` feature. + +$this->uri->assoc_to_uri() +============================ + +Takes an associative array as input and generates a URI string from it. +The array keys will be included in the string. Example:: + + $array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red'); + + $str = $this->uri->assoc_to_uri($array); + + // Produces: product/shoes/size/large/color/red + +$this->uri->uri_string() +========================= + +Returns a string with the complete URI. For example, if this is your +full URL:: + + http://example.com/index.php/news/local/345 + +The function would return this:: + + /news/local/345 + +$this->uri->ruri_string() +========================== + +This function is identical to the previous one, except that it returns +the re-routed URI in the event you are using CodeIgniter's :doc:`URI +Routing <../general/routing>` feature. + +$this->uri->total_segments() +============================= + +Returns the total number of segments. + +$this->uri->total_rsegments() +============================== + +This function is identical to the previous one, except that it returns +the total number of segments in your re-routed URI in the event you are +using CodeIgniter's :doc:`URI Routing <../general/routing>` feature. + +$this->uri->segment_array() +============================ + +Returns an array containing the URI segments. For example:: + + $segs = $this->uri->segment_array(); + + foreach ($segs as $segment) + { + echo $segment; + echo '<br />'; + } + +$this->uri->rsegment_array() +============================= + +This function is identical to the previous one, except that it returns +the array of segments in your re-routed URI in the event you are using +CodeIgniter's :doc:`URI Routing <../general/routing>` feature. diff --git a/user_guide_src/source/libraries/user_agent.rst b/user_guide_src/source/libraries/user_agent.rst new file mode 100644 index 000000000..855ece29d --- /dev/null +++ b/user_guide_src/source/libraries/user_agent.rst @@ -0,0 +1,200 @@ +################ +User Agent Class +################ + +The User Agent Class provides functions that help identify information +about the browser, mobile device, or robot visiting your site. In +addition you can get referrer information as well as language and +supported character-set information. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the User Agent class is +initialized in your controller using the $this->load->library function:: + + $this->load->library('user_agent'); + +Once loaded, the object will be available using: $this->agent + +User Agent Definitions +====================== + +The user agent name definitions are located in a config file located at: +application/config/user_agents.php. You may add items to the various +user agent arrays if needed. + +Example +======= + +When the User Agent class is initialized it will attempt to determine +whether the user agent browsing your site is a web browser, a mobile +device, or a robot. It will also gather the platform information if it +is available. + +:: + + $this->load->library('user_agent'); + + if ($this->agent->is_browser()) + { + $agent = $this->agent->browser().' '.$this->agent->version(); + } + elseif ($this->agent->is_robot()) + { + $agent = $this->agent->robot(); + } + elseif ($this->agent->is_mobile()) + { + $agent = $this->agent->mobile(); + } + else + { + $agent = 'Unidentified User Agent'; + } + + echo $agent; + + echo $this->agent->platform(); // Platform info (Windows, Linux, Mac, etc.) + +****************** +Function Reference +****************** + +$this->agent->is_browser() +=========================== + +Returns TRUE/FALSE (boolean) if the user agent is a known web browser. + +:: + + if ($this->agent->is_browser('Safari')) + { + echo 'You are using Safari.'; + } + else if ($this->agent->is_browser()) + { + echo 'You are using a browser.'; + } + + +.. note:: The string "Safari" in this example is an array key in the + list of browser definitions. You can find this list in + application/config/user_agents.php if you want to add new browsers or + change the stings. + +$this->agent->is_mobile() +========================== + +Returns TRUE/FALSE (boolean) if the user agent is a known mobile device. + +:: + + if ($this->agent->is_mobile('iphone')) + { + $this->load->view('iphone/home'); + } + else if ($this->agent->is_mobile()) + { + $this->load->view('mobile/home'); + } + else + { + $this->load->view('web/home'); + } + + +$this->agent->is_robot() +========================= + +Returns TRUE/FALSE (boolean) if the user agent is a known robot. + +.. note:: The user agent library only contains the most common robot + definitions. It is not a complete list of bots. There are hundreds of + them so searching for each one would not be very efficient. If you find + that some bots that commonly visit your site are missing from the list + you can add them to your application/config/user_agents.php file. + +$this->agent->is_referral() +============================ + +Returns TRUE/FALSE (boolean) if the user agent was referred from another +site. + +$this->agent->browser() +======================= + +Returns a string containing the name of the web browser viewing your +site. + +$this->agent->version() +======================= + +Returns a string containing the version number of the web browser +viewing your site. + +$this->agent->mobile() +====================== + +Returns a string containing the name of the mobile device viewing your +site. + +$this->agent->robot() +===================== + +Returns a string containing the name of the robot viewing your site. + +$this->agent->platform() +======================== + +Returns a string containing the platform viewing your site (Linux, +Windows, OS X, etc.). + +$this->agent->referrer() +======================== + +The referrer, if the user agent was referred from another site. +Typically you'll test for this as follows:: + + if ($this->agent->is_referral()) + { + echo $this->agent->referrer(); + } + +$this->agent->agent_string() +============================= + +Returns a string containing the full user agent string. Typically it +will be something like this:: + + Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.4) Gecko/20060613 Camino/1.0.2 + +$this->agent->accept_lang() +============================ + +Lets you determine if the user agent accepts a particular language. +Example:: + + if ($this->agent->accept_lang('en')) + { + echo 'You accept English!'; + } + +.. note:: This function is not typically very reliable since some + browsers do not provide language info, and even among those that do, it + is not always accurate. + +$this->agent->accept_charset() +=============================== + +Lets you determine if the user agent accepts a particular character set. +Example:: + + if ($this->agent->accept_charset('utf-8')) + { + echo 'You browser supports UTF-8!'; + } + +.. note:: This function is not typically very reliable since some + browsers do not provide character-set info, and even among those that + do, it is not always accurate. diff --git a/user_guide_src/source/libraries/xmlrpc.rst b/user_guide_src/source/libraries/xmlrpc.rst new file mode 100644 index 000000000..3b945769f --- /dev/null +++ b/user_guide_src/source/libraries/xmlrpc.rst @@ -0,0 +1,536 @@ +################################## +XML-RPC and XML-RPC Server Classes +################################## + +CodeIgniter's XML-RPC classes permit you to send requests to another +server, or set up your own XML-RPC server to receive requests. + +**************** +What is XML-RPC? +**************** + +Quite simply it is a way for two computers to communicate over the +internet using XML. One computer, which we will call the client, sends +an XML-RPC **request** to another computer, which we will call the +server. Once the server receives and processes the request it will send +back a **response** to the client. + +For example, using the MetaWeblog API, an XML-RPC Client (usually a +desktop publishing tool) will send a request to an XML-RPC Server +running on your site. This request might be a new weblog entry being +sent for publication, or it could be a request for an existing entry for +editing. When the XML-RPC Server receives this request it will examine +it to determine which class/method should be called to process the +request. Once processed, the server will then send back a response +message. + +For detailed specifications, you can visit the +`XML-RPC <http://www.xmlrpc.com/>`_ site. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the XML-RPC and XML-RPCS classes +are initialized in your controller using the $this->load->library +function: + +To load the XML-RPC class you will use:: + + $this->load->library('xmlrpc'); + +Once loaded, the xml-rpc library object will be available using: +$this->xmlrpc + +To load the XML-RPC Server class you will use:: + + $this->load->library('xmlrpc'); + $this->load->library('xmlrpcs'); + +Once loaded, the xml-rpcs library object will be available using: +$this->xmlrpcs + +.. note:: When using the XML-RPC Server class you must load BOTH the + XML-RPC class and the XML-RPC Server class. + +Sending XML-RPC Requests +======================== + +To send a request to an XML-RPC server you must specify the following +information: + +- The URL of the server +- The method on the server you wish to call +- The *request* data (explained below). + +Here is a basic example that sends a simple Weblogs.com ping to the +`Ping-o-Matic <http://pingomatic.com/>`_ + +:: + + $this->load->library('xmlrpc'); + + $this->xmlrpc->server('http://rpc.pingomatic.com/', 80); + $this->xmlrpc->method('weblogUpdates.ping'); + + $request = array('My Photoblog', 'http://www.my-site.com/photoblog/'); + $this->xmlrpc->request($request); + + if ( ! $this->xmlrpc->send_request()) + { + echo $this->xmlrpc->display_error(); + } + +Explanation +----------- + +The above code initializes the XML-RPC class, sets the server URL and +method to be called (weblogUpdates.ping). The request (in this case, the +title and URL of your site) is placed into an array for transportation, +and compiled using the request() function. Lastly, the full request is +sent. If the send_request() method returns false we will display the +error message sent back from the XML-RPC Server. + +Anatomy of a Request +==================== + +An XML-RPC request is simply the data you are sending to the XML-RPC +server. Each piece of data in a request is referred to as a request +parameter. The above example has two parameters: The URL and title of +your site. When the XML-RPC server receives your request, it will look +for parameters it requires. + +Request parameters must be placed into an array for transportation, and +each parameter can be one of seven data types (strings, numbers, dates, +etc.). If your parameters are something other than strings you will have +to include the data type in the request array. + +Here is an example of a simple array with three parameters:: + + $request = array('John', 'Doe', 'www.some-site.com'); + $this->xmlrpc->request($request); + +If you use data types other than strings, or if you have several +different data types, you will place each parameter into its own array, +with the data type in the second position:: + + $request = array ( + array('John', 'string'), + array('Doe', 'string'), + array(FALSE, 'boolean'), + array(12345, 'int') + ); + $this->xmlrpc->request($request); + +The `Data Types <#datatypes>`_ section below has a full list of data +types. +Creating an XML-RPC Server +========================== + +An XML-RPC Server acts as a traffic cop of sorts, waiting for incoming +requests and redirecting them to the appropriate functions for +processing. + +To create your own XML-RPC server involves initializing the XML-RPC +Server class in your controller where you expect the incoming request to +appear, then setting up an array with mapping instructions so that +incoming requests can be sent to the appropriate class and method for +processing. + +Here is an example to illustrate:: + + $this->load->library('xmlrpc'); + $this->load->library('xmlrpcs'); + + $config['functions']['new_post'] = array('function' => 'My_blog.new_entry'), + $config['functions']['update_post'] = array('function' => 'My_blog.update_entry'); + $config['object'] = $this; + + $this->xmlrpcs->initialize($config); + $this->xmlrpcs->serve(); + +The above example contains an array specifying two method requests that +the Server allows. The allowed methods are on the left side of the +array. When either of those are received, they will be mapped to the +class and method on the right. + +The 'object' key is a special key that you pass an instantiated class +object with, which is necessary when the method you are mapping to is +not part of the CodeIgniter super object. + +In other words, if an XML-RPC Client sends a request for the new_post +method, your server will load the My_blog class and call the new_entry +function. If the request is for the update_post method, your server +will load the My_blog class and call the update_entry function. + +The function names in the above example are arbitrary. You'll decide +what they should be called on your server, or if you are using +standardized APIs, like the Blogger or MetaWeblog API, you'll use their +function names. + +There are two additional configuration keys you may make use of when +initializing the server class: debug can be set to TRUE in order to +enable debugging, and xss_clean may be set to FALSE to prevent sending +data through the Security library's xss_clean function. + +Processing Server Requests +========================== + +When the XML-RPC Server receives a request and loads the class/method +for processing, it will pass an object to that method containing the +data sent by the client. + +Using the above example, if the new_post method is requested, the +server will expect a class to exist with this prototype:: + + class My_blog extends CI_Controller { + + function new_post($request) + { + + } + } + +The $request variable is an object compiled by the Server, which +contains the data sent by the XML-RPC Client. Using this object you will +have access to the *request parameters* enabling you to process the +request. When you are done you will send a Response back to the Client. + +Below is a real-world example, using the Blogger API. One of the methods +in the Blogger API is getUserInfo(). Using this method, an XML-RPC +Client can send the Server a username and password, in return the Server +sends back information about that particular user (nickname, user ID, +email address, etc.). Here is how the processing function might look:: + + class My_blog extends CI_Controller { + + function getUserInfo($request) + { + $username = 'smitty'; + $password = 'secretsmittypass'; + + $this->load->library('xmlrpc'); + + $parameters = $request->output_parameters(); + + if ($parameters['1'] != $username AND $parameters['2'] != $password) + { + return $this->xmlrpc->send_error_message('100', 'Invalid Access'); + } + + $response = array(array('nickname' => array('Smitty','string'), + 'userid' => array('99','string'), + 'url' => array('http://yoursite.com','string'), + 'email' => array('jsmith@yoursite.com','string'), + 'lastname' => array('Smith','string'), + 'firstname' => array('John','string') + ), + 'struct'); + + return $this->xmlrpc->send_response($response); + } + } + +Notes: +------ + +The output_parameters() function retrieves an indexed array +corresponding to the request parameters sent by the client. In the above +example, the output parameters will be the username and password. + +If the username and password sent by the client were not valid, and +error message is returned using send_error_message(). + +If the operation was successful, the client will be sent back a response +array containing the user's info. + +Formatting a Response +===================== + +Similar to *Requests*, *Responses* must be formatted as an array. +However, unlike requests, a response is an array **that contains a +single item**. This item can be an array with several additional arrays, +but there can be only one primary array index. In other words, the basic +prototype is this:: + + $response = array('Response data', 'array'); + +Responses, however, usually contain multiple pieces of information. In +order to accomplish this we must put the response into its own array so +that the primary array continues to contain a single piece of data. +Here's an example showing how this might be accomplished:: + + $response = array ( + array( + 'first_name' => array('John', 'string'), + 'last_name' => array('Doe', 'string'), + 'member_id' => array(123435, 'int'), + 'todo_list' => array(array('clean house', 'call mom', 'water plants'), 'array'), + ), + 'struct' + ); + +Notice that the above array is formatted as a struct. This is the most +common data type for responses. + +As with Requests, a response can be one of the seven data types listed +in the `Data Types <#datatypes>`_ section. + +Sending an Error Response +========================= + +If you need to send the client an error response you will use the +following:: + + return $this->xmlrpc->send_error_message('123', 'Requested data not available'); + +The first parameter is the error number while the second parameter is +the error message. + +Creating Your Own Client and Server +=================================== + +To help you understand everything we've covered thus far, let's create a +couple controllers that act as XML-RPC Client and Server. You'll use the +Client to send a request to the Server and receive a response. + +The Client +---------- + +Using a text editor, create a controller called xmlrpc_client.php. In +it, place this code and save it to your applications/controllers/ +folder:: + + <?php + + class Xmlrpc_client extends CI_Controller { + + function index() + { + $this->load->helper('url'); + $server_url = site_url('xmlrpc_server'); + + $this->load->library('xmlrpc'); + + $this->xmlrpc->server($server_url, 80); + $this->xmlrpc->method('Greetings'); + + $request = array('How is it going?'); + $this->xmlrpc->request($request); + + if ( ! $this->xmlrpc->send_request()) + { + echo $this->xmlrpc->display_error(); + } + else + { + echo '<pre>'; + print_r($this->xmlrpc->display_response()); + echo '</pre>'; + } + } + } + ?> + +.. note:: In the above code we are using a "url helper". You can find more + information in the :doc:`Helpers Functions <../general/helpers>` page. + +The Server +---------- + +Using a text editor, create a controller called xmlrpc_server.php. In +it, place this code and save it to your applications/controllers/ +folder:: + + <?php + + class Xmlrpc_server extends CI_Controller { + + function index() + { + $this->load->library('xmlrpc'); + $this->load->library('xmlrpcs'); + + $config['functions']['Greetings'] = array('function' => 'Xmlrpc_server.process'); + + $this->xmlrpcs->initialize($config); + $this->xmlrpcs->serve(); + } + + + function process($request) + { + $parameters = $request->output_parameters(); + + $response = array( + array( + 'you_said' => $parameters['0'], + 'i_respond' => 'Not bad at all.'), + 'struct'); + + return $this->xmlrpc->send_response($response); + } + } + ?> + + +Try it! +------- + +Now visit the your site using a URL similar to this:: + + example.com/index.php/xmlrpc_client/ + +You should now see the message you sent to the server, and its response +back to you. + +The client you created sends a message ("How's is going?") to the +server, along with a request for the "Greetings" method. The Server +receives the request and maps it to the "process" function, where a +response is sent back. + +Using Associative Arrays In a Request Parameter +=============================================== + +If you wish to use an associative array in your method parameters you +will need to use a struct datatype:: + + $request = array( + array( + // Param 0 + array( + 'name'=>'John' + ), + 'struct' + ), + array( + // Param 1 + array( + 'size'=>'large', + 'shape'=>'round' + ), + 'struct' + ) + ); + $this->xmlrpc->request($request); + +You can retrieve the associative array when processing the request in +the Server. + +:: + + $parameters = $request->output_parameters(); + $name = $parameters['0']['name']; + $size = $parameters['1']['size']; + $size = $parameters['1']['shape']; + +************************** +XML-RPC Function Reference +************************** + +$this->xmlrpc->server() +======================= + +Sets the URL and port number of the server to which a request is to be +sent:: + + $this->xmlrpc->server('http://www.sometimes.com/pings.php', 80); + +$this->xmlrpc->timeout() +======================== + +Set a time out period (in seconds) after which the request will be +canceled:: + + $this->xmlrpc->timeout(6); + +$this->xmlrpc->method() +======================= + +Sets the method that will be requested from the XML-RPC server:: + + $this->xmlrpc->method('method'); + +Where method is the name of the method. + +$this->xmlrpc->request() +======================== + +Takes an array of data and builds request to be sent to XML-RPC server:: + + $request = array(array('My Photoblog', 'string'), 'http://www.yoursite.com/photoblog/'); + $this->xmlrpc->request($request); + +$this->xmlrpc->send_request() +============================== + +The request sending function. Returns boolean TRUE or FALSE based on +success for failure, enabling it to be used conditionally. + +$this->xmlrpc->set_debug(TRUE); +================================ + +Enables debugging, which will display a variety of information and error +data helpful during development. + +$this->xmlrpc->display_error() +=============================== + +Returns an error message as a string if your request failed for some +reason. + +:: + + echo $this->xmlrpc->display_error(); + +$this->xmlrpc->display_response() +================================== + +Returns the response from the remote server once request is received. +The response will typically be an associative array. + +:: + + $this->xmlrpc->display_response(); + +$this->xmlrpc->send_error_message() +===================================== + +This function lets you send an error message from your server to the +client. First parameter is the error number while the second parameter +is the error message. + +:: + + return $this->xmlrpc->send_error_message('123', 'Requested data not available'); + +$this->xmlrpc->send_response() +=============================== + +Lets you send the response from your server to the client. An array of +valid data values must be sent with this method. + +:: + + $response = array( + array( + 'flerror' => array(FALSE, 'boolean'), + 'message' => "Thanks for the ping!" + ) + 'struct'); + return $this->xmlrpc->send_response($response); + +Data Types +========== + +According to the `XML-RPC spec <http://www.xmlrpc.com/spec>`_ there are +seven types of values that you can send via XML-RPC: + +- *int* or *i4* +- *boolean* +- *string* +- *double* +- *dateTime.iso8601* +- *base64* +- *struct* (contains array of values) +- *array* (contains array of values) + diff --git a/user_guide_src/source/libraries/zip.rst b/user_guide_src/source/libraries/zip.rst new file mode 100644 index 000000000..c27718273 --- /dev/null +++ b/user_guide_src/source/libraries/zip.rst @@ -0,0 +1,208 @@ +################## +Zip Encoding Class +################## + +CodeIgniter's Zip Encoding Class classes permit you to create Zip +archives. Archives can be downloaded to your desktop or saved to a +directory. + +Initializing the Class +====================== + +Like most other classes in CodeIgniter, the Zip class is initialized in +your controller using the $this->load->library function:: + + $this->load->library('zip'); + +Once loaded, the Zip library object will be available using: $this->zip + +Usage Example +============= + +This example demonstrates how to compress a file, save it to a folder on +your server, and download it to your desktop. + +:: + + $name = 'mydata1.txt'; + $data = 'A Data String!'; + + $this->zip->add_data($name, $data); + + // Write the zip file to a folder on your server. Name it "my_backup.zip" + $this->zip->archive('/path/to/directory/my_backup.zip'); + + // Download the file to your desktop. Name it "my_backup.zip" + $this->zip->download('my_backup.zip'); + +****************** +Function Reference +****************** + +$this->zip->add_data() +======================= + +Permits you to add data to the Zip archive. The first parameter must +contain the name you would like given to the file, the second parameter +must contain the file data as a string:: + + $name = 'my_bio.txt'; + $data = 'I was born in an elevator...'; + + $this->zip->add_data($name, $data); + +You are allowed multiple calls to this function in order to add several +files to your archive. Example:: + + $name = 'mydata1.txt'; + $data = 'A Data String!'; + $this->zip->add_data($name, $data); + + $name = 'mydata2.txt'; + $data = 'Another Data String!'; + $this->zip->add_data($name, $data); + +Or you can pass multiple files using an array:: + + $data = array( + 'mydata1.txt' => 'A Data String!', + 'mydata2.txt' => 'Another Data String!' + ); + + $this->zip->add_data($data); + + $this->zip->download('my_backup.zip'); + +If you would like your compressed data organized into sub-folders, +include the path as part of the filename:: + + $name = 'personal/my_bio.txt'; + $data = 'I was born in an elevator...'; + + $this->zip->add_data($name, $data); + +The above example will place my_bio.txt inside a folder called +personal. + +$this->zip->add_dir() +====================== + +Permits you to add a directory. Usually this function is unnecessary +since you can place your data into folders when using +$this->zip->add_data(), but if you would like to create an empty folder +you can do so. Example:: + + $this->zip->add_dir('myfolder'); // Creates a folder called "myfolder" + +$this->zip->read_file() +======================== + +Permits you to compress a file that already exists somewhere on your +server. Supply a file path and the zip class will read it and add it to +the archive:: + + $path = '/path/to/photo.jpg'; + + $this->zip->read_file($path); + + // Download the file to your desktop. Name it "my_backup.zip" + $this->zip->download('my_backup.zip'); + +If you would like the Zip archive to maintain the directory structure of +the file in it, pass TRUE (boolean) in the second parameter. Example:: + + $path = '/path/to/photo.jpg'; + + $this->zip->read_file($path, TRUE); + + // Download the file to your desktop. Name it "my_backup.zip" + $this->zip->download('my_backup.zip'); + +In the above example, photo.jpg will be placed inside two folders: +path/to/ + +$this->zip->read_dir() +======================= + +Permits you to compress a folder (and its contents) that already exists +somewhere on your server. Supply a file path to the directory and the +zip class will recursively read it and recreate it as a Zip archive. All +files contained within the supplied path will be encoded, as will any +sub-folders contained within it. Example:: + + $path = '/path/to/your/directory/'; + + $this->zip->read_dir($path); + + // Download the file to your desktop. Name it "my_backup.zip" + $this->zip->download('my_backup.zip'); + +By default the Zip archive will place all directories listed in the +first parameter inside the zip. If you want the tree preceding the +target folder to be ignored you can pass FALSE (boolean) in the second +parameter. Example:: + + $path = '/path/to/your/directory/'; + + $this->zip->read_dir($path, FALSE); + +This will create a ZIP with the folder "directory" inside, then all +sub-folders stored correctly inside that, but will not include the +folders /path/to/your. + +$this->zip->archive() +===================== + +Writes the Zip-encoded file to a directory on your server. Submit a +valid server path ending in the file name. Make sure the directory is +writable (666 or 777 is usually OK). Example:: + + $this->zip->archive('/path/to/folder/myarchive.zip'); // Creates a file named myarchive.zip + +$this->zip->download() +====================== + +Causes the Zip file to be downloaded from your server. The function must +be passed the name you would like the zip file called. Example:: + + $this->zip->download('latest_stuff.zip'); // File will be named "latest_stuff.zip" + +.. note:: Do not display any data in the controller in which you call + this function since it sends various server headers that cause the + download to happen and the file to be treated as binary. + +$this->zip->get_zip() +====================== + +Returns the Zip-compressed file data. Generally you will not need this +function unless you want to do something unique with the data. Example:: + + $name = 'my_bio.txt'; + $data = 'I was born in an elevator...'; + + $this->zip->add_data($name, $data); + + $zip_file = $this->zip->get_zip(); + +$this->zip->clear_data() +========================= + +The Zip class caches your zip data so that it doesn't need to recompile +the Zip archive for each function you use above. If, however, you need +to create multiple Zips, each with different data, you can clear the +cache between calls. Example:: + + $name = 'my_bio.txt'; + $data = 'I was born in an elevator...'; + + $this->zip->add_data($name, $data); + $zip_file = $this->zip->get_zip(); + + $this->zip->clear_data(); + + $name = 'photo.jpg'; + $this->zip->read_file("/path/to/photo.jpg"); // Read the file's contents + + + $this->zip->download('myphotos.zip'); + |