';
}
}
}
}
/**
* Plugin handler
* @package Mambo
*/
class mosMambotHandler {
/** @var array An array of functions in event groups */
var $_events=null;
/** @var array An array of lists */
var $_lists=null;
/** @var array An array of mambots */
var $_bots=null;
/** @var array An array of bools showing if corresponding bot is registered */
var $_registered=array();
/** @var int Index of the mambot being loaded */
var $_loading=null;
/**
* Constructor
*/
function mosMambotHandler() {
$my = mamboCore::is_set('currentUser') ? mamboCore::get('currentUser') : null;
$gid = $my ? $my->gid : 0;
$this->_events = array();
$database =& mamboDatabase::getInstance();
$database->setQuery( "SELECT folder, element, published, params, CONCAT_WS('/',folder,element) AS lookup"
. "\nFROM #__mambots"
. "\nWHERE published >= 1 AND access <= $gid"
. "\nORDER BY ordering"
);
$this->_bots = $database->loadObjectList();
if (!$this->_bots) $this->_bots = array();
}
/**
* Singleton accessor
*/
function &getInstance () {
static $instance;
if (!is_object($instance)) $instance = new mosMambotHandler();
return $instance;
}
/**
* Register a class-type mambot, provided it has a perform method
* - can register for multiple events if desired
* @param object The mambot object
* @param mixed string or array of strings - the mambot events to be registered
* @param int the subscript for use in the main array of mambots
*/
function _botRegister (&$botObject, &$selected, $i) {
$function = array(&$botObject, 'perform');
if (!is_callable($function)) return;
if (is_array($selected)) foreach ($selected as $select) $this->_botRegister($botObject, $select);
$this->_events[$selected][] = array ($function, $i);
$this->_registered[$i] = true;
}
/**
* Loads all the bot files for a particular group
* @param string The group name, relates to the sub-directory in the mambots directory
*/
function loadBotGroup( $group ) {
global $_MAMBOTS;
$group = trim( $group );
$total = 0;
$basepath = mamboCore::get('mosConfig_absolute_path');
foreach ($this->_bots as $i=>$bot) {
if ($bot->folder != $group OR isset($this->_registered[$i])) continue;
$path = "$basepath/mambots/$bot->folder/$bot->element.php";
if (file_exists( $path )) {
$this->_loading = $i;
require_once( $path );
if (!isset($this->_registered[$i])) {
$botclass = str_replace('.','_',$bot->element);
if (class_exists($botclass)) {
$newbot = new $botclass();
if (is_callable(array(&$newbot, 'register'))) {
$selected = $newbot->register();
$this->_botRegister($newbot, $selected, $i);
}
unset($newbot);
}
}
$total++;
}
}
$this->_loading = null;
if ($total) return true;
return false;
}
/**
* Registers a function to a particular event group
* @param string The event name
* @param string The function name
*/
function registerFunction( $event, $function ) {
$this->_events[$event][] = array( $function, $this->_loading );
$this->_registered[$this->_loading] = true;
}
/**
* Makes a option for a particular list in a group
* @param string The group name
* @param string The list name
* @param string The value for the list option
* @param string The text for the list option
*/
function addListOption( $group, $listName, $value, $text='' ) {
$this->_lists[$group][$listName][] = mosHTML::makeOption( $value, $text );
}
/**
* @param string The group name
* @param string The list name
* @return array
*/
function getList( $group, $listName ) {
return $this->_lists[$group][$listName];
}
/**
* Calls all functions according to passed parameters
* @param string The event name
* @param array An array of arguments
* @param boolean True is unpublished bots are to be processed
* @return array An array of results from each function call
*/
function &_runBots ($event, $args, $doUnpublished=false) {
$result = array();
if (isset( $this->_events[$event] )) {
foreach ($this->_events[$event] as $func) {
if (is_callable( $func[0] )) {
$botparams = $this->_bots[$func[1]]->params;
$args[] = new mosParameters($botparams);
$args[] = $event;
if ($doUnpublished) {
$args[0] = $this->_bots[$func[1]]->published;
$result[] = call_user_func_array( $func[0], $args );
} else if ($this->_bots[$func[1]]->published) {
$result[] = call_user_func_array( $func[0], $args );
}
}
}
}
return $result;
}
/**
* Calls all functions associated with an event group
* @param string The event name
* @param array An array of arguments
* @param boolean True is unpublished bots are to be processed
* @return array An array of results from each function call
*/
function trigger( $event, $args=null, $doUnpublished=false ) {
if ($args === null) $args = array();
// prepend the published argument
if ($doUnpublished) array_unshift( $args, null );
$result =& $this->_runBots($event, $args, $doUnpublished);
return $result;
}
/**
* Same as trigger but only returns the first event and
* allows for a variable argument list
* @param string The event name
* @return array The result of the first function call
*/
function call( $event ) {
$args =& func_get_args();
array_shift( $args );
$result =& $this->_runBots($event, $args);
if (isset($result[0])) return $result[0];
return null;
}
}
/**
* Users Table Class
*
* Provides access to the mos_templates table
* @package Mambo
*/
class mosUser extends mosDBTable {
/** @var int Unique id*/
var $id=null;
/** @var string The users real name (or nickname)*/
var $name=null;
/** @var string The login name*/
var $username=null;
/** @var string email*/
var $email=null;
/** @var string MD5 encrypted password*/
var $password=null;
/** @var string */
var $usertype=null;
/** @var int */
var $block=null;
/** @var int */
var $sendEmail=null;
/** @var int The group id number */
var $gid=null;
/** @var int Group number from ACL */
var $grp=null;
/** @var datetime */
var $registerDate=null;
/** @var datetime */
var $lastvisitDate=null;
/** @var string activation hash*/
var $activation=null;
/** @var string */
var $params=null;
/**
* @param database A database connector object
*/
function mosUser() {
$database =& mamboDatabase::getInstance();
$this->mosDBTable( '#__users', 'id', $database );
}
/**
* Return true if this user is an administrator, false otherwise
*/
function isAdmin() {
return ( strtolower( $this->usertype ) == 'superadministrator' OR strtolower( $this->usertype ) == 'super administrator' OR (isset($this->grp) AND $this->grp == 16) ) ? true : false;
}
/**
* Fill a user object with information from the current session
*/
function getSessionData() {
$session =& mosSession::getCurrent();
$this->id = intval( $session->userid );
$this->username = $session->username;
$this->usertype = $session->usertype;
$this->gid = intval ($session->gid);
}
function getSession () {
$this->id = mosGetParam( $_SESSION, 'session_user_id', 0 );
$this->username = mosGetParam( $_SESSION, 'session_username', '' );
$this->usertype = mosGetParam( $_SESSION, 'session_usertype', '' );
$this->gid = mosGetParam( $_SESSION, 'session_gid', 0 );
$this->grp = mosGetParam( $_SESSION, 'session_grp', 0);
}
/**
* Validation and filtering
* @return boolean True is satisfactory
*/
function check() {
Global $mosConfig_absolute_path;
include $mosConfig_absolute_path . ('/language/english.php');
$this->_error = '';
if ($this->name == '') $this->_error = _REGWARN_NAME;
elseif ($this->username == '') $this->_error = _REGWARN_UNAME;
elseif (strlen($this->username) < 3 OR preg_match("/[\\<\\>\\\"\\'\\%\\;\\(\\)\\&\\+\\-]/", $this->username)) $this->_error = sprintf( _VALID_AZ09, _PROMPT_UNAME, 2 );
elseif (($this->email == '') OR preg_match("/[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}/", $this->email ) == 0) $this->_error = _REGWARN_MAIL;
else {
// check for existing username
$username = strtolower($this->username);
$this->_db->setQuery( "SELECT COUNT(id) FROM #__users "
. "\nWHERE LOWER(username)='$username' AND id!='$this->id'"
);
if ($this->_db->loadResult()) $this->_error = _REGWARN_INUSE;
elseif (mamboCore::get('mosConfig_uniquemail')) {
// check for existing email
$this->_db->setQuery( "SELECT COUNT(id) FROM #__users "
. "\nWHERE email='$this->email' AND id!='$this->id'"
);
if ($this->_db->loadResult()) $this->_error = _REGWARN_EMAIL_INUSE;
}
}
if ($this->_error) return false;
return true;
}
function store( $updateNulls=false ) {
global $acl, $migrate;
$section_value = 'users';
if( $this->id AND !$migrate) {
// update existing record
$ret = $this->_db->updateObject( $this->_tbl, $this, 'id', $updateNulls );
// syncronise ACL
// single group handled at the moment
// trivial to expand to multiple groups
$groups = $acl->get_object_groups( $section_value, $this->id, 'ARO' );
$acl->del_group_object( $groups[0], $section_value, $this->id, 'ARO' );
$acl->add_group_object( $this->gid, $section_value, $this->id, 'ARO' );
$object_id = $acl->get_object_id( $section_value, $this->id, 'ARO' );
$acl->edit_object( $object_id, $section_value, $this->_db->getEscaped( $this->name ), $this->id, 0, 0, 'ARO' );
}
else {
// new record
$ret = $this->_db->insertObject( $this->_tbl, $this, 'id' );
// syncronise ACL
$acl->add_object( $section_value, $this->_db->getEscaped( $this->name ), $this->id, null, null, 'ARO' );
$acl->add_group_object( $this->gid, $section_value, $this->id, 'ARO' );
}
if ($ret) return true;
$this->_error = "mosUser::store failed " . $this->_db->getErrorMsg();
return false;
}
function delete($oid=null) {
global $acl;
$k = $this->_tbl_key;
if ($oid) $this->id = intval( $oid );
$aro_id = $acl->get_object_id( 'users', $this->$k, 'ARO' );
$acl->del_object( $aro_id, 'ARO', true );
// $authoriser = mosAuthorisationAdmin::getInstance();
// $authoriser->dropAccess('mosUser', $this->id);
$this->_error = '';
$this->_db->setQuery( "DELETE FROM $this->_tbl WHERE id = '".$this->id."'" );
if ($this->_db->query()) {
// cleanup related data
// :: private messaging
$this->_db->setQuery( "DELETE FROM #__messages_cfg WHERE user_id='".$this->id."'" );
if (!$this->_db->query()) $this->_error = $this->_db->getErrorMsg();
else {
$this->_db->setQuery( "DELETE FROM #__messages WHERE user_id_to='".$this->$k."'" );
if (!$this->_db->query()) $this->_error = $this->_db->getErrorMsg();
}
} else $this->_error = $this->_db->getErrorMsg();
if ($this->_error) return false;
return true;
}
}
/**
* User login details class
* @package Mambo
*/
class mosLoginDetails {
var $_user = '';
var $_password = '';
var $_remember = '';
function mosLoginDetails ($user, $password='', $remember='') {
$this->_user = $user;
$this->_password = $password;
$this->_remember = $remember;
}
function getUser () {
return $this->_user;
}
function getPassword () {
return $this->_password;
}
function getRemember () {
return $this->_remember;
}
}
/**
* Mambo Mainframe class
*
* Provide many supporting API functions
* @package Mambo
*/
class mosMainFrame {
/** @var database Internal database class pointer */
var $_db=null;
/** @var object A default option (e.g. component) */
var $_option=null;
/** @var string The current template */
var $_template=null;
/** @var array An array to hold global user state within a session */
var $_userstate=null;
/** @var array An array of page meta information */
var $_head=null;
/** @var string Custom html string to append to the pathway */
var $_custom_pathway=array();
/**
* Class constructor
* @param database A database connection object
* @param string The url option
* @param string The path of the mos directory
*/
function mosMainFrame( &$db, $option, $basePath, $isAdmin=false ) {
$this->_db =& $db;
// load the configuration values
//return( $this->loadConfig() );
$this->_setTemplate($isAdmin);
if (substr($option,0,4) != 'com_') $this->_option = "com_$option";
else $this->_option = $option;
if (isset( $_SESSION['session_userstate'] )) $this->_userstate =& $_SESSION['session_userstate'];
else $this->_userstate = null;
$this->_head['title'] = $GLOBALS['mosConfig_sitename'];
$this->_head['meta'] = array();
$this->_head['custom'] = array();
mosMainFrame::getInstance($this);
}
/**
* Get the current user - deprecated - use mamboCore instead
*/
function getUser() {
return mamboCore::get('currentUser');
}
/**
* Logout the current user - deprecated - use the code here directly
*/
function logout() {
require_once(mamboCore::get('mosConfig_absolute_path').'/includes/authenticator.php');
$authenticator =& mamboAuthenticator::getInstance();
$authenticator->logoutUser();
}
/**
* Login a user given name and password - deprecated - use the code here directly
*/
function login ($username=null,$passwd=null) {
require_once(mamboCore::get('mosConfig_absolute_path').'/includes/authenticator.php');
$authenticator =& mamboAuthenticator::getInstance();
return $authenticator->loginUser($username, $passwd);
}
/**
* @param object
*/
function &getInstance () {
global $mainframe;
if (isset($mainframe)) {
return $mainframe;
} else {
$result = null;
return $result;
}
}
/**
* @param string
*/
function setPageTitle( $title=null ) {
if (mamboCore::get('mosConfig_pagetitles')) {
$title = trim(htmlspecialchars($title));
$base = mamboCore::get('mosConfig_sitename');
$this->_head['title'] = $title ? $title.' - '.$base : $base;
}
}
/**
* @return string
*/
function getPageTitle() {
return $this->_head['title'];
}
/**
* @param string The value of the name attibute
* @param string The value of the content attibute
* @param string Text to display before the tag
* @param string Text to display after the tag
*/
function addMetaTag( $name, $content, $prepend='', $append='' ) {
list($name, $content) = $this->_tidyMetaData($name, $content);
$prepend = trim($prepend);
$append = trim($append);
$this->_head['meta'][$name] = array($content, $prepend, $append);
}
/**
* @param string The value of the name attibute
*/
function _getMetaTag ($name) {
return isset($this->_head['meta'][$name]) ? $this->_head['meta'][$name] : array('', '', '');
}
/**
* @param string The value of the name attibute
* @param string The value of the content attibute to append to the existing
*/
function _tidyMetaData($name, $content) {
$result[] = trim(htmlspecialchars($name));
$result[] = trim(htmlspecialchars($content));
return $result;
}
/**
* @param string The value of the name attibute
* @param string The value of the content attibute to append to the existing
* Tags ordered in with Site Keywords and Description first
*/
function appendMetaTag( $name, $content, $ifEmpty=false ) {
list($name, $content) = $this->_tidyMetaData($name, $content);
$tag = $this->_getMetaTag($name);
if ($tag[0] AND $ifEmpty) return;
if ($tag[0] AND $content) $content .= ', ';
$tag[0] = $content.$tag[0];
$this->_head['meta'][$name] = $tag;
}
/**
* @param string The value of the name attibute
* @param string The value of the content attibute to append to the existing
*/
function prependMetaTag( $name, $content ) {
list($name, $content) = $this->_tidyMetaData($name, $content);
$tag = $this->_getMetaTag($name);
$tag[0] = $content.$tag[0];
$this->_head['meta'][$name] = $tag;
}
/**
* Adds a custom html string to the head block
* @param string The html to add to the head
*/
function addCustomHeadTag( $html ) {
$this->_head['custom'][] = trim( $html );
}
/**
* @return string
*/
function getHead() {
$head[] = ''.$this->_head['title'].'';
foreach ($this->_head['meta'] as $name=>$meta) {
if ($meta[1]) $head[] = $meta[1];
$head[] = '';
if ($meta[2]) $head[] = $meta[2];
}
foreach ($this->_head['custom'] as $html) $head[] = $html;
return implode( "\n", $head )."\n";
}
/**
* @return string
*/
function getCustomPathWay() {
return $this->_custom_pathway;
}
function appendPathWay($html) {
$this->_custom_pathway[] = $html;
}
/**
* Gets the value of a user state variable
* @param string The name of the variable
*/
function getUserState( $var_name ) {
return is_array($this->_userstate) ? mosGetParam($this->_userstate, $var_name, null) : null;
}
/**
* Sets the value of a user state variable
* @param string The name of the variable
* @param string The value of the variable
*/
function setUserState( $var_name, $var_value ) {
if (is_array( $this->_userstate )) $this->_userstate[$var_name] = $var_value;
}
/**
* Gets the value of a user state variable
* @param string The name of the user state variable
* @param string The name of the variable passed in a request
* @param string The default value for the variable if not found
*/
function getUserStateFromRequest( $var_name, $req_name, $var_default=null ) {
if (is_array($this->_userstate)) {
if (isset($_REQUEST[$req_name])) $this->setUserState($var_name, $_REQUEST[$req_name]);
else if (isset($var_default) AND !isset($this->_userstate[$var_name])) $this->setUserState($var_name, $var_default);
return $this->_userstate[$var_name];
} else {
return null;
}
}
/**
* Initialises the user session
*
* Old sessions are flushed based on the configuration value for the cookie
* lifetime. If an existing session, then the last access time is updated.
* If a new session, a session id is generated and a record is created in
* the mos_sessions table.
*/
function &initSession() {
$session =& mosSession::getCurrent();
return $session;
}
/**
* @param string The name of the variable (from configuration.php)
* @return mixed The value of the configuration variable or null if not found
*/
function getCfg( $varname ) {
return mamboCore::get('mosConfig_'.$varname);
}
function _setTemplate( $isAdmin=false ) {
global $Itemid;
$cur_template = '';
$sql = "SELECT template, client_id, menuid FROM #__templates_menu WHERE (client_id=0 or client_id=1)";
if (isset($Itemid) AND $Itemid) $sql .= " AND (menuid=0 OR menuid=$Itemid)";
else $sql .= " AND menuid=0";
$sql .= " ORDER BY client_id, menuid";
$this->_db->setQuery($sql);
$templates = $this->_db->loadObjectList();
foreach ($templates as $template) {
if ($template->client_id == 1) {
if ($isAdmin) $cur_template = $template->template;
}
else $cur_template = $template->template;
}
if ($isAdmin) {
$path = mamboCore::get('mosConfig_absolute_path')."/administrator/templates/$cur_template/index.php";
if (!file_exists( $path )) $cur_template = 'mambo_admin';
}
else {
// TemplateChooser Start
$mos_user_template = mosGetParam( $_COOKIE, 'mos_user_template', '' );
$mos_change_template = mosGetParam( $_REQUEST, 'mos_change_template', $mos_user_template );
if ($mos_change_template) {
// check that template exists in case it was deleted
$path = mamboCore::get('mosConfig_absolute_path')."/templates/$mos_change_template/index.php";
if (strpos($mos_change_template,'..') == false AND strpos($mos_change_template,':') == false AND file_exists($path)) {
$lifetime = 60*10;
$cur_template = $mos_change_template;
setcookie( "mos_user_template", "$mos_change_template", time()+$lifetime);
} else setcookie( "mos_user_template", "", time()-3600 );
}
// TemplateChooser End
}
$this->_template = $cur_template;
}
function getTemplate() {
return $this->_template;
}
/**
* Checks to see if an image exists in the current templates image directory
* if it does it loads this image. Otherwise the default image is loaded.
* Also can be used in conjunction with the menulist param to create the chosen image
* load the default or use no image
*/
function ImageCheck( $file, $directory='/images/M_images/', $param=NULL, $param_directory='/images/M_images/', $alt=NULL, $name='image', $type=1, $align='middle' ) {
$basepath = mamboCore::get('mosConfig_live_site');
if ($param) $image = $basepath.$param_directory.$param;
else {
$endpath = '/templates/'.$this->getTemplate().'/images/'.$file;
if (file_exists(mamboCore::get('mosConfig_absolute_path').$endpath)) $image = $basepath.$endpath;
else $image = $basepath.$directory.$file; // outputs only path to image
}
// outputs actual html tag
if ($type) $image = '';
return $image;
}
/**
* Returns the first to be found of one or more files, or null
*
*/
function tryFiles ($first_choice, $second_choice=null, $third_choice=null) {
if (file_exists($first_choice)) return $first_choice;
elseif ($second_choice AND file_exists($second_choice)) return $second_choice;
elseif ($third_choice AND file_exists($third_choice)) return $third_choice;
else return null;
}
/**
* Returns a standard path variable
*
*/
function getPath( $varname, $option='' ) {
$base = mamboCore::get('mosConfig_absolute_path');
$origoption = $option;
if (!$option) $option = $this->_option;
$name = substr($option,4);
$bac_admin = "$base/administrator/components/com_admin/";
$baco = "$base/administrator/components/$option/";
$bttc = "$base/templates/$this->_template/components/";
$bco = "$base/components/$option/";
$bai = "$base/administrator/includes/";
$bi = "$base/includes/";
switch ($varname) {
case 'front': return $this->tryFiles ($bco."$name.php");
case 'front_html': return $this->tryFiles ($bttc."$name.html.php", $bco."$name.html.php");
case 'admin': return $this->tryFiles ($baco."admin.$name.php", $bac_admin.'admin.admin.php');
case 'admin_html': return $this->tryFiles ($baco."admin.$name.html.php", $bac_admin.'admin.admin.html.php');
case 'toolbar': return $this->tryFiles ($baco."toolbar.$name.php");
case 'toolbar_html': return $this->tryFiles ($baco."toolbar.$name.html.php");
case 'toolbar_default': return $this->tryFiles ($bai.'toolbar.html.php');
case 'class': return $this->tryFiles ($bco."$name.class.php", $baco."$name.class.php", $bi."$name.php");
case 'com_xml': return $this->tryFiles ($baco."$name.xml", $bco."$name.xml");
case 'mod0_xml':
if ($origoption) $path = $base."/modules/$option.xml";
else $path = $base.'/modules/custom.xml';
return $this->tryFiles ($path);
case 'mod1_xml':
if ($origoption) $path = $base."/administrator/modules/$option.xml";
else $path = $base.'/administrator/modules/custom.xml';
return $this->tryFiles ($path);
case 'bot_xml': return $this->tryFiles ($base."/mambots/$option.xml");
case 'menu_xml': return $this->tryFiles ($base."/administrator/components/com_menus/$option/$option.xml");
case 'installer_html': return $this->tryFiles($base."/administrator/components/com_installer/$option/$option.html.php");
case 'installer_class': return $this->tryFiles($base."/administrator/components/com_installer/$option/$option.class.php");
}
}
/**
* Detects a 'visit'
*
* This function updates the agent and domain table hits for a particular
* visitor. The user agent is recorded/incremented if this is the first visit.
* A cookie is set to mark the first visit.
*/
function detect() {
if (mamboCore::get('mosConfig_enable_stats') == 1) {
if (mosGetParam( $_COOKIE, 'mosvisitor', 0 )) return;
setcookie( "mosvisitor", "1" );
$agent = $_SERVER['HTTP_USER_AGENT'];
$browser = mosGetBrowser( $agent );
$os = mosGetOS( $agent );
$domain = gethostbyaddr( $_SERVER['REMOTE_ADDR'] );
// tease out the last element of the domain
$tldomain = split( "\.", $domain );
$tldomain = $tldomain[count( $tldomain )-1];
if (is_numeric( $tldomain )) {
$tldomain = "Unknown";
}
$this->_db->setQuery( "SELECT count(*), type FROM #__stats_agents WHERE (agent='$browser' AND type=0) OR (agent='$os' AND type=1) OR (agent='$tldomain' AND type=2) GROUP BY type");
$stats = $this->_db->loadObjectList();
$sql['browser'] = "INSERT INTO #__stats_agents (agent,type) VALUES ('$browser',0)";
$sql['os'] = "INSERT INTO #__stats_agents (agent,type) VALUES ('$os',1)";
$sql['domain'] = "INSERT INTO #__stats_agents (agent,type) VALUES ('$tldomain',2)";
if ($stats) foreach ($stats as $stat) {
if ($stat->type == 0) $sql['agents'] = "UPDATE #__stats_agents SET hits=(hits+1) WHERE agent='$browser' AND type=0";
if ($stat->type == 1) $sql['os'] = "UPDATE #__stats_agents SET hits=(hits+1) WHERE agent='$os' AND type=1";
if ($stat->type == 2) $sql['domain'] = "UPDATE #__stats_agents SET hits=(hits+1) WHERE agent='$tldomain' AND type=2";
}
$this->_db->setQuery(implode('; ',$sql));
$this->_db->query_batch();
}
}
/**
* @return correct Itemid for Content Item
*/
function getItemid ($id, $typed=1, $link=1, $bs=1, $bc=1, $gbs=1) {
require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
$handler =& contentHandler::getInstance();
return $handler->getItemid($id, $typed, $link, $bs, $bc, $gbs);
}
function liveBookMark () {
// support for Firefox Live Bookmarks ability for site syndication
$live_bookmark = 0;
$c_handler =& mosComponentHandler::getInstance();
$params =& $c_handler->getParamsByName('Syndicate');
if (!is_null($params)){
$live_bookmark = $params->get( 'live_bookmark', 0 );
}
if ($live_bookmark) {
// custom bookmark file name
$bookmark_file = $params->get( 'bookmark_file', $live_bookmark );
$link_file = mamboCore::get('mosConfig_live_site').'/cache/'. $bookmark_file;
$filename = mamboCore::get('mosConfig_absolute_path').'/cache/'. $bookmark_file;
$cache = $params->get( 'cache', 1 );
$cache_time = $params->get( 'cache_time', 3600 );
$title = $params->def( 'title', mamboCore::get('mosConfig_sitename') );
// checks to see if cache file exists, to determine whether to create a new one
if ( !file_exists( $filename ) || ( ( time() - filemtime( $filename ) ) > $cache_time ) ) {
$task = 'live_bookmark';
// sets bookmark feed type
$_GET['feed'] = str_replace( '.xml', '', $live_bookmark );
// loads rss component to create bookmark file
require_once( mamboCore::get('mosConfig_absolute_path').'/components/com_rss/rss.php' );
}
// outputs link tag for page
?>
appendMetaTag( 'description', mamboCore::get('mosConfig_MetaDesc'), true );
$this->appendMetaTag( 'keywords', mamboCore::get('mosConfig_MetaKeys'), true );
echo $this->getHead();
if (mamboCore::get('mosConfig_sef')) {
echo "\r\n";
}
$my = mamboCore::get('currentUser');
if ( $my->id ) {
?>
liveBookMark();
// outputs link tag for page
$configuration =& mamboCore::getMamboCore();
?>
getBlogSectionCount();
}
function getBlogCategoryCount() {
require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
$handler =& new contentHandler();
return $handler->getBlogCategoryCount();
}
function getGlobalBlogSectionCount() {
require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
$handler =& new contentHandler();
return $handler->getGlobalBlogSectionCount();
}
function getStaticContentCount() {
require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
$handler =& new contentHandler();
return $handler->getStaticContentCount();
}
function getContentItemLinkCount() {
require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
$handler =& new contentHandler();
return $handler->getContentItemLinkCount();
}
/**
* retained for backward compatability
*/
}
/**
* Class to support function caching
* @package Mambo
*/
class mosCache {
/**
* @return object A function cache object
*/
function &getCache( $group='' ) {
$mosConfig_absolute_path = mamboCore::get('mosConfig_absolute_path');
require_once($mosConfig_absolute_path.'/includes/Cache/Lite/Function.php');
$path = mamboCore::get('mosConfig_cachepath');
$caching = mamboCore::get('mosConfig_caching');
$time = mamboCore::get('mosConfig_cachetime');
$options = array(
'cacheDir' => "$path/",
'caching' => $caching,
'defaultGroup' => $group,
'lifeTime' => $time
);
$cache =& new Cache_Lite_Function( $options );
return $cache;
}
/**
* Cleans the cache
*/
function cleanCache ($group=false) {
if (mamboCore::get('mosConfig_caching')) {
$cache =& mosCache::getCache( $group );
$cache->clean( $group );
}
}
}
/**
* Session database table class
* @package Mambo
*/
class mosSession extends mosDBTable {
/** @var int Primary key */
var $session_id=null;
/** @var time */
var $time=null;
/** @var int User ID */
var $userid=0;
/** @var string */
var $usertype=null;
/** @var string */
var $username='';
/** @var int User group ID */
var $gid=0;
/** @var int */
var $guest=1;
/** @var string */
var $_session_cookie=null;
/**
* @param database A database connector object
*/
function mosSession() {
$database =& mamboDatabase::getInstance();
$this->mosDBTable( '#__session', 'session_id', $database );
$this->time = time();
}
function validate ($user) {
// check against db record of session
$session_id = mosGetParam( $_SESSION, 'session_id', '' );
$logintime = mosGetParam( $_SESSION, 'session_logintime', '' );
if ($session_id == md5( $user->id.$user->username.$user->usertype.$logintime )) {
$current_time = time();
$database =& mamboDatabase::getInstance();
$database->setQuery ("UPDATE #__session"
. "\nSET time='$current_time', guest=-3-guest"
. "\nWHERE session_id='$session_id'"
. " AND username = '" . $database->getEscaped( $user->username ) . "'"
. " AND userid = " . intval( $user->id )
);
if (!$result = $database->query()) echo $database->stderr();
elseif ($database->getAffectedRows() == 1) return true;
}
return false;
}
function &getCurrent () {
static $currentSession;
if (!is_object($currentSession)) {
$currentSession = new mosSession();
mosSession::purge();
$sessionCookieName = md5('site'.mamboCore::get('mosConfig_live_site'));
$sessioncookie = mosGetParam($_COOKIE, $sessionCookieName, null);
$usercookie = mosGetParam($_COOKIE, 'usercookie', null);
if ($currentSession->load(md5($sessioncookie.$_SERVER['REMOTE_ADDR']))) {
// Session cookie exists, update time in session table
$currentSession->time = time();
$currentSession->update();
} else {
$currentSession->generateId();
if (!$currentSession->insert()) {
die( $currentSession->getError() );
}
setcookie( $sessionCookieName, $currentSession->getCookie(), time() + 43200, '/' );
//$_COOKIE["sessioncookie"] = $session->getCookie();
if ($usercookie) {
// Remember me cookie exists. Login with usercookie info.
require_once (mamboCore::get('mosConfig_absolute_path').'/includes/authenticator.php');
$authenticator =& mamboAuthenticator::getInstance();
$authenticator->authenticateUser ($message, $usercookie['username'], $usercookie['password'], null, $currentSession);
}
}
}
return $currentSession;
}
function insert() {
$ret = $this->_db->insertObject( $this->_tbl, $this );
if( !$ret ) {
$this->_error = strtolower(get_class( $this ))."::store failed " . $this->_db->stderr();
return false;
} else {
return true;
}
}
function update( $updateNulls=false ) {
$ret = $this->_db->updateObject( $this->_tbl, $this, 'session_id', $updateNulls );
if( !$ret ) {
$this->_error = strtolower(get_class( $this ))."::store failed " . $this->_db->stderr();
return false;
} else {
return true;
}
}
function generateId() {
$failsafe = 20;
$randnum = 0;
while ($failsafe--) {
$randnum = md5( uniqid( microtime(), 1 ) );
if ($randnum != "") {
$cryptrandnum = md5( $randnum );
$this->_db->setQuery( "SELECT $this->_tbl_key FROM $this->_tbl WHERE $this->_tbl_key=MD5('$randnum')" );
if(!($result = $this->_db->query())) {
die( $this->_db->stderr( true ));
// todo: handle gracefully
}
if ($this->_db->getNumRows($result) == 0) {
break;
}
}
}
$this->_session_cookie = $randnum;
$this->session_id = md5( $randnum . $_SERVER['REMOTE_ADDR'] );
}
function getCookie() {
return $this->_session_cookie;
}
function purge() {
$past = time() - intval(mamboCore::get('mosConfig_lifetime'));
$adminpast = time() - 3600;
$database =& mamboDatabase::getInstance();
$database->setQuery("DELETE FROM #__session WHERE (time<$past AND guest>=0) OR (time<$adminpast AND guest<0)");
return $database->query();
}
}
/**
* Parameters handler
* @package Mambo
*/
class mosParameters {
/** @var object */
var $_params = null;
/** @var string The raw params string */
var $_raw = null;
/**
* Constructor
* @param string The raw parms text
* @param string Path to the xml setup file
* @var string The type of setup file
*/
function mosParameters( $text, $process_sections = false) {
$this->_params = $this->parse( $text, $process_sections );
$this->_raw = $text;
}
/**
* Get the result of parsing the string provided on creation
* @return string parsed result
*/
function getParams () {
return $this->_params;
}
/**
* @param string The name of the param
* @param string The value of the parameter
* @return string The set value
*/
function set( $key, $value='' ) {
$this->_params->$key = $value;
return $value;
}
/**
* Sets a default value if not alreay assigned
* @param string The name of the param
* @param string The value of the parameter
* @return string The set value
*/
function def( $key, $value='' ) {
return $this->set( $key, $this->get( $key, $value ) );
}
/**
* @param string The name of the param
* @param mixed The default value if not found
* @return string
*/
function get( $key, $default='' ) {
if (isset( $this->_params->$key )) return $this->_params->$key === '' ? $default : $this->_params->$key;
else return $default;
}
/**
* Look to see if string is bracketed by opener and closer
* If so, extract and trim the bracketed string
* Otherwise, return a null string
**/
function getBracketed ($text, $opener, $closer) {
if (strlen($text) > 1 AND ($text[0] != $opener OR substr($text,-1) != $closer)) return '';
else return trim(substr($text,1,-1));
}
/**
* Parse an .ini string, based on phpDocumentor phpDocumentor_parse_ini_file function
* @param mixed The ini string or array of lines
* @param boolean add an associative index for each section [in brackets]
* @return object
*/
function parse( $txt, $process_sections = false ) {
$result = new stdClass();
if (is_string($txt)) $lines = explode( "\n", $txt );
elseif (is_array($txt)) $lines = $txt;
else return $result;
$sec_name = '';
$unparsed = 0;
foreach ($lines as $line) {
// ignore comments and null lines
$line = trim($line);
if (strlen($line) == 0 OR $line[0] == ';') continue;
if ($sec_name = $this->getBracketed($line, '[', ']')) {
if ($process_sections) $result->$sec_name = new stdClass();
continue;
}
if (count($propsetter = explode ('=', $line, 2)) == 2) {
$property = trim($propsetter[0]);
if ($pquoted = $this->getBracketed($property, '"', '"')) $property = stripcslashes($pquoted);
$value = trim($propsetter[1]);
if ($value == 'false') $value = false;
elseif ($value == 'true') $value = true;
else if ($vquoted = $this->getBracketed($value, '"', '"')) $value = stripcslashes($vquoted);
if ($process_sections AND $sec_name) $result->$sec_name->$property = $value;
else $result->$property = $value;
}
else {
$property = '__invalid' . $unparsed++ . '__';
if ($process_sections AND $sec_name) $result->$sec_name->$property = $line;
else $result->$property = $line;
}
}
return $result;
}
/**
* @param string The name of the control, or the default text area if a setup file is not found
* @return string HTML
*/
function render( $name='params' ) {
if (is_file($this->_path)) {
$parser = new mosXMLParams ($this->_path, $this, $name);
if (count($parser->html)) return implode("\n", $parser->html);
}
$raw = $this->_raw;
return "";
}
/**
* special handling for textarea param
*/
function textareaHandling( &$txt ) {
foreach ($txt as $key=>$value) $txt[$key] = str_replace("\n", ' ', $value);
return implode( "\n", $txt );
}
}
/**
* Page generation time
* @package Mambo
*/
class mosProfiler {
var $start=0;
var $prefix='';
function mosProfiler( $prefix='' ) {
$this->start = $this->getmicrotime();
$this->prefix = $prefix;
}
function mark( $label ) {
return sprintf ( "\n
$this->prefix %.3f $label
", $this->getmicrotime() - $this->start );
}
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
/**
* @author Mikolaj Jedrzejak
* @copyright Copyright Mikolaj Jedrzejak (c) 2003-2004
* @version 1.0 2004-07-27 00:37
* @link http://www.unicode.org Unicode Homepage
* @link http://www.mikkom.pl My Homepage
*
**/
$PATH_TO_CLASS = dirname(ereg_replace("\\\\","/",__FILE__)) . "/" . "ConvertTables" . "/";
define ("CONVERT_TABLES_DIR", $PATH_TO_CLASS);
define ("DEBUG_MODE", 1);
/**
* -- 1.0 2004-07-28 --
*
* -- The most important thing --
* I want to thank all people who helped me fix all bugs, small and big once.
* I hope that you don't mind that your names are in this file.
*
* -- Some Apache issues --
* I get info from Lukas Lisa, that in some cases with special apache configuration
* you have to put header() function with proper encoding to get your result
* displayed correctly.
* If you want to see what I mean, go to demo.php and demo1.php
*
* -- BETA 1.0 2003-10-21 --
*
* -- You should know about... --
* For good understanding this class you shouls read all this stuff first :) but if you are
* in a hurry just start the demo.php and see what's inside.
* 1. That I'm not good in english at 03:45 :) - so forgive me all mistakes
* 2. This class is a BETA version because I haven't tested it enough
* 3. Feel free to contact me with questions, bug reports and mistakes in PHP and this documentation (email below)
*
* -- In a few words... --
* Why ConvertCharset class?
*
* I have made this class because I had a lot of problems with diferent charsets. First because people
* from Microsoft wanted to have thair own encoding, second because people from Macromedia didn't
* thought about other languages, third because sometimes I need to use text written on MAC, and of course
* it has its own encoding :)
*
* Notice & remember:
* - When I'm saying 1 byte string I mean 1 byte per char.
* - When I'm saying multibyte string I mean more than one byte per char.
*
* So, this are main FEATURES of this class:
* - conversion between 1 byte charsets
* - conversion from 1 byte to multi byte charset (utf-8)
* - conversion from multibyte charset (utf-8) to 1 byte charset
* - every conversion output can be save with numeric entities (browser charset independent - not a full truth)
*
* This is a list of charsets you can operate with, the basic rule is that a char have to be in both charsets,
* otherwise you'll get an error.
*
* - WINDOWS
* - windows-1250 - Central Europe
* - windows-1251 - Cyrillic
* - windows-1252 - Latin I
* - windows-1253 - Greek
* - windows-1254 - Turkish
* - windows-1255 - Hebrew
* - windows-1256 - Arabic
* - windows-1257 - Baltic
* - windows-1258 - Viet Nam
* - cp874 - Thai - this file is also for DOS
*
* - DOS
* - cp437 - Latin US
* - cp737 - Greek
* - cp775 - BaltRim
* - cp850 - Latin1
* - cp852 - Latin2
* - cp855 - Cyrylic
* - cp857 - Turkish
* - cp860 - Portuguese
* - cp861 - Iceland
* - cp862 - Hebrew
* - cp863 - Canada
* - cp864 - Arabic
* - cp865 - Nordic
* - cp866 - Cyrylic Russian (this is the one, used in IE "Cyrillic (DOS)" )
* - cp869 - Greek2
*
* - MAC (Apple)
* - x-mac-cyrillic
* - x-mac-greek
* - x-mac-icelandic
* - x-mac-ce
* - x-mac-roman
*
* - ISO (Unix/Linux)
* - iso-8859-1
* - iso-8859-2
* - iso-8859-3
* - iso-8859-4
* - iso-8859-5
* - iso-8859-6
* - iso-8859-7
* - iso-8859-8
* - iso-8859-9
* - iso-8859-10
* - iso-8859-11
* - iso-8859-12
* - iso-8859-13
* - iso-8859-14
* - iso-8859-15
* - iso-8859-16
*
* - MISCELLANEOUS
* - gsm0338 (ETSI GSM 03.38)
* - cp037
* - cp424
* - cp500
* - cp856
* - cp875
* - cp1006
* - cp1026
* - koi8-r (Cyrillic)
* - koi8-u (Cyrillic Ukrainian)
* - nextstep
* - us-ascii
* - us-ascii-quotes
*
* - DSP implementation for NeXT
* - stdenc
* - symbol
* - zdingbat
*
* - And specially for old Polish programs
* - mazovia
*
* -- Now, to the point... --
* Here are main variables.
*
* DEBUG_MODE
*
* You can set this value to:
* - -1 - No errors or comments
* - 0 - Only error messages, no comments
* - 1 - Error messages and comments
*
* Default value is 1, and during first steps with class it should be left as is.
*
* CONVERT_TABLES_DIR
*
* This is a place where you store all files with charset encodings. Filenames should have
* the same names as encodings. My advise is to keep existing names, because thay
* were taken from unicode.org (www.unicode.org), and after update to unicode 3.0 or 4.0
* the names of files will be the same, so if you want to save your time...uff, leave the
* names as thay are for future updates.
*
* The directory with edings files should be in a class location directory by default,
* but of course you can change it if you like.
*
* @package All about charset...
* @author Mikolaj Jedrzejak
* @copyright Copyright Mikolaj Jedrzejak (c) 2003-2004
* @version 1.0 2004-07-27 23:11
* @access public
*
* @link http://www.unicode.org Unicode Homepage
**/
class ConvertCharset {
var $RecognizedEncoding; //This value keeps information if string contains multibyte chars.
var $Entities; // This value keeps information if output should be with numeric entities.
/**
* CharsetChange::NumUnicodeEntity()
*
* Unicode encoding bytes, bits representation.
* Each b represents a bit that can be used to store character data.
* - bytes, bits, binary representation
* - 1, 7, 0bbbbbbb
* - 2, 11, 110bbbbb 10bbbbbb
* - 3, 16, 1110bbbb 10bbbbbb 10bbbbbb
* - 4, 21, 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
*
* This function is written in a "long" way, for everyone who woluld like to analize
* the process of unicode encoding and understand it. All other functions like HexToUtf
* will be written in a "shortest" way I can write tham :) it does'n mean thay are short
* of course. You can chech it in HexToUtf() (link below) - very similar function.
*
* IMPORTANT: Remember that $UnicodeString input CANNOT have single byte upper half
* extended ASCII codes, why? Because there is a posibility that this function will eat
* the following char thinking it's miltibyte unicode char.
*
* @param string $UnicodeString Input Unicode string (1 char can take more than 1 byte)
* @return string This is an input string olso with unicode chars, bus saved as entities
* @see HexToUtf()
**/
function UnicodeEntity ($UnicodeString)
{
$OutString = "";
$StringLenght = strlen ($UnicodeString);
for ($CharPosition = 0; $CharPosition < $StringLenght; $CharPosition++)
{
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
if ($AsciiChar < 128) //1 7 0bbbbbbb (127)
{
$OutString .= $Char;
}
else if ($AsciiChar >> 5 == 6) //2 11 110bbbbb 10bbbbbb (2047)
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$AsciiChar = ($FirstByte * 64) + $SecondByte;
$Entity = sprintf ("%d;", $AsciiChar);
$OutString .= $Entity;
}
else if ($AsciiChar >> 4 == 14) //3 16 1110bbbb 10bbbbbb 10bbbbbb
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$ThidrByte = ($AsciiChar & 63);
$AsciiChar = ((($FirstByte * 64) + $SecondByte) * 64) + $ThidrByte;
$Entity = sprintf ("%d;", $AsciiChar);
$OutString .= $Entity;
}
else if ($AsciiChar >> 3 == 30) //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$ThidrByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$FourthByte = ($AsciiChar & 63);
$AsciiChar = ((((($FirstByte * 64) + $SecondByte) * 64) + $ThidrByte) * 64) + $FourthByte;
$Entity = sprintf ("%d;", $AsciiChar);
$OutString .= $Entity;
}
}
return $OutString;
}
/**
* ConvertCharset::HexToUtf()
*
* This simple function gets unicode char up to 4 bytes and return it as a regular char.
* It is very similar to UnicodeEntity function (link below). There is one difference
* in returned format. This time it's a regular char(s), in most cases it will be one or two chars.
*
* @param string $UtfCharInHex Hexadecimal value of a unicode char.
* @return string Encoded hexadecimal value as a regular char.
* @see UnicodeEntity()
**/
function HexToUtf ($UtfCharInHex)
{
$OutputChar = "";
$UtfCharInDec = hexdec($UtfCharInHex);
if($UtfCharInDec<128) $OutputChar .= chr($UtfCharInDec);
else if($UtfCharInDec<2048)$OutputChar .= chr(($UtfCharInDec>>6)+192).chr(($UtfCharInDec&63)+128);
else if($UtfCharInDec<65536)$OutputChar .= chr(($UtfCharInDec>>12)+224).chr((($UtfCharInDec>>6)&63)+128).chr(($UtfCharInDec&63)+128);
else if($UtfCharInDec<2097152)$OutputChar .= chr($UtfCharInDec>>18+240).chr((($UtfCharInDec>>12)&63)+128).chr(($UtfCharInDec>>6)&63+128). chr($UtfCharInDec&63+128);
return $OutputChar;
}
/**
* CharsetChange::MakeConvertTable()
*
* This function creates table with two SBCS (Single Byte Character Set). Every conversion
* is through this table.
*
* - The file with encoding tables have to be save in "Format A" of unicode.org charset table format! This is usualy writen in a header of every charset file.
* - BOTH charsets MUST be SBCS
* - The files with encoding tables have to be complet (Non of chars can be missing, unles you are sure you are not going to use it)
*
* "Format A" encoding file, if you have to build it by yourself should aplly these rules:
* - you can comment everything with #
* - first column contains 1 byte chars in hex starting from 0x..
* - second column contains unicode equivalent in hex starting from 0x....
* - then every next column is optional, but in "Format A" it should contain unicode char name or/and your own comment
* - the columns can be splited by "spaces", "tabs", "," or any combination of these
* - below is an example
*
*
* #
* # The entries are in ANSI X3.4 order.
* #
* 0x00 0x0000 # NULL end extra comment, if needed
* 0x01 0x0001 # START OF HEADING
* # Oh, one more thing, you can make comments inside of a rows if you like.
* 0x02 0x0002 # START OF TEXT
* 0x03 0x0003 # END OF TEXT
* next line, and so on...
*
*
* You can get full tables with encodings from http://www.unicode.org
*
* @param string $FirstEncoding Name of first encoding and first encoding filename (thay have to be the same)
* @param string $SecondEncoding Name of second encoding and second encoding filename (thay have to be the same). Optional for building a joined table.
* @return array Table necessary to change one encoding to another.
**/
function MakeConvertTable ($FirstEncoding, $SecondEncoding = "")
{
$ConvertTable = array();
for($i = 0; $i < func_num_args(); $i++)
{
/**
* Because func_*** can't be used inside of another function call
* we have to save it as a separate value.
**/
$FileName = func_get_arg($i);
if (!is_file(CONVERT_TABLES_DIR . $FileName))
{
print $this->DebugOutput(0, 0, CONVERT_TABLES_DIR . $FileName); //Print an error message
exit;
}
$FileWithEncTabe = fopen(CONVERT_TABLES_DIR . $FileName, "r") or die(); //This die(); is just to make sure...
while(!feof($FileWithEncTabe))
{
/**
* We asume that line is not longer
* than 1024 which is the default value for fgets function
**/
if($OneLine=trim(fgets($FileWithEncTabe, 1024)))
{
/**
* We don't need all comment lines. I check only for "#" sign, because
* this is a way of making comments by unicode.org in thair encoding files
* and that's where the files are from :-)
**/
if (substr($OneLine, 0, 1) != "#")
{
/**
* Sometimes inside the charset file the hex walues are separated by
* "space" and sometimes by "tab", the below preg_split can also be used
* to split files where separator is a ",", "\r", "\n" and "\f"
**/
$HexValue = preg_split ("/[\s,]+/", $OneLine, 3); //We need only first 2 values
/**
* Sometimes char is UNDEFINED, or missing so we can't use it for convertion
**/
if (substr($HexValue[1], 0, 1) != "#")
{
$ArrayKey = strtoupper(str_replace(strtolower("0x"), "", $HexValue[1]));
$ArrayValue = strtoupper(str_replace(strtolower("0x"), "", $HexValue[0]));
$ConvertTable[func_get_arg($i)][$ArrayKey] = $ArrayValue;
}
} //if (substr($OneLine,...
} //if($OneLine=trim(f...
} //while(!feof($FirstFileWi...
} //for($i = 0; $i < func_...
/**
* The last thing is to check if by any reason both encoding tables are not the same.
* For example, it will happen when you save the encoding table file with a wrong name
* - of another charset.
**/
if ((func_num_args() > 1) && (count($ConvertTable[$FirstEncoding]) == count($ConvertTable[$SecondEncoding])) && (count(array_diff_assoc($ConvertTable[$FirstEncoding], $ConvertTable[$SecondEncoding])) == 0))
{
print $this->DebugOutput(1, 1, "$FirstEncoding, $SecondEncoding");
}
return $ConvertTable;
}
/**
* ConvertCharset::Convert()
*
* This is a basic function you are using. I hope that you can figure out this function syntax :-)
*
* @param string $StringToChange The string you want to change :)
* @param string $FromCharset Name of $StringToChange encoding, you have to know it.
* @param string $ToCharset Name of a charset you want to get for $StringToChange.
* @param boolean $TurnOnEntities Set to true or 1 if you want to use numeric entities insted of regular chars.
* @return string Converted string in brand new encoding :)
* @version 1.0 2004-07-27 01:09
**/
function Convert ($StringToChange, $FromCharset, $ToCharset, $TurnOnEntities = false)
{
/**
* Check are there all variables
**/
if ($StringToChange == "")
{
print $this->DebugOutput(0, 3, "\$StringToChange");
}
else if ($FromCharset == "")
{
print $this->DebugOutput(0, 3, "\$FromCharset");
}
else if ($ToCharset == "")
{
print $this->DebugOutput(0, 3, "\$ToCharset");
}
/**
* Now a few variables need to be set.
**/
$NewString = "";
$this->Entities = $TurnOnEntities;
/**
* For all people who like to use uppercase for charset encoding names :)
**/
$FromCharset = strtolower($FromCharset);
$ToCharset = strtolower($ToCharset);
/**
* Of course you can make a conversion from one charset to the same one :)
* but I feel obligate to let you know about it.
**/
if ($FromCharset == $ToCharset)
{
print $this->DebugOutput(1, 0, $FromCharset);
}
if (($FromCharset == $ToCharset) AND ($FromCharset == "utf-8"))
{
print $this->DebugOutput(0, 4, $FromCharset);
exit;
}
/**
* This divison was made to prevent errors during convertion to/from utf-8 with
* "entities" enabled, because we need to use proper destination(to)/source(from)
* encoding table to write proper entities.
*
* This is the first case. We are convertinf from 1byte chars...
**/
if ($FromCharset != "utf-8")
{
/**
* Now build table with both charsets for encoding change.
**/
if ($ToCharset != "utf-8")
{
$CharsetTable = $this->MakeConvertTable ($FromCharset, $ToCharset);
}
else
{
$CharsetTable = $this->MakeConvertTable ($FromCharset);
}
/**
* For each char in a string...
**/
for ($i = 0; $i < strlen($StringToChange); $i++)
{
$HexChar = "";
$UnicodeHexChar = "";
$HexChar = strtoupper(dechex(ord($StringToChange[$i])));
// This is fix from Mario Klingemann, it prevents
// droping chars below 16 because of missing leading 0 [zeros]
if (strlen($HexChar)==1) $HexChar = "0".$HexChar;
//end of fix by Mario Klingemann
// This is quick fix of 10 chars in gsm0338
// Thanks goes to Andrea Carpani who pointed on this problem
// and solve it ;)
if (($FromCharset == "gsm0338") && ($HexChar == '1B')) {
$i++;
$HexChar .= strtoupper(dechex(ord($StringToChange[$i])));
}
// end of workarround on 10 chars from gsm0338
if ($ToCharset != "utf-8")
{
if (in_array($HexChar, $CharsetTable[$FromCharset]))
{
$UnicodeHexChar = array_search($HexChar, $CharsetTable[$FromCharset]);
$UnicodeHexChars = explode("+",$UnicodeHexChar);
for($UnicodeHexCharElement = 0; $UnicodeHexCharElement < count($UnicodeHexChars); $UnicodeHexCharElement++)
{
if (array_key_exists($UnicodeHexChars[$UnicodeHexCharElement], $CharsetTable[$ToCharset]))
{
if ($this->Entities == true)
{
$NewString .= $this->UnicodeEntity($this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]));
}
else
{
$NewString .= chr(hexdec($CharsetTable[$ToCharset][$UnicodeHexChars[$UnicodeHexCharElement]]));
}
}
else
{
print $this->DebugOutput(0, 1, $StringToChange[$i]);
}
} //for($UnicodeH...
}
else
{
print $this->DebugOutput(0, 2,$StringToChange[$i]);
}
}
else
{
if (in_array("$HexChar", $CharsetTable[$FromCharset]))
{
$UnicodeHexChar = array_search($HexChar, $CharsetTable[$FromCharset]);
/**
* Sometimes there are two or more utf-8 chars per one regular char.
* Extream, example is polish old Mazovia encoding, where one char contains
* two lettes 007a (z) and 0142 (l slash), we need to figure out how to
* solve this problem.
* The letters are merge with "plus" sign, there can be more than two chars.
* In Mazowia we have 007A+0142, but sometimes it can look like this
* 0x007A+0x0142+0x2034 (that string means nothing, it just shows the possibility...)
**/
$UnicodeHexChars = explode("+",$UnicodeHexChar);
for($UnicodeHexCharElement = 0; $UnicodeHexCharElement < count($UnicodeHexChars); $UnicodeHexCharElement++)
{
if ($this->Entities == true)
{
$NewString .= $this->UnicodeEntity($this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]));
}
else
{
$NewString .= $this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]);
}
} // for
}
else
{
print $this->DebugOutput(0, 2, $StringToChange[$i]);
}
}
}
}
/**
* This is second case. We are encoding from multibyte char string.
**/
else if($FromCharset == "utf-8")
{
$HexChar = "";
$UnicodeHexChar = "";
$CharsetTable = $this->MakeConvertTable ($ToCharset);
foreach ($CharsetTable[$ToCharset] as $UnicodeHexChar => $HexChar)
{
if ($this->Entities == true) {
$EntitieOrChar = $this->UnicodeEntity($this->HexToUtf($UnicodeHexChar));
}
else
{
$EntitieOrChar = chr(hexdec($HexChar));
}
$StringToChange = str_replace($this->HexToUtf($UnicodeHexChar), $EntitieOrChar, $StringToChange);
}
$NewString = $StringToChange;
}
return $NewString;
}
/**
* ConvertCharset::DebugOutput()
*
* This function is not really necessary, the debug output could stay inside of
* source code but like this, it's easier to manage and translate.
* Besides I couldn't find good coment/debug class :-) Maybe I'll write one someday...
*
* All messages depend on DEBUG_MODE level, as I was writing before you can set this value to:
* - -1 - No errors or notces are shown
* - 0 - Only error messages are shown, no notices
* - 1 - Error messages and notices are shown
*
* @param int $Group Message groupe: error - 0, notice - 1
* @param int $Number Following message number
* @param mix $Value This walue is whatever you want, usualy it's some parameter value, for better message understanding.
* @return string String with a proper message.
**/
function DebugOutput ($Group, $Number, $Value = false)
{
//$Debug [$Group][$Number] = "Message, can by with $Value";
//$Group[0] - Errors
//$Group[1] - Notice
$Debug[0][0] = "Error, can NOT read file: " . $Value . " ";
$Debug[0][1] = "Error, can't find maching char \"". $Value ."\" in destination encoding table!" . " ";
$Debug[0][2] = "Error, can't find maching char \"". $Value ."\" in source encoding table!" . " ";
$Debug[0][3] = "Error, you did NOT set variable " . $Value . " in Convert() function." . " ";
$Debug[0][4] = "You can NOT convert string from " . $Value . " to " . $Value . "!" . " ";
$Debug[1][0] = "Notice, you are trying to convert string from ". $Value ." to ". $Value .", don't you feel it's strange? ;-)" . " ";
$Debug[1][1] = "Notice, both charsets " . $Value . " are identical! Check encoding tables files." . " ";
$Debug[1][2] = "Notice, there is no unicode char in the string you are trying to convert." . " ";
if (DEBUG_MODE >= $Group)
{
return $Debug[$Group][$Number];
}
} // function DebugOutput
} //class ends here
?>