Migration SVN

This commit is contained in:
2016-02-21 14:28:40 +01:00
commit df45f10305
1455 changed files with 20440 additions and 0 deletions

137
system/api/action.api.php Executable file
View File

@@ -0,0 +1,137 @@
<?php
/**
* @class action
* @brief Manage actions
* @author Vincent Giersch
* @date 12/08/2009
* @version 0.1
*/
class action {
/**
* @brief Check if the action is in progress
* @param action_id -> id of action
* @param hosting_id-> id of the hosting, optionnaly
* @param is_parent_id -> bool(true) if the param 'action_id' is a 'parent_id'
* @return 0 : Action not found
* @return 1 : Action is in state 'added', it can be deleted
* @return 2 : Action is in execution or finished
*/
static private function checkBeforeDeleteAction($action_id, $is_parent_id = null)
{
$action_id = $_SESSION['database']->clearString($action_id);
$can_cancel = 1;
if ( !is_null($is_parent_id) ) {
$req = "SELECT id, parent_id, status FROM actions WHERE parent_id = '$action_id'";
$actions = $_SESSION['database']->fetchObject($req);
foreach ( $actions as $action ) {
if ( $action->status != 'added' ) $can_cancel = 2;
}
return $can_cancel;
}
else {
$req = "SELECT id, parent_id,s tatus FROM actions WHERE id = '$action_id'";
$action = $_SESSION['database']->fetchObject($req);
if ( !isset($action[0]) || !is_object($action[0]) ) return 0;
if ( $action[0]->status == 'added' ) return 1;
return 2;
}
} // End of checkBeforeDeleteAction
/**
* @brief Model : Delete action
* @param action_id -> id of action
* @param is_parent_id -> bool(true) if the param 'action_id' is a 'parent_id'
* @return always bool(true)
*/
static private function deleteAction($action_id, $is_parent_id = null)
{
$action_id = $_SESSION['database']->clearString($action_id);
if( !is_null($is_parent_id) )
$_SESSION['database']->execRequest("DELETE FROM actions WHERE parent_id = '$action_id' OR id = '$action_id'");
else
$_SESSION['database']->execRequest("DELETE FROM actions WHERE id = '$action_id'");
return true;
} // End of deleteAction
/**
* @brief Controller : Cancel an action
* @param action_id -> id of action
* @param is_parent_id -> bool(true) if the param 'action_id' is a 'parent_id'
* @return 0 : Action not found or isn't related to hosting_id (if specified)
* @return 1 : Action has been cancelled (Ok)
* @return 2 : Action can't be cancelled because is in execution or finished
*/
static public function userCancelAction($action_id, $is_parent_id = null)
{
$return_check = self::checkBeforeDeleteAction($action_id, $is_parent_id);
if ( $return_check == 0 || $return_check == 3)
return 0;
elseif ( $return_check == 2)
return 2;
else {
self::deleteAction($action_id, $is_parent_id);
return 1;
}
} // End of userCancelAction
/**
* @brief Model : Add action
* @param servers_id -> id of service
* @param hosting_d -> id of the hosting
* @param data -> array, data about the task
* @param parent_id -> optionally, the id of the group
* @return last action id
*/
static private function addAction($service_id, $data, $hosting_id, $parent_id = null)
{
$data = $_SESSION['database']->clearString(json_encode($data));
$service_id = $_SESSION['database']->clearString($service_id);
$parent_id = ( is_null($parent_id) ) ? 'null' : $parent_id = $_SESSION['database']->clearString($parent_id);
$req = "INSERT INTO actions
SET
parent_id = '$parent_id',
created_at = CURRENT_TIMESTAMP,
status = 'added',
hosting_id = '$hosting_id',
servers_id = '$service_id',
data = '$data'";
$_SESSION['database']->execRequest($req);
return $_SESSION['database']->getInsertId();
} // End of addAction
/**
* @brief Controller : Add action on the tasklist
* @param servers_id -> id of service
* @param data -> array, data about the task
* @return
*/
static public function userAddAction($service_id, $data, $parent_id = null)
{
$hosting_id = $_SESSION['hosting']->information_hosting->id;
return self::addAction($service_id, $data, $hosting_id, $parent_id);
} // End of userAddAction
/**
* @brief Controller : Add a group of actions on the tasklist
* @param data -> array, the group of actions
* @return id of the group of actions
* @todo Delete this function
*/
/*static public function userAddGroupAction($data)
{
$parent_id = null;
$hosting_id = $_SESSION['hosting']->information_hosting->id;
foreach( $data as $key => $value ) {
if ( is_null($parent_id) ) $parent_id = self::addAction($value['service_id'], $value['data'], $hosting_id);
else self::addAction($value['service_id'], $value['data'], $hosting_id, $parent_id);
}
return $parent_id;
} // End of userAddAction */
} // End of class
?>

22
system/api/api.php Executable file
View File

@@ -0,0 +1,22 @@
<?php
/**
* @function __autoload
* @brief Autoload an API when it is called
*/
function __autoload ($api_name)
{
require_once(PATH_API.strtolower($api_name).'.api.php');
}
/**
* @function redirect()
* @brief Redirect and stop execution
* @param url -> name of module to redirect (not an url)
*/
function redirect($url)
{
header('Location: '.TPL_HOST.$url);
exit();
}

252
system/api/cron.api.php Executable file
View File

@@ -0,0 +1,252 @@
<?php
/**
* @class cron
* @brief Manage, edit, add, delete, test Cronjobs
*
* @author Benjamin Mercier
* @data 12/08/2009
* @version 0.1
*/
class cron
{
private $cron_records = null;
/**
* @brief List crons for the current hosting
* @param hosting_id ID of the current hosting
* @param start First record to extract (optional)
* @param extract_number Number of record to extract (optional)
* @return array or null if empty
*/
public function userListCrons( $hosting_id, $start = null, $extract_number = null)
{
$hosting_id = $_SESSION['database']->clearString($hosting_id);
if ( !is_null($start) and !is_null($extract_number)) {
$start = $_SESSION['database']->clearString($start);
$extract_number = $_SESSION['database']->clearString($extract_number);
$limit = " LIMIT $start, $extract_number";
} else $limit = null;
$req = "SELECT id, address, UNIX_TIMESTAMP(created_at) AS created_at, execute_every, UNIX_TIMESTAMP(executed_at) AS executed_at, is_active
FROM service_cron WHERE hosting_id = '$hosting_id' ORDER BY created_at DESC$limit";
$query = $_SESSION['database']->fetchObject($req);
return $query;
}
/**
* @brief add a Cronjob for current user
* @param address Url of the script to call
* @param frequency Frequency of the task execution
* @param first_start Date/Time for the first execution
* @return 0 : Address is not openable
* @return 1 : Cronjob added
* @return 2 : Limit of cronjob for the current offer is reached
*
* @todo Manage the 'first_start' parameter
*/
public function userAddCron( $address, $frequency, $first_start, $active=true )
{
// Check Time for executing
$frequency = intval($frequency);
if ( $frequency == CRON_NO_SPECIFIED_TIME ) {
$active=false;
} elseif ( $frequency < CRON_MIN_TIME ) {
$frequency = CRON_MIN_TIME;
}
// Check if address is openable
$address_test = $this->checkAddress($address);
if ( !$address_test ) return 0;
// Check quota
if ( $_SESSION['hosting']->information_hosting->offer_crons_number >= 0 ) {
$current_number_crons = $this->countCronjobs( $_SESSION['hosting']->information_hosting->id );
if ( $current_number_crons >= $_SESSION['hosting']->information_hosting->offer_crons_number ) return 2;
}
// Get the ID of the current hosting
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$this->addCron( $hosting_id, $address, $frequency, true);
return true;
} // End of userAddCron
/**
* @brief Active an deactivated cron
* @param cron_id ID of the cron
* @return : 0 Cron is not found
* @return : 1 Cron activated
* @return : 2 Cron is already activated
*/
public function userActiveCron( $cron_id )
{
$cron = $_SESSION['database']->clearString($cron_id);
$req = "SELECT hosting_id, is_active FROM service_cron WHERE id = '$cron'";
$query = $_SESSION['database']->fetchObject($req);
if ( count($query) == 0 ) return 0;
if( $query[0]->hosting_id != $_SESSION['hosting']->information_hosting->id )
throw new myException('Hosting_id is not attribued for this cron');
if ( $query[0]->is_active == 'true' ) return 2;
$req = "UPDATE service_cron SET is_active = 'true' WHERE id = '$cron'";
$_SESSION['database']->execRequest($req);
return 1;
}
/**
* @brief Deactivate a cron
* @param cron_id : ID of the cron
* @return : 0 Cron is not found
* @return : 1 Cron deactivated
* @return : 2 Cron is already deactivated
*/
public function userDeactiveCron( $cron_id )
{
$cron = $_SESSION['database']->clearString($cron_id);
$req = "SELECT hosting_id, is_active FROM service_cron WHERE id = '$cron'";
$query = $_SESSION['database']->fetchObject($req);
if ( count($query) == 0 ) return 0;
if( $query[0]->hosting_id != $_SESSION['hosting']->information_hosting->id )
throw new myException('Hosting_id is not attribued for this cron');
if ( $query[0]->is_active == 'false' ) return 2;
$req = "UPDATE service_cron SET is_active = 'false' WHERE id = '$cron'";
$_SESSION['database']->execRequest($req);
return 1;
}
/**
* @brief Delete a cron for the current hosting
* @param cron_id Id of the cron to delete
* @return True or false if not found
*/
public function userDeleteCron( $cron_id )
{
$cron_id_s = $_SESSION['database']->clearString($cron_id);
$req = "SELECT hosting_id FROM service_cron WHERE id ='$cron_id_s'";
$query = $_SESSION['database']->fetchObject($req);
if ( count($query) == 0 ) return false;
if ( $query[0]->hosting_id != $_SESSION['hosting']->information_hosting->id )
throw new myException('Hosting_id is not attribued for this cron');
$this->deleteCron( $cron_id );
return true;
} // End of userDeleteCron
/**
* @brief try to open an url by fsockopen.
* @param address web Address
* @return true Web respond
* @return false Web did not respond or not ready
*/
public function checkAddress( $address )
{
if ( !textVerification::verifUrl($address) ) return false;
$url_info = parse_url($address);
if ( $url_info['scheme'] == 'http' ) $port = 80;
elseif ( $url_info['scheme'] == 'https' ) $port = 443;
else $port = 80;
$handle = fsockopen( $url_info['host'], $port, $errno, $errstr, CRON_TIMEOUT);
if ($handle !== false) {
fclose($handle);
return true;
} else {
return false;
}
} // End of checkAddress
/**
* @brief Select all cronjob to execute. For server.
* @todo make this function when the daemons are dev.
*/
public function serverListToTestCrons()
{
}
/**
* @brief Count total cronjobs for a user
* @param hosting_id : ID of the hosting to count
* @param (optionnal) active_cron : True of False, count only active jobs, or count total jobs
* @return Total of cronjobs
*/
private function countCronJobs( $hosting_id, $only_active = false )
{
$hosting_id = $_SESSION['database']->clearString($hosting_id);
if ( $only_active ) $clause = " AND is_active = 'true'";
else $clause = null;
$req = "SELECT COUNT(id) AS total FROM service_cron WHERE hosting_id = '$hosting_id'$clause";
$query = $_SESSION['database']->fetchObject($req);
return $query[0]->total;
}
/**
* @brief adding Cron
* @param hosting_id Id of the hosting
* @param address Address to cron
* @param time Time in seconds to re-execute
* @param is_active Activation of the cron (true/false)
*/
private function addCron( $hosting_id, $address, $time, $is_active)
{
$hosting_id = $_SESSION['database']->clearString($hosting_id);
$address = $_SESSION['database']->clearString($address);
$time = $_SESSION['database']->clearString($time);
if ( $is_active ) $is_active = 'true';
else $is_active = 'false';
$req = "INSERT INTO service_cron
SET
hosting_id = '$hosting_id',
address = '$address',
created_at = NOW(),
execute_every = '$time',
is_active = '$is_active'";
$query = $_SESSION['database']->execRequest($req);
return true;
}
/**
* @brief delete cron identified by id
* @param cron_id Id of the cron
* @return true
*/
private function deleteCron( $cron_id )
{
$cron_id = $_SESSION['database']->clearString($cron_id);
$req = "DELETE FROM service_cron WHERE id = '$cron_id'";
$_SESSION['database']->execRequest($req);
return true;
}
/**
* @brief Get number of all crontab records for the current hosting
* @return number of history records registered for the user
*/
public function userCountCronRecords()
{
if( !is_null($this->cron_records) ) {
return $this->cron_records;
}
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$req = "SELECT COUNT(id) AS total FROM service_cron WHERE hosting_id = '$hosting_id'";
$result = $_SESSION['database']->fetchObject($req);
$this->cron_records = $result[0]->total;
return $this->cron_records;
}
/**
* @brief Get number of crons records pages, regarding the total count of records and the count of items to be shown per page
* @return number of pages availables
*/
public function userCountTotalPages()
{
$items_count = $this->userCountCronRecords();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
}
?>

125
system/api/database.api.php Executable file
View File

@@ -0,0 +1,125 @@
<?php
/**
* @class database
* @brief Manage, edit, add, delete, test database
*
* @author Benjamin Mercier
* @data 14/08/2009
* @version 0.1
*/
class database
{
/**
* @brief Add a database for a hosting
* @param name : Name of the database
* @param password : Password of the database
* @return -1 : Quota of databases is reached
* @return -2 : Syntax of database is forbidden
* @return -3 : Complete name is too long
* @return -4 : Database already existing
* @return 1 : Databases added for creation
*/
public function userAddDatabase( $name, $password, $comment = null )
{
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$mysql_service = $_SESSION['hosting']->information_hosting->mysql_id;
// Quota
if ( $_SESSION['hosting']->information_hosting->offer_domains_number >= 0 ) {
$current_number_mysql = $this->countDatabases( $_SESSION['hosting']->information_hosting->id );
if ( $current_number_mysql >= $_SESSION['hosting']->information_hosting->offer_domains_number ) return -1;
}
// Check syntax and with of db name
if ( !textVerification::verifDatabaseName($name) ) return -2;
if ( strlen($_SESSION['hosting']->information_hosting->id.'_'.$name) > 16 ) return -3;
// Check existence of database
if ( $this->checkDatabaseExistence( $_SESSION['hosting']->information_hosting->id, $name ) ) return -4
$action_id = $this->createDatabase( $mysql_service, $name )
$this->createUserForDatabase(
$mysql_service,
$name,
$password,
$_SESSION['hosting']->information_hosting->id,
$name,
'normal',
$action_id
);
// inserer en db
}
public function userListDatabase()
{
}
public function userDeleteDatabase()
{
}
public function userChangePasswordForDatabase()
{
}
/**
* @brief Create user for db
* @param service_id : Id of the mysql service
* @param name : Name of the user
* @param password : Password of the user
* @param db_hosting: Hosting_id of the DB
* @param db_name : Name of the database
* @param (optionnal) level : Level of the user. "normal" is for customer
* @param (optionnal) create_db_action : Id action of database creation if create_db in same time of create_user.
*/
private function createUserForDatabase( $service_id, $name, $password, $db_hosting, $db_name, $level = 'normal', $create_db_action = null )
{
$data = array();
$data['action'] = 'create_user';
$data['name'] = $name;
$data['password'] = $password;
$data['db_hosting'] = $db_hosting;
$data['db_name'] = $db_name;
$data['level'] = $level;
$action = action::userAddAction($service_id, $data, $create_db_action);
return $action;
}
/**
* @brief Create database
* @param service_id : Id of the mysql service
* @param name : Name of database
*/
private function createDatabase( $service_id, $name )
{
$data = array();
$data['action'] = 'create_database';
$data['name'] = $name;
$action = action::userAddAction($service_id, $data);
return $action;
}
private function checkDatabaseExistence()
{
}
/**
* @brief Count databases for one hosting
* @param hosting_id : Id of the hosting
* @return Number of databases
*/
private function countDatabases( $hosting_id )
{
$hosting_id = $_SESSION['database']->clearString($hosting_id);
$req = "SELECT COUNT(id) AS total FROM service_database WHERE hosting_id = '$hosting_id'";
$query = $_SESSION['database']->fetchObject($req);
return $query[0]->total;
}
}
?>

161
system/api/history.api.php Executable file
View File

@@ -0,0 +1,161 @@
<?php
/**
* @class history
* @brief Manage, Display history of activity
* @author Vincent Lemoine
* @date 29/04/2009
* @modified Xavier Perrissoud
* @date 01/05/2009
* @version 0.1
*
* This class manages the history of the differents actions made on a hosting and/or an user account
*/
class history {
private $history_records = null;
/**
* @brief Save current action to history
* @param message_key -> message of action
* @param user_id -> the user id of action
* @return boolean
*
* Add an action record in the history list for a given user.
*/
public function add($message_key, $user_id)
{
$message_key = $_SESSION['database']->clearString($message_key);
$user_id = $_SESSION['database']->clearString($user_id);
// hosting_id <20> r<>cuperer
$hosting_id = 1;
$ip = $_SERVER['REMOTE_ADDR'];
$req = "INSERT INTO history
SET
date = NOW(),
user_id = '$user_id',
hosting_id = '$hosting_id',
ip = '$ip',
message_key = '$message_key'";
$_SESSION['database']->execRequest($req);
// Update cache if needed
if ( !is_null($this->history_records) ) {
$this->history_records++;
}
return true;
} // End of actiontoHistory
/**
* @brief List all history actions with a given clause
* @param start -> Record of starting listing
* @param extract -> Number of records to extract
* @param clause -> SQL clause for listing
* @return array with information (nul if empty)
*/
private function listHistoryByClause($start = NULL, $extract = NULL, $clause = NULL)
{
$lang = new lang();
if ( !is_null($start) and !is_null($extract) ) {
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
if ( !is_null($clause) ) {
$clause = "WHERE $clause";
}
$req = "SELECT
h.message_key AS action,
i.base_name AS hosting,
h.ip AS ip,
UNIX_TIMESTAMP(h.date) AS date
FROM history AS h
LEFT JOIN hostings AS i
ON i.id = h.hosting_id
$clause $limit";
$result = $_SESSION['database']->fetchObject($req);
foreach ( $result as $key => $value )
{
$result[$key]->action = $lang->getWordFromLangFile($result[$key]->action);
}
return $result;
} // End of listHistoryByClause
/**
* @brief List all history actions for the current user
* @param start -> Record of starting listing
* @param extract -> Number of records to extract
* @return array with information (nul if empty)
*/
public function userListHistory($start = NULL, $extract = NULL)
{
$lang = new lang();
if ( !is_null($start) and !is_null($extract) ) {
$limit = " LIMIT $start, $extract";
} else $limit = NULL;
$user_id = $_SESSION['user']->information_user->userid;
$result = $this->listHistoryByClause($start,$extract, "h.user_id='$user_id'");
$time = $lang->userGetTimeFormat();
$date = $lang->userGetDateFormat();
foreach ( $result as $key => $value )
{
$result[$key]->date = date("$date $time" , $result[$key]->date);
}
return $result;
} // End of userListHistory
/**
* @brief Get number of all history records for the current user
* @param None
* @return number of history records registered for the user
*
* Get the total of all actions recorded in the history list for the current user.<br />
* This value is got the first time from the database (generating a SQL request) and is then stocked in a cache variable, so, other calls to this method won't generate another SQL request.
*/
public function userCountHistoryRecords()
{
// Try to get the value from the cache
if( !is_null($this->history_records) ) {
return $this->history_records;
}
$user_id = $_SESSION['user']->information_user->userid;
$req = "SELECT COUNT(id) AS total FROM history WHERE user_id='$user_id'";
$result = $_SESSION['database']->fetchObject($req);
$this->history_records = $result[0]->total;
return $this->history_records;
}
/**
* @brief Get number of history records pages, regarding the total count of records and the count of items to be shown per page
* @param None
* @return number of pages availables
*
* Calculate the total pages needed to show all the history actions records for the current user.
*/
public function userCountTotalPages()
{
$items_count = $this->userCountHistoryRecords();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
} // End of class

329
system/api/hosting.api.php Executable file
View File

@@ -0,0 +1,329 @@
<?php
/**
* @class hosting
* @brief Manage, display hostings
*
* @author Vincent Lemoine
*
* @modified Benjamin Mercier
* @date 18/07/2009
* @version 0.1
*/
class hosting {
/**
* @brief Array with information from current hosting for all API.
* @brief Null when hosting is not initialized
*/
public $information_hosting = null;
/**
* @brief Cache variable with total of hostings for the current user for all API
*/
private $user_hostings_count = null;
/**
* @brief Result test for userInitializeHosting.
* @brief Get the result code before be used by userCheckAccess
*/
private $result_test = null;
/**
* @brief initialize the hosting of the user
* @return 0 : Hosting deactivated
* @return 1 : No hosting specified
* @return 2 : Data server is deactivated
* @return 3 : MySQL server is deactivated
* @return 4 : dns server is deactivated
* @return 5 : mail server is deactivated
* @return 6 : web server is deactivated
* @return 7 : All is okay, information setting
*/
public function userInitializeHosting()
{
if ( !isset($_SESSION['hosting_infos']) ) {
if ( !is_null($this->information_hosting) ) throw new myException('Session hosting_information is not initialized but hosting_information is not null');
$this->result_test = 1;
return 1;
} else {
$hosting_infos = $_SESSION['database']->clearString($_SESSION['hosting_infos']);
$result = $this->listHostingsByClause(0, 1, "h.id = '$hosting_infos'");
if ( count($result) == 0 ) throw new myException('Hosting_infos is defined but cannot find the hosting associated');
if ( $result[0]->user_id != $_SESSION['user']->information_user->userid ) throw new myException('The hosting is not for the specified user');
if ( $result[0]->hosting_active == 'false' ) {
$this->result_test = 0;
return 0;
} elseif ( ($result[0]->data_active == 'false') or ($result[0]->data_server_active == 'false') ){
$this->result_test = 2;
return 2;
} elseif ( ($result[0]->mysql_active == 'false') or ($result[0]->mysql_server_active == 'false')) {
$this->result_test = 3;
return 3;
} elseif ( ($result[0]->dns1_active == 'false' or ($result[0]->dns1_server_active == 'false'))) {
$this->result_test = 4;
return 4;
} elseif ( ($result[0]->dns2_active == 'false') or ($result[0]->dns2_server_active == 'false')) {
$this->result_test = 4;
return 4;
} elseif ( ($result[0]->smtp_active == 'false') or ($result[0]->smtp_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->smtps_active == 'false') or ($result[0]->smtps_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->pop_active == 'false') or ($result[0]->pop_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->pops_active == 'false') or ($result[0]->pops_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->imap_active == 'false') or ($result[0]->imap_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->imaps_active == 'false') or ($result[0]->imaps_server_active == 'false')) {
$this->result_test = 5;
return 5;
} elseif ( ($result[0]->http_active == 'false') or ($result[0]->http_server_active == 'false')) {
$this->result_test = 6;
return 6;
}
$this->information_hosting = $result[0];
$this->result_test = 7;
$_SESSION['hosting_infos'] = $result[0]->id;
return 7;
}
} // End of initialiazeHosting
/**
* @brief Check autorization and redirect or make exception if is not correct.
* @return TRUE only, throw or redirect if not correct.
*/
public function userCheckAccess()
{
if ( is_null($this->result_test) ) throw new myException('Hosting initialization not initialized');
if ( $this->result_test == 0 ) redirect('error-5.xhtml');
elseif ( $this->result_test == 1 ) redirect('myhostings.xhtml');
elseif ( ($this->result_test > 1) and ($this->result_test < 7) ) redirect ('error-6.xhtml');
elseif ( $this->result_test == 7 ) return true;
else throw new myException('result_code is unknow');
} // End of userCheckAccess
/**
* @brief Initialize hosting by ID
* @brief ID of the hosting
* @return true : Hosting added
*/
public function userSetCurrentHosting($id)
{
$id = $_SESSION['database']->clearString($id);
$result = $this->listHostingsByClause(NULL, NULL, "h.id = '$id'");
if ( count($result) == 0 ) throw new myException('Hosting selected is not found');
elseif ( $result[0]->user_id != $_SESSION['user']->information_user->userid ) throw new myException('Hosting is not allowed to this user');
$_SESSION['hosting_infos'] = $result[0]->id;
return true;
}
/**
* @brief List all hostings of the current member
* @param start -> Record of starting listing
* @param extract -> Number of records to extract
* @return array with information (nul if empty)
*/
public function userListHostings($start = NULL, $extract = NULL)
{
$user_id=$_SESSION['user']->information_user->userid;
return $this->listHostingsByClause($start, $extract, "h.user_id = $user_id");
} // End of userListHostings
/**
* @brief List all hostings with a given clause
* @param start -> Record of starting listing
* @param extract -> Number of records to extract
* @return array with information (nul if empty)
*/
private function listHostingsByClause($start = NULL, $extract = NULL, $clause = NULL)
{
if ( !is_null($start) and !is_null($extract) ) {
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
if ( !is_null($clause) ) {
$clause = "WHERE $clause";
}
$req = "SELECT
h.id AS id,
h.base_name,
UNIX_TIMESTAMP(h.start_date) AS start_date,
UNIX_TIMESTAMP(h.end_date) AS end_date,
h.is_active AS hosting_active,
h.user_id,
h.offer_id,
dns1.id AS dns1_id,
dns1.web_ip AS dns1_ip,
dns1.port AS dns1_port,
dns1.is_active AS dns1_active,
dns1_s.is_active AS dns1_server_active,
dns2.id AS dns1_id,
dns2.web_ip AS dns2_ip,
dns2.port AS dns2_port,
dns2.is_active AS dns2_active,
dns2_s.is_active AS dns2_server_active,
data.id AS data_id,
data.web_ip AS data_ip,
data.port AS data_port,
data.is_active AS data_active,
data_s.is_active AS data_server_active,
http.id AS http_id,
http.web_ip AS http_ip,
http.port AS http_port,
http.is_active AS http_active,
http_s.is_active AS http_server_active,
smtp.id AS smtp_id,
smtp.web_ip AS smtp_ip,
smtp.port AS smtp_port,
smtp.is_active AS smtp_active,
smtp_s.is_active AS smtp_server_active,
smtps.id AS smtps_id,
smtps.web_ip AS smtps_ip,
smtps.port AS smtps_port,
smtps.is_active AS smtps_active,
smtps_s.is_active AS smtps_server_active,
pop.id AS pop_id,
pop.web_ip AS pop_ip,
pop.port AS pop_port,
pop.is_active AS pop_active,
pop_s.is_active AS pop_server_active,
pops.id AS pops_id,
pops.web_ip AS pops_ip,
pops.port AS pops_port,
pops.is_active AS pops_active,
pops_s.is_active AS pops_server_active,
imap.id AS imap_id,
imap.web_ip AS imap_ip,
imap.port AS imap_port,
imap.is_active AS imap_active,
imap_s.is_active AS imap_server_active,
imaps.id AS imaps_id,
imaps.web_ip AS imaps_ip,
imaps.port AS imaps_port,
imaps.is_active AS imaps_active,
imaps_s.is_active AS imaps_server_active,
mysql.id AS mysql_id,
mysql.web_ip AS mysql_ip,
mysql.port AS mysql_port,
mysql.is_active AS mysql_active,
mysql_s.is_active AS mysql_server_active,
o.name AS offer_name,
o.is_active AS offer_active,
o.databases_number AS offer_databases_number,
o.domains_number AS offer_domains_number,
o.crons_number AS offer_crons_number,
o.dns_domains_number AS offer_dns_domains_number,
o.virtualhosts_number AS offer_virtualhosts_number,
o.email_accounts_number AS offer_email_accounts_number,
o.email_accounts_space AS offer_email_accounts_space,
o.email_alias_number AS offer_email_alias_number,
o.space_limit AS offer_space_limit,
o.trafic_limit AS offer_trafic_limit,
o.service_smtp AS offer_service_smtp,
o.service_smtps AS offer_service_smtps,
o.service_pop AS offer_service_pop,
o.service_pops AS offer_service_pops,
o.service_imap AS offer_service_imap,
o.service_imaps AS offer_service_imaps,
o.service_mysql AS offer_service_mysql
FROM hostings AS h
LEFT JOIN services AS dns1
ON dns1.id = h.service_dns1
LEFT JOIN servers AS dns1_s
ON dns1_s.id = dns1.servers_id
LEFT JOIN services AS dns2
ON dns2.id = h.service_dns2
LEFT JOIN servers AS dns2_s
ON dns2_s.id = dns2.servers_id
LEFT JOIN services AS data
ON data.id = h.service_data
LEFT JOIN servers AS data_s
ON data_s.id = data.servers_id
LEFT JOIN services AS http
ON http.id = h.service_http
LEFT JOIN servers AS http_s
ON http_s.id = http.servers_id
LEFT JOIN services AS smtp
ON smtp.id = h.service_smtp
LEFT JOIN servers AS smtp_s
ON smtp_s.id = smtp.servers_id
LEFT JOIN services AS smtps
ON smtps.id = h.service_smtps
LEFT JOIN servers AS smtps_s
ON smtps_s.id = smtps.servers_id
LEFT JOIN services AS pop
ON pop.id = h.service_pop
LEFT JOIN servers AS pop_s
ON pop_s.id = pop.servers_id
LEFT JOIN services AS pops
ON pops.id = h.service_pops
LEFT JOIN servers AS pops_s
ON pops_s.id = pops.servers_id
LEFT JOIN services AS imap
ON imap.id = h.service_imap
LEFT JOIN servers AS imap_s
ON imap_s.id = imap.servers_id
LEFT JOIN services AS imaps
ON imaps.id = h.service_imaps
LEFT JOIN servers AS imaps_s
ON imaps_s.id = imaps.servers_id
LEFT JOIN services AS mysql
ON mysql.id = h.service_mysql
LEFT JOIN servers AS mysql_s
ON mysql_s.id = mysql.servers_id
LEFT JOIN offers AS o
ON h.offer_id = o.id
$clause $limit";
$result = $_SESSION['database']->fetchObject($req);
return $result;
} // End of listHostingsByClause
/**
* @brief Get number of hostings for the current user
* @return number of hostings for the user
*/
public function userCountHostings()
{
// Try to get the value from the cache
if( !is_null($this->user_hostings_count) ) {
return $this->user_hostings_count;
}
$user_id = $_SESSION['user']->information_user->userid;
$req = "SELECT COUNT(id) AS total FROM hostings WHERE user_id='$user_id'";
$result = $_SESSION['database']->fetchObject($req);
$this->user_hostings_count = $result[0]->total;
return $this->user_hostings_count;
}
/**
* @brief Get number of hosting pages, regarding the total count of records and the count of items to be shown per page
* @return number of pages availables
*/
public function userCountTotalPages()
{
$items_count = $this->userCountHostings();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
} // End of class
?>

159
system/api/html.api.php Executable file
View File

@@ -0,0 +1,159 @@
<?php
/**
* @class html
* @brief Generate html code for pagination requests
* @author Xavier Perrissoud
* @date 30/08/2009
* @version 0.1
*
* This class contains only static functions to generate cells content for the JavaScript controller requests.<br />
* Each web page using the JavaScript pagination engine has its own function in this class.<br />
* For simple cells content, you don't need to call this class : you can directly generate the text from the ajax.php file
*/
class html
{
/**
* @brief Generate text / html for a MyHostings page cell
* @param cell_index : Zero-based cell index
* @param hosting_datas : Datas corresponding to the current hosting entry
* @return string with html code
*
* The first and the fifth column for the "MyHosting" page needs specials texts that have to be generated regarding to the corresponding hosting status.
* These links are generated with this method ($cell_index = 0 for the first, and $cell_index = 4 for the fifth).<br />
* The function will check if the current hosting is active. If so, the first column will contain a link to the hosting details. If the hosting is suspended, the fifth column will have a link to the support ticket creation page.
*/
static public function makeHtmlForMyHostings( $cell_index, $hosting_datas )
{
$result=null;
switch( $cell_index )
{
case 0: // Hosting name
$cell_text = $hosting_datas->full_name;
if ( $hosting_datas->hosting_active == 'true' ) {
$result = '<a href="' . TPL_HOST . 'hosting/hosting-' . $hosting_datas->id . '.xhtml">';
$result .= $cell_text;
$result .= '</a>';
} else {
$result = $cell_text;
}
break;
case 4: // Hosting status
if ( $hosting_datas->hosting_active == 'true' ) {
$result = $hosting_datas->statusText;
} else {
$result = $hosting_datas->statusText . ' <a href="' . TPL_HOST . 'support-create.xhtml">';
$result .= '<img src="' . TPL_HOST . 'image/icon/error.png" class="icon" alt="Support" /></a>';
}
break;
}
return $result;
} // End of makeHtmlForMyHostings
/**
* @brief Generate text / html for a Support page cell
* @param cell_index : Zero-based cell index
* @param ticket_datas : Datas corresponding to the current ticket entry
* @return string with html code
*
* The first column for the "Support" page needs a link to get the ticket's detail page.
* This link can be generated with this method.
*/
static public function makeHtmlForSupport( $cell_index, $ticket_datas )
{
$result=null;
switch( $cell_index )
{
case 0: // Open date
$result = '<a href="' . TPL_HOST . 'support-show-' . $ticket_datas->ticket_id . '.xhtml">';
$result .= $ticket_datas->label_text . '</a>';
break;
}
return $result;
}
/**
* @brief Generate text / html for a ticket details page cell
* @param cell_index : Zero-based cell index
* @param reply_datas : Datas corresponding to the current reply entry
* @return string with html code
*
* The first column for the "Ticket Details" page needs html code showing who made the current reply, and the date of this reply.
*/
static public function makeHtmlForTicketDetails( $cell_index, $reply_datas )
{
$result=null;
switch( $cell_index )
{
case 0: // Author / Date
$result = $reply_datas->msg_author . '<br />' . $reply_datas->msg_date;
break;
}
return $result;
}
/**
* @brief Generate text / html for a Admin/Support page cell
* @param cell_index : Zero-based cell index
* @param ticket_datas : Datas corresponding to the current ticket entry
* @return string with html code
*/
static public function makeHtmlForAdminSupport( $cell_index, $ticket_datas )
{
$result=null;
switch( $cell_index )
{
case 0: // Open date
$result = '<a href="' . TPL_HOST . 'admin/support-show-' . $ticket_datas->ticket_id . '.xhtml">';
$result .= $ticket_datas->open_date . '</a>';
break;
}
return $result;
}
/**
* @brief Generate text / html for a Cron page cell
* @param cell_index : Zero-based cell index
* @param cron_datas : Datas corresponding to the current cron entry
* @return string with html code
*
*/
static public function makeHtmlForCron( $cell_index, $cron_datas )
{
$result = null;
switch ( $cell_index )
{
case 0: // Buttons
// Links for "Start/Stop"
$on_success="function(response){getPage('tbl_cron', ".$cron_datas->current_page.", ".$cron_datas->max_pages.", 1);}";
$on_failure="function(){ alert(critical_error); }";
if ( $cron_datas->is_active == 'true' ) {
$action = 'cronStopTask';
$image = 'control_stop';
} else {
$action = 'cronStartTask';
$image = 'control_play';
}
$start_stop="doSingleRequest('$action', $cron_datas->id, $on_success, $on_failure, 1);";
$result = '<a href="javascript:;" onclick="'.$start_stop.'"><img src="'.TPL_HOST.'image/icon/'.$image.'.png" alt="" class="cron_tipsy" title="'.$cron_datas->start_stop_title.'" /></a>';
// Links for "Delete"
$delete="doSingleRequest('cronDeleteTask', $cron_datas->id, $on_success, $on_failure, 1);";
$result .= '<a href="javascript:;" onclick="'.$delete.'"><img src="'.TPL_HOST.'image/icon/cross.png" alt="" class="cron_tipsy" title="'.$cron_datas->delete_title.'" /></a>';
break;
case 1: // Address
$display_address = str_replace('http://', '', htmlentities($cron_datas));
$display_address = str_replace('https://', '', $cron_datas);
if ( strlen($display_address) >= 60 ) $display_address = substr($display_address, 0, 60) . "..." ;
$result .= '<a href="javascript:;" onclick="goToCronUrl(\''.htmlentities($cron_datas).'\');">'.$display_address.'</a>';
break;
}
return $result;
}
}
?>

102
system/api/lang.api.php Executable file
View File

@@ -0,0 +1,102 @@
<?php
/**
* @class lang
* @brief Manage, select, and display lang
*
* @author Benjamin Mercier
* @data 08/03/2009
* @version 0.1
*/
class lang {
private $datetime_format = array();
/**
* @brief List all of countrie
* @param clause : Additionnal clause at end of the req
* @return Array->object of differents countries
*/
public function listCountries()
{
$req = "SELECT
id,
flag,
countrie,
is_lang
FROM countries";
$result = $_SESSION['database']->fetchObject($req);
return $result;
} // End of listCountries
/**
* @brief Return lang of current user
* @return $lang -> code of the lang (fr/en/de/etc.)
*/
public function userGetLang()
{
if ( !LANG_USE_OTHERS ) {
return LANG_DEFAULT;
}
if( !is_null($_SESSION['user']->information_user) ) {
if( !$lang = $_SESSION['user']->userGetLang() ) {
throw new myException('The user is connected but userLang has returned false');
}
$lang_allowed = unserialize(LANG_ALLOWED);
if ( !in_array($lang, $lang_allowed) ) {
throw new myException('Lang of the user is not allowed in configuration file');
}
} else {
$lang = LANG_DEFAULT;
}
return $lang;
} // End of getLang
/**
* @brief select word in lang file from key
* @param key -> 'msg_not_client' (exemple)
* @return -> 'Bienvenue sur votre futur espace membre...'
* @return false if key not found
*/
public function getWordFromLangFile( $key ) {
if ( !is_string($key) ) throw new myException('The key word is not an valid string');
$lang_file = parse_ini_file(PATH_LANG.$this->userGetLang().'/lang');
if ( !$lang_file ) throw new myException('Cannot open the lang file');
if ( isset($lang_file[$key]) ) return $lang_file[$key];
else return NULL;
}
/**
* @brief return DATE format in lang of the current user
* @return date_format
*/
public function userGetDateFormat()
{
$lang = $_SESSION['user']->userGetLang();
if ( isset($this->datetime_format[$lang]) ) return $this->datetime_format[$lang]['date'];
$req = "SELECT date_format,time_format FROM countries WHERE flag = '$lang' and is_lang = 'true'";
$result = $_SESSION['database']->fetchObject($req);
if ( count($result) == 0 or count($result) > 1 ) throw new myException('Too many of not found record of lang');
$this->datetime_format[$lang] = array('date' => $result[0]->date_format, 'time' => $result[0]->time_format);
return $result[0]->date_format;
}
/**
* @brief return TIME format in lang of the current user
* @return time_format
*/
public function userGetTimeFormat()
{
$lang = $_SESSION['user']->userGetLang();
if ( isset($this->datetime_format[$lang]) ) return $this->datetime_format[$lang]['time'];
$req = "SELECT date_format,time_format FROM countries WHERE flag = '$lang' and is_lang = 'true'";
$result = $_SESSION['database']->fetchObject($req);
if ( count($result) == 0 or count($result) > 1 ) throw new myException('Too many of not found record of lang');
$this->datetime_format[$lang] = array('date' => $result[0]->date_format, 'time' => $result[0]->time_format);
return $result[0]->time_format;
}
} // End of class
?>

152
system/api/myexception.api.php Executable file
View File

@@ -0,0 +1,152 @@
<?php
/**
* @class myException
* @brief Manage Exceptions
*
* @author Benjamin Mercier
* @data 01/03/2003
* @version 0.1
*/
class myException extends exception {
/**
* @brief Receive exceptions and manage it
* @param $exception_message -> Text generated by exception
*/
public function __construct($exception_message, $error_code = 0)
{
parent::__construct($exception_message);
$this->insertInLogFile($exception_message, $error_code);
}
/**
* @brief Insert data from exceptions in logfile
*/
public function insertInLogFile($exception_message, $error_code)
{
$get = null;
$post = null;
$session = null;
$included_files = null;
foreach ( $_GET as $key => $value ) {
$get .= "\n -> ".escapeshellcmd($key).' : '.$value;
}
if ( is_null($get) ) $get = 'none';
foreach ( $_POST as $key => $value ) {
$post .= "\n -> ".escapeshellcmd($key).' : '.$value;
}
if ( is_null($post) ) $post = 'none';
$files = get_included_files();
foreach ( $files as $key => $value ) {
$included_files .= "\n -> ".$key.' : '.$value;
}
if ( is_null($included_files) ) $included_files = 'none';
$message = "An error has been generated : \n";
$message .= "Warning : The content is protected, is not the reel content (POST,GET) !\n";
$message .= 'Date : '.date('Y-m-d H:i:s')."\n";
$message .= 'Error : '.$exception_message."\n";
$message .= 'File : '.$this->getFile()."\n";
$message .= 'Line : '.$this->getLine()."\n";
$message .= 'Code : '.$this->getCode()."\n";
if ( isset($_SERVER['HTTP_USER_AGENT']) ) $message .= 'Browser : '.@escapeshellcmd($_SERVER['HTTP_USER_AGENT'])."\n";
$message .= 'IP Address : '.$_SERVER['REMOTE_ADDR']."\n";
$message .= 'Call Page : '.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.@escapeshellcmd($_SERVER['QUERY_STRING'])."\n";
$message .= 'Request method : '.$_SERVER['REQUEST_METHOD']."\n";
$message .= 'Request timer : '.$_SERVER['REQUEST_TIME']."\n";
if ( isset($_SERVER['HTTP_REFERER']) ) $message .= 'Referer : '.@escapeshellcmd($_SERVER['HTTP_REFERER'])."\n";
$message .= 'Script path : '.$_SERVER['SCRIPT_FILENAME']."\n";
$message .= 'GET value : '.$get."\n";
$message .= 'POST value : '.$post."\n";
$message .= 'Included files : '.$included_files."\n";
$message .= "Execution traces : \n".$this->getTraceAsString()."\n";
$message .= "---------------------------------------------------\n";
$message .= "\n\n";
$file_handle = fopen (PATH_LOGS.date('Y-m-d').'.log', 'a+');
if ( !$file_handle ) {
mail('root@kelio.org', 'CRITICAL ERROR !!', 'The logfile of exceptions can\'t be open !');
}
$file_writen = fwrite ( $file_handle, $message ) ;
if ( !$file_writen ) {
mail('root@kelio.org', 'CRITICAL ERROR !!', 'The logfile of exception can\'t be written !');
}
fclose($file_handle);
if ( defined('DEBUG') and (preg_match('`ajax.php`i',$_SERVER['PHP_SELF']) == 0) ) {
$unique_id = mt_rand(0,2500);
$echo = "<div style='font-color:red;width:90%;background-color:#91020b;margin:auto;margin-bottom:20px;padding:20px;color:#fff;' id='".$unique_id."'>";
$echo .= "An error has been generated : <br />\n";
$echo .= 'Error : <strong>'.nl2br($exception_message)."</strong><br />\n";
$echo .= 'File : <strong>'.$this->getFile()."</strong><br />\n";
$echo .= 'Line : <strong>'.$this->getLine()."</strong><br />\n";
$echo .= 'Code : <strong>'.$error_code."</strong><br />\n";
$echo .= "Trace :\n".nl2br($this->getTraceAsString())."<br /><br />\n";
$echo .= "<a href='javascript:;' style='color:#fff' onclick=\"$('#".$unique_id."-2').css('display', '');\">For see complete rapport, clic here</a><br />\n";
$echo .= "<a href='javascript:;' style='color:#fff' onclick=\"$('#".$unique_id."').css('display', 'none');\">For quit this error, clic here</a><br />\n";
$echo .= "<div style='display:none;color:#fff;margin-top:20px;margin-bottom:20px;width:100%;' id='".$unique_id."-2'>".nl2br($message)."</div><br />\n";
$echo .= "</div>\n\n\n\n";
echo $echo;
}
} // End of insertInLogFile
/**
* @brief Display HTML error
*/
public function displayErrorMessage()
{
@$page = file_get_contents(PAGE_CRITICAL_ERROR);
if ( !$page ) {
die(NOLOG_ERROR);
} else {
echo $page;
}
die();
} // End of displayErrorMessage
/**
* @brief Display 'critical_error' for ajax
*/
public function displayCriticalError()
{
echo 'critical_error';
die();
}
}
/**
* @brief Manage PHP error
*/
function myErrorHandler($type, $string, $file, $line, $context){
try {
switch ($type) {
case E_USER_WARNING:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -999);
break;
case E_USER_NOTICE:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -998);
break;
case E_WARNING:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -899);
break;
case E_NOTICE:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -898);
break;
case E_ERROR:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -797);
break;
default:
throw new MyException("An PHP error has been generated :\n -> Error : ".$string."\n -> File : ".$file."\n -> Line : ".$line."\n -> Context : ".$context, -797);
}
} catch ( MyException $oException ) {
}
}
set_error_handler("myErrorHandler");
?>

