Booosta Framework 2.2

 

 

 

 

Booosta PHP-Web-Framework

 

 

 

 

 

 

 

Documentation

 

 

Peter Buzanits

 

 

Version 1.0

 

 

 

Table of Contents

The Booosta Framework

Basic structure of the Booosta Framework

Requirements

Installation

Database abstraction

Transaction functions

Data Objects

Create a data object

Flexible data objects

Flexible (serial) fields

Template Engine

Template File

Include Subtemplates

Form elements

Form Element Objects

CSelect

CShiftbox

Other form elements

Other tools

Tablelister

Lineparser

PDF Writer

Settings

Module Webapp

Override predefined functions

Data and functions in Webapp

Change behaviour of data table

Hooks

Other functions

CLI

Pass parameters to template variables

XSRF prevention

Tools

User System

Privileges

Roles

Templates

Multi language system

Module Ajax

Constructor

Response

Module Form checker

Module Excel Reader

Module Email

Module Image Gallery

Module Cache

Module UploadFile

UploadImage

Modules in development

Module Facebook

Module IMAP

The mail_message class

Preview to the future

Typo3 integration

GUI

The Booosta Framework

 

 

Booosta is a Framework for the development of PHP web applications. It provides powerful classes and functions that make life for web developers easier. It is licensed under the GPL v3 which means it is free software. Some external parts may be licensed under GPL v2 or other open source licenses.

 

Booosta is an ERAD (extreme rapid application development) environment, which provides some MVC functionality (Model, View, Controller).

 

Booosta provides modules for database abstraction, database access through data objects, a web application infrastructure, a template system, an Ajax helper class, sending emails or an image gallery.

 

It contains several external open source PHP and JavaScript projects like modules from the PEAR repository. These are provided with the Booosta release.


How does Booosta compare to the big PHP frameworks like Symfonie or Zend?

 

Those frameworks are very large ones that provide functionality for developing huge web applications. If you want to implement your own social network you should consider using one of these instead of Booosta. Booosta has been designed to develop small and mid-sized web applications very fast, easy and efficient.

 

KISS (keep it simple, stupid) has been a major design goal of Booosta. The time you use to set up one of the large frameworks for use in your application is the time you need to implement your whole application with Booosta – of course if it is really a very, very simple application that does nothing but displaying, inserting, editing and deleting database contents. More complex applications still need time to be developed ;-).

Basic structure of the Booosta Framework

 

For using Booosta you have to download the release and copy it into the root directory of your web app. You have to include lib/framework.incl.php in your PHP files. All modules and other include files you need are automatically included in the framework.incl.php.

 

 

Requirements

PHP 5.3 is required for using Booosta since version 2.0.

Installation

 

  1. 1.Download and unpack the framework.
    tar xzf booosta-2.x.x.tgz 

  2. 2.As default, mysqli is used as database module. If you are fine with that you do not need to alter anything here. If you want another database module like postgresql, you have to make a symlink named db.incl.php to the according file in the lib directory. E. g.:
    cd lib; ln -sf db_postgresql.incl.php db.incl.php 

  3. 3.Create the database and the tables included in database.sql with the mysql command line tool or with phpmyadmin. If you use another database like postgresql you probably have to alter the SQL commands in this file. 

  4. 4.Set your database connection details in local/config.incl.php 

  5. 5.If you want to use the user system, edit the encryption key in lib/key.php and set the admin password with php setadminpw mypassword 

  6. 6.Include framework.incl.php in all of your PHP files
    include_once 'lib/framework.incl.php'; 

 

 

Again in short with mysqli:

 

tar xzf booosta-2.x.x.tgz
mysql -u root -p dbname < database.sql
vi local/config.incl.php
vi lib/key.php
php setadminpw
mypassword

Database abstraction

 

Booosta provides functions for database abstraction. Currently MySQL and Postgresql are supported. Work on Sqlite is in progress.

 

To use the database abstraction you have to symlink the file db_mysqli.incl.php or db_pgsql.incl.php in the /lib folder. This is done by default for mysqli.

 

Available functions are:

 

query()

boolean query($sql, $do_log=true)

 

query() makes a SQL query to the database without returning any results from this query. It can be used to make data manipulation like insert, update or delete. This function returns 0 if no error occurred and -1 if there was an error.

 

If $do_log is set to true and the global variable $LOG_MODE is set to true the query is logged. How this logging is done you can define in the function log_db which you can alter in the include file db_mysqli.incl.php if you wish.

 

Example:

$error = query(“insert into table1 values ('foo', 'bar', '1')”);

 

 

query_value()

string query_value($sql)

 

query_value() makes a SQL query to the database and returns exactly one value from this query. If the query returns more than on value the first one is returned. It should be used to get a single value out of the database.

 

Example:

$firstname = query_value(“select firstname from customer where id='2'”);

 

 

query_value_set()

array query_value_set($sql)

 

query_value_set() makes a SQL query to the database and returns a set of values that are returned from the query. It returns a single column from several rows. So it can be seen as a vertical list of values.

 

Example:

$firstnames = query_value_set(“select firstname from customer”);

foreach($firstnames as $firstname) print “$firstname\n”;

// returns a list of all first names in the table

 

 

query_list()

array query_list($sql)

 

query_list() makes a SQL query to the database and returns a list of values from a single table record. It can be seen as a horizontal list of values.

 

Example:

$customer_data = query_list(“select firstname, lastname, age from customer where id='3'”);

 

 

query_arrays()

array query_arrays($sql)

 

query_arrays() makes a SQL query to the database and returns a set of rows from a table. The result is an array of arrays.

 

Example:

 

$data = query_arrays(“select * from customer”);

foreach($data as $d)

  foreach($d as $field=>$value)

    print “$field of record $d[id]: $value\n”;

 

// results in output like:

id of record 1: 1

firstname of record 1: George

lastname of record 1: Smith

id of record 2: 2

firstname of record 2: Ann

lastname of record 2: Taylor

 

 

last_insert_id()

integer last_insert_id()

 

last_insert_id() returns the last autoincrement value that has been inserted into the database.

 

 

 

query_index_array()

array query_index_array($sql)

 

query_index_array() returns an array that is indexed with the first result column of the response and contains the second column as value.

 

Example:

 

$result = query_index_array(“select id, firstname from customer”);

print_r($result);

 

// output:

Array(

  [1] => George

  [2] => Ann

)

 

 

query_index_valueset()

array query_index_valueset($sql, $valuefield, $indexfield)

 

query_index_valueset() returns an array that has the field in the second parameter as value and the field in the third parameter as index.

 

Example:

 

$result = query_index_valueset(“select * from customer”, “firstname”, “id”);

// leads to same result as in example above

 

 

Transaction functions

 

These functions are only working if the underlying database system supports transactions. If it does not, these functions are just doing nothing. The parameter for the transaction name is ignored by database systems that do not support named transactions such as MySQL.

 

 

transaction_start()

transaction_start($transaction_name)

 

starts a transaction

 

 

transaction_rollback()

transaction_rollback($transaction_name)

 

rollbacks a transaction

 

 

transaction_commit()

transaction_commit($transaction_name)

 

commit a transaction

 

 

Be aware that the database abstraction layer does not take any care about SQL injection prevention. If you use it you have to make sure not to use code that insecures your database!

Data Objects

 

Booosta provides data objects for the manipulation of data in the database. With data objects you do not need to use SQL code for reading, inserting, updating or deleting rows in the database. Data objects do not need to be defined by the programer. Booosta defines them by itself when connected to the database. It seeks for available tables and defines a new class for each table.

 

The name of a data object class is C_tablename, where tablename is the name of the table. If you have a table name customer, the according class is named C_customer.

 

The data objects build the Model part in the MVC concept of this framework.

 

 

Create a data object

 

