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;
}
}
?>