140
system/api/mysql.api.php Executable file
View File

@@ -0,0 +1,140 @@
<?php
/**
* @class mysql
*
* @author Benjamin Mercier
* @date 01/03/2009
* @modified Xavier Perrissoud
* @date 28/05/2009
* @version 0.1
*
* @message getInsertId and getNumRows are modified. For use : fetchObject, ou execQuery and after getInsertId/getNumrows
* @author Mogui
* @date 19/05/2009 - 15h30
*/
class mysql {
public $executed_req = 0;
private $link = NULL;
/**
* @brief Connect to mySql
* @param mysql_user -> Name of the mysql user
* @param mysql_passwors -> Password of the mysql user
* @param mysql_server -> MySQL server
* @param database -> Database of the website
* @return TRUE -> Connection to mysql has generated no error.
*/
public function connect($mysql_user, $mysql_password, $mysql_server, $database)
{
if ( !$this->link = mysqli_connect($mysql_server, $mysql_user, $mysql_password, $database) ) {
throw new myException('Error when connecting to MySQL :'.mysqli_connect_error());
} else {
return TRUE;
}
} // End of connect
/**
* @brief Execute an request
* @param Request in SQL format.
* @return TRUE -> Query has generated no error.
*/
public function execRequest($request)
{
if ( @mysqli_query($this->link, $request) ) {
$this->executed_req++;
return TRUE;
} else {
throw new myException("Error when query is executed : \n$request\n".mysqli_error($this->link));
}
} // End of execRequest
/**
* @brief Execute an request and fetch array
* @param Request in SQL format
* @return Array of False -> FALSE: no record found
*/
public function fetchArray($request)
{
if ( !@$handle = mysqli_query($this->link, $request) ) {
throw new myException("Error when query is executed :\n$request\n".mysqli_error($this->link));
}
$this->executed_req++;
$result = array();
while( $row = mysqli_fetch_assoc($handle) )
{
$result[] = $row;
}
if ( is_null($result) ) {
return FALSE;
} else {
return $result;
}
} // End of fetchArray
/**
* @brief Execute an request and return an object
* @param Request in SQL format
* @return Array of False -> FALSE: no record found
*/
public function fetchObject($request)
{
if ( !@$handle = mysqli_query($this->link, $request) ) {
throw new myException("Error when query is executed :\n$request\n".mysqli_error($this->link));
}
$this->executed_req++;
$result = array();
while( @$row = mysqli_fetch_object($handle) )
{
$result[] = $row;
}
if ( is_null($result) ) {
return FALSE;
} else {
return $result;
}
} // End of fetchObject
/**
* @brief Return the id of the last inserted object
* @return Id of the last inserted object FROM LAST REQUEST
* @modified Mogui
* @date 19/05/2009 - 15:41
*/
public function getInsertId()
{
$result = mysqli_insert_id($this->link);
return $result;
} // End of getInsertId
/**
* @brief return the number of affected entries
* @return number of affected entries FROM LAST REQUEST
* @modified Mogui
* @date 19/05/2009 - 15:38
*/
public function getNumRows()
{
$result = mysqli_num_rows($this->link);
return $result;
} // End of getId
/**
* @brief Clear string before send in sql req.
* @param value -> Value to clear
* @return Value cleared
*/
public function clearString($string)
{
return mysqli_real_escape_string($this->link, $string);
} // End of clearString
} // End of mysql
?>

155
system/api/pagination.api.php Executable file
View File

@@ -0,0 +1,155 @@
<?php
/**
* @class pagination
* @brief Generate json arrays to pass to the javascript pagination engine
* @author Xavier Perrissoud
* @date 29/08/2009
* @version 0.1
*
* This class is a wrapper for the JavaScript pagination engine. It will help you creating and adding lines
* to the result array, and to add cells to these lines.<br />
* It will also allow you to set lines or cells attributes as you would do in a classic html table
*/
class pagination
{
/**
* @brief Temporary created datas
*/
private $results = array();
/**
* @brief Add a new line to the results array
* @param None
* @return Zero-based index of this new line
*
* You will have to call this method for every line (&lt;tr&gt;) you want to add to the result table.
* It will create an empty line, and return the zero-based index of the new line in the table.
*/
public function addLine()
{
// Create the new entry
$tr = array();
// Add the tr's options array to this entry
$tr[] = array();
// Add the tr's data's array to this entry
$tr[] = array();
// Add the entry to the results array
$this->results[] = $tr;
// Return the zero-based index of the new entry
return $this->getLinesCount()-1;
}
/**
* @brief Set an attribute for a &lt;tr&gt; entry (such as id, class, style, ...)
* @param line_index Zero-based index of the line (returned by the addLine method)
* @param attr_name Name of the attribute to set
* @param attr_value Value of the attribute to set
* @return True if successfull, False otherwise
*
* Call this method to add properties to a &lt;tr&gt; entry of your table.<br />
* For example, if you want to set the class name of a line, just call this method with <tt>$attr_name = "class"</tt> and <tt>$attr_value = "class_name"</tt>.
*/
public function setLineAttribute( $line_index, $attr_name, $attr_value )
{
if ( $line_index >= $this->getLinesCount() ) return false;
// Get the concerned line entry
$tr = & $this->results[$line_index];
// Get the line's options array
$tr_opts = & $tr[0];
// Create (or update) the line attribute
$tr_opts[$attr_name] = $attr_value;
// All is ok : we can return true
return true;
}
/**
* @brief Get the number of lines already defined in the results array
* @param None
* @return Number of lines
*
* This method will return the total of lines added to the result array (total of calls to addLine ).
*/
public function getLinesCount()
{
return count($this->results);
}
/**
* @brief Add a new cell to the given line
* @param cell_value Text / Html code to put in the cell
* @param line_index Zero-based index of the line (if ommitted, the last line added is used)
* @return Zero-based index of the cell in the line
*
* You will have to call this method for every cell (&lt;td&gt;) entry that you want to add to a line.
*/
public function addCell( $cell_value, $line_index=null )
{
if ( is_null($line_index) ) $line_index = $this->getLinesCount()-1;
// Create the new cell datas
$new_cell = array( 'html' => $cell_value );
// Get the line entry in the results array
$tr = & $this->results[$line_index];
// Get the line's cells array
$tr_cells = & $tr[1];
// Add the cell to the line
$tr_cells[] = $new_cell;
// Return the new cell index
return $this->getCellsCount($line_index)-1;
}
/**
* @brief Set an attribute for a &lt;td&gt; entry (such as id, class, style, colspan, ...)
* @param line_index Zero-based index of the line
* @param cell_index Zero-based index of the cell in the line (the cell must be created before with addCell)
* @param attr_name Name of the attribute to set/modify
* @param attr_value Value of the attribute
* @return True if successfull, false otherwise
*
* Call this method to add properties to a &lt;td&gt; entry of your table.<br />
* For example, if you want to set the class name of a cell, just call this method with <tt>$attr_name = "class"</tt> and <tt>$attr_value = "class_name"</tt>.
*/
public function setCellAttribute( $line_index, $cell_index, $attr_name, $attr_value )
{
// Check the $line_index and $cell_index values
if ( ($line_index < 0) || ($line_index >= $this->getLinesCount())) return false;
if ( ($cell_index < 0) || ($cell_index >= $this->getCellsCount($line_index)) ) return false;
// Get the line entry in the results array
$tr = & $this->results[$line_index];
// Get the line's cells array
$tr_cells = & $tr[1];
// Get the cell entry
$td = & $tr_cells[$cell_index];
// Set/Modify the cell attribute
$td[$attr_name] = $attr_value;
return true;
}
/**
* @brief Get the number of cells already defined in the given line
* @param line_index : Zero-based index of the line (if ommitted, the last line is used)
* @return Number of cells in the line
*
*/
public function getCellsCount( $line_index=null)
{
if ( is_null($line_index) ) $line_index = $this->getLinesCount()-1;
// Get the line entry in the results array
$tr = & $this->results[$line_index];
// Return the number of cells
return count($tr[1]);
}
/**
* @brief Get the created results array
* @param None
* @return json array of the result table datas
*
*/
public function getResult()
{
return json_encode($this->results);
}
}
?>

49
system/api/security.api.php Executable file
View File

@@ -0,0 +1,49 @@
<?php
/**
* @class security
* @brief Manage, verify the security of the panel
*
* @author Benjamin Mercier
* @data 08/03/2009
* @version 0.1
*/
class security
{
/**
* @brief Make security controls
* @return NULL (but make exception if error is find
*/
public function __construct ()
{
// Critical verification
$this->checkMagicQuotesGPC();
// Configuration
$this->initializeTimezone();
} // End of construct
/**
* @brief Check magic_quote_gpc. If is activated, throwing exception.
* @return null
*/
private function checkMagicQuotesGPC()
{
if ( get_magic_quotes_gpc() == 1 ) {
throw new myException('PHP variable magic_quotes_gpc must be set on Off');
}
}
/**
* @brief Initialize the timezone if not set
* @return null
*/
private function initializeTimezone()
{
date_default_timezone_set(TIMEZONE);
}
} // End of class
?>

515
system/api/support.api.php Executable file
View File