You can create an empty data object by simply instantiating it with new:

 

$data = new C_customer();

 

If you want a data object filled with the data of a particular row you can use the method get_object() with the primary key of the row or a SQL where statement as parameter. If this statement results to more than one rows in the table, the first one returned is used for the object data.

 

$data = C_customer::get_object(2);  // fills the object with data from customer with id 2

$data = C_customer::get_object(“firstname='Ann'”);

 

You can get an array with data objects with the method get_objects. Without parameter it returns objects for all rows in the table. With parameter it uses the parameter as where clause in the database query.

 

$datas = C_customer::get_objects();  // all customers

$datas = C_customer::get_objects('age > 40');  // all customers over 40 years

 

You can access the data fields with the class method get()

 

$firstname = $data->get('firstname');

 

You can alter the data with the method set()

 

$data->set('firstname', 'Mary');

$data->set('myarray', 'key', 'value'); // sets a value in an array

 

You can insert a row with the method insert(). This method returns the primary key of the new row. This is useful, if you use autoincrement fields as primary key.

 

$new_id = $data->insert();

 

You can update a row with the method update(). The row must exist in the database, this means the object has to be created with get_object for having the primary key.

 

$data->update();

 

There is also the method save(). If the record is a new one, save() inserts the record, if it already exists i. e. it was loaded from the table, it updates the record. There is no problem with using save() instead of insert() and update() all the time.

 

You can delete a row with the method delete(). The row must exist in the database, this means the object has to be created with get_object for having the primary key.

 

$data->delete();

 

 

 

Flexible data objects

 

Flexible data object bring some NoSQL feeling to your database. With them you can store data fields in a table that are not one of the table columns. For using the flexible data objects your table has to have the column ser__obj (there are two underscores!). In this column all the fields are stored in a serialized form. There is nothing else to do to create a flexible data object!

 

There are some backdraws to this method of storage. You cannot select rows from the table using this fields – because there is no according column. You also cannot make joins with them or include them in a SQL calculation like sum() or max() etc. So you have to think about what you want to do with this data before deciding if you give the fields a table column or not.

 

The greatest benefits from flexible object you get in scenarios, where lots of data fields are stored, that are only used for display and not for calculation or selection. Also scenarios where lots of different data fields are stored in every row benefit a lot from these objects.

 

To add a data field to a flexible data object just add it with set():

 

$data->set('hobbies' => 'chess, hiking');

 

You also can store arrays and objects in this flexible fields:

 

$data->set('hobbies' => array('chess', 'hiking'));

 

You get the stored data from the object with the same get() function as standard data fields:

 

$hobbies = $data->get('hobbies');

 

Usually Booosta uses the PHP serialize function to serialize the data for storing it in the database. You can alternatively use a XML serialization by setting the global variable $_SERIAL_FORMAT to “xml” in framework.incl.php.

 

Serialization with XML is slower than the PHP serialization, but you can use the XML data in the database without PHP, because XML is a widely known standard.

If you find out that you would need a data field, that is only available in the serialized data, you can simply add that field to your database table. When you save the data object next time, this field will be filled with the according data. To fill the field immediately, just load every row in a data object and call the save() function.

 

 

Flexible (serial) fields

 

If you do not want to store the complete row in a serialized object, you can choose to serialize only designated columns in your table. You can tell Booosta to treat all columns with a particular name in the database as serial field. To do so, add the name of the column to the global array $SERIAL_FIELD in framework.incl.php:

 

$SERIAL_FIELD = array('settings', 'comments');

 

In this example all columns in the database named “settings” or “comments” are treated as serial fields. This means you can store arrays, objects, nested arrays or whatever in this fields. You store it with set() and read it with get() as usual. When you store an array of objects with set() and later you read it with get() you get the same array of objects.

 

Tip: If you choose to store objects in a serial field, be sure to define all the object data that should be stored as public. Protected or private data is omitted by the PHP serialize function and so not stored in the serial field.

 

 

Data objects prevent any attempts of SQL injection. All the data is correctly escaped for database storage. This is another reason to use data objects instead of only the database abstraction also for small changes to the database.

Template Engine

 

Booosta brings its own powerful template engine. It is used by creating template files which contain HTML code and variables, which are filled by the application that invokes the template engine. The Booosta template engine can work with a single template file or with nested templates. There is also the possibility to use simple programming code like if, for or while constructs inside the template files.

 

The template engine builds the View component in the MVC concept of this framework.

 

Template File

 

The template file is a simple HTML file. Everything in this file is sent to the browser as it is. As our web applications are not only static HTML pages, there are variables that can be used inside this files. A variable is noted in the form:

 

{%varname}

 

The template engine parses this and replaces this with the content of the according variable passed to the engine (see later here how to do that).

 

You can use if, for or while with a leading % in the line (must be the first character of the line):

 

%if({%age} < 18):

  {%firstname} {%lastname} is an underager!<br>

%else:

  {%firstname} {%lastname} is {%age} years old and therefore adult<br>

%endif;

 

You can use local variables with %% prefix:

 

%for({%%i}=1; {%%i} <= 10; {%%i}++):

  Line number {%%i}<br>

%endfor;

 

Include Subtemplates

 

Often it is useful to use subtemplates inside a main template. For example you can have a basic layout for your web application that is the same in all of your pages and load the output of your application into a designated area of the browser window. You can define the basic layout in the main template and load subtemplates into a <div> inside this main template, which can be positioned with CSS.

 

You define the place where the output of the subtemplate should be put by the code:

 

##INCLUDE TPLNAME##

 

where TPLNAME is the name of the subtemplate.

 

To invokes the template engine and you have to call the following function in your webapp:

 

$output = parse_template($maintemplate, $subtemplates, $variables);

 

$maintemplate is the template file for the main template. $subtemplates is an array of subtemplates. The indexes of this array are the names of the subtemplates, that is used in the ##INCLUDE statement. $variables is an array with the variables that are used in the template with the {%varname} notation. The indexes of this array are the variable names and the values the according values.

 

Here is a simple example of a template file and the usage of parse_template():

 

 

maintemplate.tpl:

 

<html>

<body>

<h1>Welcome to my web application!<h1>

 

<div id='content'>

##INCLUDE MYSUBTPL##

</div>

 

</body>

</html>

 

 

subtemplate.tpl:

 

Hello, my name is {%firstname} {%lastname} and I am {%age} years old!

 

 

index.php:

 

$data = C_user::get_object(1);

$TPL['firstname'] = $data->get('firstname');

$TPL['lastname'] = $data->get('lastname');

$TPL['age'] = $data->get('age');

 

print parse_template('maintemplate.tpl', array('MYSUBTPL'=>'subtemplate.tpl'), $TPL);

 

 

 

Form elements

 

The Booosta template engine provides a special notation for HTML form fields. This is useful in the case that this notation could change some day for example with the usage of HTML 5. If there is a change in the HTML code for a form, these changes need not to be made in all the templates but only in the default.tags.php file.

 

{FORMSTART action.php}

marks the beginning of the form. action.php is the file that is called by submitting the form.

{FORMEND}

marks the end of a form.

{FORMSTARTN action.php myname}

marks the beginning of the form with a particular name

{FORMSTARTM action.php myname}

like FORMSTARTN, but gives the form the enctype multipart/form-data

{TEXT name value}

Input element of type 'text'. It gets the name and the prefilled value provided.

{HIDDEN name value}

Input element of type 'hidden'.

{PASSWORD name value}

Input element of type 'password'.

{CHECKBOX name checked}

Input element of type 'checkbox'. If the value of checked evaluates to true in PHP, the checkbox will be checked.

{RADIO name thisvalue checkvalue}

Input element of type 'radiobutton'. If the value of checkvalue is the same as of thisvalue, the radio button will be selected.

{FILE name}

Input element of type 'file'. You need a form with enctype multipart/form-data to use this for file uploads.

{DATE name value}

Displays a date selector field.

{DATEINIT}

For using the DATE element, you must place this element on your result page. This contains code to initialize the date selector.

{TEXTAREA name cols rows
Default Text here

}

Input element of type 'textarea'. Number of columns and rows can be defined (optional). The default text that should be filled in has to start in the second line!

{SELECT name defaultvalue size

[key1]value1

[key2]value2

…}

Input element of type 'select'. defaultvalue is the value that is selected by default. size is the optional parameter for the size of the select field. From the second line the content of the select starts.

 

The valuex tells the text that should be displayed in the select and den keyx the value that will be sent by the form.

{FORMSUBMIT}

Submit button for the form.

{FORMSUBMITVAL value}

Submit button that submits a special value.

 

 

There are also some Tags that are not form elements like

 

{IMG imagename}

Image

{LINK linktext target}

Link with given text that links to target. If you want to use spaces in the linktext replace them with ~

 

As you noticed in the last row of the above table, the parts of a LINK element are seperated with spaces. But often you need spaces in the linktext which can be realized with the ~. Also the value fields of form elements like TEXT can have spaces, if you escape them with ~. This is easy if you enter hard coded values there.

 

But often you want to put in variables there. But if you type {%lastname} there and lastname holds spaces you will get ugly effects. To avoid this, you can tell the template engine to escape all spaces with ~ by using {%~lastname}.

 

Form Element Objects

Several HTML form elements can also be created in the PHP code of your application. You than can get the HTML code from the object with the get_html() method or print it out with the print_html() method. Most times it makes more sense to define the form elements in the template instead of the code. Sometimes when elements must be generated dynamically it can be necessary to create them in the PHP code.

 

This is mostly used with the two form elements select and shiftbox. Shiftbox is a combination of two multi row selects with some buttons inbetween to shift elements from one to the other. It is used to select several options out of some available ones.

CSelect

CSelect is a class that creates a HTML form select element.

 

$select = new CSelect($name, $options, $selected);

 

$name is the name of the element. This is also the name of the POST variable that will be sent to the server after the according form is submitted. $options is an array of the available options in the select. The keys of the array are the values that will be sent after a form submit. The values of the array are the values displayed in the select. $selected is the key of the element of $options that will be preselected when the select is shown.

 

Example:

$options = array('A' => 'apple', 'B' => 'banana', 'C' => 'lemon');

$select = new CSelect('fruit', $options, 'B');

$this->TPL['fruits'] = $select->get_html();

 

In the above example the HTML select can be inserted in the template with {%fruits}. It shows a select with the three visible entries apple, banana, lemon where banana is preselected. If the form is submitted the character A, B or C are submitted in the variable 'fruit'.

 

CShiftbox

A CShiftbox is a combination of two multi row selects with some buttons inbetween to shift elements from one to the other. It is used to select several options out of some available ones. In the left select there are the selected options, in the right one the unselected.

 

When the form is submitted a variable named shiftbox_name_sellist. name is the name of the shiftbox as declared in the constructor. The key values of the array that are selected are then filled into this variable seperated with a hyphen (-). You need to avoid the hyphen in the keys of course for not breaking this.

 

$box = new Cshiftbox($name, $options_selected, $all_options);

 

$name is the name of the element and determines the name of the POST variable sent to the server after the form is submitted which will be  shiftbox_name_sellist. $options_selected is an array that contains the options that will be selected (which means in the left select) when the shiftbox is displayed. $all_options is an array with all available options. This must contain all options from $options_selected!

 

Example:

 

$all_options = array('A' => 'apple', 'B' => 'banana', 'C' => 'lemon', 'D' => 'pear');

$options_selected = array('B' => 'banana', 'D' => 'pear');

$box = new Cshiftbox('fruits', $options_selected, $all_options);

$this->TPL['fruits'] = $box->get_html();

 

In the PHP script that receives the submit request:

 

$all_options = array('A' => 'apple', 'B' => 'banana', 'C' => 'lemon', 'D' => 'pear');

$selected = $this->VAR['fruits'];

$options = explode('-', $selected);

foreach($options as $option)

  print 'You selected ' . $all_options[$option] . '<br>';

Other form elements

There are several other classes that define form elements. Usually it is better to define them with their template parser syntax when you use the template parser. In every case $name is the name of the element and the POST variable sent to the server.

 

All the elements put out their HTML-Code with get_html().

 

$el = new Ccheckbox($name, $value);

If $value is a true value (which means in PHP not null, 0 or false) the checkbox will be checked.

 

$el = new Cradiobutton($name, $value);

$el->check();

$value is the value that radiobutton represents. All radiobuttons belonging to one group must have the same $name. check() selects this radiobutton.

 

Other tools

Tablelister

This class provides an easy way to display data from an array as HTML table. There are several ways to modify the way the data is displayed.

$lister = new CtableLister($data [, $tabletags]);
This creates the tablelister object. $data is an array that holds the data to display. $tabletags is a boolean parameter that indicates if the output should contain the tags <table> and </table> around the result. The default is true.

$lister->get_html();
Returns the HTML code for the table that displays the data.

$lister->set_keyfilter($filter);
Here you can filter the rows of the result by the key of the data array. This key is represented by a % in the string $filter. To show only rows, where the key of the data array is lower than 10 you have to set $filter to '%<10'.

$lister->set_fkeyfilter($filter);
Here you can filter the columns that should be displayed in your table. The column names are represented by the keys of the second level arrays in $data of the constructor. These keys are represented by a % in the string $filter. To show only the columns firstname and lastname you have to set $filter to “%=='firstname' || %=='lastname'”. To show every column except for middlename you have to set $filter to “%!='middlename'”. If you just want to provide a list of columns to display you should consider using the method show_fields instead of this method (see below).

$lister->set_header($header);
Here you can set the header of your table. The header will be displayed in the first line of the table with <th> tags. $header can be an array with the header contents or a comma separated string.

$lister->set_links($links);
Here you can set links for particular columns. $links is an array indexed with the column name. The data of this array is the link destination. You can use {name} to fill in the value of an other column of the current row in this destination. This is useful if you make a link for manipulating the current record and want to pass the value of the field id in the link (e. g. edit.php?id={id}).

$lister->set_extrafields($fields);
Here you can add additional columns to every row of the table. E. g. you can add an edit link to the end of every table row. $fields is an array that is indexed with the name of the new column and the data of the array will be displayed.

$lister->set_nvl($field, $value);
Here you can set a value that is displayed if the content of the according element in $data is empty (null value).

$lister->set_conditions($conditions);
Here you can define conditions that determine if the value of a column is displayed. If the condition fails, a &nbsp; is displayed instead of the actual content. $conditions is an array indexed with the column name. The values of the array are a string with the condition. You can use {name} to use the value of an other column in this string. E. g. array('age'=>'{age}>18') for not displaying the age of underagers in a list of people.

$lister->set_table_attribute($attribute, $value);
$lister->set_th_attribute($attribute, $value);
$lister->set_row_attribute($attribute, $value);
$lister->set_data_attribute($attribute, $value);

With this methods you can add a attribute to the tags <table>, <th>, <tr> or <td>. It will show up in the HTML code like <table attribute='value'>

$lister->set_col_data_attribute($column, $attribute, $value);
This sets an additional attribute to the <td> tag of a particular column. The name of the column is specified by $column.

$lister->show_fields($fields);
This is a shorter form of the method
set_fkeyfilter. If you do not need complex conditions in the fkeyfilter but only want to provide a list of fields to display you should better use this method. $fields can be an array of field names to display or a comma separated list.

$lister->hide_fields($fields);
This works similar to show_fields, but displays all available columns except for those in
$fields. $fields can be an array of field names to display or a comma separated list.