@@ -0,0 +1,515 @@
<?php
/**
* @class support
* @brief Manage support tickets
* @author Xavier Perrissoud
* @modified Benjamin Mercier
* @date 29/04/2009
* @version 0.1
*
*/
class support{
/**
* @brief Cache variable with total of tickets for the current user
*/
private $user_tickets = null;
/**
* @brief Cache variable with total of tickets waiting for a support reply
*/
private $waiting_tickets = null;
/**
* @brief Cache variable with total of tickets for witch the support made a reply
*/
private $replied_tickets = null;
/**
* @brief Cache array with total of messages for each tickets
*/
private $ticket_messages = array();
/**
* @brief List all tickets of a given user
* @param user_id -> id of the user for witch we want the tickets list (must be specified)
* @param start -> First ticket to extract (can be NULL)
* @param extract -> Number of tickets to extract (can be NULL)
* @return array of tickets informations (NULL if empty)
*/
public function getUserTickets($user_id, $start = NULL, $extract = NULL)
{
$user_id = $_SESSION['database']->clearString($user_id);
// if paging informations are given, create the LIMIT clause
if ( !is_null($start) and !is_null($extract) ) {
$start = $_SESSION['database']->clearString($start);
$extract = $_SESSION['database']->clearString($extract);
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
$req = "SELECT
t.id AS ticket_id,
t.subject,
UNIX_TIMESTAMP(t.open_date) AS open_date,
t.status,
h.base_name AS hosting_name
FROM tickets AS t
LEFT JOIN hostings AS h
ON h.id = t.hosting_id
WHERE t.user_id = '$user_id'
ORDER BY t.open_date DESC $limit";
$tickets_list = $_SESSION['database']->fetchObject($req);
foreach ($tickets_list as $item) {
$item->subject=stripslashes($item->subject);
}
return $tickets_list;
} // End of getUserTickets
/**
* @brief List all tickets of the current user
* @param start -> First ticket to extract (can be NULL)
* @param extract -> Number of tickets to extract (can be NULL)
* @return array of tickets informations (NULL if empty)
*/
public function userGetTickets($start = NULL, $extract = NULL)
{
$user_id=$_SESSION['user']->information_user->userid;
return $this->getUserTickets($user_id, $start, $extract);
} // End of userGetTickets
/**
* @brief List all "waiting for a reply" tickets, sorted by last message date, older in first position
* @param start -> First ticket to extract (can be NULL)
* @param extract -> Number of tickets to extract (can be NULL)
* @return array of tickets informations (NULL if empty)
*/
public function getWaitingTickets($start = NULL, $extract = NULL)
{
// if paging informations are given, create the LIMIT clause
if ( !is_null($start) and !is_null($extract) ) {
$start = $_SESSION['database']->clearString($start);
$extract = $_SESSION['database']->clearString($extract);
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
$sql = "SELECT
t.id AS ticket_id,
t.subject,
UNIX_TIMESTAMP(t.open_date) AS open_date,
t.status,
UNIX_TIMESTAMP(t.last_msg_date) AS last_msg_date,
h.base_name AS hosting_name
FROM tickets AS t
LEFT JOIN hostings AS h
ON h.id = t.hosting_id
WHERE t.status = 'asked'
ORDER BY t.last_msg_date ASC $limit";
$tickets_list = $_SESSION['database']->fetchObject($sql);
// Check if tickets list is not empty
if ( !isset($tickets_list[0]) ) return NULL;
foreach ($tickets_list as $item) {
$item->subject=stripslashes($item->subject);
}
return $tickets_list;
}
/**
* @brief List all "replied but not closed" tickets, sorted by last message date, older in first position
* @param start -> First ticket to extract (can be NULL)
* @param extract -> Number of tickets to extract (can be NULL)
* @return array of tickets informations (NULL if empty)
*/
public function getRepliedTickets($start = NULL, $extract = NULL)
{
// if paging informations are given, create the LIMIT clause
if ( !is_null($start) and !is_null($extract) ) {
$start = $_SESSION['database']->clearString($start);
$extract = $_SESSION['database']->clearString($extract);
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
$sql = "SELECT
t.id AS ticket_id,
t.subject,
UNIX_TIMESTAMP(t.open_date) AS open_date,
t.status,
UNIX_TIMESTAMP(t.last_msg_date) AS last_msg_date,
h.base_name AS hosting_name
FROM tickets AS t
LEFT JOIN hostings AS h
ON h.id = t.hosting_id
WHERE t.status = 'replied'
ORDER BY t.last_msg_date ASC $limit";
$tickets_list = $_SESSION['database']->fetchObject($sql);
// Check if tickets list is not empty
if ( !isset($tickets_list[0]) ) return NULL;
foreach ($tickets_list as $item) {
$item->subject=stripslashes($item->subject);
}
return $tickets_list;
}
/**
* @brief Extract messages related to a given ticket
* @param ticket_id -> id of the ticket for witch we want to see the messages
* @param start -> First message to extract
* @param extract -> Number of messages to extract
* @return an array (NULL if ticket_id was an invalid number) with first element = ticket summary, and others = messages
*/
public function getTicketDetails($ticket_id, $start = NULL, $extract = NULL)
{
$ticket_id = $_SESSION['database']->clearString($ticket_id);
if ( !is_null($start) and !is_null($extract) ) {
$start = $_SESSION['database']->clearString($start);
$extract = $_SESSION['database']->clearString($extract);
$limit = "LIMIT $start, $extract";
} else $limit = NULL;
// Extract ticket's summary
$req = "SELECT
t.*,
h.base_name AS hosting_name,
u.username AS user_name
FROM tickets AS t
LEFT JOIN hostings AS h
ON h.id = t.hosting_id
LEFT JOIN users AS u
ON u.id = t.user_id
WHERE t.id = '$ticket_id'";
$summary = $_SESSION['database']->fetchObject($req);
// Check if ticket id was a valid number
if ( !isset($summary[0]) ) return NULL;
$summary[0]->subject = stripslashes($summary[0]->subject);
$summary[0]->open_date = strtotime($summary[0]->open_date);
// Extract messages
$req = "SELECT
m.id AS msg_id,
UNIX_TIMESTAMP(m.posted) AS posted,
m.is_reply,
m.message
FROM tickets_msg AS m
WHERE m.ticket_id = '$ticket_id'
ORDER BY m.posted DESC
$limit";
$messages = $_SESSION['database']->fetchObject($req);
foreach ($messages as $item) {
$item->message=stripslashes($item->message);
}
// if messages list is not empty, append it to results
if ( !is_null($messages) )
$results = array_merge((array)$summary, $messages);
else
$results = (array)$summary;
return $results;
} // End of getTicketDetails
/**
* @brief Create a new ticket from a user request
* @param subject -> subject of the ticket
* @param message -> content of the ticket
* @param hosting_id -> id of the hosting entry to associate with this ticket (can be NULL)
* @return True if successfull, false otherwise
*/
public function userCreateTicket($subject, $message, $hosting_id=NULL)
{
$subject = $_SESSION['database']->clearString($subject);
$message = $_SESSION['database']->clearString($message);
$date_msg = time();
$user_id=$_SESSION['user']->information_user->userid;
$ticket_id = 0; // we actually don't know this value
if ( is_null($hosting_id) ) {
$hosting_entry='';
} else {
$hosting_id = $_SESSION['database']->clearString($hosting_id);
$hosting_entry="hosting_id = '$hosting_id',";
}
// Addind message into database
$sql1 = "INSERT INTO tickets_msg
SET
ticket_id = '$ticket_id',
posted = FROM_UNIXTIME($date_msg),
is_reply = 'false',
message = '$message'";
$_SESSION['database']->execRequest($sql1);
$msg_id = $_SESSION['database']->getInsertId();
// Adding ticket infos in database
$sql2 = "INSERT INTO tickets
SET
user_id = '$user_id',
open_date = FROM_UNIXTIME($date_msg),
first_msg_id = '$msg_id',
last_msg_date = FROM_UNIXTIME($date_msg),
last_msg_id = '$msg_id',
status = 'asked',
$hosting_entry
subject = '$subject'";
$_SESSION['database']->execRequest($sql2);
$ticket_id = $_SESSION['database']->getInsertId();
// Updating cache variable if needed
if ( !is_null($this->user_tickets) ) {
$this->user_tickets++;
}
// Updating ticket id for the message
$sql3 = "UPDATE tickets_msg
SET
ticket_id = '$ticket_id'
WHERE
id = '$msg_id'";
return $_SESSION['database']->execRequest($sql3);
} // End of userCreateTicket
/**
* @brief Check if a ticket delong to the current user
* @param ticket_id -> id of the ticket to check
* @return true if ticket if current user's one, false otherwise
*/
public function userCheckTicketId($ticket_id)
{
$user_id = $_SESSION['user']->information_user->userid;
$ticket_id = $_SESSION['database']->clearString($ticket_id);
$sql = "SELECT id FROM tickets
WHERE id = '$ticket_id'
AND user_id = '$user_id'";
$result = $_SESSION['database']->fetchObject($sql);
return ( isset($result[0]));
} // End of userCheckTicketId
/**
* @brief Add a response to a ticket (from the user)
* @param ticket_id -> id of the ticket to associate to the response
* @param message -> content of the response
* @return true if successfull, false otherwise
*/
public function userAddResponse($ticket_id, $message)
{
if ( !$this->userCheckTicketId($ticket_id) ) return false;
return $this->addResponse($ticket_id, $message, true);
} // end of userAddResponse
/**
* @brief Add a response to a ticket
* @param ticket_id -> id of the ticket to associate to the response
* @param message -> content of the response
* @param from_user -> true if the response comes from the user, false otherwise
* @return true if successfull, false otherwise
*/
public function addResponse($ticket_id, $message, $from_user)
{
$ticket_id = $_SESSION['database']->clearString($ticket_id);
$message = $_SESSION['database']->clearString($message);
$from_user = $_SESSION['database']->clearString($from_user);
$is_reply=( $from_user==true ? 'false' : 'true' );
$status = ( $is_reply=='true' ? 'replied' : 'asked' );
$date_msg = time();
$sql = "INSERT INTO tickets_msg SET
ticket_id = '$ticket_id',
posted = FROM_UNIXTIME($date_msg),
is_reply = '$is_reply',
message = '$message'";
$_SESSION['database']->execRequest($sql);
$msg_id = $_SESSION['database']->getInsertId();
if ( !$msg_id) return false;
$sql2 = "UPDATE tickets SET
last_msg_date = FROM_UNIXTIME($date_msg),
last_msg_id = '$msg_id',
status = '$status'
WHERE id='$ticket_id'";
return $_SESSION['database']->execRequest($sql2);
} // end of addResponse
/**
* @brief Close a support ticket
* @param ticket_id -> id of the ticket to close
* @param fromUser -> true if called from a user's page, false otherwise
* @return true if successfull, false otherwise
*/
public function closeTicket($ticket_id, $from_user)
{
$ticket_id = $_SESSION['database']->clearString($ticket_id);
$from_user = $_SESSION['database']->clearString($from_user);
$status = ( $from_user==true ? 'closed_by_user' : 'closed_by_support' );
$close_date = time();
$sql = "UPDATE tickets SET
status = '$status',
closed_date = FROM_UNIXTIME($close_date)
WHERE id='$ticket_id'";
return $_SESSION['database']->execRequest($sql);
} // end of closeTicket
/**
* @brief Close a support ticket (from the user)
* @param ticket_id -> id of the ticket to close
* @return true if successfull, false otherwise
*/
public function userCloseTicket($ticket_id)
{
if ( !$this->userCheckTicketId($ticket_id) ) return false;
return $this->closeTicket($ticket_id, true);
} // end of userCloseTicket
/**
* @brief Get number of tickets for the current user
* @param None
* @return number of tickets for the user
*
* Get the total of support tickets for the current user.<br />
* This value is got the first time from the database (generating a SQL request) and is then stocked in a cache variable, so, other calls to this method won't generate another SQL request.
*/
public function userCountTickets()
{
// Try to get the value from the cache
if( !is_null($this->user_tickets) ) {
return $this->user_tickets;
}
$user_id = $_SESSION['user']->information_user->userid;
$req = "SELECT COUNT(id) AS total FROM tickets WHERE user_id='$user_id'";
$result = $_SESSION['database']->fetchObject($req);
$this->user_tickets = $result[0]->total;
return $this->user_tickets;
}
/**
* @brief Get number of tickets pages for the current user, regarding the total count of tickets and the count of items to be shown per page
* @param None
* @return number of pages availables
*
* Calculate the total pages needed to show all the support tickets for the current user.
*/
public function userCountTotalPages()
{
$items_count = $this->userCountTickets();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
/**
* @brief Get the total of messages for a given ticket
* @param ticket_id Id of the ticket for witch we want to count the messages
* @return number of messages
*/
public function countTicketMessages( $ticket_id )
{
$ticket_id = $_SESSION['database']->clearString($ticket_id);
if ( isset($this->ticket_messages[$ticket_id]) ) {
return $this->ticket_messages[$ticket_id];
}
$req = "SELECT COUNT(id) AS total FROM tickets_msg WHERE ticket_id='$ticket_id'";
$result = $_SESSION['database']->fetchObject($req);
$this->ticket_messages[$ticket_id] = $result[0]->total;
return $this->ticket_messages[$ticket_id];
}
/**
* @brief Get total of details pages for a given ticket, regarding the total count of messages and the count of items to be shown per page
* @param ticket_id Id of the ticket for witch we want the total of pages
* @return number of pages availables
*/
public function countTicketTotalPages( $ticket_id )
{
$items_count = $this->countTicketMessages( $ticket_id );
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
/**
* @brief Get total of tickets waiting for a support reply
* @param None
* @return number of tickets waiting for a support reply
*
* Get the total of support tickets waiting for a support reply.<br />
* This value is got the first time from the database (generating a SQL request) and is then stocked in a cache variable, so, other calls to this method won't generate another SQL request.
*/
public function countWaitingTickets()
{
// Try to get the value from the cache
if( !is_null($this->waiting_tickets) ) {
return $this->waiting_tickets;
}
$req = "SELECT COUNT(id) AS total FROM tickets WHERE status = 'asked'";
$result = $_SESSION['database']->fetchObject($req);
$this->waiting_tickets = $result[0]->total;
return $this->waiting_tickets;
}
/**
* @brief Get total of pages for tickets waiting for a supoprt reply, regarding the total count of messages and the count of items to be shown per page
* @param None
* @return number of pages availables
*/
public function countWaitingTicketsTotalPages()
{
$items_count = $this->countWaitingTickets();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
/**
* @brief Get total of tickets for witch the support made a reply
* @param None
* @return number of tickets for witch the support made a reply
*
* Get the total of support tickets for witch the support made a reply.<br />
* This value is got the first time from the database (generating a SQL request) and is then stocked in a cache variable, so, other calls to this method won't generate another SQL request.
*/
public function countRepliedTickets()
{
// Try to get the value from the cache
if( !is_null($this->replied_tickets) ) {
return $this->replied_tickets;
}
$req = "SELECT COUNT(id) AS total FROM tickets WHERE status = 'replied'";
$result = $_SESSION['database']->fetchObject($req);
$this->replied_tickets = $result[0]->total;
return $this->replied_tickets;
}
/**
* @brief Get total of pages for tickets for witch the support made a reply, regarding the total count of messages and the count of items to be shown per page
* @param None
* @return number of pages availables
*/
public function countRepliedTicketsTotalPages()
{
$items_count = $this->countRepliedTickets();
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
} // End of class

187
system/api/template.api.php Executable file
View File

@@ -0,0 +1,187 @@
<?php
class template{
protected $_oSmarty;
private $list_module = array();
private $list_css = array();
private $list_js = array();
private $list_menu = array();
private $list_menu_title = array();
public function __construct()
{
$lang = new lang();
$this->_oSmarty = new Smarty();
$this->_oSmarty->clear_compiled_tpl();
$this->_oSmarty->template_dir = PATH_TPL.$this->userGetTemplate().'/template/';
$this->_oSmarty->compile_dir = PATH_CACHE.'smarty/compiled/';
$this->_oSmarty->cache_dir = PATH_CACHE.'smarty/cache/';
$this->_oSmarty->config_dir = PATH_LANG.$lang->userGetLang().'/';
$this->_oSmarty->load_filter('output','trimwhitespace');
$this->_oSmarty->caching = false;
$this->_oSmarty->assign('HOST', TPL_HOST);
$this->_oSmarty->assign('IMAGE', 'image/');
$this->_oSmarty->assign('TPL_IMAGE', 'theme/'.$this->userGetTemplate().'/image/');
$this->_oSmarty->assign('JAVASCRIPT', 'javascript/');
$this->_oSmarty->assign('TPL_JAVASCRIPT', 'themes/'.$this->userGetTemplate().'/javascript/');
$this->_oSmarty->assign('TPL_STYLE', 'themes/'.$this->userGetTemplate().'/style/');
$this->_oSmarty->assign('STYLE', 'style/');
$this->_oSmarty->assign('CHARSET', WEBSITE_CHARSET);
$this->_oSmarty->assign('USER_INFOS', $_SESSION['user']->information_user);
$this->loadModifiers();
} // End of __construct
public function addMenu( $title, $list_menu )
{
$lang = new lang();
if ( !is_array($list_menu) ) throw new myException('list_menu is not an array');
if ( empty($title) ) throw new myException('The title of the new menu can\'t be empty');
if ( count($this->list_menu) != count($this->list_menu_title) ) throw new myException('Arrays white information is not equal');
foreach ( $list_menu as $key => $value )
{
$list_menu[$key] = $lang->getWordFromLangFile($value);
}
$this->list_menu[] = $list_menu;
$this->list_menu_title[] = $lang->getWordFromLangFile($title);
return TRUE;
}
public function getWords($words)
{
$this->_oSmarty->assign($words);
return TRUE;
} // End of getWords
public function loadCSS($css_files)
{
if ( is_array($css_files) ) {
foreach($css_files as $key => $value)
{
if ( in_array($value, $this->list_css ) ) throw new myException("CSS file '$value' is already loaded");
$this->list_css[] = $value;
}
return TRUE;
}
if ( in_array($css_files, $this->list_css ) ) throw new myException("CSS file '$css_files' is already loaded");
$this->list_css[] = $css_files;
return TRUE;
}
public function loadJS($js_files)
{
if ( is_array($js_files) ) {
foreach($js_files as $key => $value)
{
if ( in_array($value, $this->list_js ) ) throw new myException("JS file '$value' is already loaded");
$this->list_js[] = $value;
}
return TRUE;
}
if ( in_array($js_files, $this->list_js ) ) throw new myException("JS file '$css_files' is already loaded");
$this->list_js[] = $js_files;
return TRUE;
}
public function loadTemplate($module)
{
if ( in_array($module, $this->list_module) ) {
throw new myException("Module '$module' is already loaded");
}
$this->list_module[] = $module;
return TRUE;
} // End of loadTemplate
public function parseTemplate()
{
if ( is_null($this->list_module) ) {
return FALSE;
}
$this->_oSmarty->assign('css_files', $this->list_css);
$this->_oSmarty->assign('js_files', $this->list_js);
foreach( $this->list_module as $key => $value )
{
if ( !$this->_oSmarty->template_exists($value.'.tpl') ) {
throw new myException("Template file $value is not found");
}
}
$this->_oSmarty->assign('list_menu_title', $this->list_menu_title);
$this->_oSmarty->assign('list_menu', $this->list_menu);
foreach( $this->list_module as $key => $value )
{
$this->_oSmarty->display($value.'.tpl');
}
} // End of parseTemplate
public function userGetTemplate()
{
if ( !TEMPLATE_USE_OTHERS ) {
return TEMPLATE_DEFAULT;
}
if( !$_SESSION['user']->user_not_logued ) {
if( !$template = $_SESSION['user']->userGetTemplate() ) {
throw new myException('The user is connected but getUserTemplate has returned false');
}
$template_allowed = unserialize(TEMPLATE_ALLOWED);
if ( !in_array($template, $template_allowed) ) {
throw new myException('Template of the user is not allowed in configuration file');
}
} else {
$template = TEMPLATE_DEFAULT;
}
return $template;
} // End of getTemplate
/**
* @brief assign var when the right is autorised
* @return NULL
*/
public function userSetRightsDisplay()
{
if ( !is_null($_SESSION['user']->information_user) ) {
$right = $_SESSION['user']->information_user->lvl;
if ( $right >= LEVEL_REGISTER ) $_SESSION['template']->getWords(array('is_connected' => 1));
if ( $right >= LEVEL_CUSTOMER ) $_SESSION['template']->getWords(array('is_client' => 1));
if ( $right >= LEVEL_MODERATOR ) $_SESSION['template']->getWords(array('is_moderator' => 1));
if ( $right >= LEVEL_SUPPORT ) $_SESSION['template']->getWords(array('is_support' => 1));
if ( $right >= LEVEL_ADMIN ) $_SESSION['template']->getWords(array('is_admin' => 1));
if ( $right >= LEVEL_CUSTOMER and isset($_SESSION['hosting']->information_hosting->id) ) {
$_SESSION['template']->getWords(array('hosting_specified' => $_SESSION['hosting']->information_hosting->id));
$_SESSION['template']->getWords(array('HOSTING_INFOS' => $_SESSION['hosting']->information_hosting));
}
if ( $right > LEVEL_ADMIN or $right < LEVEL_REGISTER ) throw new myException("Right is not correct '$right'");
}
} // End of displayMenus
/**
* @brief Check template existance and syntax
* @param template -> Name of template
* @return True/False
*/
public function checkTemplateExistence($template)
{
$list_template = unserialize(TEMPLATE_ALLOWED);
if ( in_array($template, $list_template) ) return true;
else return false;
}
/**
* @brief Load modifier at the startup of the script
* @brief If necessary, create a modifier for a custom modification of strings
* @brief For the exemple : {#test#|ucfirst} or {$test.test|ucfirst}
* @return null
*/
public function loadModifiers()
{
//$this->_oSmarty->register_modifier('ucfirst', 'ucfirst');
}
} // End of class
?>

View File

@@ -0,0 +1,199 @@
<?php
/**
* @class textVerification
* @brief Check the text.
*
* @author Benjamin Mercier
* @data 28/03/2009
* @modified Xavier Perrissoud
* @date 13/10/2009
* @version 0.1
* @todo Add documentation for each method (and give explicitelly each format allowed)
* @todo Add an optional param to verifUnixPath, to check if the folder exists in the user's tree
* Some unixPath verification need that the checked folder is a valid one, and that it already exists.
* For example, when adding a new virtualhost, the root directory must exists.
* Also add a returned value other than true/false if the directory does not exists
* @todo Check the "verifUnixPath" regexp
*/
class textVerification
{
static public function verifAjaxID ($ajax_id)
{
$regex = '`^[a-z0-9_]{1,40}$`i';
if (preg_match($regex, $ajax_id) == 1 ) return true;
else return false;
} // End of checkAjaxID
static public function verifFirstName ($first_name)
{
$regex = '`^[a-zA-Z., -]{1,35}$`';
if (preg_match($regex, $first_name) == 1 ) return true;
else return false;
} // End of verifFirstName
static public function verifLastName ($last_name)
{
$regex = '`^[a-zA-Z., -]{1,35}$`';
if (preg_match($regex, $last_name) == 1 ) return true;
else return false;
} // End of verifLastName
static public function verifCompany ($company)
{
$regex = '`^[a-zA-Z0-9.,& -]{0,35}$`';
if (preg_match($regex, $company) == 1 ) return true;
else return false;
} // End of verifCompany
static public function verifAddress ($address)
{
$regex = '`^[a-zA-Z0-9.,& -]{0,250}$`';
if (preg_match($regex, $address) == 1 ) return true;
else return false;
} // End of verifAddress
static public function verifCity ($city)
{
$regex = '`^[a-zA-Z -]{1,35}$`';
if (preg_match($regex, $city) == 1 ) return true;
else return false;
} // End of verifCity
static public function verifZipcode ($zipcode)
{
$regex = '`^[a-zA-Z0-9-]{1,12}$`';
if (preg_match($regex, $zipcode) == 1 ) return true;
else return false;
} // End of verifZipcode
static public function verifEmail ($email)
{
$regex = '`^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$`';
if (preg_match($regex, $email) == 1 ) return true;
else return false;
} // End of verifEmail
static public function verifPseudo ($pseudo)
{
$regex = '`^[a-z0-9]{1,9}$`';
if (preg_match($regex, $pseudo) == 1 ) return true;
else return false;
} // End of verifPseudo
static public function verifCountrieID ($countrie)
{
$regex = '`^[0-9]{1,11}$`';
if (preg_match($regex, $countrie) == 1 ) return true;
else return false;
} // End of verifCountrieID
static public function verifLangID ($lang)
{
$regex = '`^[0-9]{1,11}$`';
if (preg_match($regex, $lang) == 1 ) return true;
else return false;
} // Endd of verifLangID
static public function verifTemplate ($template)
{
$regex = '`^[a-zA-Z]{0,20}$`';
if (preg_match($regex, $template) == 1 ) return true;
else return false;
}
static public function verifHostingID ($hosting_id)
{
$regex = '`^[0-9]{1,11}$`';
if (preg_match($regex, $hosting_id) == 1 ) return true;
else return false;
} // end of verifHostingID
static public function verifID ($id)
{
$regex = '`^[1-9][0-9]{0,10}$`';
if (preg_match($regex, $id) == 1 ) return true;
else return false;
} // end of verifID
static public function verifSubject ($subject)
{
// 5 to 100 chars, begining with an alphanumeric one
$regex='`^[a-z0-9éèàçù].{4,99}$`i';
if (preg_match($regex, $subject) == 1 ) return true;
else return false;
} // End of verifSubject
static public function verifMessage ($message)
{
// 5 to 500 chars, begining with an alphanumeric one
$regex='`^[a-zA-Z0-9éèàçu].{4,499}$`mi';
if (preg_match($regex, $message) == 1 ) return true;
else return false;
} // End of verifMessage
static public function verifUrl ($url)
{
$regex='`^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;/~\+#]*[\w\-\@?^=%&amp;/~\+#])?$`i';
if (preg_match($regex, $url) == 1 ) return true;
else return false;
}
static public function verifDatabaseName ($database)
{
$regex='`^[a-z0-9_]{1,16}$`';
if (preg_match($regex, $database) == 1 ) return true;
else return false;
}
static public function verifHost ($host)
{
$regex='`^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$`';
if (preg_match($regex, $host) == 1 ) return true;
else return false;
}
static public function verifUnixPath ($dir)
{
//$regex='`^((?:\/[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)*(?:\-[a-zA-Z0-9]+)*)+)$`';
$regex='`^\/{1}([a-z0-9_-]*\.?[a-z0-9_-]*\/{1})?$`i';
if (preg_match($regex, $dir) == 1 ) return true;
else return false;
}
static public function verifBoolean ($var)
{
$regex='`^([Ff]+(alse)?|[Tt]+(rue)?|0|[\+\-]?1)$`';
if ( preg_match($regex, $var) == 1) return true;
return is_bool($var);
}
static public function verifInteger ($value, $mini=null, $maxi = null)
{
// Check if the value is a numeric one
if ( !is_numeric($value) ) return false;
// Get the real value
$value = intval($value);
// Check with the minimal value if specified
if ( !is_null($mini) ) {
if ( $value < $mini ) return false;
}
// Check with the maxi mal value if specified
if ( !is_null($maxi) ) {
if ( $value > $maxi ) return false;
}
// If all is ok, return true;
return true;
}
static public function verifPassword( $value )
{
$regex='`^[^\'"]{4,15}$`';
if (preg_match($regex, $value == 1 )) return true;
else return false;
}
} // End of class
?>

327
system/api/user.api.php Executable file
View File

@@ -0,0 +1,327 @@
<?php
/**
* @class user
* @brief Manage, display user
*
* @author Benjamin Mercier
* @date 08/03/2009
* @version 0.1
*/
class user {
/**
* @brief Array with information from current hosting for all API.
* @brief Null when user is not initialized
*/
public $information_user = null;
// obsolete, a virer
//public $user_not_logued = true;
/**
* @brief Result test for userInitialize.
* @brief Get the result code before be used by userCheckAccess
*/
public $result_test = null;
/**
* @brief Check autorisation to access for the page
* @return True ONLY : Do not use, for test !
*/
public function userCheckAccess($access_min, $access_max = null)
{
$user_statut = $this->result_test;
if ( $user_statut == 1 ) {
throw new myException('SECURITY WARNING : The password of user is not the same in DB and session');
} elseif ( $user_statut == 2 ) {
redirect('error-3.xhtml');
} elseif ( $user_statut == 3 ) {
redirect('error-4.xhtml');
}
if ( is_null($this->information_user) and $access_min == 0 ) {
return TRUE;
} elseif ( is_null($this->information_user) ) {
redirect('connection.xhtml');
}
$user_lvl = $this->information_user->lvl;
if ( $user_lvl < $access_min ) {
redirect('error-1.xhtml');
} elseif ( !is_null($access_max) and $user_lvl > $access_max ) {
redirect('error-2.xhtml');
} else {
return TRUE;
}
} // End of checkaccess
/**
* @brief Initialize information_user with all informations from the current user
* @return 0 : User not found
* @return 1 : Username & password is wrong
* @return 2 : User is not active
* @return 3 : Group is not active
* @return 4 : Evrythinks is okay :-)
* @returb 5 : User is not logued
*/
public function userInitialize()
{
// The user informations is initialized ?
if ( !is_null($this->information_user) ) {
throw new myException('The var information_user is already initialized');
}
// The sessions is existing ? No : User is not logged
if ( !isset($_SESSION['user_infos']) ) {
$this->result_test = 5;
return 5;
}
// Convert session in array
$informations = unserialize($_SESSION['user_infos']);
if ( !is_array($informations) ) {
throw new myException('the user_infos is not an array');
}
// Check the information where user_id in session database
$user_info = $this->selectInformationsFromDB($informations['user_id']);
if ( !$user_info ) throw new myException("Not user found with id '$userid'");
// User is found
// Get user, password, userid from session
$password = $informations['hash'];
$userid = $informations['user_id'];
$user_info = $user_info[0];
// The password of session and DB are differents
if ( $user_info->password != $password ) {
$this->result_test = 1;
return 1;
}
// The user is not active
elseif ( $user_info->user_active == 'false' ) {
$this->result_test = 2;
return 2;
}
// The group is not active
elseif ( $user_info->group_active == 'false' ) {
$this->result_test = 3;
return 3;
}
// All tests are passed, the user is logged
else {
$this->information_user = $user_info;
$this->result_test = 4;
return 4;
}
} // End of initializeUser
/**
* @brief Return the name of the user template
* @return Name/False : If name is empty, return false
*/
public function userGetTemplate()
{
if ( is_null($this->information_user) ) throw new myException('The user is not logued');
$template_name = $this->information_user->template;
if ( empty($template_name) ) return false;
else return $template_name;
} // End of getUserTemplate
/**
* @brief Return the lang of the user
* @return Lang/False : If lang is empty, return false
*/
public function userGetLang()
{
if ( is_null($this->information_user) ) throw new myException('The user is not logued');
$lang = $this->information_user->lang;
if ( empty($lang) ) return false;
else return $lang;
} // End of getUserLang
/**
* @brief Select informations from user in database
* @param user_id -> Id of a user, optionnaly
* @return Array with informations from user or FALSE is user is not found
*/
private function selectInformationsFromDB($user_id = NULL)
{
if ( is_null($user_id) ) {
$informations = unserialize($_SESSION['user_infos']);
if ( !is_array($informations) ) throw new myException('Need to get a user_id but informations session is not initialized');
$user_id = $informations['user_id'];
}
$req = "SELECT
u.username AS user,
u.password AS password,
u.id AS userid,
u.email AS email,
u.first_name AS first_name,
u.last_name AS last_name,
u.company AS company,
u.address AS address,
u.city AS city,
u.zipcode AS zipcode,
c.flag AS countrie,
u.template AS template,
u.is_active AS user_active,
g.is_active AS group_active,
g.name AS group_name,
g.id AS groupid,
g.lvl AS lvl,
l.flag AS lang,
l.is_lang AS lang_active
FROM users AS u
LEFT JOIN groups AS g
ON u.groups_id = g.id
LEFT JOIN countries AS c
ON u.countries_id = c.id
LEFT JOIN countries AS l
ON u.lang_id = l.id
WHERE
u.id = '$user_id'";
$user_selected = $_SESSION['database']->fetchObject($req);
if ( is_array($user_selected) ) {
if ( is_null($user_selected[0]->countrie) ) throw new myException('The user selected has no countrie flag');
elseif ( is_null($user_selected[0]->groupid) ) throw new myException('The user selected has no groupid');
elseif ( is_null($user_selected[0]->lvl) ) throw new myException('The group has not a int right '.$user_selected[0]->lvl);
else {
if ( $user_selected[0]->lang_active == 'false' ) $user_selected[0]->lang = null;
return $user_selected;
}
} else {
return FALSE;
}
} // End of selectInformationsFromDB
/**
* @brief Edit an user
* @param user_id -> ID of the user
* @param first_name -> First name of the user
* @param last_name -> Last name of the user
* @param company -> Name of the company
* @param address -> Address of the user
* @param city -> City of the user
* @param zipcode -> Zipcode of the user
* @param email -> Email of the user
* @param pseudo -> Pseudo of the user
* @param countrie_id -> Countrie of the user
* @param lang_id -> Lang of the user
* @param template -> Template of the user
* @return True : Member edited
*/
private function editMember($user_id, $first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template)
{
$user_id = $_SESSION['database']->clearString($user_id);
$first_name = $_SESSION['database']->clearString($first_name);
$last_name = $_SESSION['database']->clearString($last_name);
$company = $_SESSION['database']->clearString($company);
$address = $_SESSION['database']->clearString($address);
$city = $_SESSION['database']->clearString($city);
$zipcode = $_SESSION['database']->clearString($zipcode);
$email = $_SESSION['database']->clearString($email);
$pseudo = $_SESSION['database']->clearString($pseudo);
$countrie_id = $_SESSION['database']->clearString($countrie_id);
$lang_id = $_SESSION['database']->clearString($lang_id);
$template = $_SESSION['database']->clearString($template);
$req = "UPDATE users
SET
username = '$pseudo',
email = '$email',
template = '$template',
lang_id = '$lang_id',
first_name = '$first_name',
last_name = '$last_name',
company = '$company',
address = '$address',
city = '$city',
zipcode = '$zipcode',
countries_id = '$countrie_id',
template = '$template'
WHERE id = '$user_id'";
$_SESSION['database']->execRequest($req);
// save action to history
history::add("history_action_profile",$user_id);
return true;
} // End of editMember
/**
* @brief Edit user
* @see Description from editMember
*/
public function userEdit($first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template)
{
if ( $this->editMember($this->information_user->userid, $first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template) ) {
return true;
} else {
return false;
}
} // End of userEdit
/**
* @brief Check existence of an username
* @param username -> Name of username
* @return True/False
*/
public function checkUsernameExistence ($username)
{
$username = $_SESSION['database']->clearString($username);
$req = "SELECT COUNT(id) AS total FROM users WHERE username='$username'";
$number = $_SESSION['database']->fetchObject($req);
if ( $number[0]->total >= 1) {
return false;
} else return true;
} // End of checkUsernameExistence
/**
* @brief Check Countrie existence and activation
* @param ID -> ID of the countrie
* @param clause -> Optionnal clause for the where
* @return True/False
*/
public function checkCountrieExistence ($countrie_id)
{
$countrie_id = $_SESSION['database']->clearString($countrie_id);
$req = "SELECT COUNT(id) AS total FROM countries WHERE id = '$countrie_id'";
$result = $_SESSION['database']->fetchObject($req);
if ( $result[0]->total == 0 ) return false;
else return true;
} // End of checkCountrieExistence
/**
* @brief Check Lang existence and activation
* @param lang_id -> ID of the lang
* @return True/False
*/
public function checkLangExistence($lang_id)
{
$land_id = $_SESSION['database']->clearString($lang_id);
$req = "SELECT COUNT(id) AS total FROM countries WHERE id = '$lang_id' AND is_lang = 'true'";
$result = $_SESSION['database']->fetchObject($req);
if ( $result[0]->total == 0 ) return false;
else return true;
} // End of checkLangActivation
/**
* @biref Get information about countrie
* @param countrie_id -> ID of the countrie
* @return False/Array with informations
*/
public function getCountrieInformations( $countrie_id, $clause = NULL )
{
if ( !is_null($clause) ) $clause = " $clause";
$countrie_id = $_SESSION['database']->clearString($countrie_id);
$req = "SELECT id,flag,countrie,date_format,time_format,is_lang FROM countries WHERE id = '$countrie_id'$clause";
$result = $_SESSION['database']->fetchObject($req);
if ( count($result) == 0 ) return false;
else return $result[0];
}
} // End of class

297
system/api/vhost.api.php Executable file
View File

@@ -0,0 +1,297 @@
<?php
/**
* @class action
* @brief Manage VirtualHosts
* @author Vincent Giersch
* @date 28/08/2009
* @modified Xavier Perrissoud
* @date 13/10/2009
* @version 0.1
* @todo Uncomment the action creation in createVhost()
* @todo Review the history entry adding in createVhost() (static-like call to a non-static method of class history)
*/
class vhost
{
private $vhost_records = null;
/**
* @brief Add a VirtualHost for the current user
* @param host : Host which is related to the virtualhost
* @param doc_root : The root of the virtualhost
* @param active : boolean for activation at creation time
* @param server_admin : e-mail address of the server's admin (optional)
* @param php_values : array of additionnal options related to the vhost (optional)
* @return -2 : The vhost already exists
* @return -1 : Quota of vhosts is reached
* @return true : VirtualHost successfully added
*/
public function userAddVhost( $host, $doc_root, $active, $server_admin = null, $php_values = null )
{
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$http_service = $_SESSION['hosting']->information_hosting->http_ip;
$server_admin = ( is_null($server_admin) ? APACHE_SERVER_ADMIN : $server_admin );
$php_values = ( is_null($php_values) ) ? array() : $php_values;
// Quota
if ( $_SESSION['hosting']->information_hosting->offer_virtualhosts_number >= 0 ) {
$current_number_vhosts = $this->countVhosts( $_SESSION['hosting']->information_hosting->id );
if ( $current_number_vhosts >= $_SESSION['hosting']->information_hosting->offer_virtualhosts_number ) return -1;
}
// Check existence of the VirtualHosts
if ( $this->checkVhostExistence($host) ) return -2;
$this->createVhost(
$hosting_id,
$http_service,
$host,
$doc_root,
$active,
$server_admin,
$php_values
);
return true;
}
/**
* @brief Create VirtualHosts
* @param hosting_id : Id of the hosting
* @param service_id : Id of the HTTP service
* @param host : Host related to the virtualhost
* @param doc_root : The root of the virtualhost
* @param active : boolean for activation at creation time
* @param server_admin : the e-mail address of the member
* @param php_values : array of additionnal options related to the vhost (optionnal)
* @return true if successfull, false otherwise
*/
private function createVhost( $hosting_id, $service_id, $host, $doc_root, $active, $server_admin, $php_values)
{
// First, try to add the VHost in database
$hosting_id = $_SESSION['database']->clearString($hosting_id);
$host = $_SESSION['database']->clearString($host);
$doc_root = $_SESSION['database']->clearString($doc_root);
$active = $_SESSION['database']->clearString( strtolower($active));
$server_admin = $_SESSION['database']->clearString($server_admin);
$clean_php_values=array();
foreach ( $php_values as $key=>$value)
{
$key = $_SESSION['database']->clearString($key);
$value = $_SESSION['database']->clearString($value);
$clean_php_values[$key] = $value;
}
$values = serialize( $clean_php_values);
$req = "INSERT INTO service_vhost
SET
created_at = CURRENT_TIMESTAMP,
hosting_id = '$hosting_id',
host = '$host',
doc_root = '$doc_root',
is_active = '$active',
server_admin = '$server_admin',
php_values = '$values'";
$_SESSION['database']->execRequest($req);
$vhost = $_SESSION['database']->getInsertId();
if ( $active == 'true' )
{
// Add action
$data = array();
$data['action'] = 'create_vhost';
$data['host'] = $host;
$data['vhost_id'] = $vhost;
$data['doc_root'] = $doc_root;
$data['server_admin'] = $server_admin;
$data['php_values'] = $values;
// $action = action::userAddAction($service_id, $data);
}
// save action to history
history::add("history_action_new_domain",$_SESSION['user']->information_user->userid);
return true;
}
/**
* @brief Delete a VirtualHost
* @param host : Host which is related to the virtualhost
*/
public function userDeleteVhost( $host )
{
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$http_service = $_SESSION['hosting']->information_hosting->http_ip;
return $this->deleteVhost(
$hosting_id,
$http_service,
$host
);
}
/* @brief Delete VirtualHosts
* @param hosting_id : Id of the hosting
* @param service_id : Id of the HTTP service
* @param host : Host which is related to the virtualhost
* @return -1 : Host not found
*/
private function deleteVhost( $hosting_id, $service_id, $host)
{
// Check if the hosts exists
$hosting_id = $_SESSION['database']->clearString($hosting_id);
if ( !$this->checkVhostExistence($host, false, "AND hosting_id = '$hosting_id'") ) return -1;
// Add action
$data = array();
$data['action'] = 'delete_vhost';
$data['host'] = $host;
$action = action::userAddAction($service_id, $data);
// Add Vhost to the table service_vhost
$host = $_SESSION['database']->clearString($host);
$req = "DELETE FROM service_vhost
WHERE
host = '$host'";
$_SESSION['database']->execRequest($req);
}
/**
* @brief Active a deactivated VirtualHost
* @param host : Host which is related to the virtualhost
* @param is_vhost_id : optional, if the 'host' is the id of the vhost (default false)
* @return -1 : Host not found
* @return true : Ok
*/
public function userActiveVhost( $host, $is_vhost_id = false )
{
// Check if the VirtualHost exists
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$http_service = $_SESSION['hosting']->information_hosting->http_ip;
if ( !$this->checkVhostExistence($host, $is_vhost_id, "AND hosting_id = '$hosting_id'") ) return -1;
// Active the Virtualhost
$this->activeOrNotVhost($host, true, $is_vhost_id);
}
/**
* @brief Desactive an actived VirtualHost
* @param host : Host which is related to the virtualhost
* @param is_vhost_id : optional, if the 'host' is the id of the vhost (default false)
* @return -1 : Host not found
* @return true : Ok
*/
public function userDesactiveVhost( $host, $is_vhost_id = false )
{
// Check if the VirtualHost exists
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$http_service = $_SESSION['hosting']->information_hosting->http_ip;
if ( !$this->checkVhostExistence($host, $is_vhost_id, "AND hosting_id = '$hosting_id'") ) return -1;
// Active the Virtualhost
$this->activeOrNotVhost($host, false, $is_vhost_id);
}
/**
* @brief Active a VirtualHost
* @param host : VirtualHost to active
* @param active : bool(true) : Active the VirtualHost / bool(false) : Desactive the VirtualHost
* @param is_vhost_id : optional, if the 'host' is the id of the vhost (default true)
* @return always true
*/
private function activeOrNotVhost( $host , $active, $is_vhost_id = true )
{
$active = $_SESSION['database']->clearString($active);
$host = $_SESSION['database']->clearString($host);
if ( $is_vhost_id == true )
$req = "UPDATE service_vhost
SET
is_active = '$active'
WHERE id = '$host'";
else
$req = "UPDATE service_vhost
SET
is_active = '$active'
WHERE host = '$host'";
return true;
}
/**
* @brief Count VirtualHosts for one hosting
* @param hosting_id : Id of the hosting
* @return Number of vhsost
*/
private function countVhosts( $hosting_id )
{
if( !is_null($this->vhost_records) ) {
return $this->vhost_records;
}
$hosting_id = $_SESSION['database']->clearString($hosting_id);
$req = "SELECT COUNT(id) AS total FROM service_vhost WHERE hosting_id = '$hosting_id'";
$query = $_SESSION['database']->fetchObject($req);
$this->vhost_records = $query[0]->total;
return $query[0]->total;
}
/**
* @brief Check if the Vhost exists
* @param host : Host is checking
* @param is_vhost_id : optional, if the 'host' is the id of the vhost (default false)
* @param additionnal_param : optional, add a WHERE clause
* @return true if the vhosts exists
* @return false if the vhost doesn't exists
*/
private function checkVhostExistence( $host, $is_vhost_id = false, $additionnal_param = null )
{
$host = $_SESSION['database']->clearString($host);
if( $is_vhost_id == true )
$req = "SELECT COUNT(id) AS exist FROM service_vhost WHERE id = '$host' " . $additionnal_param;
else
$req = "SELECT COUNT(id) AS exist FROM service_vhost WHERE host = '$host' " . $additionnal_param;
$query = $_SESSION['database']->fetchObject($req);
if( $query[0]->exist > 0 ) return true;
else return false;
}
/**
* @brief Get number of vhosts for the current hosting (and the current user), regarding the total count of records and the count of items to be shown per page
* @return number of pages availables
*/
public function userCountTotalPages()
{
$hosting_id = $_SESSION['hosting']->information_hosting->id;
$items_count = $this->countVhosts( $hosting_id );
$pages_count = intval($items_count / RECORD_BY_PAGE);
if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
$pages_count++;
}
return $pages_count;
}
/**
* @brief List all vhosts related to the current hosting (and the current user)
* @param hosting_id ID of the current hosting
* @param start First record to extract (optional)
* @param extract_number Number of record to extract (optional)
* @return array or null if empty
*/
public function userListVHosts( $hosting_id, $start = null, $extract_number = null )
{
$hosting_id = $_SESSION['database']->clearString($hosting_id);
if ( !is_null($start) and !is_null($extract_number)) {
$start = $_SESSION['database']->clearString($start);
$extract_number = $_SESSION['database']->clearString($extract_number);
$limit = " LIMIT $start, $extract_number";
} else $limit = null;
$req = "SELECT id, UNIX_TIMESTAMP(created_at) AS created_at, host, doc_root, is_active, server_admin
FROM service_vhost WHERE hosting_id = '$hosting_id' ORDER BY created_at$limit";
$query = $_SESSION['database']->fetchObject($req);
return $query;
}
}
?>

106
system/configuration.php Executable file
View File

@@ -0,0 +1,106 @@
<?php
############################
# DEV ENVIRONNEMENT #
############################
define('DEBUG', true);
define('USER', 'server');
if ( preg_match('#/keliopanel/trunk/web/#', $_SERVER["REQUEST_URI"]) == 1 ) {
define('PATH_PREFIX', '/Users/benjamin/Sites/keliopanel/trunk/');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', 'root');
define('TPL_HOST', 'http://localhost/keliopanel/trunk/web/');
} elseif ( preg_match('`admin.kelio.org.local`', $_SERVER['SERVER_NAME']) == 1 ) {
define('PATH_PREFIX', '/home/benjamin/public_html/kp/');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', 'delta12');
define('TPL_HOST', 'http://admin.kelio.org.local/');
} elseif ( preg_match('`panel.local`', $_SERVER['SERVER_NAME']) == 1 ) {
define('PATH_PREFIX', '/Users/Benjamin/Sites/keliopanel/trunk/');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', 'root');
define('TPL_HOST', 'http://panel.local/');
} elseif ( USER == 'vincent' ) {
} elseif ( USER == 'vincordi' ) {
define('PATH_PREFIX', 'D:/Developpement/kelio/trunk/');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('TPL_HOST', 'http://'.$_SERVER['HTTP_HOST'].'/kelio/web/');
} elseif ( USER == 'xavier' ) {
define('PATH_PREFIX', 'w:/var/www/kpanel/');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', 'usbw');
define('TPL_HOST', 'http://'.$_SERVER['HTTP_HOST'].'/kpanel/web/');
} else {
define('PATH_PREFIX', '/var/www/panel-public/');
define('MYSQL_USER', 'keliopanel');
define('MYSQL_PASSWORD', 'D44Z5cZfC');
define('MYSQL_SERVER', 'localhost');
define('MYSQL_DATABASE', 'keliopanel');
define('TPL_HOST', 'http://dev.keliopanel.fr.nf/');
}
############################
# END OF DEV ENVIRONNEMENT #
############################
define('PATH_SYSTEM', PATH_PREFIX.'system/');
define('PATH_API', PATH_SYSTEM.'api/');
define('PATH_LANG', PATH_SYSTEM.'lang/');
define('PATH_BIN', PATH_SYSTEM.'bin/');
define('PATH_LOGS', PATH_PREFIX.'logs/');
define('PATH_WEB', PATH_PREFIX.'web/');
define('PATH_TPL', PATH_WEB.'themes/');
define('PATH_CACHE', PATH_PREFIX.'cache/');
define('PATH_LIB', PATH_SYSTEM.'libs/');
# Path of pages
define('PAGE_CRITICAL_ERROR', PATH_WEB.'critical_error.html');
# Lang
define('LANG_DEFAULT', 'fr');
define('LANG_ALLOWED', serialize(array('fr', 'en')));
define('LANG_USE_OTHERS', TRUE);
# Template
define('TEMPLATE_DEFAULT', 'underground');
define('TEMPLATE_ALLOWED', serialize(array('underground', 'kelio')));
define('TEMPLATE_USE_OTHERS', FALSE);
# Text of unlogeable error
define('NOLOG_ERROR', 'Erreur principale d\'exploitation, merci de contacter le support');
# Website info
define('WEBSITE_CHARSET', 'utf-8');
define('TIMEZONE', 'Europe/Paris');
# Account managing info
define('LEVEL_REGISTER', 1);
define('LEVEL_CUSTOMER', 2);
define('LEVEL_MODERATOR', 3);
define('LEVEL_SUPPORT', 4);
define('LEVEL_ADMIN', 5);
# Pagination configuration
define('RECORD_BY_PAGE', 25);
# Service : Cronjob
define('CRON_MIN_TIME', 3600);
define('CRON_NO_SPECIFIED_TIME', 0);
define('CRON_TIMEOUT', 3);
# Service : Apache
define('APACHE_SERVER_ADMIN', 'webmaster@localhost');
# - Interpreter : PHP
define('PHP_CONF_FILE', '/etc/php5/apache2/php.ini');
?>

50
system/core.php Executable file
View File

@@ -0,0 +1,50 @@
<?php
// Initialize session
session_start();
// DEV
$_SESSION['user_infos'] = serialize(array('user_id' => 1, 'login' => 'mogui', 'hash' => '5d9f71b71b207b9e665820c0dce67bdb'));
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// DEV
// Open configuration
// Open autoload api
require_once(PATH_API.'api.php');
try
{
// Initialize Error system
require_once(PATH_API.'myexception.api.php');
// Initialize mysql class
$_SESSION['database'] = new mysql();
$_SESSION['database']->connect(MYSQL_USER, MYSQL_PASSWORD, MYSQL_SERVER, MYSQL_DATABASE);
// Inclusion of libs
require_once(PATH_LIB.'smarty/Smarty.class.php');
// Initialize user class
$_SESSION['user'] = new user();
// Initialize information user
$_SESSION['user']->userInitialize();
// Initialize security class
$_SESSION['security'] = new security();
// Initialize the hosting class
$_SESSION['hosting'] = new hosting();
// Initialize the informatin hosting
$_SESSION['hosting']->userInitializeHosting();
// Initialize template class
$_SESSION['template'] = new template();
// Rights display
$_SESSION['template']->userSetRightsDisplay();
} catch (myException $error)
{
$error->displayErrorMessage();
}
?>

260
system/lang/en/lang Executable file
View File

@@ -0,0 +1,260 @@
[general]
hosting_address = "kelio.org"
faq_address = "doc.kelio.org"
hosting_title = "KelioPanel Translate By GOOGLE"
hosting_slogan = "Manage your account"
activated = "on"
deactivated = "disabled"
the = "the"
at = "at"
functional = "functional"
suspended = "suspended"
renew = "repeat"
offer = "offer"
unlimited = "unlimited"
minutes = "minutes"
hours = "hours"
days = "days"
weeks = "weeks"
_yes = "yes"
_no = "no"
[underground]
home = "Home"
my_account = "My Account"
go_kelio = "Kelio.org"
msg_no_incident = "No incidents on the network at this time. In case of failure, it will be posted at this site on the home page."
design_by = "Design by"
icons_by = "icons by"
powered_by = "Powered by"
admin = "Admin"
[sidebar]
Big title
mainmenu_title = "Main Menu"
mainmenu_hosting = "hosting"
mainmenu_admin = "Administration"
; Small title
support = "Support"
history = "History"
action = "Action Pending"
incidents = "Incidents"
my_hostings = "My hosting"
deconnection = "Disconnect"
summary = "Summary"
databases = "database"
virtualhosts = "Virtual Servers"
dns = "DNS Zones"
ftpaccounts = "FTP"
emails = "Email Accounts and Alias"
installer = "Automated Systems"
cron = "Cron job"
[index]
msg_welcome = "Welcome to your member"s area"
msg_welcome2 = "You can manage your hosting from here."
msg_not_client = "Welcome to your new member"s area. In order to have access to all sections and to manage your account, please get in touch with our customer service."
msg_not_client2 = "Please contact our customer service"
msg_not_client3 = "You can do this by calling <strong> XX.XX.XX.XX.XX </ strong>, by email to <strong> notsend@vzprovider.com </ strong> or by mail following: <br /> <strong> VzProvider </ strong> <br /> 1 avenue des Champs Elysées 75001 Paris <br /> "
msg_not_client4 = "We remain at your disposal for any questions or problems. And hope you enjoy using our services."
msg_client1 = "Welcome to your member area. To perform actions on your hosting"
msg_client2 = "In case of any other concerns or questions, please contact us via the Support section."
clic_here = "click here"
[myaccount]
manage_my_account = "Edit My Personal Information"
msg_pseudo = "The nickname is used in your dealings with the media. It can also be used in place of your email address when connecting."
msg_company = "If the account belongs to a company, please enter your name here. This field is optional."
msg_template = "The theme of the panel consists of the graphic and layout elements on the member"s area. If the choice has been disabled by the administrative team, it can be applied."
msg_email = "If you change your email address, you will be disconnected immediately. It will take you again to continue using the panel."
msg_info_help = "You can get details on some fields by running your mouse over the name of it."
result_manage_account = "Change your data"
result_manage_account_ok = "Your data has been modified"
missing_first_name = "You have not entered your name."
format_first_name = "Please check the syntax of the name."
missing_last_name = "You did not enter your last name."
format_last_name = "Please check the syntax of the family name."
format_company = "The syntax of the company name does not fit."
missing_address = "You did not address before."
format_address = "The syntax of the address is not appropriate."
missing_city = "You have not entered the city."
format_city = "The syntax of the city can be taken into account."
missing_zipcode = "You have not entered a zip code."
format_zipcode = "The syntax of the postcode is not appropriate."
missing_email = "You did not enter your email."
format_email = "The syntax of the email address is not appropriate."
missing_pseudo = "You have not chosen a name."
format_pseudo = "The syntax of pseudo inappropriate."
pseudo_already_used = "The username is already used by another person."
lang_not_autorized = "The language of the panel could not be taken into account. The administrative team has not authorized the change."
template_not_autorized = "The theme of the panel could not be taken into account. The administrative team has not authorized the change."
missing_old_password = "You have not entered your old password."
format_old_password = "The syntax of the old password can not be taken into account."
missing_new_password1 = "You have not entered a new password."
format_new_password1 = "The syntax of the new password can not be taken into account."
missing_new_password2 = "You did not confirm the new password."
format_new_password2 = "The syntax of the confirmation of the new password can not be taken into account."
incorrect_password = "Your old password does not match in the database."
password_changed = "Your password has been changed."
[myhostings]
list_hostings = "List of my hosting"
hosting_base_name = "Account name"
hosting_begin = "Start Date"
hosting_end = "End Date"
hosting_statut = "Account Status"
[hosting]
title_hosting = "Summary of your hosting
action_for_hosting = "Choose an action to do on your hosting"
info_db = "Databases"
info_virtualhost = "Virtual Servers"
info_dns = "DNS Zones"
info_ftp = "FTP"
info_mail = "Email Accounts & Alias"
info_installer = "Automated Systems"
info_information = "Information"
info_quota = "Limitations"
info_cron = "cron job"
info_basename = "Change the name of the hosting"
info_faq = "Knowledge Base (FAQ)"
info_delete_hosting = "Delete this hosting"
[informations]
infos_briefing = "Information about your offer of hosting"
infos_customer = "Owner of the hosting"
infos_offer = "Current Offering"
infos_disk = "Disk Space"
infos_trafic = "Monthly Traffic"
infos_database = "Databases"
infos_dns = "DNS Zones"
infos_virtualhost = "Virtual Servers"
infos_mail = "Mailboxes"
infos_mail_space = "Size of mailboxes"
infos_mail_alias = "Alias emails"
infos_address = "The address to use in your scripts"
port = "Port"
[history]
list_history = "History of your account"
history_description = "History of all actions performed on your account"
history_empty = "No action in your history"
history_date = "Date"
history_action = "Action performed"
history_hosting = "hosting"
history_IP = "IP Address"
history_action_password = "Change Password"
history_action_login = "Connection Panel"
history_action_new_ftp = "Adding an FTP account"
history_action_new_domain = "Adding a domain name
history_action_profile = "Changing personal information"
[support]
mnu_tickets_list = "List of tickets"
mnu_new_ticket = "Create ticket"
mnu_reply_ticket = "Post Reply"
mnu_close_ticket = "Close this ticket"
support_list = "Summary of your tickets in progress and past"
support_list_intro = "Here is the list of tickets that you open. Click on the opening date to see the detail."
support_nolist_intro = "You have any open ticket."
support_close_intro = "You"re about to close a ticket-holder. It will not be possible to answer after you complete this action."
support_admin_list1 = "List of tickets waiting for treatment"
support_admin_list_intro1 = "Here is the list of tickets awaiting reply. Click on the opening date to see the detail and be able to respond."
support_admin_nolist_intro1 = "There are currently no ticket waiting for reply."
support_admin_list2 = "List of tickets that can be closed"
support_admin_list_intro2 = "Here is the list of tickets that a reply has been made. They can be closed manually."
support_admin_nolist_intro2 = "There are currently no ticket can be closed manually."
ticket_date = "Opening Date"
ticket_last_date = "Last message"
ticket_subject = "Subject of the application"
ticket_status = "Application Status"
ticket_status_asked = "We will respond within the next few days"
ticket_status_asked_full = "Your message has been recorded. We do our best to answer you as soon as possible"
ticket_status_replied = "We have responded to your request"
ticket_status_replied_full = "We have responded to your message. If our answer for you, you can close the ticket. You can also make certain clarifications if necessary. In that case the ticket will automatically be closed one week after our response."
ticket_status_closed_user = "Ticket closed by you"
ticket_status_closed_user_full = "You have closed this ticket. It is no longer possible to add a response. To do this you must open a new ticket."
ticket_status_closed_support = "Ticket closed by us"
ticket_status_closed_support_full = "We have closed this ticket because we felt it was not necessary to provide more details. If so, thank you to open a new ticket."
ticket_status_auto_closed = "Ticket closed automatically for inactivity"
ticket_status_auto_closed_full = "This ticket was closed automatically because there was no activity on the for more than a week."
support_show = "Details of the ticket"
support_show_intro = "Here is a chronological list of the messages exchanged within the selected ticket."
contact_support = "Request Assistance"
no_hosting_associated = "None"
ticket_date_legend = "Opening Date"
ticket_subject_legend = "Purpose of Request"
ticket_subject_title = "Enter a subject to explicit ticket. This value must contain between 5 and 100 characters, and begin with an alphanumeric character."
ticket_status_legend = "Current status of the ticket"
ticket_avail_actions = "Actions available"
ticket_msg_legend = "Message / Question"
ticket_reply_legend = "Your answer"
button_new_legend = "OK and send the request"
button_reply_legend = "OK and send the answer"
button_cancel_legend = "Cancel"
ticket_msg_title = "Be as specific as possible when drafting your message. It should contain between 5 and 500 characters, and begin with an alphanumeric character."
ticket_hosting_legend = "hosting concerned
ticket_hosting_title = "If you want to associate an hosting to this ticket, select it from the list below against"
ticket_msg_author_you = "You"
ticket_msg_author_us = "We"
support_create_result = "Registration of the new ticket"
support_create = "Open a new ticket"
support_create_intro = "Please fill all the form fields below."
support_create_helpmsg = "You can get details on some fields by running your mouse over the name thereof."
result_support_create_ok = "The new ticket data were recorded successfully. We will respond as soon as possible."
error_hosting_id = "Error with the ID of the hosting."
error_subject_missing = "You did not enter the subject of your request."
error_subject_format = "Check the format of the subject of the request."
error_message_missing = "You did not enter the content of your message."
error_message_format = "Check the format of the message."
error_database_query = "There was an error while updating the database. We apologize for this inconvenience."
error_ticket_id_not_valid = "The ID of the ticket does not match."
support_action_result = "Validation of your action"
result_support_reply_ok = "Your answer has been saved successfully. We will learn as soon as possible."
result_support_admin_reply_ok = "Your answer has been saved successfully."
result_support_close_ok = "The ticket was closed successfully."
[error]
msg_inadequate_right1 = "Law Invalid"
msg_inadequate_right2 = "You do not have the right to view this page. <br /> This is probably because you try to access a page that does is for e. <br /> If you have any questions You can contact our customer service. "
[crons]
mnu_list_crons = "Tasks list"
mnu_add_cron = "Add a task"
btn_new_cron = "Validate and create the task"
crons = "Cron jobs"
crons_list_title = "List of your cron jobs"
crons_list_notask = "You don't have any cron job yet."
cron_task_description = "Une tâche cron est une tâche lancée à intervalle régulier. Cela vous permet d'automatiser certains de vos scripts, comme par exemple la sauvegarde de vos bases de données, ou l'envoi de mails à une heure fixe.<br />Vous pouvez stopper momentanément ou supprimer vos tâches en cliquant sur les icônes appropriés.<br /> Si le serveur ne peut être joint au moment d'exécuter le script, la tache est mise en pause. Dans ce cas, vous devrez la ré-activer après vous êtres assuré que celle-ci fonctionne correctement."
cron_task_url = "Full url"
cron_task_lastexec = "Last execution"
cron_task_frequency = "Frequency"
cron_frequency_title = "Enter the frequency at witch the task has to be executed. This value can't be lower than"
cron_task_action = "Action"
cron_task_activation = "Activation"
cron_create_result = "Validation of the new task"
result_cron_create_ok = "The new task has been created successfully"
cron_create = "Adding a cron task"
cron_create_intro = "Please fill all the form fields below."
cron_create_helpmsg = "You can get details on some fields by running your mouse over the name thereof."
cron_task_first_exec = "First execution in"
result_cron_create_ok = "The new task has been successfully added."
error_cron_address_missing = "You didn't specified the script url."
error_cron_address_format = "Check the script url format."
error_cron_freq_missing = "You didn't specified the frequency for the execution of the script."
error_cron_freq_format = "Check the script execution frequency format."
error_cron_first_start_format = "Check the first execution delay format."
error_cron_url_unreacheable = "The cron script is unreacheable."
error_cron_max_reached = "Maxinum cron tasks reached."
error_cron_freq_too_small = "Execution frequency is lower than the allowed value."
cron_start_title = "Click here to enable this task."
cron_stop_title = "Click here to disable this task."
cron_delete_title = "Click here to delete this task."
cron_goto_confirm = "Do you really want to go to this address ?"
[vhosts]
vhosts = "Virtuals servers"
mnu_list_vhosts = "Virtuals Servers list"
mnu_add_vhost = "Add a virtual server"
vhosts_list_title = "List of your virtual servers"
vhost_description = "Virtual Host description : this have to be written..."

288
system/lang/fr/lang Executable file
View File

@@ -0,0 +1,288 @@
; ###############################
; !! WARNING !!
; Do not use same key !!
; NE PAS UTILISER LA MEME CLE POUR LES VARIABLES !
; CHAQUE PHRASE DOIT AVOIR UNE CLE DIFFERENTE !
; (au sein du fichier, pas du module)
; ###############################
lang = fr
; General is charged at start of the script.
; Is for general word (at, the, server, mysql, etc.)
; General word must start with lower caracter.(use {#activated|capitalize#} if necessary)
[general]
hosting_address = "kelio.org"
faq_address = "doc.kelio.org"
hosting_title = "KP"
hosting_slogan = "Administrez votre compte"
activated = "activé"
deactivated = "désactivé"
the = "le"
at = "à"
functional = "fonctionnel"
suspended = "suspendu"
renew = "renouveler"
offer = "offre"
unlimited = "illimité"
minutes = "minutes"
hours = "heures"
days = "jours"
weeks = "semaines"
_yes = "oui"
_no = "non"
[underground]
home = "Accueil"
my_account = "Mon compte"
go_kelio = "Kelio.org"
msg_no_incident = "Aucun incident sur le réseau à cet instant. En cas de panne, celle-ci sera affiché à cet emplacement sur la page d'accueil."
design_by = "Design par"
icons_by = "Icones par"
powered_by = "Propulsé par"
admin = "Admin"
[sidebar]
; Big title
mainmenu_title = "Menu principal"
mainmenu_hosting = "Hébergements"
mainmenu_admin = "Administration"
; Small title
support = "Support"
history = "Historique"
actions = "Actions en attente"
incidents = "Incidents"
my_hostings = "Mes hébergements"
deconnection = "Déconnexion"
summary = "Récapitulatif"
databases = "Bases de données"
virtualhosts = "Serveurs virtuel"
dns = "Zones DNS"
ftpaccounts = "Comptes FTP"
emails = "Alias et Comptes email"
installer = "Installations automatisés"
cron = "Tâches CRON"
[index]
msg_welcome = "Bienvenue sur votre espace membre"
msg_welcome2 = "Vous pouvez gérer votre hébergement à partir d'ici."
msg_not_client = "Bienvenue sur votre futur espace membre. Afin d'avoir accès a toutes les sections et de pouvoir gérer votre compte, veuillez vous mettre en relation avec notre service client."
msg_not_client2 = "Pour cela, contactez notre service client"
msg_not_client3 = "Vous pouvez faire cette démarche par téléphone au <strong>XX.XX.XX.XX.XX</strong>, par email a <strong>notsend@vzprovider.com</strong> ou par courrier a l'adresse suivante :<br /><strong>VzProvider</strong><br />1 avenue des champs Elysées<br />75001 Paris"
msg_not_client4 = "Nous restons à votre écoute pour toutes vos questions ou problèmes. Et vous souhaitons une agréable utilisation de nos services."
msg_client1 = "Bienvenue sur votre espace membre. Pour effectuer des actions sur vos hébergements"
msg_client2 = "En cas de soucis ou toute autres question, vous pouvez nous joindre via la section Support."
clic_here = "cliquez ici"
[myaccount]
manage_my_account = "Modifier mes informations personnelles"
msg_pseudo = "Le pseudonyme est utilisé lors de vos échanges avec le support. Celui-ci peut aussi être utilisé à la place de votre adresse email lors de la connexion."
msg_company = "Si le compte appartient à une entreprise, veuillez entrer son nom commercial ici. Ce champs n'est pas obligatoire."
msg_template = "Le theme du panel consiste en la charte graphique et la disposition des éléments sur l'espace membre. Si le choix a été désactivé par l'équipe administrative, celui-ci ne pourra être appliqué."
msg_email = "Si vous modifiez votre adresse email, vous serez déconnecté immédiatement après. Il faudra vous reconnecter pour continuer à utiliser le panel."
msg_info_help = "Vous pouvez obtenir des détails sur certains champs en passant votre souris sur le nom de celui-ci."
result_manage_account = "Modification des données de votre compte"
result_manage_account_ok = "Vos données ont bien été modifiées"
missing_first_name = "Vous n'avez pas entré votre prénom."
format_first_name = "Veuillez vérifier la syntaxe du prénom."
missing_last_name = "Vous n'avez pas entré votre nom de famille."
format_last_name = "Veuillez vérifier la syntaxe du nom de famille."
format_company = "La syntaxe du nom de l'entreprise ne convient pas."
missing_address = "Vous n'avez pas saisi d'adresse."
format_address = "La syntaxe de l'adresse ne convient pas."
missing_city = "Vous n'avez pas entré la ville."
format_city = "La syntaxe de la ville ne peut être prise en compte."
missing_zipcode = "Vous n'avez pas saisi de code postal."
format_zipcode = "La syntaxe du code postal ne convient pas."
missing_email = "Vous n'avez pas entré votre email."
format_email = "La syntaxe de l'adresse email ne convient pas."
missing_pseudo = "Vous n'avez pas choisi de pseudo."
format_pseudo = "La syntaxe du pseudo ne convient pas."
pseudo_already_used = "Le pseudo est déjà  utilisé par une autre personne."
lang_not_autorized = "La langue du panel n'a pu être prise en compte. L'équipe administrative n'a pas autorisé le changement."
template_not_autorized = "Le thème du panel n'a pu être pris en compte. L'équipe administrative n'a pas autorisé le changement."
missing_old_password = "Vous n'avez pas entré votre ancien mot de passe."
format_old_password = "La syntaxe de l'ancien mot de passe ne peut être prise en compte."
missing_new_password1 = "Vous n'avez pas saisi de nouveau mot de passe."
format_new_password1 = "La syntaxe du nouveau mot de passe ne peut être prise en compte."
missing_new_password2 = "Vous n'avez pas confirmé le nouveau mot de passe."
format_new_password2 = "La syntaxe de la confirmation du nouveau mot de passe ne peut être prise en compte."
incorrect_password = "Votre ancien mot de passe ne correspond pas à celui en base de données.'"
password_changed = "Votre mot de passe a bien été changé."
[myhostings]
list_hostings = "Liste de mes hébergements"
hosting_base_name = "Nom du compte"
hosting_begin = "Date de début"
hosting_end = "Date de fin"
hosting_statut = "Etat du compte"
[hosting]
title_hosting = "Récapitulatif de votre hébergement"
action_for_hosting = "Veuillez choisir une action à faire sur votre hébergement"
info_db = "Bases de données"
info_virtualhost = "Serveurs Virtuel"
info_dns = "Zones DNS"
info_ftp = "Comptes FTP"
info_mail = "Comptes et Alias email"
info_installer = "Installations automatisés"
info_information = "Informations"
info_quota = "Limitations"
info_cron = "Tâches CRON"
info_basename = "Changer le nom de l'hébergement"
info_faq = "Base de connaissances (FAQ)"
info_delete_hosting = "Supprimer cet hébergement"
[informations]
infos_briefing = "Informations à propos de votre offre d'hébergement"
infos_customer = "Propriétaire de l'hébergement"
infos_offer = "Offre actuelle"
infos_disk = "Espace disque"
infos_trafic = "Trafic mensuel"
infos_database = "Bases de données"
infos_dns = "Zones DNS"
infos_virtualhost = "Serveurs Virtuels"
infos_mail = "Boites emails"
infos_mail_space = "Taille des boites emails"
infos_mail_alias = "Alias emails"
infos_address = "Les adresses à utiliser dans vos scripts"
port = "Port"
[history]
list_history = "Historique de votre compte"
history_description = "Historique de toutes les actions effectuées sur votre compte"
history_empty = "Aucune action dans votre historique"
history_date = "Date"
history_action = "Action effectuée"
history_hosting = "Hébergement"
history_IP = "Adresse IP"
history_action_password = "Modification du mot de passe"
history_action_login = "Connexion au panel"
history_action_new_ftp = "Ajout d'un compte FTP"
history_action_new_domain = "Ajout d'un nom de domaine"
history_action_profile = "Modification des informations personnelles"
[support]
; Sub-menu entries
mnu_tickets_list = "Liste des tickets"
mnu_new_ticket = "Créer un ticket"
mnu_reply_ticket = "Poster une réponse"
mnu_close_ticket = "Fermer ce ticket"
; Titles
support_list = "Récapitulatif de vos tickets en-cours et passés"
support_list_intro = "Voici la liste des tickets que vous avez ouvert. Cliquez sur la date d'ouverture pour en voir le détail."
support_nolist_intro = "Vous n'avez encore ouvert aucun ticket."
support_close_intro = "Vous vous apprêtez à fermer un ticket-support. Il ne sera plus possible d'y répondre après avoir effectué cette action."
support_admin_list1 = "Liste des tickets en attente de traitement"
support_admin_list_intro1 = "Voici la liste des tickets en attente de réponse. Cliquez sur la date d'ouverture pour en voir le détail et ainsi être en mesure de répondre."
support_admin_nolist_intro1 = "Il n'y a actuellement aucun ticket en attente de réponse."
support_admin_list2 = "Liste des tickets pouvant être fermés"
support_admin_list_intro2 = "Voici la liste des tickets auxquels une réponse a été apportée. Ils peuvent désormais être fermés manuellement."
support_admin_nolist_intro2 = "Il n'y a actuellement aucun ticket pouvant être fermé manuellement."
; Tickets list Headers
ticket_date = "Date d'ouverture"
ticket_last_date = "Dernier message"
ticket_subject = "Sujet de la demande"
ticket_status = "Etat de la demande"
; Tickets status
ticket_status_asked = "Nous allons vous répondre dans les prochains jours"
ticket_status_asked_full = "Votre message a bien été enregistré. Nous faisons tout notre possible pour vous répondre dans les plus brefs délais"
ticket_status_replied = "Nous avons répondu à votre demande"
ticket_status_replied_full = "Nous avons répondu à votre message. Si notre réponse vous convient, vous pouvez fermer le ticket. Vous pouvez également apporter certaines précisions si vous le jugez nécessaire. Le cas échéant, le ticket sera automatiquement fermé une semaine après notre réponse."
ticket_status_closed_user = "Ticket fermé par vos soins"
ticket_status_closed_user_full = "Vous avez fermé ce ticket. Il n'est désormais plus possible d'y ajouter une réponse. Vous devrez pour cela ouvrir un nouveau ticket."
ticket_status_closed_support = "Ticket fermé par nos soins"
ticket_status_closed_support_full = "Nous avons fermé ce ticket car nous avons jugé qu'il n'était pas nécessaire d'y apporter plus de précision. Le cas échéant, merci d'ouvrir un nouveau ticket."
ticket_status_auto_closed = "Ticket fermé automatiquement pour inactivité"
ticket_status_auto_closed_full = "Ce ticket a été fermé automatiquement car il n'y a pas eut d'activité le concernant pendant plus d'une semaine."
; Ticket details
support_show = "Détails du ticket"
support_show_intro = "Voici la liste chronologique des messages échangés dans le cadre du ticket sélectionné."
contact_support = "Demander une assistance"
no_hosting_associated = "Aucun"
; forms and table legends
ticket_date_legend = "Date d'ouverture"
ticket_subject_legend = "Objet de la demande"
ticket_subject_title = "Donnez un sujet explicite à ce ticket. Cette valeur doit contenir entre 5 et 100 caractères, et commencer par un caractère alphanumérique."
ticket_status_legend = "Etat actuel du ticket"
ticket_avail_actions = "Actions disponibles"
ticket_msg_legend = "Message / Question"
ticket_reply_legend = "Votre réponse"
button_new_legend = "Valider et envoyer la demande"
button_reply_legend = "Valider et envoyer la réponse"
button_cancel_legend = "Annuler"
ticket_msg_title = "Soyez le plus précis possible lors de la rédaction de votre message. Il doit contenir entre 5 et 500 caractères, et commencer par un caractère alphanumérique."
ticket_hosting_legend = "Hébergement concerné"
ticket_hosting_title = "Si vous désirez associer un hébergement à ce ticket, sélectionnez-le dans la liste ci-contre"
ticket_msg_author_you = "Vous"
ticket_msg_author_us = "Nous"
; New ticket
support_create_result = "Enregistrement du nouveau ticket"
support_create = "Ouvrir un nouveau ticket"
support_create_intro = "Merci de remplir tous les champs du formulaire ci-dessous."
support_create_helpmsg = "Vous pouvez obtenir des détails sur certains champs en passant votre souris sur le nom de ceux-ci."
result_support_create_ok = "Les données du nouveau ticket on été enregistrées avec succès. Nous allons vous répondre dans les plus brefs délais."
error_hosting_id = "Erreur avec l'ID de l'hébergement."
error_subject_missing = "Vous n'avez pas entré le sujet de votre demande."
error_subject_format = "Vérifiez le format du sujet de la demande."
error_message_missing = "Vous n'avez pas entré le contenu de votre message."
error_message_format = "Vérifiez le format du message."
error_database_query = "Il y a eut une erreur lors de la mise à jour de la base de données. Nous sommes désolés pour ce contretemps."
error_ticket_id_not_valid = "L'identifiant du ticket ne correspond pas."
; reply
support_action_result = "Validation de votre action"
result_support_reply_ok = "Votre réponse a été enregistrée avec succès. Nous allons en prendre connaissance dans les plus brefs délais."
result_support_admin_reply_ok = "Votre réponse a été enregistrée avec succès."
result_support_close_ok = "Le ticket a été fermé avec succès."
[error]
msg_inadequate_right1 = "Droit non valide"
msg_inadequate_right2 = "Vous n'avez pas les droit requis pour visionner cette page.<br />Cela vient probablement du fait que vous essayez d'acceder a une page qui ne vous est destinée.<br />En cas de questions, vous pouvez contacter notre service client."
error_title = "Une erreur a eu lieu"
error_not_in_offer = "Votre offre actuelle ne vous permet pas de disposer de cette fonctionnalité.<br />Vous ne pouvez donc pas accéder à cette page."
error_clichere_for_summary = "Cliquez ici pour revenir au récapitulatif des actions."
[crons]
mnu_list_crons = "Liste des tâches"
mnu_add_cron = "Ajouter une tâche"
btn_new_cron = "Valider et créer la tâche"
crons = "Tâches CRON"
crons_list_title = "Liste de vos tâches cron"
crons_list_notask = "Vous ne disposez d'aucune tache actuellement."
cron_task_description = "Une tâche cron est une tâche lancée à intervalle régulier. Cela vous permet d'automatiser certains de vos scripts, comme par exemple la sauvegarde de vos bases de données, ou l'envoi de mails à une heure fixe.<br />Vous pouvez stopper momentanément ou supprimer vos tâches en cliquant sur les icônes appropriés.<br /> Si le serveur ne peut être joint au moment d'exécuter le script, la tache est mise en pause. Dans ce cas, vous devrez la ré-activer après vous êtres assuré que celle-ci fonctionne correctement."
cron_task_url = "Adresse complète"
cron_task_lastexec = "Dernière exécution"
cron_task_frequency = "Fréquence"
cron_frequency_title = "Entrez la fréquence à laquelle la tâche doit être exécutée. Cette valeur ne peut être inférieure à"
cron_task_action = "Action"
cron_task_activation = "Activation"
cron_create_result = "Validation de la nouvelle tâche"
result_cron_create_ok = "La nouvelle tâche a été créée avec succès"
cron_create = "Ajouter une tâche cron"
cron_create_intro = "Merci de remplir tous les champs du formulaire ci-dessous."
cron_create_helpmsg = "Vous pouvez obtenir des détails sur certains champs en passant votre souris sur le nom de ceux-ci."
cron_task_first_exec = "Première exécution dans"
result_cron_create_ok = "La nouvelle tâche a été ajoutée avec succès."
error_cron_address_missing = "Vous n'avez pas entré l'adresse du script à exécuter."
error_cron_address_format = "Vérifiez le format de l'adresse du script à exécuter."
error_cron_freq_missing = "Vous n'avez pas entré la fréquence à laquelle le script doit être exécuté."
error_cron_freq_format = "Vérifiez le format de la fréquence d'exécution du script."
error_cron_first_start_format = "Vérifiez le format du délai avant la première exécution."
error_cron_url_unreacheable = "Le script à exécuter n'est pas atteignable."
error_cron_max_reached = "Nombre maximum de tâches cron atteind."
error_cron_freq_too_small = "La fréquence d'exécution est inférieure à la valeur minimale acceptée."
cron_start_title = "Cliquez ici pour activer la tâche."
cron_stop_title = "Cliquez ici pour désactiver la tâche."
cron_delete_title = "Cliquez ici pour supprimer la tâche."
cron_goto_confirm = "Souhaitez vous vraiment vous rendre à cette adresse ?"
[vhosts]
vhosts = "Serveurs virtuels"
mnu_list_vhosts = "Liste des serveurs virtuels"
mnu_add_vhost = "Ajouter un serveur virtuel"
vhosts_list_title = "Liste de vos serveurs virtuels"
vhost_description = "Description d'un serveur virtuel : à rédiger..."

View File

@@ -0,0 +1,393 @@
<?php
/**
* Config_File class.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @version 2.6.19-dev
* @copyright Copyright: 2001-2005 New Digital Group, Inc.
* @author Andrei Zmievski <andrei@php.net>
* @access public
* @package Smarty
*/
/* $Id: Config_File.class.php 2786 2008-09-18 21:04:38Z Uwe.Tews $ */
/**
* Config file reading class
* @package Smarty
*/
class Config_File {
/**#@+
* Options
* @var boolean
*/
/**
* Controls whether variables with the same name overwrite each other.
*/
var $overwrite = true;
/**
* Controls whether config values of on/true/yes and off/false/no get
* converted to boolean values automatically.
*/
var $booleanize = true;
/**
* Controls whether hidden config sections/vars are read from the file.
*/
var $read_hidden = true;
/**
* Controls whether or not to fix mac or dos formatted newlines.
* If set to true, \r or \r\n will be changed to \n.
*/
var $fix_newlines = true;
/**#@-*/
/** @access private */
var $_config_path = "";
var $_config_data = array();
/**#@-*/
/**
* Constructs a new config file class.
*
* @param string $config_path (optional) path to the config files
*/
function Config_File($config_path = NULL)
{
if (isset($config_path))
$this->set_path($config_path);
}
/**
* Set the path where configuration files can be found.
*
* @param string $config_path path to the config files
*/
function set_path($config_path)
{
if (!empty($config_path)) {
if (!is_string($config_path) || !file_exists($config_path) || !is_dir($config_path)) {
$this->_trigger_error_msg("Bad config file path '$config_path'");
return;
}
if(substr($config_path, -1) != DIRECTORY_SEPARATOR) {
$config_path .= DIRECTORY_SEPARATOR;
}
$this->_config_path = $config_path;
}
}
/**
* Retrieves config info based on the file, section, and variable name.
*
* @param string $file_name config file to get info for
* @param string $section_name (optional) section to get info for
* @param string $var_name (optional) variable to get info for
* @return string|array a value or array of values
*/
function get($file_name, $section_name = NULL, $var_name = NULL)
{
if (empty($file_name)) {
$this->_trigger_error_msg('Empty config file name');
return;
} else {
$file_name = $this->_config_path . $file_name;
if (!isset($this->_config_data[$file_name]))
$this->load_file($file_name, false);
}
if (!empty($var_name)) {
if (empty($section_name)) {
return $this->_config_data[$file_name]["vars"][$var_name];
} else {
if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name]))
return $this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name];
else
return array();
}
} else {
if (empty($section_name)) {
return (array)$this->_config_data[$file_name]["vars"];
} else {
if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"]))
return (array)$this->_config_data[$file_name]["sections"][$section_name]["vars"];
else
return array();
}
}
}
/**
* Retrieves config info based on the key.
*
* @param $file_name string config key (filename/section/var)
* @return string|array same as get()
* @uses get() retrieves information from config file and returns it
*/
function &get_key($config_key)
{
list($file_name, $section_name, $var_name) = explode('/', $config_key, 3);
$result = &$this->get($file_name, $section_name, $var_name);
return $result;
}
/**
* Get all loaded config file names.
*
* @return array an array of loaded config file names
*/
function get_file_names()
{
return array_keys($this->_config_data);
}
/**
* Get all section names from a loaded file.
*
* @param string $file_name config file to get section names from
* @return array an array of section names from the specified file
*/
function get_section_names($file_name)
{
$file_name = $this->_config_path . $file_name;
if (!isset($this->_config_data[$file_name])) {
$this->_trigger_error_msg("Unknown config file '$file_name'");
return;
}
return array_keys($this->_config_data[$file_name]["sections"]);
}
/**
* Get all global or section variable names.
*
* @param string $file_name config file to get info for
* @param string $section_name (optional) section to get info for
* @return array an array of variables names from the specified file/section
*/
function get_var_names($file_name, $section = NULL)
{
if (empty($file_name)) {
$this->_trigger_error_msg('Empty config file name');
return;
} else if (!isset($this->_config_data[$file_name])) {
$this->_trigger_error_msg("Unknown config file '$file_name'");
return;
}
if (empty($section))
return array_keys($this->_config_data[$file_name]["vars"]);
else
return array_keys($this->_config_data[$file_name]["sections"][$section]["vars"]);
}
/**
* Clear loaded config data for a certain file or all files.
*
* @param string $file_name file to clear config data for
*/
function clear($file_name = NULL)
{
if ($file_name === NULL)
$this->_config_data = array();
else if (isset($this->_config_data[$file_name]))
$this->_config_data[$file_name] = array();
}
/**
* Load a configuration file manually.
*
* @param string $file_name file name to load
* @param boolean $prepend_path whether current config path should be
* prepended to the filename
*/
function load_file($file_name, $prepend_path = true)
{
if ($prepend_path && $this->_config_path != "")
$config_file = $this->_config_path . $file_name;
else
$config_file = $file_name;
ini_set('track_errors', true);
$fp = @fopen($config_file, "r");
if (!is_resource($fp)) {
$this->_trigger_error_msg("Could not open config file '$config_file'");
return false;
}
$contents = ($size = filesize($config_file)) ? fread($fp, $size) : '';
fclose($fp);
$this->_config_data[$config_file] = $this->parse_contents($contents);
return true;
}
/**
* Store the contents of a file manually.
*
* @param string $config_file file name of the related contents
* @param string $contents the file-contents to parse
*/
function set_file_contents($config_file, $contents)
{
$this->_config_data[$config_file] = $this->parse_contents($contents);
return true;
}
/**
* parse the source of a configuration file manually.
*
* @param string $contents the file-contents to parse
*/
function parse_contents($contents)
{
if($this->fix_newlines) {
// fix mac/dos formatted newlines
$contents = preg_replace('!\r\n?!', "\n", $contents);
}
$config_data = array();
$config_data['sections'] = array();
$config_data['vars'] = array();
/* reference to fill with data */
$vars =& $config_data['vars'];
/* parse file line by line */
preg_match_all('!^.*\r?\n?!m', $contents, $match);
$lines = $match[0];
for ($i=0, $count=count($lines); $i<$count; $i++) {
$line = $lines[$i];
if (empty($line)) continue;
if ( substr($line, 0, 1) == '[' && preg_match('!^\[(.*?)\]!', $line, $match) ) {
/* section found */
if (substr($match[1], 0, 1) == '.') {
/* hidden section */
if ($this->read_hidden) {
$section_name = substr($match[1], 1);
} else {
/* break reference to $vars to ignore hidden section */
unset($vars);
$vars = array();
continue;
}
} else {
$section_name = $match[1];
}
if (!isset($config_data['sections'][$section_name]))
$config_data['sections'][$section_name] = array('vars' => array());
$vars =& $config_data['sections'][$section_name]['vars'];
continue;
}
if (preg_match('/^\s*(\.?\w+)\s*=\s*(.*)/s', $line, $match)) {
/* variable found */
$var_name = rtrim($match[1]);
if (strpos($match[2], '"""') === 0) {
/* handle multiline-value */
$lines[$i] = substr($match[2], 3);
$var_value = '';
while ($i<$count) {
if (($pos = strpos($lines[$i], '"""')) === false) {
$var_value .= $lines[$i++];
} else {
/* end of multiline-value */
$var_value .= substr($lines[$i], 0, $pos);
break;
}
}
$booleanize = false;
} else {
/* handle simple value */
$var_value = preg_replace('/^([\'"])(.*)\1$/', '\2', rtrim($match[2]));
$booleanize = $this->booleanize;
}
$this->_set_config_var($vars, $var_name, $var_value, $booleanize);
}
/* else unparsable line / means it is a comment / means ignore it */
}
return $config_data;
}
/**#@+ @access private */
/**
* @param array &$container
* @param string $var_name
* @param mixed $var_value
* @param boolean $booleanize determines whether $var_value is converted to
* to true/false
*/
function _set_config_var(&$container, $var_name, $var_value, $booleanize)
{
if (substr($var_name, 0, 1) == '.') {
if (!$this->read_hidden)
return;
else
$var_name = substr($var_name, 1);
}
if (!preg_match("/^[a-zA-Z_]\w*$/", $var_name)) {
$this->_trigger_error_msg("Bad variable name '$var_name'");
return;
}
if ($booleanize) {
if (preg_match("/^(on|true|yes)$/i", $var_value))
$var_value = true;
else if (preg_match("/^(off|false|no)$/i", $var_value))
$var_value = false;
}
if (!isset($container[$var_name]) || $this->overwrite)
$container[$var_name] = $var_value;
else {
settype($container[$var_name], 'array');
$container[$var_name][] = $var_value;
}
}
/**
* @uses trigger_error() creates a PHP warning/error
* @param string $error_msg
* @param integer $error_type one of
*/
function _trigger_error_msg($error_msg, $error_type = E_USER_WARNING)
{
trigger_error("Config_File error: $error_msg", $error_type);
}
/**#@-*/
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

157
system/libs/smarty/debug.tpl Executable file
View File

@@ -0,0 +1,157 @@
{* Smarty *}
{* debug.tpl, last updated version 2.1.0 *}
{assign_debug_info}
{capture assign=debug_output}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Smarty Debug Console</title>
{literal}
<style type="text/css">
/* <![CDATA[ */
body, h1, h2, td, th, p {
font-family: sans-serif;
font-weight: normal;
font-size: 0.9em;
margin: 1px;
padding: 0;
}
h1 {
margin: 0;
text-align: left;
padding: 2px;
background-color: #f0c040;
color: black;
font-weight: bold;
font-size: 1.2em;
}
h2 {
background-color: #9B410E;
color: white;
text-align: left;
font-weight: bold;
padding: 2px;
border-top: 1px solid black;
}
body {
background: black;
}
p, table, div {
background: #f0ead8;
}
p {
margin: 0;
font-style: italic;
text-align: center;
}
table {
width: 100%;
}
th, td {
font-family: monospace;
vertical-align: top;
text-align: left;
width: 50%;
}
td {
color: green;
}
.odd {
background-color: #eeeeee;
}
.even {
background-color: #fafafa;
}
.exectime {
font-size: 0.8em;
font-style: italic;
}
#table_assigned_vars th {
color: blue;
}
#table_config_vars th {
color: maroon;
}
/* ]]> */
</style>
{/literal}
</head>
<body>
<h1>Smarty Debug Console</h1>
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
{section name=templates loop=$_debug_tpls}
{section name=indent loop=$_debug_tpls[templates].depth}&nbsp;&nbsp;&nbsp;{/section}
<font color={if $_debug_tpls[templates].type eq "template"}brown{elseif $_debug_tpls[templates].type eq "insert"}black{else}green{/if}>
{$_debug_tpls[templates].filename|escape:html}</font>
{if isset($_debug_tpls[templates].exec_time)}
<span class="exectime">
({$_debug_tpls[templates].exec_time|string_format:"%.5f"})
{if %templates.index% eq 0}(total){/if}
</span>
{/if}
<br />
{sectionelse}
<p>no templates included</p>
{/section}
</div>
<h2>assigned template variables</h2>
<table id="table_assigned_vars">
{section name=vars loop=$_debug_keys}
<tr class="{cycle values="odd,even"}">
<th>{ldelim}${$_debug_keys[vars]|escape:'html'}{rdelim}</th>
<td>{$_debug_vals[vars]|@debug_print_var}</td></tr>
{sectionelse}
<tr><td><p>no template variables assigned</p></td></tr>
{/section}
</table>
<h2>assigned config file variables (outer template scope)</h2>
<table id="table_config_vars">
{section name=config_vars loop=$_debug_config_keys}
<tr class="{cycle values="odd,even"}">
<th>{ldelim}#{$_debug_config_keys[config_vars]|escape:'html'}#{rdelim}</th>
<td>{$_debug_config_vals[config_vars]|@debug_print_var}</td></tr>
{sectionelse}
<tr><td><p>no config vars assigned</p></td></tr>
{/section}
</table>
</body>
</html>
{/capture}
{if isset($_smarty_debug_output) and $_smarty_debug_output eq "html"}
{$debug_output}
{else}
<script type="text/javascript">
// <![CDATA[
if ( self.name == '' ) {ldelim}
var title = 'Console';
{rdelim}
else {ldelim}
var title = 'Console_' + self.name;
{rdelim}
_smarty_console = window.open("",title.value,"width=680,height=600,resizable,scrollbars=yes");
_smarty_console.document.write('{$debug_output|escape:'javascript'}');
_smarty_console.document.close();
// ]]>
</script>
{/if}

View File

@@ -0,0 +1,5 @@
title = Welcome to Smarty!
cutoff_size = 40
[setup]
bold = true

View File

@@ -0,0 +1,25 @@
<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->compile_check = true;
$smarty->debugging = true;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill");
$smarty->assign("FirstName",array("John","Mary","James","Henry"));
$smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
$smarty->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"),
array("I", "J", "K", "L"), array("M", "N", "O", "P")));
$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
$smarty->assign("option_values", array("NY","NE","KS","IA","OK","TX"));
$smarty->assign("option_output", array("New York","Nebraska","Kansas","Iowa","Oklahoma","Texas"));
$smarty->assign("option_selected", "NE");
$smarty->display('index.tpl');
?>

View File

@@ -0,0 +1,2 @@
</BODY>
</HTML>

View File

@@ -0,0 +1,6 @@
<HTML>
<HEAD>
{popup_init src="/javascripts/overlib.js"}
<TITLE>{$title} - {$Name}</TITLE>
</HEAD>
<BODY bgcolor="#ffffff">

View File

@@ -0,0 +1,81 @@
{config_load file=test.conf section="setup"}
{include file="header.tpl" title=foo}
<PRE>
{* bold and title are read from the config file *}
{if #bold#}<b>{/if}
{* capitalize the first letters of each word of the title *}
Title: {#title#|capitalize}
{if #bold#}</b>{/if}
The current date and time is {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
The value of global assigned variable $SCRIPT_NAME is {$SCRIPT_NAME}
Example of accessing server environment variable SERVER_NAME: {$smarty.server.SERVER_NAME}
The value of {ldelim}$Name{rdelim} is <b>{$Name}</b>
variable modifier example of {ldelim}$Name|upper{rdelim}
<b>{$Name|upper}</b>
An example of a section loop:
{section name=outer loop=$FirstName}
{if $smarty.section.outer.index is odd by 2}
{$smarty.section.outer.rownum} . {$FirstName[outer]} {$LastName[outer]}
{else}
{$smarty.section.outer.rownum} * {$FirstName[outer]} {$LastName[outer]}
{/if}
{sectionelse}
none
{/section}
An example of section looped key values:
{section name=sec1 loop=$contacts}
phone: {$contacts[sec1].phone}<br>
fax: {$contacts[sec1].fax}<br>
cell: {$contacts[sec1].cell}<br>
{/section}
<p>
testing strip tags
{strip}
<table border=0>
<tr>
<td>
<A HREF="{$SCRIPT_NAME}">
<font color="red">This is a test </font>
</A>
</td>
</tr>
</table>
{/strip}
</PRE>
This is an example of the html_select_date function:
<form>
{html_select_date start_year=1998 end_year=2010}
</form>
This is an example of the html_select_time function:
<form>
{html_select_time use_24_hours=true}
</form>
This is an example of the html_options function:
<form>
<select name=states>
{html_options values=$option_values selected=$option_selected output=$option_output}
</select>
</form>
{include file="footer.tpl"}

View File

@@ -0,0 +1,4 @@
<?php /* Smarty version 2.6.19, created on 2008-06-06 13:02:20
compiled from footer.tpl */ ?>
</BODY>
</HTML>

View File

@@ -0,0 +1,5 @@
<?php $_config_vars = array (
'title' => 'Welcome to Smarty!',
'cutoff_size' => '40',
'bold' => true,
); ?>

View File

@@ -0,0 +1,147 @@
<?php /* Smarty version 2.6.19, created on 2008-06-06 13:10:14
compiled from index.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'config_load', 'index.tpl', 1, false),array('function', 'html_select_date', 'index.tpl', 64, false),array('function', 'html_select_time', 'index.tpl', 70, false),array('function', 'html_options', 'index.tpl', 77, false),array('modifier', 'capitalize', 'index.tpl', 9, false),array('modifier', 'date_format', 'index.tpl', 12, false),array('modifier', 'upper', 'index.tpl', 22, false),)), $this); ?>
<?php echo smarty_function_config_load(array('file' => "test.conf",'section' => 'setup'), $this);?>
<?php $_smarty_tpl_vars = $this->_tpl_vars;
$this->_smarty_include(array('smarty_include_tpl_file' => "header.tpl", 'smarty_include_vars' => array('title' => 'foo')));
$this->_tpl_vars = $_smarty_tpl_vars;
unset($_smarty_tpl_vars);
?>
<PRE>
<?php if ($this->_config[0]['vars']['bold']): ?><b><?php endif; ?>
Title: <?php echo ((is_array($_tmp=$this->_config[0]['vars']['title'])) ? $this->_run_mod_handler('capitalize', true, $_tmp) : smarty_modifier_capitalize($_tmp)); ?>
<?php if ($this->_config[0]['vars']['bold']): ?></b><?php endif; ?>
The current date and time is <?php echo ((is_array($_tmp=time())) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y-%m-%d %H:%M:%S") : smarty_modifier_date_format($_tmp, "%Y-%m-%d %H:%M:%S")); ?>
The value of global assigned variable $SCRIPT_NAME is <?php echo $this->_tpl_vars['SCRIPT_NAME']; ?>
Example of accessing server environment variable SERVER_NAME: <?php echo $_SERVER['SERVER_NAME']; ?>
The value of {$Name} is <b><?php echo $this->_tpl_vars['Name']; ?>
</b>
variable modifier example of {$Name|upper}
<b><?php echo ((is_array($_tmp=$this->_tpl_vars['Name'])) ? $this->_run_mod_handler('upper', true, $_tmp) : smarty_modifier_upper($_tmp)); ?>
</b>
An example of a section loop:
<?php unset($this->_sections['outer']);
$this->_sections['outer']['name'] = 'outer';
$this->_sections['outer']['loop'] = is_array($_loop=$this->_tpl_vars['FirstName']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['outer']['show'] = true;
$this->_sections['outer']['max'] = $this->_sections['outer']['loop'];
$this->_sections['outer']['step'] = 1;
$this->_sections['outer']['start'] = $this->_sections['outer']['step'] > 0 ? 0 : $this->_sections['outer']['loop']-1;
if ($this->_sections['outer']['show']) {
$this->_sections['outer']['total'] = $this->_sections['outer']['loop'];
if ($this->_sections['outer']['total'] == 0)
$this->_sections['outer']['show'] = false;
} else
$this->_sections['outer']['total'] = 0;
if ($this->_sections['outer']['show']):
for ($this->_sections['outer']['index'] = $this->_sections['outer']['start'], $this->_sections['outer']['iteration'] = 1;
$this->_sections['outer']['iteration'] <= $this->_sections['outer']['total'];
$this->_sections['outer']['index'] += $this->_sections['outer']['step'], $this->_sections['outer']['iteration']++):
$this->_sections['outer']['rownum'] = $this->_sections['outer']['iteration'];
$this->_sections['outer']['index_prev'] = $this->_sections['outer']['index'] - $this->_sections['outer']['step'];
$this->_sections['outer']['index_next'] = $this->_sections['outer']['index'] + $this->_sections['outer']['step'];
$this->_sections['outer']['first'] = ($this->_sections['outer']['iteration'] == 1);
$this->_sections['outer']['last'] = ($this->_sections['outer']['iteration'] == $this->_sections['outer']['total']);
?>
<?php if ((1 & ($this->_sections['outer']['index'] / 2))): ?>
<?php echo $this->_sections['outer']['rownum']; ?>
. <?php echo $this->_tpl_vars['FirstName'][$this->_sections['outer']['index']]; ?>
<?php echo $this->_tpl_vars['LastName'][$this->_sections['outer']['index']]; ?>
<?php else: ?>
<?php echo $this->_sections['outer']['rownum']; ?>
* <?php echo $this->_tpl_vars['FirstName'][$this->_sections['outer']['index']]; ?>
<?php echo $this->_tpl_vars['LastName'][$this->_sections['outer']['index']]; ?>
<?php endif; ?>
<?php endfor; else: ?>
none
<?php endif; ?>
An example of section looped key values:
<?php unset($this->_sections['sec1']);
$this->_sections['sec1']['name'] = 'sec1';
$this->_sections['sec1']['loop'] = is_array($_loop=$this->_tpl_vars['contacts']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['sec1']['show'] = true;
$this->_sections['sec1']['max'] = $this->_sections['sec1']['loop'];
$this->_sections['sec1']['step'] = 1;
$this->_sections['sec1']['start'] = $this->_sections['sec1']['step'] > 0 ? 0 : $this->_sections['sec1']['loop']-1;
if ($this->_sections['sec1']['show']) {
$this->_sections['sec1']['total'] = $this->_sections['sec1']['loop'];
if ($this->_sections['sec1']['total'] == 0)
$this->_sections['sec1']['show'] = false;
} else
$this->_sections['sec1']['total'] = 0;
if ($this->_sections['sec1']['show']):
for ($this->_sections['sec1']['index'] = $this->_sections['sec1']['start'], $this->_sections['sec1']['iteration'] = 1;
$this->_sections['sec1']['iteration'] <= $this->_sections['sec1']['total'];
$this->_sections['sec1']['index'] += $this->_sections['sec1']['step'], $this->_sections['sec1']['iteration']++):
$this->_sections['sec1']['rownum'] = $this->_sections['sec1']['iteration'];
$this->_sections['sec1']['index_prev'] = $this->_sections['sec1']['index'] - $this->_sections['sec1']['step'];
$this->_sections['sec1']['index_next'] = $this->_sections['sec1']['index'] + $this->_sections['sec1']['step'];
$this->_sections['sec1']['first'] = ($this->_sections['sec1']['iteration'] == 1);
$this->_sections['sec1']['last'] = ($this->_sections['sec1']['iteration'] == $this->_sections['sec1']['total']);
?>
phone: <?php echo $this->_tpl_vars['contacts'][$this->_sections['sec1']['index']]['phone']; ?>
<br>
fax: <?php echo $this->_tpl_vars['contacts'][$this->_sections['sec1']['index']]['fax']; ?>
<br>
cell: <?php echo $this->_tpl_vars['contacts'][$this->_sections['sec1']['index']]['cell']; ?>
<br>
<?php endfor; endif; ?>
<p>
testing strip tags
<?php echo '<table border=0><tr><td><A HREF="'; ?><?php echo $this->_tpl_vars['SCRIPT_NAME']; ?><?php echo '"><font color="red">This is a test </font></A></td></tr></table>'; ?>
</PRE>
This is an example of the html_select_date function:
<form>
<?php echo smarty_function_html_select_date(array('start_year' => 1998,'end_year' => 2010), $this);?>
</form>
This is an example of the html_select_time function:
<form>
<?php echo smarty_function_html_select_time(array('use_24_hours' => true), $this);?>
</form>
This is an example of the html_options function:
<form>
<select name=states>
<?php echo smarty_function_html_options(array('values' => $this->_tpl_vars['option_values'],'selected' => $this->_tpl_vars['option_selected'],'output' => $this->_tpl_vars['option_output']), $this);?>
</select>
</form>
<?php $_smarty_tpl_vars = $this->_tpl_vars;
$this->_smarty_include(array('smarty_include_tpl_file' => "footer.tpl", 'smarty_include_vars' => array()));
$this->_tpl_vars = $_smarty_tpl_vars;
unset($_smarty_tpl_vars);
?>

View File

@@ -0,0 +1,263 @@
<?php /* Smarty version 2.6.19, created on 2008-06-06 13:10:14
compiled from file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'assign_debug_info', 'file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl', 3, false),array('function', 'cycle', 'file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl', 119, false),array('modifier', 'escape', 'file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl', 102, false),array('modifier', 'string_format', 'file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl', 105, false),array('modifier', 'debug_print_var', 'file:/data/www/dev.verygames.net/htdocs/lib/smarty/libs/debug.tpl', 121, false),)), $this); ?>
<?php echo smarty_function_assign_debug_info(array(), $this);?>
<?php ob_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Smarty Debug Console</title>
<?php echo '
<style type="text/css">
/* <![CDATA[ */
body, h1, h2, td, th, p {
font-family: sans-serif;
font-weight: normal;
font-size: 0.9em;
margin: 1px;
padding: 0;
}
h1 {
margin: 0;
text-align: left;
padding: 2px;
background-color: #f0c040;
color: black;
font-weight: bold;
font-size: 1.2em;
}
h2 {
background-color: #9B410E;
color: white;
text-align: left;
font-weight: bold;
padding: 2px;
border-top: 1px solid black;
}
body {
background: black;
}
p, table, div {
background: #f0ead8;
}
p {
margin: 0;
font-style: italic;
text-align: center;
}
table {
width: 100%;
}
th, td {
font-family: monospace;
vertical-align: top;
text-align: left;
width: 50%;
}
td {
color: green;
}
.odd {
background-color: #eeeeee;
}
.even {
background-color: #fafafa;
}
.exectime {
font-size: 0.8em;
font-style: italic;
}
#table_assigned_vars th {
color: blue;
}
#table_config_vars th {
color: maroon;
}
/* ]]> */
</style>
'; ?>
</head>
<body>
<h1>Smarty Debug Console</h1>
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
<?php unset($this->_sections['templates']);
$this->_sections['templates']['name'] = 'templates';
$this->_sections['templates']['loop'] = is_array($_loop=$this->_tpl_vars['_debug_tpls']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['templates']['show'] = true;
$this->_sections['templates']['max'] = $this->_sections['templates']['loop'];
$this->_sections['templates']['step'] = 1;
$this->_sections['templates']['start'] = $this->_sections['templates']['step'] > 0 ? 0 : $this->_sections['templates']['loop']-1;
if ($this->_sections['templates']['show']) {
$this->_sections['templates']['total'] = $this->_sections['templates']['loop'];
if ($this->_sections['templates']['total'] == 0)
$this->_sections['templates']['show'] = false;
} else
$this->_sections['templates']['total'] = 0;
if ($this->_sections['templates']['show']):
for ($this->_sections['templates']['index'] = $this->_sections['templates']['start'], $this->_sections['templates']['iteration'] = 1;
$this->_sections['templates']['iteration'] <= $this->_sections['templates']['total'];
$this->_sections['templates']['index'] += $this->_sections['templates']['step'], $this->_sections['templates']['iteration']++):
$this->_sections['templates']['rownum'] = $this->_sections['templates']['iteration'];
$this->_sections['templates']['index_prev'] = $this->_sections['templates']['index'] - $this->_sections['templates']['step'];
$this->_sections['templates']['index_next'] = $this->_sections['templates']['index'] + $this->_sections['templates']['step'];
$this->_sections['templates']['first'] = ($this->_sections['templates']['iteration'] == 1);
$this->_sections['templates']['last'] = ($this->_sections['templates']['iteration'] == $this->_sections['templates']['total']);
?>
<?php unset($this->_sections['indent']);
$this->_sections['indent']['name'] = 'indent';
$this->_sections['indent']['loop'] = is_array($_loop=$this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['depth']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['indent']['show'] = true;
$this->_sections['indent']['max'] = $this->_sections['indent']['loop'];
$this->_sections['indent']['step'] = 1;
$this->_sections['indent']['start'] = $this->_sections['indent']['step'] > 0 ? 0 : $this->_sections['indent']['loop']-1;
if ($this->_sections['indent']['show']) {
$this->_sections['indent']['total'] = $this->_sections['indent']['loop'];
if ($this->_sections['indent']['total'] == 0)
$this->_sections['indent']['show'] = false;
} else
$this->_sections['indent']['total'] = 0;
if ($this->_sections['indent']['show']):
for ($this->_sections['indent']['index'] = $this->_sections['indent']['start'], $this->_sections['indent']['iteration'] = 1;
$this->_sections['indent']['iteration'] <= $this->_sections['indent']['total'];
$this->_sections['indent']['index'] += $this->_sections['indent']['step'], $this->_sections['indent']['iteration']++):
$this->_sections['indent']['rownum'] = $this->_sections['indent']['iteration'];
$this->_sections['indent']['index_prev'] = $this->_sections['indent']['index'] - $this->_sections['indent']['step'];
$this->_sections['indent']['index_next'] = $this->_sections['indent']['index'] + $this->_sections['indent']['step'];
$this->_sections['indent']['first'] = ($this->_sections['indent']['iteration'] == 1);
$this->_sections['indent']['last'] = ($this->_sections['indent']['iteration'] == $this->_sections['indent']['total']);
?>&nbsp;&nbsp;&nbsp;<?php endfor; endif; ?>
<font color=<?php if ($this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['type'] == 'template'): ?>brown<?php elseif ($this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['type'] == 'insert'): ?>black<?php else: ?>green<?php endif; ?>>
<?php echo ((is_array($_tmp=$this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['filename'])) ? $this->_run_mod_handler('escape', true, $_tmp, 'html') : smarty_modifier_escape($_tmp, 'html')); ?>
</font>
<?php if (isset ( $this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['exec_time'] )): ?>
<span class="exectime">
(<?php echo ((is_array($_tmp=$this->_tpl_vars['_debug_tpls'][$this->_sections['templates']['index']]['exec_time'])) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.5f") : smarty_modifier_string_format($_tmp, "%.5f")); ?>
)
<?php if ($this->_sections['templates']['index'] == 0): ?>(total)<?php endif; ?>
</span>
<?php endif; ?>
<br />
<?php endfor; else: ?>
<p>no templates included</p>
<?php endif; ?>
</div>
<h2>assigned template variables</h2>
<table id="table_assigned_vars">
<?php unset($this->_sections['vars']);
$this->_sections['vars']['name'] = 'vars';
$this->_sections['vars']['loop'] = is_array($_loop=$this->_tpl_vars['_debug_keys']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['vars']['show'] = true;
$this->_sections['vars']['max'] = $this->_sections['vars']['loop'];
$this->_sections['vars']['step'] = 1;
$this->_sections['vars']['start'] = $this->_sections['vars']['step'] > 0 ? 0 : $this->_sections['vars']['loop']-1;
if ($this->_sections['vars']['show']) {
$this->_sections['vars']['total'] = $this->_sections['vars']['loop'];
if ($this->_sections['vars']['total'] == 0)
$this->_sections['vars']['show'] = false;
} else
$this->_sections['vars']['total'] = 0;
if ($this->_sections['vars']['show']):
for ($this->_sections['vars']['index'] = $this->_sections['vars']['start'], $this->_sections['vars']['iteration'] = 1;
$this->_sections['vars']['iteration'] <= $this->_sections['vars']['total'];
$this->_sections['vars']['index'] += $this->_sections['vars']['step'], $this->_sections['vars']['iteration']++):
$this->_sections['vars']['rownum'] = $this->_sections['vars']['iteration'];
$this->_sections['vars']['index_prev'] = $this->_sections['vars']['index'] - $this->_sections['vars']['step'];
$this->_sections['vars']['index_next'] = $this->_sections['vars']['index'] + $this->_sections['vars']['step'];
$this->_sections['vars']['first'] = ($this->_sections['vars']['iteration'] == 1);
$this->_sections['vars']['last'] = ($this->_sections['vars']['iteration'] == $this->_sections['vars']['total']);
?>
<tr class="<?php echo smarty_function_cycle(array('values' => "odd,even"), $this);?>
">
<th>{$<?php echo ((is_array($_tmp=$this->_tpl_vars['_debug_keys'][$this->_sections['vars']['index']])) ? $this->_run_mod_handler('escape', true, $_tmp, 'html') : smarty_modifier_escape($_tmp, 'html')); ?>
}</th>
<td><?php echo smarty_modifier_debug_print_var($this->_tpl_vars['_debug_vals'][$this->_sections['vars']['index']]); ?>
</td></tr>
<?php endfor; else: ?>
<tr><td><p>no template variables assigned</p></td></tr>
<?php endif; ?>
</table>
<h2>assigned config file variables (outer template scope)</h2>
<table id="table_config_vars">
<?php unset($this->_sections['config_vars']);
$this->_sections['config_vars']['name'] = 'config_vars';
$this->_sections['config_vars']['loop'] = is_array($_loop=$this->_tpl_vars['_debug_config_keys']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['config_vars']['show'] = true;
$this->_sections['config_vars']['max'] = $this->_sections['config_vars']['loop'];
$this->_sections['config_vars']['step'] = 1;
$this->_sections['config_vars']['start'] = $this->_sections['config_vars']['step'] > 0 ? 0 : $this->_sections['config_vars']['loop']-1;
if ($this->_sections['config_vars']['show']) {
$this->_sections['config_vars']['total'] = $this->_sections['config_vars']['loop'];
if ($this->_sections['config_vars']['total'] == 0)
$this->_sections['config_vars']['show'] = false;
} else
$this->_sections['config_vars']['total'] = 0;
if ($this->_sections['config_vars']['show']):
for ($this->_sections['config_vars']['index'] = $this->_sections['config_vars']['start'], $this->_sections['config_vars']['iteration'] = 1;
$this->_sections['config_vars']['iteration'] <= $this->_sections['config_vars']['total'];
$this->_sections['config_vars']['index'] += $this->_sections['config_vars']['step'], $this->_sections['config_vars']['iteration']++):
$this->_sections['config_vars']['rownum'] = $this->_sections['config_vars']['iteration'];
$this->_sections['config_vars']['index_prev'] = $this->_sections['config_vars']['index'] - $this->_sections['config_vars']['step'];
$this->_sections['config_vars']['index_next'] = $this->_sections['config_vars']['index'] + $this->_sections['config_vars']['step'];
$this->_sections['config_vars']['first'] = ($this->_sections['config_vars']['iteration'] == 1);
$this->_sections['config_vars']['last'] = ($this->_sections['config_vars']['iteration'] == $this->_sections['config_vars']['total']);
?>
<tr class="<?php echo smarty_function_cycle(array('values' => "odd,even"), $this);?>
">
<th>{#<?php echo ((is_array($_tmp=$this->_tpl_vars['_debug_config_keys'][$this->_sections['config_vars']['index']])) ? $this->_run_mod_handler('escape', true, $_tmp, 'html') : smarty_modifier_escape($_tmp, 'html')); ?>
#}</th>
<td><?php echo smarty_modifier_debug_print_var($this->_tpl_vars['_debug_config_vals'][$this->_sections['config_vars']['index']]); ?>
</td></tr>
<?php endfor; else: ?>
<tr><td><p>no config vars assigned</p></td></tr>
<?php endif; ?>
</table>
</body>
</html>
<?php $this->_smarty_vars['capture']['default'] = ob_get_contents(); $this->assign('debug_output', ob_get_contents());ob_end_clean(); ?>
<?php if (isset ( $this->_tpl_vars['_smarty_debug_output'] ) && $this->_tpl_vars['_smarty_debug_output'] == 'html'): ?>
<?php echo $this->_tpl_vars['debug_output']; ?>
<?php else: ?>
<script type="text/javascript">
// <![CDATA[
if ( self.name == '' ) {
var title = 'Console';
}
else {
var title = 'Console_' + self.name;
}
_smarty_console = window.open("",title.value,"width=680,height=600,resizable,scrollbars=yes");
_smarty_console.document.write('<?php echo ((is_array($_tmp=$this->_tpl_vars['debug_output'])) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
');
_smarty_console.document.close();
// ]]>
</script>
<?php endif; ?>

View File

@@ -0,0 +1,13 @@
<?php /* Smarty version 2.6.19, created on 2008-06-06 13:02:20
compiled from header.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'popup_init', 'header.tpl', 3, false),)), $this); ?>
<HTML>
<HEAD>
<?php echo smarty_function_popup_init(array('src' => "/javascripts/overlib.js"), $this);?>
<TITLE><?php echo $this->_tpl_vars['title']; ?>
- <?php echo $this->_tpl_vars['Name']; ?>
</TITLE>
</HEAD>
<BODY bgcolor="#ffffff">

View File

@@ -0,0 +1,67 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* assemble filepath of requested plugin
*
* @param string $type
* @param string $name
* @return string|false
*/
function smarty_core_assemble_plugin_filepath($params, &$smarty)
{
static $_filepaths_cache = array();
$_plugin_filename = $params['type'] . '.' . $params['name'] . '.php';
if (isset($_filepaths_cache[$_plugin_filename])) {
return $_filepaths_cache[$_plugin_filename];
}
$_return = false;
foreach ((array)$smarty->plugins_dir as $_plugin_dir) {
$_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename;
// see if path is relative
if (!preg_match("/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/", $_plugin_dir)) {
$_relative_paths[] = $_plugin_dir;
// relative path, see if it is in the SMARTY_DIR
if (@is_readable(SMARTY_DIR . $_plugin_filepath)) {
$_return = SMARTY_DIR . $_plugin_filepath;
break;
}
}
// try relative to cwd (or absolute)
if (@is_readable($_plugin_filepath)) {
$_return = $_plugin_filepath;
break;
}
}
if($_return === false) {
// still not found, try PHP include_path
if(isset($_relative_paths)) {
foreach ((array)$_relative_paths as $_plugin_dir) {
$_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename;
$_params = array('file_path' => $_plugin_filepath);
require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');
if(smarty_core_get_include_path($_params, $smarty)) {
$_return = $_params['new_file_path'];
break;
}
}
}
}
$_filepaths_cache[$_plugin_filename] = $_return;
return $_return;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,43 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty assign_smarty_interface core plugin
*
* Type: core<br>
* Name: assign_smarty_interface<br>
* Purpose: assign the $smarty interface variable
* @param array Format: null
* @param Smarty
*/
function smarty_core_assign_smarty_interface($params, &$smarty)
{
if (isset($smarty->_smarty_vars) && isset($smarty->_smarty_vars['request'])) {
return;
}
$_globals_map = array('g' => 'HTTP_GET_VARS',
'p' => 'HTTP_POST_VARS',
'c' => 'HTTP_COOKIE_VARS',
's' => 'HTTP_SERVER_VARS',
'e' => 'HTTP_ENV_VARS');
$_smarty_vars_request = array();
foreach (preg_split('!!', strtolower($smarty->request_vars_order)) as $_c) {
if (isset($_globals_map[$_c])) {
$_smarty_vars_request = array_merge($_smarty_vars_request, $GLOBALS[$_globals_map[$_c]]);
}
}
$_smarty_vars_request = @array_merge($_smarty_vars_request, $GLOBALS['HTTP_SESSION_VARS']);
$smarty->_smarty_vars['request'] = $_smarty_vars_request;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,79 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* create full directory structure
*
* @param string $dir
*/
// $dir
function smarty_core_create_dir_structure($params, &$smarty)
{
if (!file_exists($params['dir'])) {
$_open_basedir_ini = ini_get('open_basedir');
if (DIRECTORY_SEPARATOR=='/') {
/* unix-style paths */
$_dir = $params['dir'];
$_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
$_new_dir = (substr($_dir, 0, 1)=='/') ? '/' : getcwd().'/';
if($_use_open_basedir = !empty($_open_basedir_ini)) {
$_open_basedirs = explode(':', $_open_basedir_ini);
}
} else {
/* other-style paths */
$_dir = str_replace('\\','/', $params['dir']);
$_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir)) {
/* leading "//" for network volume, or "[letter]:/" for full path */
$_new_dir = $_root_dir[1];
/* remove drive-letter from _dir_parts */
if (isset($_root_dir[3])) array_shift($_dir_parts);
} else {
$_new_dir = str_replace('\\', '/', getcwd()).'/';
}
if($_use_open_basedir = !empty($_open_basedir_ini)) {
$_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini));
}
}
/* all paths use "/" only from here */
foreach ($_dir_parts as $_dir_part) {
$_new_dir .= $_dir_part;
if ($_use_open_basedir) {
// do not attempt to test or make directories outside of open_basedir
$_make_new_dir = false;
foreach ($_open_basedirs as $_open_basedir) {
if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir) {
$_make_new_dir = true;
break;
}
}
} else {
$_make_new_dir = true;
}
if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir, $smarty->_dir_perms) && !is_dir($_new_dir)) {
$smarty->trigger_error("problem creating directory '" . $_new_dir . "'");
return false;
}
$_new_dir .= '/';
}
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,61 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty debug_console function plugin
*
* Type: core<br>
* Name: display_debug_console<br>
* Purpose: display the javascript debug console window
* @param array Format: null
* @param Smarty
*/
function smarty_core_display_debug_console($params, &$smarty)
{
// we must force compile the debug template in case the environment
// changed between separate applications.
if(empty($smarty->debug_tpl)) {
// set path to debug template from SMARTY_DIR
$smarty->debug_tpl = SMARTY_DIR . 'debug.tpl';
if($smarty->security && is_file($smarty->debug_tpl)) {
$smarty->secure_dir[] = realpath($smarty->debug_tpl);
}
$smarty->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl';
}
$_ldelim_orig = $smarty->left_delimiter;
$_rdelim_orig = $smarty->right_delimiter;
$smarty->left_delimiter = '{';
$smarty->right_delimiter = '}';
$_compile_id_orig = $smarty->_compile_id;
$smarty->_compile_id = null;
$_compile_path = $smarty->_get_compile_path($smarty->debug_tpl);
if ($smarty->_compile_resource($smarty->debug_tpl, $_compile_path))
{
ob_start();
$smarty->_include($_compile_path);
$_results = ob_get_contents();
ob_end_clean();
} else {
$_results = '';
}
$smarty->_compile_id = $_compile_id_orig;
$smarty->left_delimiter = $_ldelim_orig;
$smarty->right_delimiter = $_rdelim_orig;
return $_results;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,44 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Get path to file from include_path
*
* @param string $file_path
* @param string $new_file_path
* @return boolean
* @staticvar array|null
*/
// $file_path, &$new_file_path
function smarty_core_get_include_path(&$params, &$smarty)
{
static $_path_array = null;
if(!isset($_path_array)) {
$_ini_include_path = ini_get('include_path');
if(strstr($_ini_include_path,';')) {
// windows pathnames
$_path_array = explode(';',$_ini_include_path);
} else {
$_path_array = explode(':',$_ini_include_path);
}
}
foreach ($_path_array as $_include_path) {
if (@is_readable($_include_path . DIRECTORY_SEPARATOR . $params['file_path'])) {
$params['new_file_path'] = $_include_path . DIRECTORY_SEPARATOR . $params['file_path'];
return true;
}
}
return false;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,23 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Get seconds and microseconds
* @return double
*/
function smarty_core_get_microtime($params, &$smarty)
{
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = (double)($mtime[1]) + (double)($mtime[0]);
return ($mtime);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,80 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Retrieves PHP script resource
*
* sets $php_resource to the returned resource
* @param string $resource
* @param string $resource_type
* @param $php_resource
* @return boolean
*/
function smarty_core_get_php_resource(&$params, &$smarty)
{
$params['resource_base_path'] = $smarty->trusted_dir;
$smarty->_parse_resource_name($params, $smarty);
/*
* Find out if the resource exists.
*/
if ($params['resource_type'] == 'file') {
$_readable = false;
if(file_exists($params['resource_name']) && is_readable($params['resource_name'])) {
$_readable = true;
} else {
// test for file in include_path
$_params = array('file_path' => $params['resource_name']);
require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');
if(smarty_core_get_include_path($_params, $smarty)) {
$_include_path = $_params['new_file_path'];
$_readable = true;
}
}
} else if ($params['resource_type'] != 'file') {
$_template_source = null;
$_readable = is_callable($smarty->_plugins['resource'][$params['resource_type']][0][0])
&& call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][0],
array($params['resource_name'], &$_template_source, &$smarty));
}
/*
* Set the error function, depending on which class calls us.
*/
if (method_exists($smarty, '_syntax_error')) {
$_error_funcc = '_syntax_error';
} else {
$_error_funcc = 'trigger_error';
}
if ($_readable) {
if ($smarty->security) {
require_once(SMARTY_CORE_DIR . 'core.is_trusted.php');
if (!smarty_core_is_trusted($params, $smarty)) {
$smarty->$_error_funcc('(secure mode) ' . $params['resource_type'] . ':' . $params['resource_name'] . ' is not trusted');
return false;
}
}
} else {
$smarty->$_error_funcc($params['resource_type'] . ':' . $params['resource_name'] . ' is not readable');
return false;
}
if ($params['resource_type'] == 'file') {
$params['php_resource'] = $params['resource_name'];
} else {
$params['php_resource'] = $_template_source;
}
return true;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,59 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* determines if a resource is secure or not.
*
* @param string $resource_type
* @param string $resource_name
* @return boolean
*/
// $resource_type, $resource_name
function smarty_core_is_secure($params, &$smarty)
{
if (!$smarty->security || $smarty->security_settings['INCLUDE_ANY']) {
return true;
}
if ($params['resource_type'] == 'file') {
$_rp = realpath($params['resource_name']);
if (isset($params['resource_base_path'])) {
foreach ((array)$params['resource_base_path'] as $curr_dir) {
if ( ($_cd = realpath($curr_dir)) !== false &&
strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) {
return true;
}
}
}
if (!empty($smarty->secure_dir)) {
foreach ((array)$smarty->secure_dir as $curr_dir) {
if ( ($_cd = realpath($curr_dir)) !== false) {
if($_cd == $_rp) {
return true;
} elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR) {
return true;
}
}
}
}
} else {
// resource is not on local file system
return call_user_func_array(
$smarty->_plugins['resource'][$params['resource_type']][0][2],
array($params['resource_name'], &$smarty));
}
return false;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,47 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* determines if a resource is trusted or not
*
* @param string $resource_type
* @param string $resource_name
* @return boolean
*/
// $resource_type, $resource_name
function smarty_core_is_trusted($params, &$smarty)
{
$_smarty_trusted = false;
if ($params['resource_type'] == 'file') {
if (!empty($smarty->trusted_dir)) {
$_rp = realpath($params['resource_name']);
foreach ((array)$smarty->trusted_dir as $curr_dir) {
if (!empty($curr_dir) && is_readable ($curr_dir)) {
$_cd = realpath($curr_dir);
if (strncmp($_rp, $_cd, strlen($_cd)) == 0
&& substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) {
$_smarty_trusted = true;
break;
}
}
}
}
} else {
// resource is not on local file system
$_smarty_trusted = call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][3],
array($params['resource_name'], $smarty));
}
return $_smarty_trusted;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,125 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Load requested plugins
*
* @param array $plugins
*/
// $plugins
function smarty_core_load_plugins($params, &$smarty)
{
foreach ($params['plugins'] as $_plugin_info) {
list($_type, $_name, $_tpl_file, $_tpl_line, $_delayed_loading) = $_plugin_info;
$_plugin = &$smarty->_plugins[$_type][$_name];
/*
* We do not load plugin more than once for each instance of Smarty.
* The following code checks for that. The plugin can also be
* registered dynamically at runtime, in which case template file
* and line number will be unknown, so we fill them in.
*
* The final element of the info array is a flag that indicates
* whether the dynamically registered plugin function has been
* checked for existence yet or not.
*/
if (isset($_plugin)) {
if (empty($_plugin[3])) {
if (!is_callable($_plugin[0])) {
$smarty->_trigger_fatal_error("[plugin] $_type '$_name' is not implemented", $_tpl_file, $_tpl_line, __FILE__, __LINE__);
} else {
$_plugin[1] = $_tpl_file;
$_plugin[2] = $_tpl_line;
$_plugin[3] = true;
if (!isset($_plugin[4])) $_plugin[4] = true; /* cacheable */
}
}
continue;
} else if ($_type == 'insert') {
/*
* For backwards compatibility, we check for insert functions in
* the symbol table before trying to load them as a plugin.
*/
$_plugin_func = 'insert_' . $_name;
if (function_exists($_plugin_func)) {
$_plugin = array($_plugin_func, $_tpl_file, $_tpl_line, true, false);
continue;
}
}
$_plugin_file = $smarty->_get_plugin_filepath($_type, $_name);
if (! $_found = ($_plugin_file != false)) {
$_message = "could not load plugin file '$_type.$_name.php'\n";
}
/*
* If plugin file is found, it -must- provide the properly named
* plugin function. In case it doesn't, simply output the error and
* do not fall back on any other method.
*/
if ($_found) {
include_once $_plugin_file;
$_plugin_func = 'smarty_' . $_type . '_' . $_name;
if (!function_exists($_plugin_func)) {
$smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", $_tpl_file, $_tpl_line, __FILE__, __LINE__);
continue;
}
}
/*
* In case of insert plugins, their code may be loaded later via
* 'script' attribute.
*/
else if ($_type == 'insert' && $_delayed_loading) {
$_plugin_func = 'smarty_' . $_type . '_' . $_name;
$_found = true;
}
/*
* Plugin specific processing and error checking.
*/
if (!$_found) {
if ($_type == 'modifier') {
/*
* In case modifier falls back on using PHP functions
* directly, we only allow those specified in the security
* context.
*/
if ($smarty->security && !in_array($_name, $smarty->security_settings['MODIFIER_FUNCS'])) {
$_message = "(secure mode) modifier '$_name' is not allowed";
} else {
if (!function_exists($_name)) {
$_message = "modifier '$_name' is not implemented";
} else {
$_plugin_func = $_name;
$_found = true;
}
}
} else if ($_type == 'function') {
/*
* This is a catch-all situation.
*/
$_message = "unknown tag - '$_name'";
}
}
if ($_found) {
$smarty->_plugins[$_type][$_name] = array($_plugin_func, $_tpl_file, $_tpl_line, true, true);
} else {
// output error
$smarty->_trigger_fatal_error('[plugin] ' . $_message, $_tpl_file, $_tpl_line, __FILE__, __LINE__);
}
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,74 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* load a resource plugin
*
* @param string $type
*/
// $type
function smarty_core_load_resource_plugin($params, &$smarty)
{
/*
* Resource plugins are not quite like the other ones, so they are
* handled differently. The first element of plugin info is the array of
* functions provided by the plugin, the second one indicates whether
* all of them exist or not.
*/
$_plugin = &$smarty->_plugins['resource'][$params['type']];
if (isset($_plugin)) {
if (!$_plugin[1] && count($_plugin[0])) {
$_plugin[1] = true;
foreach ($_plugin[0] as $_plugin_func) {
if (!is_callable($_plugin_func)) {
$_plugin[1] = false;
break;
}
}
}
if (!$_plugin[1]) {
$smarty->_trigger_fatal_error("[plugin] resource '" . $params['type'] . "' is not implemented", null, null, __FILE__, __LINE__);
}
return;
}
$_plugin_file = $smarty->_get_plugin_filepath('resource', $params['type']);
$_found = ($_plugin_file != false);
if ($_found) { /*
* If the plugin file is found, it -must- provide the properly named
* plugin functions.
*/
include_once($_plugin_file);
/*
* Locate functions that we require the plugin to provide.
*/
$_resource_ops = array('source', 'timestamp', 'secure', 'trusted');
$_resource_funcs = array();
foreach ($_resource_ops as $_op) {
$_plugin_func = 'smarty_resource_' . $params['type'] . '_' . $_op;
if (!function_exists($_plugin_func)) {
$smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", null, null, __FILE__, __LINE__);
return;
} else {
$_resource_funcs[] = $_plugin_func;
}
}
$smarty->_plugins['resource'][$params['type']] = array($_resource_funcs, true);
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,71 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Replace cached inserts with the actual results
*
* @param string $results
* @return string
*/
function smarty_core_process_cached_inserts($params, &$smarty)
{
preg_match_all('!'.$smarty->_smarty_md5.'{insert_cache (.*)}'.$smarty->_smarty_md5.'!Uis',
$params['results'], $match);
list($cached_inserts, $insert_args) = $match;
for ($i = 0, $for_max = count($cached_inserts); $i < $for_max; $i++) {
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$debug_start_time = smarty_core_get_microtime($_params, $smarty);
}
$args = unserialize($insert_args[$i]);
$name = $args['name'];
if (isset($args['script'])) {
$_params = array('resource_name' => $smarty->_dequote($args['script']));
require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php');
if(!smarty_core_get_php_resource($_params, $smarty)) {
return false;
}
$resource_type = $_params['resource_type'];
$php_resource = $_params['php_resource'];
if ($resource_type == 'file') {
$smarty->_include($php_resource, true);
} else {
$smarty->_eval($php_resource);
}
}
$function_name = $smarty->_plugins['insert'][$name][0];
if (empty($args['assign'])) {
$replace = $function_name($args, $smarty);
} else {
$smarty->assign($args['assign'], $function_name($args, $smarty));
$replace = '';
}
$params['results'] = substr_replace($params['results'], $replace, strpos($params['results'], $cached_inserts[$i]), strlen($cached_inserts[$i]));
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$smarty->_smarty_debug_info[] = array('type' => 'insert',
'filename' => 'insert_'.$name,
'depth' => $smarty->_inclusion_depth,
'exec_time' => smarty_core_get_microtime($_params, $smarty) - $debug_start_time);
}
}
return $params['results'];
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,37 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Replace nocache-tags by results of the corresponding non-cacheable
* functions and return it
*
* @param string $compiled_tpl
* @param string $cached_source
* @return string
*/
function smarty_core_process_compiled_include($params, &$smarty)
{
$_cache_including = $smarty->_cache_including;
$smarty->_cache_including = true;
$_return = $params['results'];
foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) {
$smarty->_include($_include_file_path, true);
}
foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) {
$_return = preg_replace_callback('!(\{nocache\:('.$_cache_serial.')#(\d+)\})!s',
array(&$smarty, '_process_compiled_include_callback'),
$_return);
}
$smarty->_cache_including = $_cache_including;
return $_return;
}
?>

View File

@@ -0,0 +1,101 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* read a cache file, determine if it needs to be
* regenerated or not
*
* @param string $tpl_file
* @param string $cache_id
* @param string $compile_id
* @param string $results
* @return boolean
*/
// $tpl_file, $cache_id, $compile_id, &$results
function smarty_core_read_cache_file(&$params, &$smarty)
{
static $content_cache = array();
if ($smarty->force_compile) {
// force compile enabled, always regenerate
return false;
}
if (isset($content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']])) {
list($params['results'], $smarty->_cache_info) = $content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']];
return true;
}
if (!empty($smarty->cache_handler_func)) {
// use cache_handler function
call_user_func_array($smarty->cache_handler_func,
array('read', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], null));
} else {
// use local cache file
$_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']);
$_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id);
$params['results'] = $smarty->_read_file($_cache_file);
}
if (empty($params['results'])) {
// nothing to parse (error?), regenerate cache
return false;
}
$_contents = $params['results'];
$_info_start = strpos($_contents, "\n") + 1;
$_info_len = (int)substr($_contents, 0, $_info_start - 1);
$_cache_info = unserialize(substr($_contents, $_info_start, $_info_len));
$params['results'] = substr($_contents, $_info_start + $_info_len);
if ($smarty->caching == 2 && isset ($_cache_info['expires'])){
// caching by expiration time
if ($_cache_info['expires'] > -1 && (time() > $_cache_info['expires'])) {
// cache expired, regenerate
return false;
}
} else {
// caching by lifetime
if ($smarty->cache_lifetime > -1 && (time() - $_cache_info['timestamp'] > $smarty->cache_lifetime)) {
// cache expired, regenerate
return false;
}
}
if ($smarty->compile_check) {
$_params = array('get_source' => false, 'quiet'=>true);
foreach (array_keys($_cache_info['template']) as $_template_dep) {
$_params['resource_name'] = $_template_dep;
if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) {
// template file has changed, regenerate cache
return false;
}
}
if (isset($_cache_info['config'])) {
$_params = array('resource_base_path' => $smarty->config_dir, 'get_source' => false, 'quiet'=>true);
foreach (array_keys($_cache_info['config']) as $_config_dep) {
$_params['resource_name'] = $_config_dep;
if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) {
// config file has changed, regenerate cache
return false;
}
}
}
}
$content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']] = array($params['results'], $_cache_info);
$smarty->_cache_info = $_cache_info;
return true;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,71 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* delete an automagically created file by name and id
*
* @param string $auto_base
* @param string $auto_source
* @param string $auto_id
* @param integer $exp_time
* @return boolean
*/
// $auto_base, $auto_source = null, $auto_id = null, $exp_time = null
function smarty_core_rm_auto($params, &$smarty)
{
if (!@is_dir($params['auto_base']))
return false;
if(!isset($params['auto_id']) && !isset($params['auto_source'])) {
$_params = array(
'dirname' => $params['auto_base'],
'level' => 0,
'exp_time' => $params['exp_time']
);
require_once(SMARTY_CORE_DIR . 'core.rmdir.php');
$_res = smarty_core_rmdir($_params, $smarty);
} else {
$_tname = $smarty->_get_auto_filename($params['auto_base'], $params['auto_source'], $params['auto_id']);
if(isset($params['auto_source'])) {
if (isset($params['extensions'])) {
$_res = false;
foreach ((array)$params['extensions'] as $_extension)
$_res |= $smarty->_unlink($_tname.$_extension, $params['exp_time']);
} else {
$_res = $smarty->_unlink($_tname, $params['exp_time']);
}
} elseif ($smarty->use_sub_dirs) {
$_params = array(
'dirname' => $_tname,
'level' => 1,
'exp_time' => $params['exp_time']
);
require_once(SMARTY_CORE_DIR . 'core.rmdir.php');
$_res = smarty_core_rmdir($_params, $smarty);
} else {
// remove matching file names
$_handle = opendir($params['auto_base']);
$_res = true;
while (false !== ($_filename = readdir($_handle))) {
if($_filename == '.' || $_filename == '..') {
continue;
} elseif (substr($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, 0, strlen($_tname)) == $_tname) {
$_res &= (bool)$smarty->_unlink($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, $params['exp_time']);
}
}
}
}
return $_res;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,54 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* delete a dir recursively (level=0 -> keep root)
* WARNING: no tests, it will try to remove what you tell it!
*
* @param string $dirname
* @param integer $level
* @param integer $exp_time
* @return boolean
*/
// $dirname, $level = 1, $exp_time = null
function smarty_core_rmdir($params, &$smarty)
{
if(!isset($params['level'])) { $params['level'] = 1; }
if(!isset($params['exp_time'])) { $params['exp_time'] = null; }
if($_handle = @opendir($params['dirname'])) {
while (false !== ($_entry = readdir($_handle))) {
if ($_entry != '.' && $_entry != '..') {
if (@is_dir($params['dirname'] . DIRECTORY_SEPARATOR . $_entry)) {
$_params = array(
'dirname' => $params['dirname'] . DIRECTORY_SEPARATOR . $_entry,
'level' => $params['level'] + 1,
'exp_time' => $params['exp_time']
);
smarty_core_rmdir($_params, $smarty);
}
else {
$smarty->_unlink($params['dirname'] . DIRECTORY_SEPARATOR . $_entry, $params['exp_time']);
}
}
}
closedir($_handle);
}
if ($params['level']) {
return @rmdir($params['dirname']);
}
return (bool)$_handle;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,71 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Handle insert tags
*
* @param array $args
* @return string
*/
function smarty_core_run_insert_handler($params, &$smarty)
{
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
if ($smarty->debugging) {
$_params = array();
$_debug_start_time = smarty_core_get_microtime($_params, $smarty);
}
if ($smarty->caching) {
$_arg_string = serialize($params['args']);
$_name = $params['args']['name'];
if (!isset($smarty->_cache_info['insert_tags'][$_name])) {
$smarty->_cache_info['insert_tags'][$_name] = array('insert',
$_name,
$smarty->_plugins['insert'][$_name][1],
$smarty->_plugins['insert'][$_name][2],
!empty($params['args']['script']) ? true : false);
}
return $smarty->_smarty_md5."{insert_cache $_arg_string}".$smarty->_smarty_md5;
} else {
if (isset($params['args']['script'])) {
$_params = array('resource_name' => $smarty->_dequote($params['args']['script']));
require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php');
if(!smarty_core_get_php_resource($_params, $smarty)) {
return false;
}
if ($_params['resource_type'] == 'file') {
$smarty->_include($_params['php_resource'], true);
} else {
$smarty->_eval($_params['php_resource']);
}
unset($params['args']['script']);
}
$_funcname = $smarty->_plugins['insert'][$params['args']['name']][0];
$_content = $_funcname($params['args'], $smarty);
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$smarty->_smarty_debug_info[] = array('type' => 'insert',
'filename' => 'insert_'.$params['args']['name'],
'depth' => $smarty->_inclusion_depth,
'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time);
}
if (!empty($params['args']["assign"])) {
$smarty->assign($params['args']["assign"], $_content);
} else {
return $_content;
}
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,50 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* called for included php files within templates
*
* @param string $smarty_file
* @param string $smarty_assign variable to assign the included template's
* output into
* @param boolean $smarty_once uses include_once if this is true
* @param array $smarty_include_vars associative array of vars from
* {include file="blah" var=$var}
*/
// $file, $assign, $once, $_smarty_include_vars
function smarty_core_smarty_include_php($params, &$smarty)
{
$_params = array('resource_name' => $params['smarty_file']);
require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php');
smarty_core_get_php_resource($_params, $smarty);
$_smarty_resource_type = $_params['resource_type'];
$_smarty_php_resource = $_params['php_resource'];
if (!empty($params['smarty_assign'])) {
ob_start();
if ($_smarty_resource_type == 'file') {
$smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']);
} else {
$smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']);
}
$smarty->assign($params['smarty_assign'], ob_get_contents());
ob_end_clean();
} else {
if ($_smarty_resource_type == 'file') {
$smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']);
} else {
$smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']);
}
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,96 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Prepend the cache information to the cache file
* and write it
*
* @param string $tpl_file
* @param string $cache_id
* @param string $compile_id
* @param string $results
* @return true|null
*/
// $tpl_file, $cache_id, $compile_id, $results
function smarty_core_write_cache_file($params, &$smarty)
{
// put timestamp in cache header
$smarty->_cache_info['timestamp'] = time();
if ($smarty->cache_lifetime > -1){
// expiration set
$smarty->_cache_info['expires'] = $smarty->_cache_info['timestamp'] + $smarty->cache_lifetime;
} else {
// cache will never expire
$smarty->_cache_info['expires'] = -1;
}
// collapse nocache.../nocache-tags
if (preg_match_all('!\{(/?)nocache\:[0-9a-f]{32}#\d+\}!', $params['results'], $match, PREG_PATTERN_ORDER)) {
// remove everything between every pair of outermost noache.../nocache-tags
// and replace it by a single nocache-tag
// this new nocache-tag will be replaced by dynamic contents in
// smarty_core_process_compiled_includes() on a cache-read
$match_count = count($match[0]);
$results = preg_split('!(\{/?nocache\:[0-9a-f]{32}#\d+\})!', $params['results'], -1, PREG_SPLIT_DELIM_CAPTURE);
$level = 0;
$j = 0;
for ($i=0, $results_count = count($results); $i < $results_count && $j < $match_count; $i++) {
if ($results[$i] == $match[0][$j]) {
// nocache tag
if ($match[1][$j]) { // closing tag
$level--;
unset($results[$i]);
} else { // opening tag
if ($level++ > 0) unset($results[$i]);
}
$j++;
} elseif ($level > 0) {
unset($results[$i]);
}
}
$params['results'] = implode('', $results);
}
$smarty->_cache_info['cache_serials'] = $smarty->_cache_serials;
// prepend the cache header info into cache file
$_cache_info = serialize($smarty->_cache_info);
$params['results'] = strlen($_cache_info) . "\n" . $_cache_info . $params['results'];
if (!empty($smarty->cache_handler_func)) {
// use cache_handler function
call_user_func_array($smarty->cache_handler_func,
array('write', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], $smarty->_cache_info['expires']));
} else {
// use local cache file
if(!@is_writable($smarty->cache_dir)) {
// cache_dir not writable, see if it exists
if(!@is_dir($smarty->cache_dir)) {
$smarty->trigger_error('the $cache_dir \'' . $smarty->cache_dir . '\' does not exist, or is not a directory.', E_USER_ERROR);
return false;
}
$smarty->trigger_error('unable to write to $cache_dir \'' . realpath($smarty->cache_dir) . '\'. Be sure $cache_dir is writable by the web server user.', E_USER_ERROR);
return false;
}
$_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']);
$_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id);
$_params = array('filename' => $_cache_file, 'contents' => $params['results'], 'create_dirs' => true);
require_once(SMARTY_CORE_DIR . 'core.write_file.php');
smarty_core_write_file($_params, $smarty);
return true;
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,91 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Extract non-cacheable parts out of compiled template and write it
*
* @param string $compile_path
* @param string $template_compiled
* @return boolean
*/
function smarty_core_write_compiled_include($params, &$smarty)
{
$_tag_start = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{nocache\:('.$params['cache_serial'].')#(\d+)\}\'; endif;';
$_tag_end = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{/nocache\:(\\2)#(\\3)\}\'; endif;';
preg_match_all('!('.$_tag_start.'(.*)'.$_tag_end.')!Us',
$params['compiled_content'], $_match_source, PREG_SET_ORDER);
// no nocache-parts found: done
if (count($_match_source)==0) return;
// convert the matched php-code to functions
$_include_compiled = "<?php /* Smarty version ".$smarty->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n";
$_include_compiled .= " compiled from " . strtr(urlencode($params['resource_name']), array('%2F'=>'/', '%3A'=>':')) . " */\n\n";
$_compile_path = $params['include_file_path'];
$smarty->_cache_serials[$_compile_path] = $params['cache_serial'];
$_include_compiled .= "\$this->_cache_serials['".$_compile_path."'] = '".$params['cache_serial']."';\n\n?>";
$_include_compiled .= $params['plugins_code'];
$_include_compiled .= "<?php";
$this_varname = ((double)phpversion() >= 5.0) ? '_smarty' : 'this';
for ($_i = 0, $_for_max = count($_match_source); $_i < $_for_max; $_i++) {
$_match =& $_match_source[$_i];
$source = $_match[4];
if ($this_varname == '_smarty') {
/* rename $this to $_smarty in the sourcecode */
$tokens = token_get_all('<?php ' . $_match[4]);
/* remove trailing <?php */
$open_tag = '';
while ($tokens) {
$token = array_shift($tokens);
if (is_array($token)) {
$open_tag .= $token[1];
} else {
$open_tag .= $token;
}
if ($open_tag == '<?php ') break;
}
for ($i=0, $count = count($tokens); $i < $count; $i++) {
if (is_array($tokens[$i])) {
if ($tokens[$i][0] == T_VARIABLE && $tokens[$i][1] == '$this') {
$tokens[$i] = '$' . $this_varname;
} else {
$tokens[$i] = $tokens[$i][1];
}
}
}
$source = implode('', $tokens);
}
/* add function to compiled include */
$_include_compiled .= "
function _smarty_tplfunc_$_match[2]_$_match[3](&\$$this_varname)
{
$source
}
";
}
$_include_compiled .= "\n\n?>\n";
$_params = array('filename' => $_compile_path,
'contents' => $_include_compiled, 'create_dirs' => true);
require_once(SMARTY_CORE_DIR . 'core.write_file.php');
smarty_core_write_file($_params, $smarty);
return true;
}
?>

View File

@@ -0,0 +1,35 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* write the compiled resource
*
* @param string $compile_path
* @param string $compiled_content
* @return true
*/
function smarty_core_write_compiled_resource($params, &$smarty)
{
if(!@is_writable($smarty->compile_dir)) {
// compile_dir not writable, see if it exists
if(!@is_dir($smarty->compile_dir)) {
$smarty->trigger_error('the $compile_dir \'' . $smarty->compile_dir . '\' does not exist, or is not a directory.', E_USER_ERROR);
return false;
}
$smarty->trigger_error('unable to write to $compile_dir \'' . realpath($smarty->compile_dir) . '\'. Be sure $compile_dir is writable by the web server user.', E_USER_ERROR);
return false;
}
$_params = array('filename' => $params['compile_path'], 'contents' => $params['compiled_content'], 'create_dirs' => true);
require_once(SMARTY_CORE_DIR . 'core.write_file.php');
smarty_core_write_file($_params, $smarty);
return true;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,54 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* write out a file to disk
*
* @param string $filename
* @param string $contents
* @param boolean $create_dirs
* @return boolean
*/
function smarty_core_write_file($params, &$smarty)
{
$_dirname = dirname($params['filename']);
if ($params['create_dirs']) {
$_params = array('dir' => $_dirname);
require_once(SMARTY_CORE_DIR . 'core.create_dir_structure.php');
smarty_core_create_dir_structure($_params, $smarty);
}
// write to tmp file, then rename it to avoid file locking race condition
$_tmp_file = tempnam($_dirname, 'wrt');
if (!($fd = @fopen($_tmp_file, 'wb'))) {
$_tmp_file = $_dirname . DIRECTORY_SEPARATOR . uniqid('wrt');
if (!($fd = @fopen($_tmp_file, 'wb'))) {
$smarty->trigger_error("problem writing temporary file '$_tmp_file'");
return false;
}
}
fwrite($fd, $params['contents']);
fclose($fd);
if (DIRECTORY_SEPARATOR == '\\' || !@rename($_tmp_file, $params['filename'])) {
// On platforms and filesystems that cannot overwrite with rename()
// delete the file before renaming it -- because windows always suffers
// this, it is short-circuited to avoid the initial rename() attempt
@unlink($params['filename']);
@rename($_tmp_file, $params['filename']);
}
@chmod($params['filename'], $smarty->_file_perms);
return true;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,103 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {textformat}{/textformat} block plugin
*
* Type: block function<br>
* Name: textformat<br>
* Purpose: format text a certain way with preset styles
* or custom wrap/indent settings<br>
* @link http://smarty.php.net/manual/en/language.function.textformat.php {textformat}
* (Smarty online manual)
* @param array
* <pre>
* Params: style: string (email)
* indent: integer (0)
* wrap: integer (80)
* wrap_char string ("\n")
* indent_char: string (" ")
* wrap_boundary: boolean (true)
* </pre>
* @author Monte Ohrt <monte at ohrt dot com>
* @param string contents of the block
* @param Smarty clever simulation of a method
* @return string string $content re-formatted
*/
function smarty_block_textformat($params, $content, &$smarty)
{
if (is_null($content)) {
return;
}
$style = null;
$indent = 0;
$indent_first = 0;
$indent_char = ' ';
$wrap = 80;
$wrap_char = "\n";
$wrap_cut = false;
$assign = null;
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'style':
case 'indent_char':
case 'wrap_char':
case 'assign':
$$_key = (string)$_val;
break;
case 'indent':
case 'indent_first':
case 'wrap':
$$_key = (int)$_val;
break;
case 'wrap_cut':
$$_key = (bool)$_val;
break;
default:
$smarty->trigger_error("textformat: unknown attribute '$_key'");
}
}
if ($style == 'email') {
$wrap = 72;
}
// split into paragraphs
$_paragraphs = preg_split('![\r\n][\r\n]!',$content);
$_output = '';
for($_x = 0, $_y = count($_paragraphs); $_x < $_y; $_x++) {
if ($_paragraphs[$_x] == '') {
continue;
}
// convert mult. spaces & special chars to single space
$_paragraphs[$_x] = preg_replace(array('!\s+!','!(^\s+)|(\s+$)!'), array(' ',''), $_paragraphs[$_x]);
// indent first line
if($indent_first > 0) {
$_paragraphs[$_x] = str_repeat($indent_char, $indent_first) . $_paragraphs[$_x];
}
// wordwrap sentences
$_paragraphs[$_x] = wordwrap($_paragraphs[$_x], $wrap - $indent, $wrap_char, $wrap_cut);
// indent lines
if($indent > 0) {
$_paragraphs[$_x] = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraphs[$_x]);
}
}
$_output = implode($wrap_char . $wrap_char, $_paragraphs);
return $assign ? $smarty->assign($assign, $_output) : $_output;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,40 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {assign} compiler function plugin
*
* Type: compiler function<br>
* Name: assign<br>
* Purpose: assign a value to a template variable
* @link http://smarty.php.net/manual/en/language.custom.functions.php#LANGUAGE.FUNCTION.ASSIGN {assign}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com> (initial author)
* @author messju mohr <messju at lammfellpuschen dot de> (conversion to compiler function)
* @param string containing var-attribute and value-attribute
* @param Smarty_Compiler
*/
function smarty_compiler_assign($tag_attrs, &$compiler)
{
$_params = $compiler->_parse_attrs($tag_attrs);
if (!isset($_params['var'])) {
$compiler->_syntax_error("assign: missing 'var' parameter", E_USER_WARNING);
return;
}
if (!isset($_params['value'])) {
$compiler->_syntax_error("assign: missing 'value' parameter", E_USER_WARNING);
return;
}
return "\$this->assign({$_params['var']}, {$_params['value']});";
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,122 @@
<?php
//
//
//
// array("element"=>array(array("name" => "test1","id" => "1",
// "element" => array(array("name" => "test1.1","id" => "2"),
// array("name" => "test1.2","id" => "3",
// "element" => array(array("name" => "test1.2.1","id" => "4"),
// array("name" => "test1.2.2","id" => "5")))))));
//
//
// {defun name="recursion" list=$element}
// <ul>
// {if isset($element.name)}<li><a href="{$element.id}">{$element.name}</a></li>{/if}
// {if isset($element.element)}
// {foreach from=$element.element item=element}
// {fun name="recursion" list=$element}
// {/foreach}
// {/if}
// </ul>
// {/defun}
//
//
//
/* create code for a function call */
function smarty_compiler_fun($tag_args, &$compiler) {
$_attrs = $compiler->_parse_attrs($tag_args);
if (!isset($_attrs['name'])) $compiler->_syntax_error("fun: missing name parameter");
$_func_name = $compiler->_dequote($_attrs['name']);
$_func = 'smarty_fun_'.$_func_name;
$_params = 'array(';
$_sep = '';
unset($_attrs['name']);
foreach ($_attrs as $_key=>$_value) {
$_params .= "$_sep'$_key'=>$_value";
$_sep = ',';
}
$_params .= ')';
return "$_func(\$this, $_params); ";
}
$this->register_compiler_function('fun', 'smarty_compiler_fun');
/* create code for a function declaration */
function smarty_compiler_defun($tag_args, &$compiler) {
$attrs = $compiler->_parse_attrs($tag_args);
$func_key = '"' . md5('php-5') . '[[' . md5(uniqid('sucks')) . '";';
array_push($compiler->_tag_stack, array('defun', $attrs, $tag_args, $func_key));
if (!isset($attrs['name'])) $compiler->_syntax_error("defun: missing name parameter");
$func_name = $compiler->_dequote($attrs['name']);
$func = 'smarty_fun_'.$func_name;
return $func_key . "if (!function_exists('$func')) { function $func(&\$this, \$params) { \$_fun_tpl_vars = \$this->_tpl_vars; \$this->assign(\$params); ";
}
/* create code for closing a function definition and calling said function */
function smarty_compiler_defun_close($tag_args, &$compiler) {
list($name, $attrs, $open_tag_args, $func_key) = array_pop($compiler->_tag_stack);
if ($name!='defun') $compiler->_syntax_error("unexpected {/defun}");
return " \$this->_tpl_vars = \$_fun_tpl_vars; }} " . $func_key . smarty_compiler_fun($open_tag_args, $compiler);
}
$this->register_compiler_function('/defun', 'smarty_compiler_defun_close');
/* callback to replace all $this with $smarty */
function smarty_replace_fun($match) {
$tokens = token_get_all('<?php ' . $match[2]);
/* remove trailing <?php */
$open_tag = '';
while ($tokens) {
$token = array_shift($tokens);
if (is_array($token)) {
$open_tag .= $token[1];
} else {
$open_tag .= $token;
}
if ($open_tag == '<?php ') break;
}
/* replace */
for ($i=0, $count=count($tokens); $i<$count; $i++) {
if (is_array($tokens[$i])) {
if ($tokens[$i][0] == T_VARIABLE && $tokens[$i][1] == '$this') {
$tokens[$i] = '$smarty';
} else {
$tokens[$i] = $tokens[$i][1];
}
}
}
return implode('', $tokens);
}
/* postfilter to squeeze the code to make php5 happy */
function smarty_postfilter_defun($source, &$compiler) {
$search = '("' . md5('php-5') . '\[\[[0-9a-f]{32}";)';
if ((double)phpversion()>=5.0) {
/* filter sourcecode. look for func_keys and replace all $this
in-between with $smarty */
while (1) {
$new_source = preg_replace_callback('/' . $search . '(.*)\\1/Us', 'smarty_replace_fun', $source);
if (strcmp($new_source, $source)==0) break;
$source = $new_source;
}
} else {
/* remove func_keys */
$source = preg_replace('/' . $search . '/', '', $source);
}
return $source;
}
$this->register_postfilter('smarty_postfilter_defun');
?>

View File

@@ -0,0 +1,20 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
{assign var="test" value=1}
{while ($test <= 5)}
{assign var="test" value="`$test+1`"}
jo
{endwhile}
*/
function smarty_compiler_endwhile($tag_arg, &$smarty) {
return "}";
}
?>

View File

@@ -0,0 +1,22 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
{assign var="test" value=1}
{while ($test <= 5)}
{assign var="test" value="`$test+1`"}
jo
{endwhile}
*/
function smarty_compiler_while($tag_arg, &$smarty) {
$res = $smarty->_compile_if_tag($tag_arg);
preg_match("/<\?php if (.*): \?>/",$res,$token);
return "while " . $token[1] . " {";
}
?>

View File

@@ -0,0 +1,40 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {assign_debug_info} function plugin
*
* Type: function<br>
* Name: assign_debug_info<br>
* Purpose: assign debug info to the template<br>
* @author Monte Ohrt <monte at ohrt dot com>
* @param array unused in this plugin, this plugin uses {@link Smarty::$_config},
* {@link Smarty::$_tpl_vars} and {@link Smarty::$_smarty_debug_info}
* @param Smarty
*/
function smarty_function_assign_debug_info($params, &$smarty)
{
$assigned_vars = $smarty->_tpl_vars;
ksort($assigned_vars);
if (@is_array($smarty->_config[0])) {
$config_vars = $smarty->_config[0];
ksort($config_vars);
$smarty->assign("_debug_config_keys", array_keys($config_vars));
$smarty->assign("_debug_config_vals", array_values($config_vars));
}
$included_templates = $smarty->_smarty_debug_info;
$smarty->assign("_debug_keys", array_keys($assigned_vars));
$smarty->assign("_debug_vals", array_values($assigned_vars));
$smarty->assign("_debug_tpls", $included_templates);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,25 @@
<?php
function smarty_function_bitwise($params)
{
if (!empty($params['var1']) && !empty($params['var2']) && !empty($params['op']))
{
switch ($params['op'])
{
case '&': return $params['var1'] & $params['var2']; break;
case '|': return $params['var1'] | $params['var2']; break;
case '^': return $params['var1'] ^ $params['var2']; break;
case '~': return ~$params['var1']; break;
case '<<': return $params['var1'] << $params['var2']; break;
case '>>': return $params['var1'] >> $params['var2']; break;
default: return $params['var1'] & $params['var2']; break;
}
}
else
{
return false;
}
}
?>

View File

@@ -0,0 +1,142 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {config_load} function plugin
*
* Type: function<br>
* Name: config_load<br>
* Purpose: load config file vars
* @link http://smarty.php.net/manual/en/language.function.config.load.php {config_load}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author messju mohr <messju at lammfellpuschen dot de> (added use of resources)
* @param array Format:
* <pre>
* array('file' => required config file name,
* 'section' => optional config file section to load
* 'scope' => local/parent/global
* 'global' => overrides scope, setting to parent if true)
* </pre>
* @param Smarty
*/
function smarty_function_config_load($params, &$smarty)
{
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$_debug_start_time = smarty_core_get_microtime($_params, $smarty);
}
$_file = isset($params['file']) ? $smarty->_dequote($params['file']) : null;
$_section = isset($params['section']) ? $smarty->_dequote($params['section']) : null;
$_scope = isset($params['scope']) ? $smarty->_dequote($params['scope']) : 'global';
$_global = isset($params['global']) ? $smarty->_dequote($params['global']) : false;
if (!isset($_file) || strlen($_file) == 0) {
$smarty->trigger_error("missing 'file' attribute in config_load tag", E_USER_ERROR, __FILE__, __LINE__);
}
if (isset($_scope)) {
if ($_scope != 'local' &&
$_scope != 'parent' &&
$_scope != 'global') {
$smarty->trigger_error("invalid 'scope' attribute value", E_USER_ERROR, __FILE__, __LINE__);
}
} else {
if ($_global) {
$_scope = 'parent';
} else {
$_scope = 'local';
}
}
$_params = array('resource_name' => $_file,
'resource_base_path' => $smarty->config_dir,
'get_source' => false);
$smarty->_parse_resource_name($_params);
$_file_path = $_params['resource_type'] . ':' . $_params['resource_name'];
if (isset($_section))
$_compile_file = $smarty->_get_compile_path($_file_path.'|'.$_section);
else
$_compile_file = $smarty->_get_compile_path($_file_path);
if($smarty->force_compile || !file_exists($_compile_file)) {
$_compile = true;
} elseif ($smarty->compile_check) {
$_params = array('resource_name' => $_file,
'resource_base_path' => $smarty->config_dir,
'get_source' => false);
$_compile = $smarty->_fetch_resource_info($_params) &&
$_params['resource_timestamp'] > filemtime($_compile_file);
} else {
$_compile = false;
}
if($_compile) {
// compile config file
if(!is_object($smarty->_conf_obj)) {
require_once SMARTY_DIR . $smarty->config_class . '.class.php';
$smarty->_conf_obj = new $smarty->config_class();
$smarty->_conf_obj->overwrite = $smarty->config_overwrite;
$smarty->_conf_obj->booleanize = $smarty->config_booleanize;
$smarty->_conf_obj->read_hidden = $smarty->config_read_hidden;
$smarty->_conf_obj->fix_newlines = $smarty->config_fix_newlines;
}
$_params = array('resource_name' => $_file,
'resource_base_path' => $smarty->config_dir,
$_params['get_source'] = true);
if (!$smarty->_fetch_resource_info($_params)) {
return;
}
$smarty->_conf_obj->set_file_contents($_file, $_params['source_content']);
$_config_vars = array_merge($smarty->_conf_obj->get($_file),
$smarty->_conf_obj->get($_file, $_section));
if(function_exists('var_export')) {
$_output = '<?php $_config_vars = ' . var_export($_config_vars, true) . '; ?>';
} else {
$_output = '<?php $_config_vars = unserialize(\'' . strtr(serialize($_config_vars),array('\''=>'\\\'', '\\'=>'\\\\')) . '\'); ?>';
}
$_params = (array('compile_path' => $_compile_file, 'compiled_content' => $_output, 'resource_timestamp' => $_params['resource_timestamp']));
require_once(SMARTY_CORE_DIR . 'core.write_compiled_resource.php');
smarty_core_write_compiled_resource($_params, $smarty);
} else {
include($_compile_file);
}
if ($smarty->caching) {
$smarty->_cache_info['config'][$_file] = true;
}
$smarty->_config[0]['vars'] = @array_merge($smarty->_config[0]['vars'], $_config_vars);
$smarty->_config[0]['files'][$_file] = true;
if ($_scope == 'parent') {
$smarty->_config[1]['vars'] = @array_merge($smarty->_config[1]['vars'], $_config_vars);
$smarty->_config[1]['files'][$_file] = true;
} else if ($_scope == 'global') {
for ($i = 1, $for_max = count($smarty->_config); $i < $for_max; $i++) {
$smarty->_config[$i]['vars'] = @array_merge($smarty->_config[$i]['vars'], $_config_vars);
$smarty->_config[$i]['files'][$_file] = true;
}
}
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$smarty->_smarty_debug_info[] = array('type' => 'config',
'filename' => $_file.' ['.$_section.'] '.$_scope,
'depth' => $smarty->_inclusion_depth,
'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time);
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,80 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {counter} function plugin
*
* Type: function<br>
* Name: counter<br>
* Purpose: print out a counter value
* @author Monte Ohrt <monte at ohrt dot com>
* @link http://smarty.php.net/manual/en/language.function.counter.php {counter}
* (Smarty online manual)
* @param array parameters
* @param Smarty
* @return string|null
*/
function smarty_function_counter($params, &$smarty)
{
static $counters = array();
$name = (isset($params['name'])) ? $params['name'] : 'default';
if (!isset($counters[$name])) {
$counters[$name] = array(
'start'=>1,
'skip'=>1,
'direction'=>'up',
'count'=>1
);
}
$counter =& $counters[$name];
if (isset($params['start'])) {
$counter['start'] = $counter['count'] = (int)$params['start'];
}
if (!empty($params['assign'])) {
$counter['assign'] = $params['assign'];
}
if (isset($counter['assign'])) {
$smarty->assign($counter['assign'], $counter['count']);
}
if (isset($params['print'])) {
$print = (bool)$params['print'];
} else {
$print = empty($counter['assign']);
}
if ($print) {
$retval = $counter['count'];
} else {
$retval = null;
}
if (isset($params['skip'])) {
$counter['skip'] = $params['skip'];
}
if (isset($params['direction'])) {
$counter['direction'] = $params['direction'];
}
if ($counter['direction'] == "down")
$counter['count'] -= $counter['skip'];
else
$counter['count'] += $counter['skip'];
return $retval;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,102 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {cycle} function plugin
*
* Type: function<br>
* Name: cycle<br>
* Date: May 3, 2002<br>
* Purpose: cycle through given values<br>
* Input:
* - name = name of cycle (optional)
* - values = comma separated list of values to cycle,
* or an array of values to cycle
* (this can be left out for subsequent calls)
* - reset = boolean - resets given var to true
* - print = boolean - print var or not. default is true
* - advance = boolean - whether or not to advance the cycle
* - delimiter = the value delimiter, default is ","
* - assign = boolean, assigns to template var instead of
* printed.
*
* Examples:<br>
* <pre>
* {cycle values="#eeeeee,#d0d0d0d"}
* {cycle name=row values="one,two,three" reset=true}
* {cycle name=row}
* </pre>
* @link http://smarty.php.net/manual/en/language.function.cycle.php {cycle}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Mark Priatel <mpriatel@rogers.com>
* @author credit to Gerard <gerard@interfold.com>
* @author credit to Jason Sweat <jsweat_php@yahoo.com>
* @version 1.3
* @param array
* @param Smarty
* @return string|null
*/
function smarty_function_cycle($params, &$smarty)
{
static $cycle_vars;
$name = (empty($params['name'])) ? 'default' : $params['name'];
$print = (isset($params['print'])) ? (bool)$params['print'] : true;
$advance = (isset($params['advance'])) ? (bool)$params['advance'] : true;
$reset = (isset($params['reset'])) ? (bool)$params['reset'] : false;
if (!in_array('values', array_keys($params))) {
if(!isset($cycle_vars[$name]['values'])) {
$smarty->trigger_error("cycle: missing 'values' parameter");
return;
}
} else {
if(isset($cycle_vars[$name]['values'])
&& $cycle_vars[$name]['values'] != $params['values'] ) {
$cycle_vars[$name]['index'] = 0;
}
$cycle_vars[$name]['values'] = $params['values'];
}
$cycle_vars[$name]['delimiter'] = (isset($params['delimiter'])) ? $params['delimiter'] : ',';
if(is_array($cycle_vars[$name]['values'])) {
$cycle_array = $cycle_vars[$name]['values'];
} else {
$cycle_array = explode($cycle_vars[$name]['delimiter'],$cycle_vars[$name]['values']);
}
if(!isset($cycle_vars[$name]['index']) || $reset ) {
$cycle_vars[$name]['index'] = 0;
}
if (isset($params['assign'])) {
$print = false;
$smarty->assign($params['assign'], $cycle_array[$cycle_vars[$name]['index']]);
}
if($print) {
$retval = $cycle_array[$cycle_vars[$name]['index']];
} else {
$retval = null;
}
if($advance) {
if ( $cycle_vars[$name]['index'] >= count($cycle_array) -1 ) {
$cycle_vars[$name]['index'] = 0;
} else {
$cycle_vars[$name]['index']++;
}
}
return $retval;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,44 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* Type: function
* Name: date_diff
* Version: 2.0
* Date: June 22, 2008
* Author: Matt DeKok
* Purpose: factor difference between two dates in days, weeks,
* or years
* Input: date1 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd"
* date2 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd" or $smarty.now
* assign = name of variable to assign difference to
* interval = "days" (default), "weeks", "years"
* Examples: {date_diff date1="5/12/2003" date2=$smarty.now interval="weeks"}
* {date_diff date1="5/12/2003" date2="5/10/2008" assign="diff"}{$diff}
* -------------------------------------------------------------
*/
function smarty_function_date_diff($params, &$smarty) {
$date1 = mktime(0,0,0,1,1,2000);
$date2 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$assign = null;
$interval = "days";
extract($params);
$i = 1/60/60/24;
if($interval == "weeks") {
$i = $i/7;
} elseif($interval == "years") {
$i = $i/365.25;
}
$date1 = ((is_string($date1))?strtotime($date1):$date1);
$date2 = ((is_string($date2))?strtotime($date2):$date2);
if($assign != null) {
$smarty->assign($assign,floor(($date2 - $date1)*$i));
} else {
return floor(($date2 - $date1)*$i);
}
}
?>

View File

@@ -0,0 +1,35 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {debug} function plugin
*
* Type: function<br>
* Name: debug<br>
* Date: July 1, 2002<br>
* Purpose: popup debug window
* @link http://smarty.php.net/manual/en/language.function.debug.php {debug}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @version 1.0
* @param array
* @param Smarty
* @return string output from {@link Smarty::_generate_debug_output()}
*/
function smarty_function_debug($params, &$smarty)
{
if (isset($params['output'])) {
$smarty->assign('_smarty_debug_output', $params['output']);
}
require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
return smarty_core_display_debug_console(null, $smarty);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,49 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {eval} function plugin
*
* Type: function<br>
* Name: eval<br>
* Purpose: evaluate a template variable as a template<br>
* @link http://smarty.php.net/manual/en/language.function.eval.php {eval}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
*/
function smarty_function_eval($params, &$smarty)
{
if (!isset($params['var'])) {
$smarty->trigger_error("eval: missing 'var' parameter");
return;
}
if($params['var'] == '') {
return;
}
$smarty->_compile_source('evaluated template', $params['var'], $_var_compiled);
ob_start();
$smarty->_eval('?>' . $_var_compiled);
$_contents = ob_get_contents();
ob_end_clean();
if (!empty($params['assign'])) {
$smarty->assign($params['assign'], $_contents);
} else {
return $_contents;
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,221 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {fetch} plugin
*
* Type: function<br>
* Name: fetch<br>
* Purpose: fetch file, web or ftp data and display results
* @link http://smarty.php.net/manual/en/language.function.fetch.php {fetch}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string|null if the assign parameter is passed, Smarty assigns the
* result to a template variable
*/
function smarty_function_fetch($params, &$smarty)
{
if (empty($params['file'])) {
$smarty->_trigger_fatal_error("[plugin] parameter 'file' cannot be empty");
return;
}
$content = '';
if ($smarty->security && !preg_match('!^(http|ftp)://!i', $params['file'])) {
$_params = array('resource_type' => 'file', 'resource_name' => $params['file']);
require_once(SMARTY_CORE_DIR . 'core.is_secure.php');
if(!smarty_core_is_secure($_params, $smarty)) {
$smarty->_trigger_fatal_error('[plugin] (secure mode) fetch \'' . $params['file'] . '\' is not allowed');
return;
}
// fetch the file
if($fp = @fopen($params['file'],'r')) {
while(!feof($fp)) {
$content .= fgets ($fp,4096);
}
fclose($fp);
} else {
$smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] . '\'');
return;
}
} else {
// not a local file
if(preg_match('!^http://!i',$params['file'])) {
// http fetch
if($uri_parts = parse_url($params['file'])) {
// set defaults
$host = $server_name = $uri_parts['host'];
$timeout = 30;
$accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
$agent = "Smarty Template Engine ".$smarty->_version;
$referer = "";
$uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/';
$uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : '';
$_is_proxy = false;
if(empty($uri_parts['port'])) {
$port = 80;
} else {
$port = $uri_parts['port'];
}
if(!empty($uri_parts['user'])) {
$user = $uri_parts['user'];
}
if(!empty($uri_parts['pass'])) {
$pass = $uri_parts['pass'];
}
// loop through parameters, setup headers
foreach($params as $param_key => $param_value) {
switch($param_key) {
case "file":
case "assign":
case "assign_headers":
break;
case "user":
if(!empty($param_value)) {
$user = $param_value;
}
break;
case "pass":
if(!empty($param_value)) {
$pass = $param_value;
}
break;
case "accept":
if(!empty($param_value)) {
$accept = $param_value;
}
break;
case "header":
if(!empty($param_value)) {
if(!preg_match('![\w\d-]+: .+!',$param_value)) {
$smarty->_trigger_fatal_error("[plugin] invalid header format '".$param_value."'");
return;
} else {
$extra_headers[] = $param_value;
}
}
break;
case "proxy_host":
if(!empty($param_value)) {
$proxy_host = $param_value;
}
break;
case "proxy_port":
if(!preg_match('!\D!', $param_value)) {
$proxy_port = (int) $param_value;
} else {
$smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'");
return;
}
break;
case "agent":
if(!empty($param_value)) {
$agent = $param_value;
}
break;
case "referer":
if(!empty($param_value)) {
$referer = $param_value;
}
break;
case "timeout":
if(!preg_match('!\D!', $param_value)) {
$timeout = (int) $param_value;
} else {
$smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'");
return;
}
break;
default:
$smarty->_trigger_fatal_error("[plugin] unrecognized attribute '".$param_key."'");
return;
}
}
if(!empty($proxy_host) && !empty($proxy_port)) {
$_is_proxy = true;
$fp = fsockopen($proxy_host,$proxy_port,$errno,$errstr,$timeout);
} else {
$fp = fsockopen($server_name,$port,$errno,$errstr,$timeout);
}
if(!$fp) {
$smarty->_trigger_fatal_error("[plugin] unable to fetch: $errstr ($errno)");
return;
} else {
if($_is_proxy) {
fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n");
} else {
fputs($fp, "GET $uri HTTP/1.0\r\n");
}
if(!empty($host)) {
fputs($fp, "Host: $host\r\n");
}
if(!empty($accept)) {
fputs($fp, "Accept: $accept\r\n");
}
if(!empty($agent)) {
fputs($fp, "User-Agent: $agent\r\n");
}
if(!empty($referer)) {
fputs($fp, "Referer: $referer\r\n");
}
if(isset($extra_headers) && is_array($extra_headers)) {
foreach($extra_headers as $curr_header) {
fputs($fp, $curr_header."\r\n");
}
}
if(!empty($user) && !empty($pass)) {
fputs($fp, "Authorization: BASIC ".base64_encode("$user:$pass")."\r\n");
}
fputs($fp, "\r\n");
while(!feof($fp)) {
$content .= fgets($fp,4096);
}
fclose($fp);
$csplit = split("\r\n\r\n",$content,2);
$content = $csplit[1];
if(!empty($params['assign_headers'])) {
$smarty->assign($params['assign_headers'],split("\r\n",$csplit[0]));
}
}
} else {
$smarty->_trigger_fatal_error("[plugin] unable to parse URL, check syntax");
return;
}
} else {
// ftp fetch
if($fp = @fopen($params['file'],'r')) {
while(!feof($fp)) {
$content .= fgets ($fp,4096);
}
fclose($fp);
} else {
$smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] .'\'');
return;
}
}
}
if (!empty($params['assign'])) {
$smarty->assign($params['assign'],$content);
} else {
return $content;
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,143 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_checkboxes} function plugin
*
* File: function.html_checkboxes.php<br>
* Type: function<br>
* Name: html_checkboxes<br>
* Date: 24.Feb.2003<br>
* Purpose: Prints out a list of checkbox input types<br>
* Input:<br>
* - name (optional) - string default "checkbox"
* - values (required) - array
* - options (optional) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or &nbsp;
* - output (optional) - the output next to each checkbox
* - assign (optional) - assign the output as an array to this variable
* Examples:
* <pre>
* {html_checkboxes values=$ids output=$names}
* {html_checkboxes values=$ids name='box' separator='<br>' output=$names}
* {html_checkboxes values=$ids checked=$checked separator='<br>' output=$names}
* </pre>
* @link http://smarty.php.net/manual/en/language.function.html.checkboxes.php {html_checkboxes}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
* @param array
* @param Smarty
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_checkboxes($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
$name = 'checkbox';
$values = null;
$options = null;
$selected = null;
$separator = '';
$labels = true;
$output = null;
$extra = '';
foreach($params as $_key => $_val) {
switch($_key) {
case 'name':
case 'separator':
$$_key = $_val;
break;
case 'labels':
$$_key = (bool)$_val;
break;
case 'options':
$$_key = (array)$_val;
break;
case 'values':
case 'output':
$$_key = array_values((array)$_val);
break;
case 'checked':
case 'selected':
$selected = array_map('strval', array_values((array)$_val));
break;
case 'checkboxes':
$smarty->trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING);
$options = (array)$_val;
break;
case 'assign':
break;
default:
if(!is_array($_val)) {
$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
} else {
$smarty->trigger_error("html_checkboxes: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values))
return ''; /* raise error here? */
settype($selected, 'array');
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key=>$_val)
$_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels);
} else {
foreach ($values as $_i=>$_key) {
$_val = isset($output[$_i]) ? $output[$_i] : '';
$_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels);
}
}
if(!empty($params['assign'])) {
$smarty->assign($params['assign'], $_html_result);
} else {
return implode("\n",$_html_result);
}
}
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels) {
$_output = '';
if ($labels) $_output .= '<label>';
$_output .= '<input type="checkbox" name="'
. smarty_function_escape_special_chars($name) . '[]" value="'
. smarty_function_escape_special_chars($value) . '"';
if (in_array((string)$value, $selected)) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) $_output .= '</label>';
$_output .= $separator;
return $_output;
}
?>

View File

@@ -0,0 +1,142 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_image} function plugin
*
* Type: function<br>
* Name: html_image<br>
* Date: Feb 24, 2003<br>
* Purpose: format HTML tags for the image<br>
* Input:<br>
* - file = file (and path) of image (required)
* - height = image height (optional, default actual height)
* - width = image width (optional, default actual width)
* - basedir = base directory for absolute paths, default
* is environment variable DOCUMENT_ROOT
* - path_prefix = prefix for path output (optional, default empty)
*
* Examples: {html_image file="/images/masthead.gif"}
* Output: <img src="/images/masthead.gif" width=400 height=23>
* @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Duda <duda@big.hu> - wrote first image function
* in repository, helped with lots of functionality
* @version 1.0
* @param array
* @param Smarty
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_image($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
$alt = '';
$file = '';
$height = '';
$width = '';
$extra = '';
$prefix = '';
$suffix = '';
$path_prefix = '';
$server_vars = ($smarty->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
$basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : '';
foreach($params as $_key => $_val) {
switch($_key) {
case 'file':
case 'height':
case 'width':
case 'dpi':
case 'path_prefix':
case 'basedir':
$$_key = $_val;
break;
case 'alt':
if(!is_array($_val)) {
$$_key = smarty_function_escape_special_chars($_val);
} else {
$smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
case 'link':
case 'href':
$prefix = '<a href="' . $_val . '">';
$suffix = '</a>';
break;
default:
if(!is_array($_val)) {
$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
} else {
$smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (empty($file)) {
$smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
return;
}
if (substr($file,0,1) == '/') {
$_image_path = $basedir . $file;
} else {
$_image_path = $file;
}
if(!isset($params['width']) || !isset($params['height'])) {
if(!$_image_data = @getimagesize($_image_path)) {
if(!file_exists($_image_path)) {
$smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
return;
} else if(!is_readable($_image_path)) {
$smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
return;
} else {
$smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
return;
}
}
if ($smarty->security &&
($_params = array('resource_type' => 'file', 'resource_name' => $_image_path)) &&
(require_once(SMARTY_CORE_DIR . 'core.is_secure.php')) &&
(!smarty_core_is_secure($_params, $smarty)) ) {
$smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE);
}
if(!isset($params['width'])) {
$width = $_image_data[0];
}
if(!isset($params['height'])) {
$height = $_image_data[1];
}
}
if(isset($params['dpi'])) {
if(strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) {
$dpi_default = 72;
} else {
$dpi_default = 96;
}
$_resize = $dpi_default/$params['dpi'];
$width = round($width * $_resize);
$height = round($height * $_resize);
}
return $prefix . '<img src="'.$path_prefix.$file.'" alt="'.$alt.'" width="'.$width.'" height="'.$height.'"'.$extra.' />' . $suffix;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,122 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_options} function plugin
*
* Type: function<br>
* Name: html_options<br>
* Input:<br>
* - name (optional) - string default "select"
* - values (required if no options supplied) - array
* - options (required if no values supplied) - associative array
* - selected (optional) - string default not set
* - output (required if not options supplied) - array
* Purpose: Prints the list of <option> tags generated from
* the passed parameters
* @link http://smarty.php.net/manual/en/language.function.html.options.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_options($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
$name = null;
$values = null;
$options = null;
$selected = array();
$output = null;
$extra = '';
foreach($params as $_key => $_val) {
switch($_key) {
case 'name':
$$_key = (string)$_val;
break;
case 'options':
$$_key = (array)$_val;
break;
case 'values':
case 'output':
$$_key = array_values((array)$_val);
break;
case 'selected':
$$_key = array_map('strval', array_values((array)$_val));
break;
default:
if(!is_array($_val)) {
$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
} else {
$smarty->trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values))
return ''; /* raise error here? */
$_html_result = '';
if (isset($options)) {
foreach ($options as $_key=>$_val)
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected);
} else {
foreach ($values as $_i=>$_key) {
$_val = isset($output[$_i]) ? $output[$_i] : '';
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected);
}
}
if(!empty($name)) {
$_html_result = '<select name="' . $name . '"' . $extra . '>' . "\n" . $_html_result . '</select>' . "\n";
}
return $_html_result;
}
function smarty_function_html_options_optoutput($key, $value, $selected) {
if(!is_array($value)) {
$_html_result = '<option label="' . smarty_function_escape_special_chars($value) . '" value="' .
smarty_function_escape_special_chars($key) . '"';
if (in_array((string)$key, $selected))
$_html_result .= ' selected="selected"';
$_html_result .= '>' . smarty_function_escape_special_chars($value) . '</option>' . "\n";
} else {
$_html_result = smarty_function_html_options_optgroup($key, $value, $selected);
}
return $_html_result;
}
function smarty_function_html_options_optgroup($key, $values, $selected) {
$optgroup_html = '<optgroup label="' . smarty_function_escape_special_chars($key) . '">' . "\n";
foreach ($values as $key => $value) {
$optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected);
}
$optgroup_html .= "</optgroup>\n";
return $optgroup_html;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,156 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_radios} function plugin
*
* File: function.html_radios.php<br>
* Type: function<br>
* Name: html_radios<br>
* Date: 24.Feb.2003<br>
* Purpose: Prints out a list of radio input types<br>
* Input:<br>
* - name (optional) - string default "radio"
* - values (required) - array
* - options (optional) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or &nbsp;
* - output (optional) - the output next to each radio button
* - assign (optional) - assign the output as an array to this variable
* Examples:
* <pre>
* {html_radios values=$ids output=$names}
* {html_radios values=$ids name='box' separator='<br>' output=$names}
* {html_radios values=$ids checked=$checked separator='<br>' output=$names}
* </pre>
* @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
* @param array
* @param Smarty
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_radios($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
$name = 'radio';
$values = null;
$options = null;
$selected = null;
$separator = '';
$labels = true;
$label_ids = false;
$output = null;
$extra = '';
foreach($params as $_key => $_val) {
switch($_key) {
case 'name':
case 'separator':
$$_key = (string)$_val;
break;
case 'checked':
case 'selected':
if(is_array($_val)) {
$smarty->trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING);
} else {
$selected = (string)$_val;
}
break;
case 'labels':
case 'label_ids':
$$_key = (bool)$_val;
break;
case 'options':
$$_key = (array)$_val;
break;
case 'values':
case 'output':
$$_key = array_values((array)$_val);
break;
case 'radios':
$smarty->trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead', E_USER_WARNING);
$options = (array)$_val;
break;
case 'assign':
break;
default:
if(!is_array($_val)) {
$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
} else {
$smarty->trigger_error("html_radios: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values))
return ''; /* raise error here? */
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key=>$_val)
$_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids);
} else {
foreach ($values as $_i=>$_key) {
$_val = isset($output[$_i]) ? $output[$_i] : '';
$_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids);
}
}
if(!empty($params['assign'])) {
$smarty->assign($params['assign'], $_html_result);
} else {
return implode("\n",$_html_result);
}
}
function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids) {
$_output = '';
if ($labels) {
if($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!', '_', $name . '_' . $value));
$_output .= '<label for="' . $_id . '">';
} else {
$_output .= '<label>';
}
}
$_output .= '<input type="radio" name="'
. smarty_function_escape_special_chars($name) . '" value="'
. smarty_function_escape_special_chars($value) . '"';
if ($labels && $label_ids) $_output .= ' id="' . $_id . '"';
if ((string)$value==$selected) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) $_output .= '</label>';
$_output .= $separator;
return $_output;
}
?>

View File

@@ -0,0 +1,331 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_select_date} plugin
*
* Type: function<br>
* Name: html_select_date<br>
* Purpose: Prints the dropdowns for date selection.
*
* ChangeLog:<br>
* - 1.0 initial release
* - 1.1 added support for +/- N syntax for begin
* and end year values. (Monte)
* - 1.2 added support for yyyy-mm-dd syntax for
* time value. (Jan Rosier)
* - 1.3 added support for choosing format for
* month values (Gary Loescher)
* - 1.3.1 added support for choosing format for
* day values (Marcus Bointon)
* - 1.3.2 support negative timestamps, force year
* dropdown to include given date unless explicitly set (Monte)
* - 1.3.4 fix behaviour of 0000-00-00 00:00:00 dates to match that
* of 0000-00-00 dates (cybot, boots)
* @link http://smarty.php.net/manual/en/language.function.html.select.date.php {html_select_date}
* (Smarty online manual)
* @version 1.3.4
* @author Andrei Zmievski
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_html_select_date($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
require_once $smarty->_get_plugin_filepath('shared','make_timestamp');
require_once $smarty->_get_plugin_filepath('function','html_options');
/* Default values. */
$prefix = "Date_";
$start_year = strftime("%Y");
$end_year = $start_year;
$display_days = true;
$display_months = true;
$display_years = true;
$month_format = "%B";
/* Write months as numbers by default GL */
$month_value_format = "%m";
$day_format = "%02d";
/* Write day values using this format MB */
$day_value_format = "%d";
$year_as_text = false;
/* Display years in reverse order? Ie. 2000,1999,.... */
$reverse_years = false;
/* Should the select boxes be part of an array when returned from PHP?
e.g. setting it to "birthday", would create "birthday[Day]",
"birthday[Month]" & "birthday[Year]". Can be combined with prefix */
$field_array = null;
/* <select size>'s of the different <select> tags.
If not set, uses default dropdown. */
$day_size = null;
$month_size = null;
$year_size = null;
/* Unparsed attributes common to *ALL* the <select>/<input> tags.
An example might be in the template: all_extra ='class ="foo"'. */
$all_extra = null;
/* Separate attributes for the tags. */
$day_extra = null;
$month_extra = null;
$year_extra = null;
/* Order in which to display the fields.
"D" -> day, "M" -> month, "Y" -> year. */
$field_order = 'MDY';
/* String printed between the different fields. */
$field_separator = "\n";
$time = time();
$all_empty = null;
$day_empty = null;
$month_empty = null;
$year_empty = null;
$extra_attrs = '';
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'prefix':
case 'time':
case 'start_year':
case 'end_year':
case 'month_format':
case 'day_format':
case 'day_value_format':
case 'field_array':
case 'day_size':
case 'month_size':
case 'year_size':
case 'all_extra':
case 'day_extra':
case 'month_extra':
case 'year_extra':
case 'field_order':
case 'field_separator':
case 'month_value_format':
case 'month_empty':
case 'day_empty':
case 'year_empty':
$$_key = (string)$_value;
break;
case 'all_empty':
$$_key = (string)$_value;
$day_empty = $month_empty = $year_empty = $all_empty;
break;
case 'display_days':
case 'display_months':
case 'display_years':
case 'year_as_text':
case 'reverse_years':
$$_key = (bool)$_value;
break;
default:
if(!is_array($_value)) {
$extra_attrs .= ' '.$_key.'="'.smarty_function_escape_special_chars($_value).'"';
} else {
$smarty->trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (preg_match('!^-\d+$!', $time)) {
// negative timestamp, use date()
$time = date('Y-m-d', $time);
}
// If $time is not in format yyyy-mm-dd
if (preg_match('/^(\d{0,4}-\d{0,2}-\d{0,2})/', $time, $found)) {
$time = $found[1];
} else {
// use smarty_make_timestamp to get an unix timestamp and
// strftime to make yyyy-mm-dd
$time = strftime('%Y-%m-%d', smarty_make_timestamp($time));
}
// Now split this in pieces, which later can be used to set the select
$time = explode("-", $time);
// make syntax "+N" or "-N" work with start_year and end_year
if (preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match)) {
if ($match[1] == '+') {
$end_year = strftime('%Y') + $match[2];
} else {
$end_year = strftime('%Y') - $match[2];
}
}
if (preg_match('!^(\+|\-)\s*(\d+)$!', $start_year, $match)) {
if ($match[1] == '+') {
$start_year = strftime('%Y') + $match[2];
} else {
$start_year = strftime('%Y') - $match[2];
}
}
if (strlen($time[0]) > 0) {
if ($start_year > $time[0] && !isset($params['start_year'])) {
// force start year to include given date if not explicitly set
$start_year = $time[0];
}
if($end_year < $time[0] && !isset($params['end_year'])) {
// force end year to include given date if not explicitly set
$end_year = $time[0];
}
}
$field_order = strtoupper($field_order);
$html_result = $month_result = $day_result = $year_result = "";
$field_separator_count = -1;
if ($display_months) {
$field_separator_count++;
$month_names = array();
$month_values = array();
if(isset($month_empty)) {
$month_names[''] = $month_empty;
$month_values[''] = '';
}
for ($i = 1; $i <= 12; $i++) {
$month_names[$i] = strftime($month_format, mktime(0, 0, 0, $i, 1, 2000));
$month_values[$i] = strftime($month_value_format, mktime(0, 0, 0, $i, 1, 2000));
}
$month_result .= '<select name=';
if (null !== $field_array){
$month_result .= '"' . $field_array . '[' . $prefix . 'Month]"';
} else {
$month_result .= '"' . $prefix . 'Month"';
}
if (null !== $month_size){
$month_result .= ' size="' . $month_size . '"';
}
if (null !== $month_extra){
$month_result .= ' ' . $month_extra;
}
if (null !== $all_extra){
$month_result .= ' ' . $all_extra;
}
$month_result .= $extra_attrs . '>'."\n";
$month_result .= smarty_function_html_options(array('output' => $month_names,
'values' => $month_values,
'selected' => (int)$time[1] ? strftime($month_value_format, mktime(0, 0, 0, (int)$time[1], 1, 2000)) : '',
'print_result' => false),
$smarty);
$month_result .= '</select>';
}
if ($display_days) {
$field_separator_count++;
$days = array();
if (isset($day_empty)) {
$days[''] = $day_empty;
$day_values[''] = '';
}
for ($i = 1; $i <= 31; $i++) {
$days[] = sprintf($day_format, $i);
$day_values[] = sprintf($day_value_format, $i);
}
$day_result .= '<select name=';
if (null !== $field_array){
$day_result .= '"' . $field_array . '[' . $prefix . 'Day]"';
} else {
$day_result .= '"' . $prefix . 'Day"';
}
if (null !== $day_size){
$day_result .= ' size="' . $day_size . '"';
}
if (null !== $all_extra){
$day_result .= ' ' . $all_extra;
}
if (null !== $day_extra){
$day_result .= ' ' . $day_extra;
}
$day_result .= $extra_attrs . '>'."\n";
$day_result .= smarty_function_html_options(array('output' => $days,
'values' => $day_values,
'selected' => $time[2],
'print_result' => false),
$smarty);
$day_result .= '</select>';
}
if ($display_years) {
$field_separator_count++;
if (null !== $field_array){
$year_name = $field_array . '[' . $prefix . 'Year]';
} else {
$year_name = $prefix . 'Year';
}
if ($year_as_text) {
$year_result .= '<input type="text" name="' . $year_name . '" value="' . $time[0] . '" size="4" maxlength="4"';
if (null !== $all_extra){
$year_result .= ' ' . $all_extra;
}
if (null !== $year_extra){
$year_result .= ' ' . $year_extra;
}
$year_result .= ' />';
} else {
$years = range((int)$start_year, (int)$end_year);
if ($reverse_years) {
rsort($years, SORT_NUMERIC);
} else {
sort($years, SORT_NUMERIC);
}
$yearvals = $years;
if(isset($year_empty)) {
array_unshift($years, $year_empty);
array_unshift($yearvals, '');
}
$year_result .= '<select name="' . $year_name . '"';
if (null !== $year_size){
$year_result .= ' size="' . $year_size . '"';
}
if (null !== $all_extra){
$year_result .= ' ' . $all_extra;
}
if (null !== $year_extra){
$year_result .= ' ' . $year_extra;
}
$year_result .= $extra_attrs . '>'."\n";
$year_result .= smarty_function_html_options(array('output' => $years,
'values' => $yearvals,
'selected' => $time[0],
'print_result' => false),
$smarty);
$year_result .= '</select>';
}
}
// Loop thru the field_order field
for ($i = 0; $i <= 2; $i++){
$c = substr($field_order, $i, 1);
switch ($c){
case 'D':
$html_result .= $day_result;
break;
case 'M':
$html_result .= $month_result;
break;
case 'Y':
$html_result .= $year_result;
break;
}
// Add the field seperator
if($i < $field_separator_count) {
$html_result .= $field_separator;
}
}
return $html_result;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,194 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_select_time} function plugin
*
* Type: function<br>
* Name: html_select_time<br>
* Purpose: Prints the dropdowns for time selection
* @link http://smarty.php.net/manual/en/language.function.html.select.time.php {html_select_time}
* (Smarty online manual)
* @author Roberto Berto <roberto@berto.net>
* @credits Monte Ohrt <monte AT ohrt DOT com>
* @param array
* @param Smarty
* @return string
* @uses smarty_make_timestamp()
*/
function smarty_function_html_select_time($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','make_timestamp');
require_once $smarty->_get_plugin_filepath('function','html_options');
/* Default values. */
$prefix = "Time_";
$time = time();
$display_hours = true;
$display_minutes = true;
$display_seconds = true;
$display_meridian = true;
$use_24_hours = true;
$minute_interval = 1;
$second_interval = 1;
/* Should the select boxes be part of an array when returned from PHP?
e.g. setting it to "birthday", would create "birthday[Hour]",
"birthday[Minute]", "birthday[Seconds]" & "birthday[Meridian]".
Can be combined with prefix. */
$field_array = null;
$all_extra = null;
$hour_extra = null;
$minute_extra = null;
$second_extra = null;
$meridian_extra = null;
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'prefix':
case 'time':
case 'field_array':
case 'all_extra':
case 'hour_extra':
case 'minute_extra':
case 'second_extra':
case 'meridian_extra':
$$_key = (string)$_value;
break;
case 'display_hours':
case 'display_minutes':
case 'display_seconds':
case 'display_meridian':
case 'use_24_hours':
$$_key = (bool)$_value;
break;
case 'minute_interval':
case 'second_interval':
$$_key = (int)$_value;
break;
default:
$smarty->trigger_error("[html_select_time] unknown parameter $_key", E_USER_WARNING);
}
}
$time = smarty_make_timestamp($time);
$html_result = '';
if ($display_hours) {
$hours = $use_24_hours ? range(0, 23) : range(1, 12);
$hour_fmt = $use_24_hours ? '%H' : '%I';
for ($i = 0, $for_max = count($hours); $i < $for_max; $i++)
$hours[$i] = sprintf('%02d', $hours[$i]);
$html_result .= '<select name=';
if (null !== $field_array) {
$html_result .= '"' . $field_array . '[' . $prefix . 'Hour]"';
} else {
$html_result .= '"' . $prefix . 'Hour"';
}
if (null !== $hour_extra){
$html_result .= ' ' . $hour_extra;
}
if (null !== $all_extra){
$html_result .= ' ' . $all_extra;
}
$html_result .= '>'."\n";
$html_result .= smarty_function_html_options(array('output' => $hours,
'values' => $hours,
'selected' => strftime($hour_fmt, $time),
'print_result' => false),
$smarty);
$html_result .= "</select>\n";
}
if ($display_minutes) {
$all_minutes = range(0, 59);
for ($i = 0, $for_max = count($all_minutes); $i < $for_max; $i+= $minute_interval)
$minutes[] = sprintf('%02d', $all_minutes[$i]);
$selected = intval(floor(strftime('%M', $time) / $minute_interval) * $minute_interval);
$html_result .= '<select name=';
if (null !== $field_array) {
$html_result .= '"' . $field_array . '[' . $prefix . 'Minute]"';
} else {
$html_result .= '"' . $prefix . 'Minute"';
}
if (null !== $minute_extra){
$html_result .= ' ' . $minute_extra;
}
if (null !== $all_extra){
$html_result .= ' ' . $all_extra;
}
$html_result .= '>'."\n";
$html_result .= smarty_function_html_options(array('output' => $minutes,
'values' => $minutes,
'selected' => $selected,
'print_result' => false),
$smarty);
$html_result .= "</select>\n";
}
if ($display_seconds) {
$all_seconds = range(0, 59);
for ($i = 0, $for_max = count($all_seconds); $i < $for_max; $i+= $second_interval)
$seconds[] = sprintf('%02d', $all_seconds[$i]);
$selected = intval(floor(strftime('%S', $time) / $second_interval) * $second_interval);
$html_result .= '<select name=';
if (null !== $field_array) {
$html_result .= '"' . $field_array . '[' . $prefix . 'Second]"';
} else {
$html_result .= '"' . $prefix . 'Second"';
}
if (null !== $second_extra){
$html_result .= ' ' . $second_extra;
}
if (null !== $all_extra){
$html_result .= ' ' . $all_extra;
}
$html_result .= '>'."\n";
$html_result .= smarty_function_html_options(array('output' => $seconds,
'values' => $seconds,
'selected' => $selected,
'print_result' => false),
$smarty);
$html_result .= "</select>\n";
}
if ($display_meridian && !$use_24_hours) {
$html_result .= '<select name=';
if (null !== $field_array) {
$html_result .= '"' . $field_array . '[' . $prefix . 'Meridian]"';
} else {
$html_result .= '"' . $prefix . 'Meridian"';
}
if (null !== $meridian_extra){
$html_result .= ' ' . $meridian_extra;
}
if (null !== $all_extra){
$html_result .= ' ' . $all_extra;
}
$html_result .= '>'."\n";
$html_result .= smarty_function_html_options(array('output' => array('AM', 'PM'),
'values' => array('am', 'pm'),
'selected' => strtolower(strftime('%p', $time)),
'print_result' => false),
$smarty);
$html_result .= "</select>\n";
}
return $html_result;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,177 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_table} function plugin
*
* Type: function<br>
* Name: html_table<br>
* Date: Feb 17, 2003<br>
* Purpose: make an html table from an array of data<br>
* Input:<br>
* - loop = array to loop through
* - cols = number of columns, comma separated list of column names
* or array of column names
* - rows = number of rows
* - table_attr = table attributes
* - th_attr = table heading attributes (arrays are cycled)
* - tr_attr = table row attributes (arrays are cycled)
* - td_attr = table cell attributes (arrays are cycled)
* - trailpad = value to pad trailing cells with
* - caption = text for caption element
* - vdir = vertical direction (default: "down", means top-to-bottom)
* - hdir = horizontal direction (default: "right", means left-to-right)
* - inner = inner loop (default "cols": print $loop line by line,
* $loop will be printed column by column otherwise)
*
*
* Examples:
* <pre>
* {table loop=$data}
* {table loop=$data cols=4 tr_attr='"bgcolor=red"'}
* {table loop=$data cols="first,second,third" tr_attr=$colors}
* </pre>
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Messju Mohr <messju at lammfellpuschen dot de>
* @author credit to boots <boots dot smarty at yahoo dot com>
* @version 1.1
* @link http://smarty.php.net/manual/en/language.function.html.table.php {html_table}
* (Smarty online manual)
* @param array
* @param Smarty
* @return string
*/
function smarty_function_html_table($params, &$smarty)
{
$table_attr = 'border="1"';
$tr_attr = '';
$th_attr = '';
$td_attr = '';
$cols = $cols_count = 3;
$rows = 3;
$trailpad = '&nbsp;';
$vdir = 'down';
$hdir = 'right';
$inner = 'cols';
$caption = '';
if (!isset($params['loop'])) {
$smarty->trigger_error("html_table: missing 'loop' parameter");
return;
}
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'loop':
$$_key = (array)$_value;
break;
case 'cols':
if (is_array($_value) && !empty($_value)) {
$cols = $_value;
$cols_count = count($_value);
} elseif (!is_numeric($_value) && is_string($_value) && !empty($_value)) {
$cols = explode(',', $_value);
$cols_count = count($cols);
} elseif (!empty($_value)) {
$cols_count = (int)$_value;
} else {
$cols_count = $cols;
}
break;
case 'rows':
$$_key = (int)$_value;
break;
case 'table_attr':
case 'trailpad':
case 'hdir':
case 'vdir':
case 'inner':
case 'caption':
$$_key = (string)$_value;
break;
case 'tr_attr':
case 'td_attr':
case 'th_attr':
$$_key = $_value;
break;
}
}
$loop_count = count($loop);
if (empty($params['rows'])) {
/* no rows specified */
$rows = ceil($loop_count/$cols_count);
} elseif (empty($params['cols'])) {
if (!empty($params['rows'])) {
/* no cols specified, but rows */
$cols_count = ceil($loop_count/$rows);
}
}
$output = "<table $table_attr>\n";
if (!empty($caption)) {
$output .= '<caption>' . $caption . "</caption>\n";
}
if (is_array($cols)) {
$cols = ($hdir == 'right') ? $cols : array_reverse($cols);
$output .= "<thead><tr>\n";
for ($r=0; $r<$cols_count; $r++) {
$output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>';
$output .= $cols[$r];
$output .= "</th>\n";
}
$output .= "</tr></thead>\n";
}
$output .= "<tbody>\n";
for ($r=0; $r<$rows; $r++) {
$output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n";
$rx = ($vdir == 'down') ? $r*$cols_count : ($rows-1-$r)*$cols_count;
for ($c=0; $c<$cols_count; $c++) {
$x = ($hdir == 'right') ? $rx+$c : $rx+$cols_count-1-$c;
if ($inner!='cols') {
/* shuffle x to loop over rows*/
$x = floor($x/$cols_count) + ($x%$cols_count)*$rows;
}
if ($x<$loop_count) {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[$x] . "</td>\n";
} else {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">$trailpad</td>\n";
}
}
$output .= "</tr>\n";
}
$output .= "</tbody>\n";
$output .= "</table>\n";
return $output;
}
function smarty_function_html_table_cycle($name, $var, $no) {
if(!is_array($var)) {
$ret = $var;
} else {
$ret = $var[$no % count($var)];
}
return ($ret) ? ' '.$ret : '';
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,165 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {mailto} function plugin
*
* Type: function<br>
* Name: mailto<br>
* Date: May 21, 2002
* Purpose: automate mailto address link creation, and optionally
* encode them.<br>
* Input:<br>
* - address = e-mail address
* - text = (optional) text to display, default is address
* - encode = (optional) can be one of:
* * none : no encoding (default)
* * javascript : encode with javascript
* * javascript_charcode : encode with javascript charcode
* * hex : encode with hexidecimal (no javascript)
* - cc = (optional) address(es) to carbon copy
* - bcc = (optional) address(es) to blind carbon copy
* - subject = (optional) e-mail subject
* - newsgroups = (optional) newsgroup(s) to post to
* - followupto = (optional) address(es) to follow up to
* - extra = (optional) extra tags for the href link
*
* Examples:
* <pre>
* {mailto address="me@domain.com"}
* {mailto address="me@domain.com" encode="javascript"}
* {mailto address="me@domain.com" encode="hex"}
* {mailto address="me@domain.com" subject="Hello to you!"}
* {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"}
* {mailto address="me@domain.com" extra='class="mailto"'}
* </pre>
* @link http://smarty.php.net/manual/en/language.function.mailto.php {mailto}
* (Smarty online manual)
* @version 1.2
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Jason Sweat (added cc, bcc and subject functionality)
* @param array
* @param Smarty
* @return string
*/
function smarty_function_mailto($params, &$smarty)
{
$extra = '';
if (empty($params['address'])) {
$smarty->trigger_error("mailto: missing 'address' parameter");
return;
} else {
$address = $params['address'];
}
$text = $address;
// netscape and mozilla do not decode %40 (@) in BCC field (bug?)
// so, don't encode it.
$search = array('%40', '%2C');
$replace = array('@', ',');
$mail_parms = array();
foreach ($params as $var=>$value) {
switch ($var) {
case 'cc':
case 'bcc':
case 'followupto':
if (!empty($value))
$mail_parms[] = $var.'='.str_replace($search,$replace,rawurlencode($value));
break;
case 'subject':
case 'newsgroups':
$mail_parms[] = $var.'='.rawurlencode($value);
break;
case 'extra':
case 'text':
$$var = $value;
default:
}
}
$mail_parm_vals = '';
for ($i=0; $i<count($mail_parms); $i++) {
$mail_parm_vals .= (0==$i) ? '?' : '&';
$mail_parm_vals .= $mail_parms[$i];
}
$address .= $mail_parm_vals;
$encode = (empty($params['encode'])) ? 'none' : $params['encode'];
if (!in_array($encode,array('javascript','javascript_charcode','hex','none')) ) {
$smarty->trigger_error("mailto: 'encode' parameter must be none, javascript or hex");
return;
}
if ($encode == 'javascript' ) {
$string = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>\');';
$js_encode = '';
for ($x=0; $x < strlen($string); $x++) {
$js_encode .= '%' . bin2hex($string[$x]);
}
return '<script type="text/javascript">eval(unescape(\''.$js_encode.'\'))</script>';
} elseif ($encode == 'javascript_charcode' ) {
$string = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
for($x = 0, $y = strlen($string); $x < $y; $x++ ) {
$ord[] = ord($string[$x]);
}
$_ret = "<script type=\"text/javascript\" language=\"javascript\">\n";
$_ret .= "<!--\n";
$_ret .= "{document.write(String.fromCharCode(";
$_ret .= implode(',',$ord);
$_ret .= "))";
$_ret .= "}\n";
$_ret .= "//-->\n";
$_ret .= "</script>\n";
return $_ret;
} elseif ($encode == 'hex') {
preg_match('!^(.*)(\?.*)$!',$address,$match);
if(!empty($match[2])) {
$smarty->trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.");
return;
}
$address_encode = '';
for ($x=0; $x < strlen($address); $x++) {
if(preg_match('!\w!',$address[$x])) {
$address_encode .= '%' . bin2hex($address[$x]);
} else {
$address_encode .= $address[$x];
}
}
$text_encode = '';
for ($x=0; $x < strlen($text); $x++) {
$text_encode .= '&#x' . bin2hex($text[$x]).';';
}
$mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
return '<a href="'.$mailto.$address_encode.'" '.$extra.'>'.$text_encode.'</a>';
} else {
// no encoding
return '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,84 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {math} function plugin
*
* Type: function<br>
* Name: math<br>
* Purpose: handle math computations in template<br>
* @link http://smarty.php.net/manual/en/language.function.math.php {math}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_math($params, &$smarty)
{
// be sure equation parameter is present
if (empty($params['equation'])) {
$smarty->trigger_error("math: missing equation parameter");
return;
}
$equation = $params['equation'];
// make sure parenthesis are balanced
if (substr_count($equation,"(") != substr_count($equation,")")) {
$smarty->trigger_error("math: unbalanced parenthesis");
return;
}
// match all vars in equation, make sure all are passed
preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match);
$allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
foreach($match[1] as $curr_var) {
if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
$smarty->trigger_error("math: function call $curr_var not allowed");
return;
}
}
foreach($params as $key => $val) {
if ($key != "equation" && $key != "format" && $key != "assign") {
// make sure value is not empty
if (strlen($val)==0) {
$smarty->trigger_error("math: parameter $key is empty");
return;
}
if (!is_numeric($val)) {
$smarty->trigger_error("math: parameter $key: is not numeric");
return;
}
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
}
}
eval("\$smarty_math_result = ".$equation.";");
if (empty($params['format'])) {
if (empty($params['assign'])) {
return $smarty_math_result;
} else {
$smarty->assign($params['assign'],$smarty_math_result);
}
} else {
if (empty($params['assign'])){
printf($params['format'],$smarty_math_result);
} else {
$smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
}
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,119 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {popup} function plugin
*
* Type: function<br>
* Name: popup<br>
* Purpose: make text pop up in windows via overlib
* @link http://smarty.php.net/manual/en/language.function.popup.php {popup}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_popup($params, &$smarty)
{
$append = '';
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'text':
case 'trigger':
case 'function':
case 'inarray':
$$_key = (string)$_value;
if ($_key == 'function' || $_key == 'inarray')
$append .= ',' . strtoupper($_key) . ",'$_value'";
break;
case 'caption':
case 'closetext':
case 'status':
$append .= ',' . strtoupper($_key) . ",'" . str_replace("'","\'",$_value) . "'";
break;
case 'fgcolor':
case 'bgcolor':
case 'textcolor':
case 'capcolor':
case 'closecolor':
case 'textfont':
case 'captionfont':
case 'closefont':
case 'fgbackground':
case 'bgbackground':
case 'caparray':
case 'capicon':
case 'background':
case 'frame':
$append .= ',' . strtoupper($_key) . ",'$_value'";
break;
case 'textsize':
case 'captionsize':
case 'closesize':
case 'width':
case 'height':
case 'border':
case 'offsetx':
case 'offsety':
case 'snapx':
case 'snapy':
case 'fixx':
case 'fixy':
case 'padx':
case 'pady':
case 'timeout':
case 'delay':
$append .= ',' . strtoupper($_key) . ",$_value";
break;
case 'sticky':
case 'left':
case 'right':
case 'center':
case 'above':
case 'below':
case 'noclose':
case 'autostatus':
case 'autostatuscap':
case 'fullhtml':
case 'hauto':
case 'vauto':
case 'mouseoff':
case 'followmouse':
case 'closeclick':
if ($_value) $append .= ',' . strtoupper($_key);
break;
default:
$smarty->trigger_error("[popup] unknown parameter $_key", E_USER_WARNING);
}
}
if (empty($text) && !isset($inarray) && empty($function)) {
$smarty->trigger_error("overlib: attribute 'text' or 'inarray' or 'function' required");
return false;
}
if (empty($trigger)) { $trigger = "onmouseover"; }
$retval = $trigger . '="return overlib(\''.preg_replace(array("!'!","![\r\n]!"),array("\'",'\r'),$text).'\'';
$retval .= $append . ');"';
if ($trigger == 'onmouseover')
$retval .= ' onmouseout="nd();"';
return $retval;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,40 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {popup_init} function plugin
*
* Type: function<br>
* Name: popup_init<br>
* Purpose: initialize overlib
* @link http://smarty.php.net/manual/en/language.function.popup.init.php {popup_init}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_popup_init($params, &$smarty)
{
$zindex = 1000;
if (!empty($params['zindex'])) {
$zindex = $params['zindex'];
}
if (!empty($params['src'])) {
return '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:'.$zindex.';"></div>' . "\n"
. '<script type="text/javascript" language="JavaScript" src="'.$params['src'].'"></script>' . "\n";
} else {
$smarty->trigger_error("popup_init: missing src parameter");
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,43 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty capitalize modifier plugin
*
* Type: modifier<br>
* Name: capitalize<br>
* Purpose: capitalize words in the string
* @link http://smarty.php.net/manual/en/language.modifiers.php#LANGUAGE.MODIFIER.CAPITALIZE
* capitalize (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return string
*/
function smarty_modifier_capitalize($string, $uc_digits = false)
{
smarty_modifier_capitalize_ucfirst(null, $uc_digits);
return preg_replace_callback('!\'?\b\w(\w|\')*\b!', 'smarty_modifier_capitalize_ucfirst', $string);
}
function smarty_modifier_capitalize_ucfirst($string, $uc_digits = null)
{
static $_uc_digits = false;
if(isset($uc_digits)) {
$_uc_digits = $uc_digits;
return;
}
if(substr($string[0],0,1) != "'" && !preg_match("!\d!",$string[0]) || $_uc_digits)
return ucfirst($string[0]);
else
return $string[0];
}
?>

View File

@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty cat modifier plugin
*
* Type: modifier<br>
* Name: cat<br>
* Date: Feb 24, 2003
* Purpose: catenate a value to a variable
* Input: string to catenate
* Example: {$var|cat:"foo"}
* @link http://smarty.php.net/manual/en/language.modifier.cat.php cat
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @version 1.0
* @param string
* @param string
* @return string
*/
function smarty_modifier_cat($string, $cat)
{
return $string . $cat;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,32 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty count_characters modifier plugin
*
* Type: modifier<br>
* Name: count_characteres<br>
* Purpose: count the number of characters in a text
* @link http://smarty.php.net/manual/en/language.modifier.count.characters.php
* count_characters (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param boolean include whitespace in the character count
* @return integer
*/
function smarty_modifier_count_characters($string, $include_spaces = false)
{
if ($include_spaces)
return(strlen($string));
return preg_match_all("/[^\s]/",$string, $match);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty count_paragraphs modifier plugin
*
* Type: modifier<br>
* Name: count_paragraphs<br>
* Purpose: count the number of paragraphs in a text
* @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php
* count_paragraphs (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return integer
*/
function smarty_modifier_count_paragraphs($string)
{
// count \r or \n characters
return count(preg_split('/[\r\n]+/', $string));
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty count_sentences modifier plugin
*
* Type: modifier<br>
* Name: count_sentences
* Purpose: count the number of sentences in a text
* @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php
* count_sentences (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return integer
*/
function smarty_modifier_count_sentences($string)
{
// find periods with a word before but not after.
return preg_match_all('/[^\s]\.(?!\w)/', $string, $match);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty count_words modifier plugin
*
* Type: modifier<br>
* Name: count_words<br>
* Purpose: count the number of words in a text
* @link http://smarty.php.net/manual/en/language.modifier.count.words.php
* count_words (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return integer
*/
function smarty_modifier_count_words($string)
{
// split text by ' ',\r,\n,\f,\t
$split_array = preg_split('/\s+/',$string);
// count matches that contain alphanumerics
$word_count = preg_grep('/[a-zA-Z0-9\\x80-\\xff]/', $split_array);
return count($word_count);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,58 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Include the {@link shared.make_timestamp.php} plugin
*/
require_once $smarty->_get_plugin_filepath('shared', 'make_timestamp');
/**
* Smarty date_format modifier plugin
*
* Type: modifier<br>
* Name: date_format<br>
* Purpose: format datestamps via strftime<br>
* Input:<br>
* - string: input date string
* - format: strftime format for output
* - default_date: default date if $string is empty
* @link http://smarty.php.net/manual/en/language.modifier.date.format.php
* date_format (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string
* @param string
* @return string|void
* @uses smarty_make_timestamp()
*/
function smarty_modifier_date_format($string, $format = '%b %e, %Y', $default_date = '')
{
if ($string != '') {
$timestamp = smarty_make_timestamp($string);
} elseif ($default_date != '') {
$timestamp = smarty_make_timestamp($default_date);
} else {
return;
}
if (DIRECTORY_SEPARATOR == '\\') {
$_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
$_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
if (strpos($format, '%e') !== false) {
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $timestamp));
}
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $timestamp));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $timestamp);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,90 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty debug_print_var modifier plugin
*
* Type: modifier<br>
* Name: debug_print_var<br>
* Purpose: formats variable contents for display in the console
* @link http://smarty.php.net/manual/en/language.modifier.debug.print.var.php
* debug_print_var (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array|object
* @param integer
* @param integer
* @return string
*/
function smarty_modifier_debug_print_var($var, $depth = 0, $length = 40)
{
$_replace = array(
"\n" => '<i>\n</i>',
"\r" => '<i>\r</i>',
"\t" => '<i>\t</i>'
);
switch (gettype($var)) {
case 'array' :
$results = '<b>Array (' . count($var) . ')</b>';
foreach ($var as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat('&nbsp;', $depth * 2)
. '<b>' . strtr($curr_key, $_replace) . '</b> =&gt; '
. smarty_modifier_debug_print_var($curr_val, ++$depth, $length);
$depth--;
}
break;
case 'object' :
$object_vars = get_object_vars($var);
$results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>';
foreach ($object_vars as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat('&nbsp;', $depth * 2)
. '<b> -&gt;' . strtr($curr_key, $_replace) . '</b> = '
. smarty_modifier_debug_print_var($curr_val, ++$depth, $length);
$depth--;
}
break;
case 'boolean' :
case 'NULL' :
case 'resource' :
if (true === $var) {
$results = 'true';
} elseif (false === $var) {
$results = 'false';
} elseif (null === $var) {
$results = 'null';
} else {
$results = htmlspecialchars((string) $var);
}
$results = '<i>' . $results . '</i>';
break;
case 'integer' :
case 'float' :
$results = htmlspecialchars((string) $var);
break;
case 'string' :
$results = strtr($var, $_replace);
if (strlen($var) > $length ) {
$results = substr($var, 0, $length - 3) . '...';
}
$results = htmlspecialchars('"' . $results . '"');
break;
case 'unknown type' :
default :
$results = strtr((string) $var, $_replace);
if (strlen($results) > $length ) {
$results = substr($results, 0, $length - 3) . '...';
}
$results = htmlspecialchars($results);
}
return $results;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,32 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty default modifier plugin
*
* Type: modifier<br>
* Name: default<br>
* Purpose: designate default value for empty variables
* @link http://smarty.php.net/manual/en/language.modifier.default.php
* default (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string
* @return string
*/
function smarty_modifier_default($string, $default = '')
{
if (!isset($string) || $string === '')
return $default;
else
return $string;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,93 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty escape modifier plugin
*
* Type: modifier<br>
* Name: escape<br>
* Purpose: Escape the string according to escapement type
* @link http://smarty.php.net/manual/en/language.modifier.escape.php
* escape (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param html|htmlall|url|quotes|hex|hexentity|javascript
* @return string
*/
function smarty_modifier_escape($string, $esc_type = 'html', $char_set = 'ISO-8859-1')
{
switch ($esc_type) {
case 'html':
return htmlspecialchars($string, ENT_QUOTES, $char_set);
case 'htmlall':
return htmlentities($string, ENT_QUOTES, $char_set);
case 'url':
return rawurlencode($string);
case 'urlpathinfo':
return str_replace('%2F','/',rawurlencode($string));
case 'quotes':
// escape unescaped single quotes
return preg_replace("%(?<!\\\\)'%", "\\'", $string);
case 'hex':
// escape every character into hex
$return = '';
for ($x=0; $x < strlen($string); $x++) {
$return .= '%' . bin2hex($string[$x]);
}
return $return;
case 'hexentity':
$return = '';
for ($x=0; $x < strlen($string); $x++) {
$return .= '&#x' . bin2hex($string[$x]) . ';';
}
return $return;
case 'decentity':
$return = '';
for ($x=0; $x < strlen($string); $x++) {
$return .= '&#' . ord($string[$x]) . ';';
}
return $return;
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
case 'mail':
// safe way to display e-mail address on a web page
return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string);
case 'nonstd':
// escape non-standard chars, such as ms document quotes
$_res = '';
for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {
$_ord = ord(substr($string, $_i, 1));
// non-standard char, escape it
if($_ord >= 126){
$_res .= '&#' . $_ord . ';';
}
else {
$_res .= substr($string, $_i, 1);
}
}
return $_res;
default:
return $string;
}
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,28 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty indent modifier plugin
*
* Type: modifier<br>
* Name: indent<br>
* Purpose: indent lines of text
* @link http://smarty.php.net/manual/en/language.modifier.indent.php
* indent (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param integer
* @param string
* @return string
*/
function smarty_modifier_indent($string,$chars=4,$char=" ")
{
return preg_replace('!^!m',str_repeat($char,$chars),$string);
}
?>

View File

@@ -0,0 +1,26 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty lower modifier plugin
*
* Type: modifier<br>
* Name: lower<br>
* Purpose: convert string to lowercase
* @link http://smarty.php.net/manual/en/language.modifier.lower.php
* lower (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return string
*/
function smarty_modifier_lower($string)
{
return strtolower($string);
}
?>

View File

@@ -0,0 +1,35 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty plugin
*
* Type: modifier<br>
* Name: money<br>
* Date: Jui 17, 2007
* Purpose: convert to d.dd
* Input:<br>
* - contents = contents to replace
* - preceed_test = if true, includes preceeding break tags
* in replacement
* Example: {$text|money}
* @link
* money (Smarty online manual)
* @version 1.0
* @author Julien Lacroix <julien at verygames dot net>
* @param string
* @return string
*/
function smarty_modifier_money($string)
{
return money_format('%i', $string);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,35 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty plugin
*
* Type: modifier<br>
* Name: nl2br<br>
* Date: Feb 26, 2003
* Purpose: convert \r\n, \r or \n to <<br>>
* Input:<br>
* - contents = contents to replace
* - preceed_test = if true, includes preceeding break tags
* in replacement
* Example: {$text|nl2br}
* @link http://smarty.php.net/manual/en/language.modifier.nl2br.php
* nl2br (Smarty online manual)
* @version 1.0
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @return string
*/
function smarty_modifier_nl2br($string)
{
return nl2br($string);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,48 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty regex_replace modifier plugin
*
* Type: modifier<br>
* Name: regex_replace<br>
* Purpose: regular expression search/replace
* @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php
* regex_replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string|array
* @param string|array
* @return string
*/
function smarty_modifier_regex_replace($string, $search, $replace)
{
if(is_array($search)) {
foreach($search as $idx => $s)
$search[$idx] = _smarty_regex_replace_check($s);
} else {
$search = _smarty_regex_replace_check($search);
}
return preg_replace($search, $replace, $string);
}
function _smarty_regex_replace_check($search)
{
if (($pos = strpos($search,"\0")) !== false)
$search = substr($search,0,$pos);
if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) {
/* remove eval-modifier from $search */
$search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]);
}
return $search;
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,30 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty replace modifier plugin
*
* Type: modifier<br>
* Name: replace<br>
* Purpose: simple search/replace
* @link http://smarty.php.net/manual/en/language.modifier.replace.php
* replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string
* @param string
* @return string
*/
function smarty_modifier_replace($string, $search, $replace)
{
return str_replace($search, $replace, $string);
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,30 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty spacify modifier plugin
*
* Type: modifier<br>
* Name: spacify<br>
* Purpose: add spaces between characters in a string
* @link http://smarty.php.net/manual/en/language.modifier.spacify.php
* spacify (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string
* @return string
*/
function smarty_modifier_spacify($string, $spacify_char = ' ')
{
return implode($spacify_char,
preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY));
}
/* vim: set expandtab: */
?>

View File

@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty string_format modifier plugin
*
* Type: modifier<br>
* Name: string_format<br>
* Purpose: format strings via sprintf
* @link http://smarty.php.net/manual/en/language.modifier.string.format.php
* string_format (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param string
* @param string
* @return string
*/
function smarty_modifier_string_format($string, $format)
{
return sprintf($format, $string);
}
/* vim: set expandtab: */
?>

Some files were not shown because too many files have changed in this diff Show More