$lister->set_foreignkey_db($field [, $table [, $idfield [, $showfield]]]);
This method sets a foreign key on the field
$field. When the table is displayed, tablelister looks into the database table $table (which defaults to $field – i. e. the same name as the field) and selects the row from this database table with the identifier $idfield (default 'id') that matches the value of the actual field. It then retrieves the value of the column $showfield (default 'name') in this row and displays this value.

Example:

You have two database tables: employee and division. Each record of employee has a reference to division that represents the companys division that employee belongs to. The table employee only holds the id of the according record in division. Now you want to display a table with all employees but you want the name of the division instead of the id in your list.

// DB table employee: [id, name, address, division]
// DB table division: [id, name]

$lister->set_foreignkey_db('division');
// same as:
$lister->set_foreignkey_db('division', 'division', 'id', 'name');

 

$lister->set_foreignkey_array($field, $data);
This method works like
set_foreignkey_db, but gathers the foreign key data from the array $data instead of a database table. This arrays has to be indexed with the values found in the current field $field and have the data that should be displayed.

Example:

$hotels = array(array('name'=>'Excelsior', 'rating'=>'4'), …);
$ratings = array('5'=>'excellent', '4'=>'good', '3'=>'average', '2'=>'bad', '1'=>'awful');
$lister = new CtableLister($hotels);
$lister->set_foreignkey_array('rating', $ratings);
print $lister->get_html();

Lineparser

The lineparser is a simple but powerful class that allows you to have several functions applied to a set of lines. These lines can be the lines of a text (separated by newlines) or elements of an array. To use the lineparser you  derive a new class from the class Lineparser and add methods. All self defined method names have to start with parse_ . The parser reads the input lines, calls all the parse_* methods on them and puts out an array with the parsed lines.

$parser = new Lineparser($input);
This constructs the Lineparser object. $input can be an array with the input lines, a file or a string.

$parser->get_result([$delete_empty_lines]);
This returns an arrays with the result lines. if $delete_empty_lines ist set to true (default is false), then all empty lines in the result are deleted.

Example:

class myParser extends Lineparser {
 protected function parse_trimspaces(&$d, $k) { $d = preg_replace('/ +/', ' ', $d); }
 protected function parse_delunderscore(&$d, $k) { $d = str_replace('_', '', $d); }
}

$parser = new myParser('inputfile.txt');
$result = $parser->get_result();

This example reads inputfile.txt, replaces multiple spaces by one space and deletes all underscores in every line. The result comes as an array of the parsed lines. If you pass an array to the constructor, you can access the key of the current array element with $k in your methods.

PDF Writer

The PDF Writer allows you to convert HTML code to PDF files. It uses the open source software TCPDF underneath. The resulting PDF file can be saved on the disk, downloaded from the web server or you can obtain the raw PDF data for using it in your PHP script.

$writer = new pdfwriter($html);
This constructs your pdfwriter object and passes the HTML code to it.

$writer->set_html_content($html);
With this method you can pass the HTML code at a later time after object creation.

$writer->set_page_orientation($orientation);
With this you can select the page orientation. Valid values are 'P' for portrait or 'L' for landscape.

$writer->set_page_format($format);
Here you can select the page format. An example would be 'A4'. All ISO and ANSI standards are supported. Refer to the file lib/ext_tcpdf/tcpdf.php around line 2200 to see a list of them.

$writer->set_author($name);
Here you can set the authors name that will appear in the PDF.

$writer->set_title($title);
Here you can set the title that will appear in the PDF.

$writer->set_subject($subject);
Here you can set the subject that will appear in the PDF.

$writer->set_keywords($keywords);
Here you can set the keywords that will appear in the PDF.

$writer->set_font($font);
Here you can set the font that will be used in the PDF.

$writer->set_fontsize($fontsize);
Here you can set the fontsize that will be used in the PDF.

$writer->set_fontstyle($fontstyle);
Here you can set the fontstyle that will be used in the PDF. Possible values are: B: bold, I: italic, U: underline, D: line-trough, O: overline or any combination of these.

$writer->add_image($file, $x, $y);
Images included in the HTML are included in the resulting PDF. Anyway you can additionally add images with this method. $file is the file name of the image, $x and $y are the coordinates of the upper left corner of the image in pixels on the page.

$writer->download([$filename]);
This method delivers the PDF file as download to the users browser. $filename is the name that the downloaded file will get. Default ist download.pdf.

$writer->save([$filename]);
This method saves the PDF file on the disk. $filename defaults to document.pdf.

$writer->get_data();
This method returns the raw PDF data.

Settings

Im most web applications you need to store several key-value pairs in your database e. g. for saving particular settings. For this purpose you have the small class Settings. This class makes it easier to read and store values in tables that work as key-value stores. A table named settings is available in your database after installation of Booosta.

$settings = new Settings([$table [, $attribute [, $value]]]);
This creates the Settings object. You can pass the name of the database table, the name oft the table column that holds the attribute name (the key) of the record and the name of the column that holds the data (value) to the constructor. The defaults are settings, attribute and value which are the correct names for the predefined database table.

$settings->set($attribute, $value [, $save]);
This method lets you set a value in your store. If you set the parameter $save to false the value will not be written to the database and only be available in the current object as long this object lives. You can write all the values in the object by calling the save method. The default for $save is true.

$settings->save();
This method writes all changes made to the Settings object to the database. If you used the set method with false as third parameter you need to do that to make all changes to the object persistant.

$settings->get([$attribute]);
This method returns the value of the given attribute. If the parameter is omitted, an array with all settings will be returned.

Module Webapp

 

One of the powerful modules of Booosta is the Webapp module. It provides a class named Webapp, which can be used for building web applications with little coding. For using it, you derive your own class from webapp and override some functions or add additional function to it.

 

For realizing a very primitive web application that only has functions for displaying, adding, editing and deleting records in the database, you need almost no coding! Just derive your class where you set the “name” variable to the database table name and create your templates for the web forms, call the run() method of your webapp object and you are done.

 

 

 

Of course you need to do more coding, if you want to realize more complex web applications.

 

Basic structure of a PHP file using Webapp:

 

<?php

include_once 'lib/webapp.incl.php';

 

class myapp extends Webapp

{

  protected $name = 'person';

}

 

$app = new myapp();

$app->run();

?>

 

The variable $name (in the example 'person') must be the name of the database table to make the application running without changes in the code. You also need the template files that are used to display something in the users browser. The templates should reside in the directory tpl and the first template should have the name name_default.tpl where name again is the name of the according database table.

 

You can pass $name as parameter for the constructor instead of defining it as class variable. This is useful if you do not want to define any other variables or methods in your class. Finally you can call the object as a function instead of calling the run() method.

 

<?php
include_once 'lib/webapp.incl.php';

$app = new Webapp('person');

$app();
?>

 

Without any coding the default action of the webapp is to put out a list of all the records in the table with some links to edit or delete the records. They are provided in the template variable {%liste} which can be used in the template file.

 

 

If you want your web application to do something else, you must override the object function action_default(). Everything you must know about that will be discussed later here. Let us first look at the other templates we need. We need one template for creating new records and for editing records. They should be named name_new.tpl and name_edit.tpl

 

The edit template should look somehow like this:

 

{FORMSTART index.php}

{HIDDEN action editdo}

{HIDDEN id {%id}}

 

Firstname: {TEXT firstname {%firstname}} <br>

{FORMSUBMIT}

{FORMEND}

 

The hidden action editdo is necessary to tell the webapp object to invoke the function action_editdo() which again can be overridden. The hidden field id is the primary key of the database table. To make the provided action_editdo() function work properly without overriding it, the name of the primary key column must be id.

 

The new template looks almost similar but has some changes:

 

The action has to be newdo.

The hidden field id can be omitted.

You do not need the default values in the form.

 

 

Override predefined functions

 

If there is a GET or POST parameter named action when the run() function is called, an object function named action_value() is called where value is the value of the action parameter. You can define that function in your class derived from Webapp.

 

The functions action_default(), action_new(), action_edit() and action_delete() are predefined, but can be overridden by just defining them in the class. These function define what to happen if the user chooses to create a new record, to edit or delete one. This means it displays a proper form or something else.

 

The actual insertion, edit or deletion of the record is done by the functions action_newdo(), action_editdo() and action_deletedo(). This is why you must pass a value for the action parameter in your templates. You also can override those functions of course.

 

 

Data and functions in Webapp

 

$this->VAR

An array with all the POST and GET variables that have been passed to the PHP script.

 

$this->TPL

An array that contains all the variables that are available to the template engine.

 

$this->maintpl

The name of the main template file. Just set this variable to load the according file as main template in the template engine.

 

$this->idfield

This variable contains the name of the primary key column in the database. It defaults to 'id'.

 

$this->id

This variable contains the content of the parameter in VAR with the primary key column.

 

$this->phpself

This variable contains the name of the current PHP script.

 

$this->goback

If this variable is set to true and the special template feedback.tpl is loaded than the users browser is redirected to the page set in $this->backpage. Otherwise it displays the message in $this->TPL['output'] and a link to $this->backpage is displayed.

 

$this->backpage

see description at $this->goback

 

 

Change behaviour of data table

 

By default the action_default() function shows the content of the table selected with $this->name in you class. It shows all data fields and an edit plus a delete link. You can change this behaviour with the following functions:

 

show_fields($fields)

Selects the database fields that are displayed. $fields is a comma seperated list or an array of field names.

 

Example:

$obj->show_fields('firstname,lastname');

 

 

hide_fields($fields)

Selects the database fields that are not displayed. All other fields are shown. $fields is a comma seperated list or an array of field names.

 

Example:

$obj->hide_fields('street,postcode,phone');

 

set_header($header)

Shows a table header on top of the displayed records. $header is an array with the field names as index and the text to display as data.

 

Example:

$obj->set_header(array('firstname'=>'Givenname', 'lastname'=>'Family name'));

 

 

default_clause($clause)

Sets a SQL where clause that is used to select the records from the database table for display.

 

Example:

$obj->default_clause('age < 18');  // show only underagers

 

 

set_editvars($vars)

The automatic use of POST and GET parameters to edit database records can lead to a potential security risk. If users know the structure of your database table they can edit any field in the record they actual edit by passing a parameter with the same name. To prevent this you can define which fields should be edited in the table by calling this function. $vars is a comma seperated list of field names or an array with the field names.

 

Example:

$obj->set_editvars('firstname,lastname,street,city,postcode');

 

Hooks

If you do not override the default functions like action_edit(), you can change the behaviour of these functions by using so called hook functions. These are functions that are called before or after the code of the function. Usually these functions do nothing. You can override these functions in your class to make them doing something. You could set some template variables there for example.

 

 

before_action_default()
before_default()

after_action_default()
after_default()

are executed before and after the action_default() function. You should use the before_action_default() and after_action_default() functions. before_default() and after_default() are only there for backwards compatibility.

 

after_action_delete()

is executed after action_delete(). That is the function that displays the question whether you are really sure to delete the record. You can change the links that are displayed with the variables

$this->TPL['yeslink'] and $this->TPL['nolink'].

 

before_action_deleteyes()

after_action_deleteyes()

is executed before and after action_deleteyes(). That is the function that is called after the user clicked on “Yes” when asked if he really wants do delete a record.

 

before_delete_($id)

after_delete_($id)

is executed before and after the delete_($id) function which is the function that deletes the record from the database. $id is the primary key of the record. If before_delete_($id) returns the string 'EXIT' the function delete_($id) is interrupted and the deletion will not be done.

 

after_action_new()

is executed after action_new(). This is the function that displays the form for the data of the new record.

 

before_action_newdo()

after_action_newdo()

is executed before and after action_newdo(). That is the function that is called after the user submits the form with the data for a new record.

 

before_add_($data, $obj)

after_add_($data)

is executed before and after the add_($data) function which is the function that inserts a new record into the table. $data is an array with the data for the new record. $obj is the data object that is used to insert the data. See the section about data objects in this manual to read more about data objects. If you want to manipulate the data to be inserted you must alter the data object and not the data array! This array is only passed to give you convenient access to the data.

 

after_action_edit()

is executed after action_edit(). This is the function that displays the form for the data of the  record to edit.

 

before_action_editdo()

after_action_editdo()

is executed before and after action_editdo(). That is the function that is called after the user submits the form with the data for a record to edit.

 

before_edit_($id, $data, $obj)

after_edit_($id, $data)

is executed before and after the edit_($id, $data) function which is the function that inserts a new record into the table. $id is the primary key of the record to edit. $data is an array with the data for the record. $obj is the data object that is used to update the data. See the section about data objects in this manual to read more about data objects. If you want to manipulate the data to be updated you must alter the data object and not the data array! This array is only passed to give you convenient access to the data.

Other functions

get_dbobject([$id])

You can get a data object with get_dbobject. The $name variable of the current object has to be set. If there is a current record (i. e. parameter $id is set) you can omit the parameter.

 

raise_error($message[, $backpage]);

With this function you can stop the current work and put out $message on the page. The message is displayed where the normal output of the current function would be displayed.

 

 

CLI

You can also use the Webapp class when calling php on the command line (cli). You can pass all parameters as key-value pair separated by =. E. g.

 

#> php myapp.php action=edit id=9

 

This should result in the same behavior like you would have called the script via Apache with

 

http://myhost.com/myapp.php?action=edit&id=9

 

Pass parameters to template variables

If you have a lot of parameters passed to your script and you need them all in your templates, you can call

 

$this->vars2tpl($varlist);

 

$varlist holds a comma separated list of variable names e. g. 'firstname,lastname,city'

 

This has the same effect as if you would call

 

$this->TPL[$varname] = $this->VAR[$varname];

 

for every variable in this list.

 

You also can tell your webapp object to pass all of the parameters to the template with

 

$this->pass_vars_to_template = true;

 

for example in the init() function. Be aware that this is a potential security risk as users of your application can pass any parameter to your app which is then used by the template engine! We recommend to not use this feature!

 

XSRF prevention

 

Cross site request forgery is an attack where malicious users get authenticated users to click on links where they trigger actions they never wanted. They could submit forms which have never been displayed to them. Booosta has a method to prevent this form of attacks. When you choose to use this feature, a checksum ist generated with every form and sent to the (brave) users browser. When a user submits a form, the system first checks, if this checksum is submitted back and is correct. If not, an error message is displayed on the screen and the action in not executed.

 

If you want use this feature in the default insert, edit and delete functions, you have to set

 

$this->use_form_token = true;

 

for example in init().

 

If you want to use it in you own functions, you have to generate a token with

 

$this->TPL['mytoken'] = $this->generate_form_token();

 

The resulting token has to be added to your form in a hidden field

 

{HIDDEN mytoken {%mytoken}}

 

In the function that receives the input of your form you check the token with

 

if($this->check_form_token('mytoken')) { /* do something */ }

else { /* display an error message */ }

 

The tokens are only valid a certain amount of time. Default is 1800 seconds – half an hour. You can change this in your webapp object with

 

$this->form_token_time = $new_value;

 

Tools

There is a small tool provided with Booosta that automatically creates three standard templates for an existing database table. They are stored in tpl/. First is tablename_default.tpl, which can be used to show an overview of the existing records for use with the module Webapp.

Second is tablename_new.tpl which provides a form for adding new records and the third is tablename_edit.tpl which provides a form for editing existing records. To use it, the database connection has to be set up in local/config.incl.php.

php mktpl.php tablename scriptname

tablename is the name of the database table that should be served by the templates. scriptname is the  name of the PHP script that should be called in the HTML forms.

Example:

php mktpl.php adressen adressen.php

 

User System

From Version 2.1 Booosta has a build-in user system. This system provides login, logout, creation and administration of users on two levels.

 

First level are administration users (adminusers). Those can be seen as the superusers of the application. Adminusers are usually the owners of a web app or their employees. For example employees of the company that runs the web app.

 

Second level are the ordinary users (users). Those are the actual users of the app that use the intended functionality of the app. For example the customers of the company that runs the web app and use the app to order products.

 

If you do not use the user system, you can delete the whole directory usersystem from your installation and remove the lines that include user.incl.php and usersystem.incl.php in lib/framework.incl.php.

 

After the installation of Booosta there is an index.php which is a link to user.php. That script is the main script that runs when the user logs in. There is also the script admin.php, which is the main script for the adminuser. If you open index.php, user.php or admin.php in a browser you will be redirected to the login page for the user oder adminuser, if no one is logged in.

 

After a successful login the browser will be redirected to the user.php or admin.php again. Whenever a script requires a logged in user, those redirections will be performed.

 

When you write you own scripts that require logged in users, you have to derive your app class from Webappadmin or Webappuser rather than from Webapp. After creation of the app object, you have to call the method auth_user() to make the app check for a logged in user and redirect to the login screen if not.

 

auth_user($usertype)

This method checks if a user of the usertype is logged in and if not, it redirects the browser to the proper login page.

 

$usertype is the type the logged in user has to have. This can be adminuser or user. The parameter is optional. If omitted, it defaults to adminuser in a Webappadmin object and to user in a Webappuser object.

 

Example:

$app = new Webappuser('person');

$app->auth_user();

$app->run();

 

 

Basically there is no difference between adminusers and users. These are just two classes of users. The effective difference between them in the application is defined by the programmer. If you write a web application you define in every PHP script which user class is required. The administration scripts of the Booosta user system all require adminusers to be logged in.

 

In your webapp object the current user is represented by a user object held in the variable $user. To inspect this object you could use

print_r( $this->user );

 

 

Privileges

 

Booosta also offers the possibility to grant fine graned privileges to users. For this reason there are privileges that are managed in the user system. Privileges for managing the user system itself are predefined in the default Booosta installation. For example create user or delete adminuser are existing privileges.

 

In the adminuser interface of the user system you can create, edit or delete all available privileges. Usually, these privileges are completely ignored by the application. This means the application does not check, if the logged in user has any privileges. You can change this by changing the setting for $this->auth_actions in the constructor of the class Webapp in lib/webapp.incl.php.

 

If this is set to true all create, edit and delete actions in the webapp require the logged in user to have the according  privileges. As default the necessary privileges are named “create tablename”, “edit tablename” and “delete tablename”, where tablename is the name of the database table. You can change the name of the necessary privileges by setting the array $this->privs in your class.

 

Example:

 

class myapp extends Webappuser {

  protected function init() {

    $this->privs = array('create' => 'my create privilege',
     'edit' =>  'editpriv', 'delete' => 'mydelpriv');

  }

}

 

If you implement you own functions beside the predefined functions like action_edit() you can also make use of the privileges. You can call the function has_privilege() on a user object every time. It returns a boolean value indicating if the user has the privilege or not.

 

Example:

 

if(!$this->user->has_privilege('edit data'))
 $this->raise_error('Missing privilege');

 

 

Roles

 

To avoid having to grant the same privileges to several users there are roles. A role is basically a collection of privileges. Roles can be granted to users like privileges can be. Users having a role have all the privileges granted to this role. Users can be granted several roles. And roles can have subroles. A role having a subrole inherits all the privileges from that subroles.

 

In your program you cannot query if a user has a role. You only can query if a user has a privilege. It does not matter if that privilege is granted to the user directly or via a role.

 

The administration of the user system is located in the subdirectory usersystem in a Booosta installation. You can study the PHP scripts there get an idea, how programming with Booosta works, as all the scripts there use the Booosta framework. See how the hook functions are used to manipulate the behavior of the default functions.

 

Templates

For displaying the pages after login for users and admins there are templates in the directory usersystem/tpl. If you want to change the menu and add links to it you need to change the files usersystem/tpl/user_actions.tpl and admin_actions.tpl. There is an example line commented out with <!-- and --> where you can remove the comment characters and adopt it to your needs. So you could for example alter

<!-- <li>{LINK Example {%base_dir}example.php}</li> -->

to

<li>{LINK Address {%base_dir}addresses.php}</li>

Do not remove the {%base_dir} in this line because it is needed!

Multi language system

 

Booosta applications can be written multi lingual. There are two basic things that implement this multi lingual behavior. The first is the template system. Multi lingual templates are realized by simply creating each template file for every supported language. The files for the different languages are identified by the file extension. This extension is the two letter language code. For example de for German or es for Spanish. If the template parser does not find the template file with the right extension, it uses the template file without any language extension.

 

If you need a language dependent text in a variable, there exists the method t() in the webapp class. It takes a string as parameter. For every language you support you have to maintain a file named lang.code in your web applications root directory, where code is again the two letter language code. If you support german and spanish you have to create the files lang.de and lang.es in your web apps root directory.

 

In this file an array named $LANG_ is defined. The indexes of this array are the strings that are passed to the t() method. The values are the desired texts in the according language. There is a stub language file named lang.de in the root directory of a Booosta installation. You can use that if you plan to support the german language or rename it for any other language. If you also want to translate the user system files, you have to copy the template files in tpl/ and copy the usersystem/lang.de and translate the values of the $LANG_ array inside.

 

You finally have to change the extension of the included language file in the last line of the lang.xx file. If you do not want to translate the user system and use the english version just delete or comment out this include line.

 

Example:

 

tpl/mytemplate.tpl.de:

 

Willkommen auf der Seite, {%title} {%lastname}!

 

 

myfile.php:

 

[...]

$obj = C_Person::get_object(1);

$this->TPL['title'] = $this->t($obj->get('title'));

$this->TPL['lastname'] = $obj->get('lastname');

[...]

 

 

lang.de:

 

[...]

'Mr.' => 'Herr',

'Mrs.' => 'Frau',

'Ms.' => 'Fräulein',

[...]

 

So how does the system determine which language ist the “actual” language? There is a session variable named LANG ($_SESSION['LANG']) which is evaluated by the constructor of the webapp class. This variable should contain the two letter language code. You also can set the object variable lang in you webapp object manually:

 

$this->lang = 'de';

 

If you want to display your application in your users language, you have to add the language in the users settings when adding or editing the user, for example with:

 

$obj->set('usersettings_', 'lang', $userlang);

 

in before_add_() in usersystem/user_register.php. To apply this setting you can set the session variable LANG to this value in the after_auth_success() hook function of your user class.

 

 

Module Ajax

 

AJAX (asyncronous javascript and XML) is a powerful method to send requests from a loaded page and use the result from this request without reloading the page. Ajax is rather complicated to implement, but the Booosta module Ajax makes this easier.

 

All you have to do is to create a PHP object from the class Ajax and to implement the Javascript functions that are executed before sending the request and after receiving an answer.

 

Example:

 

index.php:

<?php

$ajax = new Ajax('news', 'myresult');

$javascript = $ajax->get_javascript();

?>

 

<script type='text/javascript'>

<?php print $javascript; ?>

 

function request_news_() {

  var mynumber = document.getElementById('mynumber');

  url_news = 'ajax.php?number=' + mynumber;

}

 

function response_news_() {

  alert('The result of the calculation is' + xml_result_news);

}

 

 

As you see in the example, there are some naming conventions in the Javascript code. You have to define a function request_name_() where name is the first parameter of the constructor of the PHP object. In this function you must set the global Javascript variable url_name with the URL of the Ajax call. All parameters have to be added as GET parameters.

 

To process the result from the Ajax call you have to define the function response_name_(). You can access the result of the call in the global Javascript variable xml_result_name.

 

The called script which provides the XML response must return a XML construct in the following form:

 

<?xml version="1.0" ?>

<root>

  <name>

    result

  </name>

</root>

 

where name is the second parameter to the constructor of the Ajax object ('myresult' in the above example).

 

Constructor

The constructor of the Ajax class can handle several types of parameters. The class acts different depending of this parameters. Those parameters can be strings, arrays or arrays of arrays. Here is an explanation of the various ways to instantiate an Ajax object:

 

new Ajax('myname');  

# get result in xml_result_result

 

new Ajax('myname', 'myresult);  

# get result in xml_result_myresult

 

new Ajax('myname', array('res1', 'res2'));  

# get results in xml_result_myname_res1 and xml_result_myname_res2

 

new Ajax(array('name1', 'name2'), 'myresult');  

# get results in xml_result_name1_myresult and xml_result_name2_myresult

 

new Ajax(array('name1', 'name2'), array('name1'=>'res1', 'name2'=>'res2'));  

# get results in xml_result_res1 and xml_result_res2

 

new Ajax(array('name1', 'name2'),  array('res1', 'res2'));  

# get results in xml_result_$name_res1 and xml_result_$name_res2

 

new Ajax(array('name1', 'name2'), array('name1'=>array('res1', 'res2'), 'name2'=>array('res3', 'res4')))  

# get results in xml_result_$name_$res

 

 

If you pass an array as first parameter, the Ajax class creates several requesters. In example 4 – 7 it would create two requesters (name1 and name2). If you pass an array as second parameter then several result fields are returned.

 

Response

You can use the method print_response to deliver a result for the ajax call in the called script. If you call this out of a webapp object, you should set the $no_output value to true to avoid parsing of the template.

 

First parameter ist the tag name that should be used and the second is the value to return. If this is an array, several values are returned.

 

$result = array('first result', 'second result');

Ajax::print_response(null, $result);

Module Form checker

 

 

In HTML 4 there are no built in ways to validate form contents without sending them to the server. This changes in HTML 5, but currently most browsers do not support HTML 5 completely. To provide that functionality with JavaScript there is the Form checker module.

 

This module can check the following things before submitting the form:

 

 

To use the form checker you need to create an instance of the checkForm class. As parameters to the constructor you provide the form name (default: form0) and the name of the JavaScript function that should be created (default: checkForm). The second parameter is important if you have several form checkers which need to create different functions.

 

After creation of the object you can use the following functions to define checks for form fields:

 

$check = new checkForm();

$check->add_required_field($name);

$check->add_number_field($name);

$check->add_email_field($name);

$check->add_equal_field($name1, $name2);

$check->add_regexp_field($name, $regexp);

 

Where $name are the names of the HTML form fields. $regexp is a string with the regular expression.

 

You get the resulting JavaScript code with

 

$check->get_javascript();

 

In the form tag you must add a

 

onSubmit='return checkForm();'

 

You can set individual error messages that pop up when a condition is violated with

 

$check->set_errormessage($type, $message)

 

where $type is one of  required_field,  number_field,  email_field,  add_equal_field,  regexp_field. In $message you can provide the error message that should be displayed. You can use {field} in the text which will be replaced with the name of the according field.

 

Module Excel Reader

 

 

There is a Booosta module for reading and parsing MS Excel files. It provides an array with the values in the Excel file. If the Excel file has the structure of having field names in the first line and the according data in all the next lines this module returns a nested array with all the values. It is an array which contains arrays that represent one line in the file indexed by the name of the column from the first line.

 

You use the Excel reader by creating an object of the class Excelreader:

 

$reader = new Excelreader($excelfile, $mapping);

 

The first parameter is the Excel file you want to read. The $mapping parameter is an array which maps the column names in the first line Excels file to different names in the resulting array. The indexes of it are the names in the Excel file and the values the new names. The last parameter is optional. You get the data without mapping with

 

$reader->get_indexed_data();

 

and the data with mapped column names with

 

$reader->get_mapped_data();

 

 

Module Email

 

Booosta provides an Modue for sending e-mail. It can send it's mails via the PHP mail function, with sendmail or over SMTP. For using this module create an instance of the Email class. To send it, call the send() function.

 

$mail = new Email($sender, $receivers, $subject, $content);

$mail->send();

 

Before sending, you can add additional content with

 

$mail->add_content($text);

 

you can add additional receivers and cc/bcc with

 

$mail->add_receivers($list);
$mail->set_cc($list);
$mail->set_bcc($list);

 

where $list is an array of mail addresses. You can add attachments with

 

$mail->add_attachments($list);

 

where $list is an array of attachments which in fact are the names of files that should be attached. You can add built in images with

 

$mail->add_images($list);

 

where $list is an array whose indexes are the names of the images and the values the file names of the images. You include those images in your HTML mail with

 

<img src='cid:name'>

 

where name is the name from the array index.

 

Per default the content you pass to the constructor is HTML code. If you want to pass plain text you must set the content type with

 

$mail->set_contenttype('text');

 

Usually the PHP mail function is used to send them mail. If you want to use the sendmail program on the server you need to set

 

$mail->set_backend('sendmail');

 

If you want to use SMTP you have to set

 

$mail->set_backend('smtp');

$param = array('host'=>$host, 'port'=>$port, 'auth'=>$auth, 'username'=>$user, 'password'=>$pass);

$mail->set_smtp_params($param);

 

where host and port are the desired SMTP host, auth indicates to use authentication (boolean) and username, password are the credentials for the authentication.

Module Image Gallery

 

 

Booosta comes with a JavaScript image gallery. Actually it uses a Jquery based simple gallery that just opens a window and displays a list of pictures in there. In the future this underlying gallery may be exchanged against an other technology, but the behavior of the class and its programming should remain the same.

 

To use that gallery you make an instance of the class ImageGallery.

 

$gallery = new ImageGallery($img_path, $lib_path);

 

$img_path is the directory, where all the images are located. All displayed images have to be in the same directory. $lib_path is the path of the gallery library files (e. g. lib/ext_imagegallery).

 

Not all the images in the image path are displayed. You have to add the desired images with

 

$gallery->add_image($file, $title, $description);

 

$file is the name of the image file, $title and $description are display in the gallery and are optional. You can anyway add all images in the img_path with

 

$gallery->add_all_images($extension);

 

$extension is an optional parameter which filters the images with a special extension. This way you can add only all .jpg images for example. You can provide several extensions by passing an array with all the desired extensions.

 

To make the image gallery work, you must put some code in your web application to initialize the gallery. The necessary code can be got by calling

 

$code = $gallery->get_html_includes();

 

To actually show the gallery the user has to click a link which can be got by

 

$link = $gallery->get_html_link();

 

 

Module Cache

Often you have to handle data that is very time consuming to gather. Maybe you have to do large calculations to get to this data or you have to load it from the Internet which is slow. If you need the same data very often, it is clever to cache this data.

This only works if you can identify data with a unique key, e. g. a URL. You also need to be sure, that the same key always results in the same data. If an URL always shows different data, you should not cache it.

Currently there are two methods for storing the cache: Database and Session. With the database storage the cached data is stored in a database table. After installation of Booosta there is a database table named cache. It is a memory table, which is not written to disk persistantly. If you like to have your cache data on the disk of your database server, you should change the table type. Refer to the manual of your database (e. g. mysql) how to do that.

For using the cache you have to derive a new class from the class Cache_DB (or Cache_Session). There you have to define the function retrieve($key). This function should put together all the data that should be cached and return it.

 

Example:

class my_cache extends Cache_DB {
 protected function retrieve($url) {
   return file_get_contents($url);
 }
}

$cache = new my_cache();
$page = $cache->get('http://www.mysite.com');

 

The first time this script is called the HTML code of the website ist loaded from the Internet and stored in the database cache. All further calls do not load the page again but read the content from the cache.

Available functions for the cache class are:

$cache->set_validity($seconds);
Sets the validity of the cache. Cache entries older than this will be ignored and the data will be retrieved again.

$cache->get($key);
Gets the data from the cache. There is no way to determine whether the data comes from the cache or from the original source.

$cache->is_valid($key);
$cache->is_invalid($key);

Determines if there is a valid entry in the cache for the given key.

$cache->invalidate($key);
Deletes the entry for the given key from the cache if exists.

$cache->clear();
Deletes all the entries in the cache.

$cache->cleanup();
Deletes all entries in the cache, that are older than $validity.

Module UploadFile

Some applications require files to be uploaded to the server. UploadFile is a module that handles those uploads. There is also a special class for handling picture uploads called UploadImage.

The form that takes the file name has to have the attribute enctype='multipart/form-data'. In the template parser this can easily achieved with the tag {FORMSTARTM …}. The form field can be created with {FILE …}.

 

$file = new UploadFile($name, [$path, [$keepname]]);

This creates the UploadFile object. $name has to be the name of the file field in the form that the user submitted. $path is the local path on the webspace where the uploaded file will be stored. Default is uploadfiles/ . $keepname is a boolean parameter that indicates that the original name of the uploaded file should be kept. If it is set to false (which is the default), a new unique filename will be created. If you set ist to true, the file will be stored with its original name. If a file with this name already exists, it will be overwritten.

You can use the uploaded file with

$file->get_url();
This gives you the filename including the path relative to the web root.

$file->get_html();
This gives you a HTML link to the uploaded file.

$file->get_filename();
This gives you the name of the uploaded file on the disk.

$file->get_extension();
This gives you the extension of the uploaded file (e. g. jpg)

$file->is_valid();
This tells you if the upload succeeded and the file is available.

$file->destroy();
This deletes the uploaded file from the disk.

 

Example

template.tpl:
{FORMSTARTM upload.php}
{FILE myfile}
{FORMSUBMIT}
{FORMEND}

upload.php:
$file = new UploadFile('myfile', 'files/', true);
if($file->is_valid())
 $this->TPL['file_link'] = $file->get_html();

UploadImage

A subclass of UploadFile is UploadImage. It has additional methods to deal with uploaded images. Some of these methods let you manipulate the images. There is a choise of three image manipulation libraries: gd, imagick and gmagick. Per default gd is used. You have to install the according library on your webserver to make those methods work. How to do that depends on your distribution. Most popular distributions have all of those graphics libraries available in their packet management.

The UploadImage object is created the same way like the UploadFile object:

$file = new UploadFile($name, [$path, [$keepname]]);
Parameters are the same like in the super class.

The additional methods are:

$file->set_glib($lib);
Sets the used graphics library. Possible values are gd, imagick and gmagick. If you use the gd library you do not need to call this method.

$file->get_html([$width, $height]);
This outputs a HTML <img>-Tag for displaying the images on a web page. If $width and $height are omitted the image is displayed in its original size.

$file->resize($maxWidth, $maxHeight);
Resizes the image on the disk inside the rectangle defined by the parameters. The ratio of the original width and height is kept.

$file->get_width();
Returns the actual width of the image.

$file->get_height();
Returns the actual height of the image.

 

If you have your own image manipulation library for PHP, you can easily use it by defining your own class derived from UploadImage. You just have to change the default $glib variable and to define the methods for resize, get_width and get_height.

class MyUploadImage extends UploadImage {
 protected $glib = 'xyz';

 public function resize_xyz { /* your code here */ }
 public function get_width_xyz { /* your code here */ }
 public function get_height_xyz { /* your code here */ }
}

$image = new MyUploadImage('myimage');
if($image->is_valid()){
 $image->resize(1024, 1024);  // uses your resize_xyz!
 $this->TPL['imagelink'] = $image->get_html();
}

Modules in development

 

There are several modules that are still under development. This means that only a part of the functionality is already implemented. More features will be added in the future, but there is no plan when exactly they will be added. All developers are invited to contribute to those modules – as well as to all the other modules or core functions of Booosta.

 

 

Module Facebook

 

Facebook provides an API for developing Facebook applications which can be run by Facebook users on the Facebook website. This module provides some of useful Facebook functions. The Facebook module class extends the Webapp module class, so all functionality of the Webapp module is also available in the Facebook module.

 

 

$app = new FacebookApp();

 

You can get the actual users friend list with get_friendlist:

This returns an array with arrays with the friends data.

 

$friends = $app->get_friendlist();

 

 

You can get the names of all friends of the actual user with get_friendnames:

This returns an array whose index are the userids and the data the names of the friends.

 

$friends = $app->get_friendnames();

 

 

You can get the userids of all friends of the actual user with get_friendids:

This returns an array with all userids of the friends.

 

$friends = $app->get_friendids();

 

 

You can post to the wall of a user with post_to_wall:

 

$app->post_to_wall($data, $userid);

 

$data is the content to post. It can be a string that will be posted on the wall. It also can be an array which has to have at least two entries: “name” and “message”, which are the name of the post and the text that has to be posted. $userid is the numerical Facebook userid of the user on whose wall this is to post. If this parameter is omitted, the post is done to the actual users wall.

 

 

You can provide a link for inviting friends to the app with get_invite_js:

 

$js = $app->get_invite_js($text);

 

$text is the text the invited user should see. This returns a bunch of JavaScript that should be included in the output sent to the browser – for example with a {%variable} in a template. To invoke the invitation you can provide a JavaScript link to the user in the form javascript:invite_friends()

 

Example:

 

$js = $app->get_invite_js('Join my fancy app!');

$app->TPL['js'] = $js;

 

Template:

 

{%js}

{LINK Invite javascript:invite_friends();}

 

Module IMAP

 

This module provides functions for retrieving mail from an IMAP server. Only some basic functions are implemented yet.

 

 

$imap = new imap_account($server, $user, $password);

 

You can get the number of messages in the mailbox with

 

$num = $imap->get_msg_num();

 

You can retrieve a message with

 

$msg = $imap->get_mail_message($num);

 

$num is the number of the message in the mailbox. Messages are numbered from 1. If you use the number of messages in the mailbox as $num, you get the latest message. The result is a mail_message object. The mail_message class is described here later.

 

You can get the latest message in the mailbox also with

 

$msg = $imap->get_last_message($delete);

 

$delete is an optional parameter. If it is true, the returned message is deleted from the mailbox.

 

You can get the list of folders of the IMAP account with

 

$imap->get_folderlist();

 

 

The mail_message class

 

Some of the functions of the imap_account class return objects of the class mail_message. They represent a single mail message. You can obtain certain informations from the message with the following functions whose names should be self explaining:

 

$msg->get_subject();

$msg->get_sender();

$msg->get_recipient();

$msg->get_text();

 

 

Preview to the future

Typo3 integration

Work is in progress to make it possible to write Typo3 extensions with Booosta. The idea is to be able to convert a normal web application into a Typo3 extension and vice versa with only very little modifications.

Code of this project is already distributed with Booosta. If you want to join the development or help testing contact the programmer at peter@icb.at .

GUI

There is also a sub project that wants to bring JavaScript GUI elements into the framework. Actually extjs is used for that reason. Also some jQuery GUI elements are in experimential use in development version of Booosta. Some of the code is included in the source distribution. You can watch it. But if you want to try it you have to install extjs yourself.