View of /mambo/branches/4.5.4/index.php
Parent Directory
|
Revision Log
Revision 89 -
(download)
(annotate)
Sat Dec 31 10:56:58 2005 UTC (7 years, 5 months ago) by counterpoint
File size: 101791 byte(s)
Sat Dec 31 10:56:58 2005 UTC (7 years, 5 months ago) by counterpoint
File size: 101791 byte(s)
Addition of mosFileManager and mosDirectory classes, further reduction of mambofunc.php.
<?php /** * @version $Id: index.php,v 1.47 2005/08/26 08:10:43 mambofoundation Exp $ * @package Mambo * @copyright (C) 2000 - 2005 Miro International Pty Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * Mambo is Free Software */ /** Set flag that this is a parent file */ define( '_VALID_MOS', 1 ); $protects = array('_REQUEST', '_GET', '_POST', '_COOKIE', '_FILES', '_SERVER', '_ENV', 'GLOBALS', '_SESSION'); foreach ($protects as $protect) { if ( in_array($protect , array_keys($_REQUEST)) || in_array($protect , array_keys($_GET)) || in_array($protect , array_keys($_POST)) || in_array($protect , array_keys($_COOKIE)) || in_array($protect , array_keys($_FILES))) { die("Invalid Request."); } } /** * Utility function to return a value from a named array or a specified default */ define( "_MOS_NOTRIM", 0x0001 ); define( "_MOS_ALLOWHTML", 0x0002 ); define( "_MOS_ALLOWRAW", 0x0004 ); define( "_MOS_NOMAGIC", 0x0008 ); function mosGetParam( &$arr, $name, $def=null, $mask=0 ) { if (isset( $arr[$name] )) { if (is_array($arr[$name])) foreach ($arr[$name] as $key=>$element) $result[$key] = mosGetParam ($arr[$name], $key, $def, $mask); else { $result = $arr[$name]; if (!($mask&_MOS_NOTRIM)) $result = trim($result); if (!is_numeric( $result)) { if (!($mask&_MOS_ALLOWHTML)) $result = strip_tags($result); if (!($mask&_MOS_ALLOWRAW)) { if (is_numeric($def)) $result = intval($result); } } } return $result; } else { return $def; } } function sefRelToAbs ($string) { $sef = mosSEF::getInstance(); return $sef->sefRelToAbs($string); } /** * @version $Id: version.php,v 1.6 2005/08/17 04:03:42 eddieajau Exp $ * @package Mambo * @copyright (C) 2000 - 2005 Miro International Pty Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * Mambo is Free Software */ /** Version information */ class version { /** @var string Product */ var $PRODUCT = 'Mambo'; /** @var int Main Release Level */ var $RELEASE = '4.5'; /** @var string Development Status */ var $DEV_STATUS = 'Stable'; /** @var int Sub Release Level */ var $DEV_LEVEL = '4'; /** @var string Codename */ var $CODENAME = 'Titan'; /** @var string Date */ var $RELDATE = '17-Aug-2005'; /** @var string Time */ var $RELTIME = '03:00'; /** @var string Timezone */ var $RELTZ = 'GMT'; /** @var string Copyright Text */ var $COPYRIGHT = 'Copyright 2000 - 2005 Miro International Pty Ltd. All rights reserved.'; /** @var string URL */ var $URL = '<a href="http://www.mamboserver.com">Mambo</a> is Free Software released under the GNU/GPL License.'; } class mamboCore { var $rootPath = ''; var $Itemid = 0; var $option = ''; var $_db; var $do_gzip_compress = false; var $_section_limit = 250; var $_section_status = 0; var $_sections; function mamboCore () { global $adminside; $this->rootPath = $this->allButLast('/',$_SERVER['SCRIPT_FILENAME']); if ($adminside) $this->rootPath = substr($this->rootPath,0,strlen($this->rootPath)-14); $this->checkConfig(); $this->Itemid = mosGetParam($_REQUEST, 'Itemid', 0); $this->getConfig(); $this->fixLanguage(); $this->secure(); } function &getMamboCore () { static $instance; if (!is_object($instance)) $instance = new mamboCore(); return $instance; } function rootPath () { if (realpath($this->rootPath) === false) die ('Invalid program load path'); return $this->rootPath; } function get ($property) { $config =& mamboCore::getMamboCore(); if ($property == 'mosConfig_absolute_path' AND realpath($config->mosConfig_absolute_path) === false) die ('Invalid program load path'); if (isset($config->$property)) return $config->$property; trigger_error("Invalid property ($property) requested from mamboCore"); return null; } function is_set ($property) { $config =& mamboCore::getMamboCore(); return isset($config->$property); } function set ($property, $value) { $config =& mamboCore::getMamboCore(); $config->$property = $value; $GLOBALS[$property] = $value; return $value; } function checkConfig () { // checks for configuration file, if none found loads installation page if (!file_exists($this->rootPath.'configuration.php') OR filesize($this->rootPath.'configuration.php') < 10 ) { header( 'Location: installation/index.php' ); exit(); } } function getConfig () { $code = ''; $f = @fopen($this->rootPath.'configuration.php','rb'); if ($f) { while ($f AND !feof($f)) { $line = fgets($f, 256); $altered = str_replace('$', '$this->', $line); if ($line != $altered) $code .= $altered; } } else { header( 'Location: installation/index.php' ); exit(); } fclose($f); eval($code); preg_match_all('/\$this\-\>([A-Za-z_][A-Za-z0-9_]*)/', $code, $matches); foreach ($matches[1] as $match) $GLOBALS[$match] = $this->$match; if (!isset($this->mosConfig_register_globals)) { $this->mosConfig_register_globals = 0; $GLOBALS['mosConfig_register_globals'] = 0; } } function offlineCheck (&$user, &$database) { if ($this->mosConfig_offline) { require_once($this->rootPath().'/administrator/includes/admin.php'); session_name(md5($this->mosConfig_live_site)); session_start(); if ($user =& checkAdminSession($database)) return; include("$this->mosConfig_absolute_path/offline.php"); exit(); } } function fixLanguage () { if (isset($this->mosConfig_lang) AND $this->mosConfig_lang); else $this->set('mosConfig_lang', 'english'); $language_file = "$this->mosConfig_absolute_path/language/$this->mosConfig_lang.php"; if (file_exists($language_file)) require_once ($language_file); } function secure () { $this->mosConfig_unsecure_site = $this->mosConfig_live_site; if ($_SERVER['SERVER_PORT'] == 443) { if (!isset($this->mosConfig_secure_site)) $this->mosConfig_secure_site = str_replace('http://', 'https://', $this->mosConfig_live_site); $this->mosConfig_live_site = $this->mosConfig_secure_site; } } function handleGlobals () { $superglobals = array($_SERVER, $_ENV, $_FILES, $_COOKIE, $_POST, $_GET); if (isset( $_SESSION )) array_unshift ( $superglobals , $_SESSION ); // Emulate register_globals on if (!ini_get('register_globals') && $this->mosConfig_register_globals) { while(list($key,$value)=each($_GET)) { if (!isset($GLOBALS[$key])) $GLOBALS[$key]=$value; } } // Emulate register_globals off elseif (ini_get('register_globals') && !$this->mosConfig_register_globals) { foreach ( $superglobals as $superglobal ) { foreach ( $superglobal as $key => $value) { unset( $GLOBALS[$key]); } } } } function determineOptionAndItemid () { if ($option = strtolower(mosGetParam($_REQUEST, 'option'))); else { if (!is_object($this->_db)) $this->_db = mamboDatabase::getInstance(); $menuhandler = mosMenuHandler::getInstance(); $menus =& $menuhandler->getByParentOrder($this->Itemid, 'mainmenu'); $this->Itemid = $menus[0]->id; $link = $menus[0]->link; if (($pos = strpos( $link, '?' )) !== false) $link = substr( $link, $pos+1 ). '&Itemid='.$this->Itemid; parse_str( $link, $temp ); /** this is a patch, need to rework when globals are handled better */ foreach ($temp as $k=>$v) $GLOBALS[$k] = $_REQUEST[$k] = $v; if (isset($temp['option'])) $option = $temp['option']; else return ''; } /** patch to lessen the impact on templates */ if ($option == 'search') $option = 'com_search'; // checking if we can find the Itemid thru the content if ( $option == 'com_content' && $this->Itemid === 0 ) $this->Itemid = $this->getItemid(mosGetParam($_REQUEST, 'id', 0 )); return $option; } function redirect ($url, $msg='') { $callcheck = array('InputFilter', 'process'); if (!is_callable($callcheck)) require_once(mamboCore::get('mosConfig_absolute_path').'/includes/phpinputfilter/class.inputfilter.php'); // specific filters $iFilter =& new InputFilter(); $url = $iFilter->process( $url ); $message = trim($iFilter->process($msg)); if ($iFilter->badAttributeValue(array('href', $url))) $url = $GLOBALS['mosConfig_live_site']; if ($message) { if (strpos($url, '?')) $url .= '&mosmsg='.urlencode($message); else $url .= '?mosmsg='.urlencode($message); } if (headers_sent()) echo "<script>document.location.href='$url';</script>\n"; else { @ob_end_clean(); // clear output buffer header( "Location: $url" ); } exit(); } function logMessage ($text) { // JS Popup message if (mosGetParam( $_POST, 'message', 0 )) { ?> <script type="text/javascript"> <!--// alert( "<?php echo $text; ?>" ); //--> </script> <?php } if ($return = mosGetParam( $_REQUEST, 'return', '' )) { $this->redirect( $return ); } else { $this->redirect( $this->mosConfig_live_site.'/index.php' ); } } function handleLogin ($session) { require_once($this->rootPath().'/includes/authenticator.php'); $authenticator = mamboAuthenticator::getInstance(); $authenticator->loginUser(); $this->logMessage(_LOGIN_SUCCESS); } function handleLogout ($session) { require_once($this->rootPath().'/includes/authenticator.php'); $authenticator = mamboAuthenticator::getInstance(); $authenticator->logoutUser(); @session_destroy(); $this->logMessage(_LOGOUT_SUCCESS); } function standardHeaders () { header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); header( 'Cache-Control: no-store, no-cache, must-revalidate' ); header( 'Cache-Control: post-check=0, pre-check=0', false ); header( 'Pragma: no-cache' ); $mambothandler = mosMambotHandler::getInstance(); $mambothandler->loadBotGroup('system'); $mambothandler->trigger('onHeaders', array($this)); } function initGzip() { $this->do_gzip_compress = FALSE; //zlib.output_compression and ob_gzhandler don't get along well so we'll check to make //that zlib.output_compression is not enable in the php.ini before turning on ob_gzhandler if ( $this->mosConfig_gzip == 1 && (int)ini_get('zlib.output_compression') != 1 ) { $phpver = phpversion(); $useragent = mosGetParam( $_SERVER, 'HTTP_USER_AGENT', '' ); $canZip = mosGetParam( $_SERVER, 'HTTP_ACCEPT_ENCODING', '' ); if ( $phpver >= '4.0.4pl1' && ( strpos($useragent,'compatible') !== false || strpos($useragent,'Gecko') !== false ) ) { if ( extension_loaded('zlib') ) { ob_start( 'ob_gzhandler' ); return; } } else if ( $phpver > '4.0' ) { if ( strpos($canZip,'gzip') !== false ) { if (extension_loaded( 'zlib' )) { $this->do_gzip_compress = TRUE; ob_start(); ob_implicit_flush(0); header( 'Content-Encoding: gzip' ); return; } } } } ob_start(); } /** * Perform GZIP */ function doGzip() { if ( $this->do_gzip_compress ) { /** *Borrowed from php.net! */ $gzip_contents = ob_get_contents(); ob_end_clean(); $gzip_size = strlen($gzip_contents); $gzip_crc = crc32($gzip_contents); $gzip_contents = gzcompress($gzip_contents, 9); $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4); echo "\x1f\x8b\x08\x00\x00\x00\x00\x00"; echo $gzip_contents; echo pack('V', $gzip_crc); echo pack('V', $gzip_size); } else { ob_end_flush(); } } function getLastPart ($separator, $field) { $parts = explode($separator, $field); return $parts[count($parts)-1]; } function allButLast ($separator, $field) { $lastSize = strlen(mamboCore::getLastPart($separator,$field)); return substr($field, 0, strlen($field)-$lastSize); } function getSection ($id) { $limit = $this->_section_limit; if (!$this->_section_status) { $this->_db->setQuery("SELECT i.id, i.sectionid FROM #__content AS i, #__sections AS s WHERE i.sectionid=s.id ORDER BY i.id DESC LIMIT $limit"); $sections = $this->_db->loadObjectList(); if ($sections) { foreach ($sections as $section) $this->_sections[$section->id] = $section->sectionid; $this->_section_status = count($sections); } } if ($this->_section_status) { if (isset($this->_sections[$id])) return $this->_sections[$id]; if (count($this->_sections) < $limit) return 0; $this->_db->setQuery("SELECT i.sectionid FROM #__content AS i, #__sections AS s WHERE i.sectionid=s.id AND i.id=$id"); return $this->_db->loadResult(); } else return 0; } function getItemid ($id, $typed=1, $link=1, $bs=1, $bc=1, $gbs=1) { if (!is_object($this->_db)) $this->_db = mamboDatabase::getInstance(); $_Itemid = null; $menuhandler = mosMenuHandler::getInstance(); if ($typed) { // Search for typed link $_Itemid = $menuhandler->getIDByTypeLink('content_typed', "index.php?option=com_content&task=view&id=$id"); } if ($_Itemid == null AND $link) { // Search for item link $_Itemid = $menuhandler->getIDByTypeLink('content_item_link', "index.php?option=com_content&task=view&id=$id"); } $sectionid = $this->getSection($id); if ($_Itemid == null) { // Search in sections $_Itemid = $menuhandler->getIDByTypeCid ('content_section', $sectionid); } if ($_Itemid == null) { // Search in sections $_Itemid = $menuhandler->getIDByTypeCid ('content_blog_section', $sectionid); } if ($_Itemid == null) { // Search in sections $_Itemid = $menuhandler->getIDByTypeCid ('content_blog_category', $sectionid); } if ($_Itemid == null AND $gbs) { // Search in global blog section $_Itemid = $menuhandler->getIDByTypeCid('content_blog_section', 0); } /* if ($_Itemid == '') { // Search in global blog category $this->_db->setQuery( "SELECT id " ."\nFROM #__menu " ."\nWHERE type='content_blog_category' AND published='1' AND componentid=0" ); $_Itemid = $this->_db->loadResult(); } */ if ($_Itemid) $this->Itemid = $_Itemid; return $this->Itemid; } } /** * Sorts an Array of objects */ class mosObjectSorter { var $_keyname = ''; var $_direction = 0; var $_object_array = array(); function mosObjectSorter (&$a, $k, $sort_direction=1) { $this->_keyname = $k; $this->_direction = $sort_direction; $this->_object_array =& $a; $this->sort(); } function mosObjectCompare (&$a, &$b) { $key = $this->_keyname; if ($a->$key > $b->$key) return $this->_direction; if ($a->$key < $b->$key) return -$this->_direction; return 0; } function sort () { usort($this->_object_array, array($this,'mosObjectCompare')); } } /** * Pathway handler * @package Mambo */ class mosPathway { /** @var array Names for display in pathway */ var $_names = null; /** @var array URLs for links from pathway */ var $_urls = null; /** * Constructor */ function mosPathway () { $menuhandler = mosMenuHandler::getInstance(); $menus =& $menuhandler->getByParentOrder(0,'mainmenu'); $home = $menus[0]; $this->_names[] = $home->name; $this->_urls[] = sefRelToAbs($home->link."&Itemid=$home->id"); } /** * Singleton accessor */ function &getInstance () { static $instance; if (!is_object($instance)) $instance = new mosPathway(); return $instance; } /** * Add an item to the pathway */ function addItem ($name, $url) { $last = count($this->_names) - 1; if (!$name) return; if ($name == $this->_names[$last] AND $url == $this->_urls[$last]) return; $this->_names[$last+1] = $name; $this->_urls[$last+1] = $url; } function reduceToOne () { for ($i = count($this->_names) - 1; $i > 0; $i--) { unset($this->_names[$i]); unset($this->_urls[$i]); } } /** * Make a pathway string for display */ function makePathway () { $mainframe = mosMainFrame::getInstance(); $result = "<span class='pathway'>"; $config = mamboCore::getMamboCore(); $rootpath = $config->rootPath(); $imgPath = 'templates/'.$mainframe->getTemplate().'/images/arrow.png'; if (file_exists( "$rootpath/$imgPath" )) $img = "<img src='$config->mosConfig_live_site/$imgPath' border='0' alt='arrow' />"; else { $imgPath = '/images/M_images/arrow.png'; if (file_exists( "$rootpath/$imgPath" )) $img = "<img src='$config->mosConfig_live_site/images/M_images/arrow.png' alt='arrow' />"; else $img = '>'; } $last = count($this->_names) - 1; foreach ($this->_names as $i=>$name) { if ($i === $last) $result .= "$name</span>"; else { $sefurl = sefRelToAbs($this->_urls[$i]); $result .= "<a href='$sefurl' class='pathway'>$name</a>"; $result .= " $img "; } } return $result; } } /** * Module database table class * @package Mambo */ class mosMenu extends mosDBTable { /** @var int Primary key */ var $id=null; /** @var string */ var $menutype=null; /** @var string */ var $name=null; /** @var string */ var $link=null; /** @var int */ var $type=null; /** @var int */ var $published=null; /** @var int */ var $componentid=null; /** @var int */ var $parent=null; /** @var int */ var $sublevel=null; /** @var int */ var $ordering=null; /** @var boolean */ var $checked_out=null; /** @var datetime */ var $checked_out_time=null; /** @var boolean */ var $pollid=null; /** @var string */ var $browserNav=null; /** @var int */ var $access=null; /** @var int */ var $utaccess=null; /** @var string */ var $params=null; /** * @param database A database connector object */ function mosMenu( $dummy ) { $db = mamboDatabase::getInstance(); $this->mosDBTable( '#__menu', 'id', $db ); } /** * binds an array/hash to this object * @param int $oid optional argument, if not specifed then the value of current key is used * @return any result from the database operation */ function load( $oid=null ) { $k = $this->_tbl_key; if ($oid !== null) $this->$k = $oid; if ($this->$k === null) return false; $menuhandler = mosMenuHandler::getInstance(); $menu = $menuhandler->getMenuById($this->$k); if ($menu) { foreach (get_object_vars($menu) as $key=>$data) $this->$key = $data; return true; } else return false; } } /** * File Manager including safe mode provision? * @package Mambo */ class mosFileManager { /** * Singleton accessor */ function &getInstance () { static $instance; if (!is_object($instance)) $instance = new mosFileManager(); return $instance; } /** * Function to strip additional / or \ in a path name * @param string The path * @param boolean Add trailing slash */ function mosPathName($p_path, $p_addtrailingslash=true) { if (substr(PHP_OS, 0, 3) == 'WIN') { $retval = str_replace( '/', '\\', $p_path ); if ($p_addtrailingslash AND substr( $retval, -1 ) != '\\') $retval .= '\\'; // Remove double \\ $retval = str_replace( '\\\\', '\\', $retval ); } else { $retval = str_replace( '\\', '/', $p_path ); if ($p_addtrailingslash AND substr( $retval, -1 ) != '/') $retval .= '/'; // Remove double // $retval = str_replace('//','/',$retval); } return $retval; } /** * Chmods files and directories recursively to mos global permissions. Available from 4.5.2 up. * @param path The starting file or directory (no trailing slash) * @param filemode Integer value to chmod files. NULL = dont chmod files. * @param dirmode Integer value to chmod directories. NULL = dont chmod directories. * @return TRUE=all succeeded FALSE=one or more chmods failed */ function mosChmod($path) { $fileperms = mamboCore::get('mosConfig_fileperms'); $dirperms = mamboCore::get('mosConfig_dirperms'); if ($fileperms != '') $filemode = octdec($fileperms); else $filemode = null; if ($dirperms != '') $dirmode = octdec($dirperms); else $dirmode = null; if (isset($filemode) OR isset($dirmode)) return $this->mosChmodRecursive($path, $filemode, $dirmode); return true; } // mosChmod /** * Chmods files and directories recursively to given permissions. Available from 4.5.2 up. * @param path The starting file or directory (no trailing slash) * @param filemode Integer value to chmod files. NULL = dont chmod files. * @param dirmode Integer value to chmod directories. NULL = dont chmod directories. * @return TRUE=all succeeded FALSE=one or more chmods failed */ function mosChmodRecursive($path, $filemode=NULL, $dirmode=NULL) { $ret = true; if (is_dir($path)) { $topdir =& new mosDirectory($path); $files = $topdir->listFiles ('', 'file', true); $dirs = $topdir->listFiles ('', 'dir', true); } else { $files = array($path); $dirs = array(); } if (isset($filemode)) foreach ($files as $file) $ret = @chmod($file, $filemode) ? $ret : false; if (isset($dirmode)) foreach ($dirs as $dir) $ret = @chmod($dir, $dirmode) ? $ret : false; return $ret; } } class mosDirectory { var $path = ''; function mosDirectory ($path) { if (substr($path,strlen($path)-1,1) == '/') $this->path = $path; else $this->path = $path.'/'; } function &listFiles ($pattern='', $type='file', $recurse=false, $fullpath=false) { $results = array(); if ($dir = @opendir($this->path)) { while ($file = readdir($dir)) { if (($file == 'index.html') OR (substr($file,0,1) == '.')) continue; if (is_dir($this->path.$file)) { if ($recurse) { $subdir =& new mosDirectory($this->path.$file); $results = array_merge($results, $subdir->listFiles($pattern, $type, $recurse)); unset($subdir); } if ($type == 'file') continue; } elseif ($type == 'dir') continue; if ($pattern AND !preg_match( "/$pattern/", $file )) continue; if ($fullpath) $results = $this->path.$file; else $results[] = $file; } closedir($dir); } return $results; } function getSize () { $totalsize = 0; $files = $this->listFiles(); foreach ($files as $file) $totalsize += filesize($this->path.$file); return $totalsize; } } /** * Menu handler * @package Mambo */ class mosMenuHandler { /** @var array Menu objects currently available */ var $_menus = null; /** @var array Counts of menu items by type and published status */ var $_counts = null; /** @var array Access to stored menu objects by ID */ var $_idlinks = null; /** @var array Items that may be useful for setting Itemid */ var $_byParentOrder = null; /** * Constructor */ function mosMenuHandler() { global $my; $database = mamboDatabase::getInstance(); $sql = "SELECT * FROM #__menu ORDER BY name"; $this->_menus =& $database->doSQLget($sql, 'mosMenu'); if (!$this->_menus) $this->_menus = array(); foreach ($this->_menus as $key=>$menu) { $this->_idlinks[$menu->id] = $key; if ($menu->published == 1) $this->_byParentOrder[$menu->parent][$menu->ordering][$menu->menutype] = $key; if (isset($this->_counts[$menu->menutype][$menu->published])) $this->_counts[$menu->menutype][$menu->published]++; else $this->_counts[$menu->menutype][$menu->published] = 1; } if ($this->_byParentOrder) { foreach ($this->_byParentOrder as $parent=>$outer) ksort($this->_byParentOrder[$parent]); ksort($this->_byParentOrder); } } /** * Singleton accessor */ function &getInstance () { static $instance; if (!is_object($instance)) $instance = new mosMenuHandler(); return $instance; } function &getMenuByID ($id) { if (isset($this->_idlinks[$id])) { $key = $this->_idlinks[$id]; return $this->_menus[$key]; } $result = null; return $result; } function getMenuCount ($type, $published) { if (isset($this->_counts[$type][$published])) return $this->_counts[$type][$published]; else return 0; } function &getMenusByType ($types) { $checker = explode(',', $types); $result = null; foreach ($this->_menus as $menu) { if (in_array($menu->menutype, $checker)) $result[] = $menu; } return $result; } function getIDByTypeLink ($type, $link) { foreach ($this->_menus as $menu) { if ($menu->published == 1 AND ($type == '*' OR $menu->type == $type) AND $menu->link == $link) return $menu->id; } return null; } function getIDLikeLink ($link) { $exact = $this->getIdByTypeLink('*', $link); if ($exact !== null) return $exact; foreach ($this->_menus as $menu) { if ($menu->published == 1 AND strpos($menu->link,$link) === 0) return $menu->id; } return null; } function getIDByTypeCid ($type, $componentid) { foreach ($this->_menus as $menu) { if ($menu->published == 1 AND $menu->type == $type AND $menu->componentid == $componentid) return $menu->id; } return null; } function getGlobalBlogSectionCount () { $count = 0; foreach ($this->_menus as $menu) { if ($menu->type == 'content_blog_section' AND $menu->published == 1 AND $menu->componentid == 0) $count++; } return $count; } function getContentItemid ($Itemid, $type, $id, $catid=0) { if ($Itemid) return $Itemid; foreach ($this->_menus as $menu) { if (strpos($menu->link,'index.php?option=com_content') === false AND strpos($menu->link,'index.php?option=content') === false) continue; if (strpos($menu->link, $type) === false) continue; if ($catid) { if (strpos($menu->link, "&id=$catid") === false) continue; if (strpos($menu->link, "§ionid=$id") === false) continue; } elseif (strpos($menu->link, "&id=$id") === false) continue; return $menu->id; } return 0; } function maxAccessLink ($link) { $access = 0; foreach ($this->_menus as $menu) { if (strpos($menu->link,$link) === 0 AND $menu->access > $access) $access = $menu->access; } return $access; } function &getByParentOrder ($Itemid, $menutype, $maxaccess=0, $noparent=false) { $result = array(); if ($this->_byParentOrder !== null) { foreach ($this->_byParentOrder as $parent=>$outer) { foreach ($outer as $ordering=>$inner) { foreach ($inner as $mtype=>$last) { $key = $this->_byParentOrder[$parent][$ordering][$mtype]; $menu = $this->_menus[$key]; if ($menutype AND $mtype != $menutype) continue; if ($Itemid AND $Itemid != $menu->id) continue; if ($maxaccess AND $menu->access > $maxaccess) continue; if ($noparent AND $parent != 0) continue; $result[] = $this->_menus[$key]; } } } } return $result; } function setPathway ($Itemid) { if ($Itemid) { $menu = $this->getMenuByID($Itemid); if ($menu->parent) $this->setPathway($menu->parent); $pathway = mosPathway::getInstance(); $pathway->addItem($menu->name, $menu->link."&Itemid=$Itemid"); } } /** * Checks whether a menu option is within the users access level * @param int Item id number * @param string The menu option * @param int The users group ID number * @param database A database connector object * @return boolean True if the visitor's group at least equal to the menu access */ function menuCheck( $Itemid, $menu_option, $task, $gid ) { if ($Itemid) { $menu = $this->getMenuByID($Itemid); $access = $menu->access; } else { $dblink="index.php?option=$menu_option"; if ($task!='') $dblink .= "&task=$task"; $access = $this->maxAccessLink($dblink); } return ($access <= $gid); } function mosGetMenuLink( &$mitem, $level=0, &$params, $Itemid ) { $txt = ''; switch ($mitem->type) { case 'separator': case 'component_item_link': break; case 'content_item_link': $temp = split("&task=view&id=", $mitem->link); if (isset($temp[1])) { $configuration = mamboCore::getMamboCore(); $mitem->link .= '&Itemid='.$configuration->getItemid($temp[1]); } break; case 'url': $link = strtolower($mitem->link); if (substr($link,0,10) == 'index.php?' AND strpos($link,'itemid=') === false) $mitem->link .= '&Itemid='. $mitem->id; break; case 'content_typed': default: $mitem->link .= '&Itemid='.$mitem->id; break; } // Active Menu highlighting if ( $Itemid == $mitem->id ) $id = 'id="active_menu'.$params->get( 'class_sfx' ).'"'; else $id = ''; $mitem->link = ampReplace( $mitem->link ); if (strcasecmp(substr($mitem->link,0,4), 'http')) $mitem->link = sefRelToAbs( $mitem->link ); if ($level > 0) $menuclass = 'sublevel'; else $menuclass = 'mainlevel'; $menuclass .= $params->get( 'class_sfx'); switch ($mitem->browserNav) { // cases are slightly different case 1: // open in a new window $txt = '<a href="'. $mitem->link .'" target="_blank" class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</a>'; break; case 2: // open in a popup window $txt = "<a href=\"#\" onclick=\"javascript: window.open('". $mitem->link ."', '', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=550'); return false\" class=\"$menuclass\" ". $id .">". $mitem->name ."</a>\n"; break; case 3: // don't link it $txt = '<span class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</span>'; break; default: // formerly case 2 // open in parent window $txt = '<a href="'. $mitem->link .'" class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</a>'; break; } if ( $params->get( 'menu_images' ) ) { $menu_params =& new mosParameters( $mitem->params ); $menu_image = $menu_params->def( 'menu_image', -1 ); if ($menu_image AND $menu_image <> '-1') { $image = '<img src="'. mamboCore::get('mosConfig_live_site') .'/images/stories/'. $menu_image .'" border="0" alt="'. $mitem->name .'"/>'; if ( $params->get('menu_images_align')) $txt = $txt .' '. $image; else $txt = $image .' '. $txt; } } return $txt; } /** * Vertically Indented Menu */ function mosShowVIMenu( &$params ) { global $my, $cur_template, $Itemid; if (mamboCore::get('mosConfig_shownoauth')) $maxaccess = 0; else $maxaccess = $my->gid; $rows =& $this->getByParentOrder(0, $params->get('menutype'), $maxaccess); foreach ($rows as $i=>$row) $crosslink[$row->id] = $i; // indent icons $base = mamboCore::get('mosConfig_live_site'); switch ( $params->get( 'indent_image' ) ) { case '1': // Default images for ( $i = 1; $i < 7; $i++ ) { $img[$i] = "<img src=\"$base/images/M_images/indent$i.png\" alt=\"indent$i\" />"; } break; case '2': // Use Params for ( $i = 1; $i < 7; $i++ ) { $parm = $params->get('indent_image'. $i); if ($parm == '-1' ) $img[$i] = NULL; else $img[$i] = "<img src=\"$base/images/M_images/$parm\" alt=\"indent$i\" />"; } break; case '3': // None for ( $i = 1; $i < 7; $i++ ) $img[$i] = NULL; break; default: // Template $imgpath = $base.'/templates/'. $cur_template .'/images'; for ( $i = 1; $i < 7; $i++ ) { $img[$i] = "<img src=\"$base/templates/$cur_template/images/indent$i.png\" alt=\"indent$i\" />"; } break; } $indents = array( // block prefix / item prefix / item suffix / block suffix array( '<table width="100%" border="0" cellpadding="0" cellspacing="0">', '<tr align="left"><td>' , '</td></tr>', '</table>' ), array( '', '<div style="padding-left: 4px">'. $img[1] , '</div>', '' ), array( '', '<div style="padding-left: 8px">'. $img[2] , '</div>', '' ), array( '', '<div style="padding-left: 12px">'. $img[3] , '</div>', '' ), array( '', '<div style="padding-left: 16px">'. $img[4] , '</div>', '' ), array( '', '<div style="padding-left: 20px">'. $img[5] , '</div>', '' ), array( '', '<div style="padding-left: 24px">'. $img[6] , '</div>', '' ), ); // establish the hierarchy of the menu $children = array(); // first pass - collect children foreach ($rows as $v ) $children[$v->parent][] = $v; // second pass - collect 'open' menus $open = array( $Itemid ); for ($i = 0; $i < 20 AND isset($crosslink[$open[$i]]) AND isset($rows[$crosslink[$open[$i]]]); $i++) { $next = $rows[$crosslink[$open[$i]]]->parent; if ($next) $open[$i+1] = $next; else break; } $this->mosRecurseVIMenu( 0, 0, $children, $open, $indents, $params ); } /** * Utility function to recursively work through a vertically indented * hierarchial menu */ function mosRecurseVIMenu( $id, $level, &$children, &$open, &$indents, &$params ) { global $Itemid; if (@$children[$id]) { $n = min( $level, count($indents )-1); echo "\n".$indents[$n][0]; foreach ($children[$id] as $row) { echo "\n".$indents[$n][1]; echo $this->mosGetMenuLink( $row, $level, $params, $Itemid ); // show menu with menu expanded - submenus visible if ($params->get('expand_menu') OR in_array($row->id, $open)) $this->mosRecurseVIMenu( $row->id, $level+1, $children, $open, $indents, $params ); echo $indents[$n][2]; } echo "\n".$indents[$n][3]; } } /** * Draws a horizontal 'flat' style menu (very simple case) */ function mosShowHFMenu( &$params, $style=0 ) { global $my, $cur_template, $Itemid; if (mamboCore::get('mosConfig_shownoauth')) $maxaccess = 0; else $maxaccess = $my->gid; $rows =& $this->getByParentOrder(0, $params->get('menutype'), $maxaccess, true); $links = array(); foreach ($rows as $row) $links[] = $this->mosGetMenuLink( $row, 0, $params, $Itemid ); $menuclass = 'mainlevel'. $params->get( 'class_sfx' ); if (count( $links )) { if ($style == 1) { echo '<ul id="'. $menuclass .'">'; foreach ($links as $link) echo '<li>' . $link . '</li>'; echo '</ul>'; } else { echo '<table width="100%" border="0" cellpadding="0" cellspacing="1">'; echo '<tr>'; echo '<td nowrap="nowrap">'; echo '<span class="'. $menuclass .'"> '. $params->get( 'end_spacer' ) .' </span>'; echo implode( '<span class="'. $menuclass .'"> '. $params->get( 'spacer' ) .' </span>', $links ); echo '<span class="'. $menuclass .'"> '. $params->get( 'end_spacer' ) .' </span>'; echo '</td></tr>'; echo '</table>'; } } } } /** * 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 int Index of the mambot being loaded */ var $_loading=null; /** * Constructor */ function mosMambotHandler() { global $my; $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 <= $my->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; } /** * 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) continue; $path = "$basepath/mambots/$bot->folder/$bot->element.php"; if (file_exists( $path )) { $this->_loading = $i; require_once( $path ); $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 ); } /** * 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 (function_exists( $func[0] )) { $args[] = $this->_bots[$func[1]]->params; 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; } } /** * Database connector class * @subpackage Database * @package Mambo */ class database { /** @var string Internal variable to hold the query sql */ var $_sql=''; /** @var int Internal variable to hold the database error number */ var $_errorNum=0; /** @var string Internal variable to hold the database error message */ var $_errorMsg=''; /** @var string Internal variable to hold the prefix used on all database tables */ var $_table_prefix=''; /** @var Internal variable to hold the connector resource */ var $_resource=''; /** @var Internal variable to hold the last query cursor */ var $_cursor=null; /** @var boolean Debug option */ var $_debug=0; /** @var array A log of queries */ var $_log=array(); /** * Database object constructor * @param string Database host * @param string Database user name * @param string Database user password * @param string Database name * @param string Common prefix for all tables */ function database( $host='localhost', $user, $pass, $db, $table_prefix ) { // perform a number of fatality checks, then die gracefully if (!function_exists( 'mysql_connect' )) $this->forceOffline(1); if (!($this->_resource = @mysql_connect( $host, $user, $pass ))) $this->forceOffline(2); if (!mysql_select_db($db)) $this->forceOffline(3); $this->_table_prefix = $table_prefix; } function forceOffline ($error_number) { $mosSystemError = $error_number; $basePath = dirname( __FILE__ ); include $basePath . '/configuration.php'; include $basePath . '/offline.php'; exit(); } /** * @param int */ function debug( $level ) { $this->_debug = intval( $level ); } function debug_trace () { trigger_error( $this->_errorNum, E_USER_NOTICE ); //echo "<pre>" . $this->_sql . "</pre>\n"; if (function_exists('debug_backtrace')) { foreach(debug_backtrace() as $back) { if (@$back['file']) { echo '<br />'.$back['file'].':'.$back['line']; } } } } /** * @return int The error number for the most recent query */ function getErrorNum() { return $this->_errorNum; } /** * @return string The error message for the most recent query */ function getErrorMsg() { return str_replace( array( "\n", "'" ), array( '\n', "\'" ), $this->_errorMsg ); } /** * Get a database escaped string * @return string */ function getEscaped( $text ) { return mysql_escape_string( $text ); } /** * Get a quoted database escaped string * @return string */ function Quote( $text ) { return '\'' . mysql_escape_string( $text ) . '\''; } /** * Sets the SQL query string for later execution. * * This function replaces a string identifier <var>$prefix</var> with the * string held is the <var>_table_prefix</var> class variable. * * @param string The SQL query * @param string The common table prefix */ function setQuery( $sql, $prefix='#__' ) { $this->_sql = $this->replacePrefix($sql, $prefix); } /** * This function replaces a string identifier <var>$prefix</var> with the * string held is the <var>_table_prefix</var> class variable. * * @param string The SQL query * @param string The common table prefix * @author thede, David McKinnis */ function replacePrefix ($sql, $prefix='#__') { $done = ''; while (strlen($sql)) { if ($double = preg_match('/\"([^\\\"]|\\.)*"/', $sql,$matches_double,PREG_OFFSET_CAPTURE) OR $single = preg_match("/\'([^\\\']|\\.)*'/", $sql,$matches_single,PREG_OFFSET_CAPTURE)) { if ($single == 0 OR ($double AND $matches_double[0][1] < $matches_single[0][1])) { $done .= str_replace($prefix, $this->_table_prefix, substr($sql,0,$matches_double[0][1])).$matches_double[0][0]; $sql = substr($sql,$matches_double[0][1]+strlen($matches_double[0][0])); } else { $done .= str_replace($prefix, $this->_table_prefix, substr($sql,0,$matches_single[0][1])).$matches_single[0][0]; $sql = substr($sql,$matches_single[0][1]+strlen($matches_single[0][0])); } } else return $done.str_replace($prefix, $this->_table_prefix,$sql); } return $done; } /** * @return string The current value of the internal SQL vairable */ function getQuery($sql='') { if ($sql == '') $sql = $this->_sql; return "<pre>" . htmlspecialchars( $sql ) . "</pre>"; } /** * Execute the query * @return mixed A database resource if successful, FALSE if not. */ function query($sql = '') { global $mosConfig_debug; if ($sql == '') $sql = $this->_sql; if ($this->_debug) $this->_log[] = $sql; if ($this->_cursor = mysql_query($sql, $this->_resource)) { $this->_errorNum = 0; $this->_errorMsg = ''; return $this->_cursor; } else { $this->_errorNum = mysql_errno( $this->_resource ); $this->_errorMsg = mysql_error( $this->_resource )." SQL=$sql"; if ($this->_debug) $this->debug_trace(); return false; } } function query_batch( $abort_on_error=true, $p_transaction_safe = false) { $this->_errorNum = 0; $this->_errorMsg = ''; if ($p_transaction_safe) { $si = mysql_get_server_info(); preg_match_all( "/(\d+)\.(\d+)\.(\d+)/i", $si, $m ); $prefix = ''; if ($m[1] >= 4) $prefix = 'START TRANSACTION; '; elseif ($m[2] >= 23) { if ($m[3] >= 19) $prefix = 'BEGIN WORK; '; elseif ($m[3] >= 17) $prefix = 'BEGIN; '; } if ($prefix) $this->_sql = $prefix.$this->_sql.'; COMMIT;'; } $query_split = preg_split ("/[;]+/", $this->_sql); $error = 0; foreach ($query_split as $command_line) { $command_line = trim( $command_line ); if ($command_line != '') { if (!$this->query($command_line)) { $error = 1; echo 'xxx '; if ($abort_on_error) { return $this->_cursor; } } } } return $error ? false : true; } /** * Diagnostic function */ function explain() { if (!($cur = $this->query("EXPLAIN ".$this->_sql))) return null; $headline = $header = $body = ''; $buf = '<table cellspacing="1" cellpadding="2" border="0" bgcolor="#000000" align="center">'; $buf .= $this->getQuery("EXPLAIN ".$this->_sql); while ($row = mysql_fetch_assoc($cur)) { $body .= "<tr>"; foreach ($row as $k=>$v) { if ($headline == '') $header .= "<th bgcolor=\"#ffffff\">$k</th>"; $body .= "<td bgcolor=\"#ffffff\">$v</td>"; } $headline = $header; $body .= "</tr>"; } $buf .= "<tr>$headline</tr>$body</table><br /> "; mysql_free_result( $cur ); return "<div style=\"background-color:#FFFFCC\" align=\"left\">$buf</div>"; } /** * @return int The number of rows returned from the most recent query. */ function getNumRows( $cur=null ) { return mysql_num_rows( $cur ? $cur : $this->_cursor ); } /** * Load an array of retrieved database objects or values * @param int Database cursor * @param string The field name of a primary key * @return array If <var>key</var> is empty as sequential list of returned records. * If <var>key</var> is not empty then the returned array is indexed by the value * the database key. Returns <var>null</var> if the query fails. */ function &retrieveResults ($key='', $max=0, $result_type='row') { $results = array(); $sql_function = 'mysql_fetch_'.$result_type; if ($cur = $this->query()) { while ($row = $sql_function($cur)) { if ($key != '') $results[$row->$key] = $row; else $results[] = $row; if ($max AND count($results) >= $max) break; } mysql_free_result($cur); } return $results; } /** * This method loads the first field of the first row returned by the query. * * @return The value returned in the query or null if the query failed. */ function loadResult() { $results =& $this->retrieveResults('', 1, 'row'); if (count($results)) return $results[0][0]; else return null; } /** * Load an array of single field results into an array */ function loadResultArray($numinarray = 0) { $results =& $this->retrieveResults('', 0, 'row'); $values = array(); foreach ($results as $result) $values[] = $result[$numinarray]; if (count($values)) return $values; else return null; } /** * Load a assoc list of database rows * @param string The field name of a primary key * @return array If <var>key</var> is empty as sequential list of returned records. */ function loadAssocList( $key='' ) { $results =& $this->retrieveResults($key, 0, 'assoc'); if (count($results)) return $results[0][0]; else return null; } /** * Copy the named array content into the object as properties * only existing properties of object are filled. when undefined in hash, properties wont be deleted * @param array the input array * @param obj byref the object to fill of any class * @param string * @param boolean */ function mosBindArrayToObject( $array, &$obj, $ignore='', $prefix=NULL, $checkSlashes=true ) { if (!is_array($array) OR !is_object($obj)) return false; if ($prefix == null) $prefix = ''; foreach (get_object_vars($obj) as $k => $v) { if( substr( $k, 0, 1 ) != '_' AND strpos($ignore, $k) === false) { if (isset($array[$prefix.$k])) { $obj->$k = ($checkSlashes AND get_magic_quotes_gpc()) ? $this->mosStripslashes( $array[$k] ) : $array[$k]; } } } return true; } /** * Strip slashes from strings or arrays of strings * @param value the input string or array */ function mosStripslashes(&$value) { if (is_string($value)) $ret = stripslashes($value); else { if (is_array($value)) { $ret = array(); while (list($key,$val) = each($value)) { $ret[$key] = mosStripslashes($val); } // while } else $ret = $value; } // if return $ret; } // mosStripSlashes /** * This global function loads the first row of a query into an object * * If an object is passed to this function, the returned row is bound to the existing elements of <var>object</var>. * If <var>object</var> has a value of null, then all of the returned query fields returned in the object. * @param string The SQL query * @param object The address of variable */ function loadObject( &$object ) { if ($object != null) { $results =& $this->retrieveResults('', 1, 'assoc'); if (count($results)) { $this->mosBindArrayToObject($results[0], $object, null, null, false); return true; } } else { $results =& $this->retrieveResults('', 1, 'object'); if (count($results)) { $object = $results[0]; return true; } else $object = null; } return false; } /** * Load a list of database objects * @param string The field name of a primary key * @return array If <var>key</var> is empty as sequential list of returned records. * If <var>key</var> is not empty then the returned array is indexed by the value * the database key. Returns <var>null</var> if the query fails. */ function loadObjectList( $key='' ) { $results =& $this->retrieveResults($key, 0, 'object'); if (count($results)) return $results; else return null; } /** * @return The first row of the query. */ function loadRow() { $results =& $this->retrieveResults('', 1, 'row'); if (count(results)) return $results[0]; else return null; } /** * Load a list of database rows (numeric column indexing) * @param string The field name of a primary key * @return array If <var>key</var> is empty as sequential list of returned records. * If <var>key</var> is not empty then the returned array is indexed by the value * the database key. Returns <var>null</var> if the query fails. */ function loadRowList( $key='' ) { $results =& $this->retrieveResults('', 0, 'row'); if (count(results)) return $results; else return null; } /** * Document::db_insertObject() * * { Description } * * @param [type] $keyName * @param [type] $verbose */ function insertObject( $table, &$object, $keyName = NULL, $verbose=false ) { $fmtsql = "INSERT INTO $table ( %s ) VALUES ( %s ) "; $fields = array(); foreach (get_object_vars( $object ) as $k => $v) { if (is_array($v) OR is_object($v) OR $v === NULL OR $k[0] == '_') continue; $fields[] = "`$k`"; $values[] = "'" . $this->getEscaped( $v ) . "'"; } if (!isset($fields)) die ('class database method insertObject - no fields'); $this->setQuery( sprintf( $fmtsql, implode( ",", $fields ), implode( ",", $values ) ) ); ($verbose) && print "$sql<br />\n"; if (!$this->query()) return false; $id = mysql_insert_id(); ($verbose) && print "id=[$id]<br />\n"; if ($keyName && $id) $object->$keyName = $id; return true; } /** * Document::db_updateObject() * * { Description } * * @param [type] $updateNulls */ function updateObject( $table, &$object, $keyName, $updateNulls=true ) { $fmtsql = "UPDATE $table SET %s WHERE %s"; $tmp = array(); foreach (get_object_vars( $object ) as $k => $v) { if (is_array($v) OR is_object($v) OR $k[0] == '_' OR ($v === null AND !$updateNulls)) continue; if( $k == $keyName ) { // PK not to be updated $where = "$keyName='" . $this->getEscaped( $v ) . "'"; continue; } if ($v) $v = $this->getEscaped($v); $tmp[] = "`$k`='$v'"; } if (!isset($tmp)) return true; if (!isset($where)) die ('database class updateObject method - no key value'); $this->setQuery( sprintf( $fmtsql, implode( ",", $tmp ) , $where ) ); return $this->query(); } /** * @param boolean If TRUE, displays the last SQL statement sent to the database * @return string A standised error message */ function stderr( $showSQL = false ) { return "DB function failed with error number $this->_errorNum" ."<br /><font color=\"red\">$this->_errorMsg</font>" .($showSQL ? "<br />SQL = <pre>$this->_sql</pre>" : ''); } function insertid() { return mysql_insert_id(); } function getVersion() { return mysql_get_server_info(); } /** * Fudge method for ADOdb compatibility */ function GenID( $foo1=null, $foo2=null ) { return '0'; } /** * @return array A list of all the tables in the database */ function getTableList() { $this->setQuery( 'SHOW tables' ); $this->query(); return $this->loadResultArray(); } /** * @param array A list of table names * @return array A list the create SQL for the tables */ function getTableCreate( $tables ) { $result = array(); foreach ($tables as $tblval) { $this->setQuery( 'SHOW CREATE table ' . $tblval ); $this->query(); $result[$tblval] = $this->loadResultArray( 1 ); } return $result; } /** * @param array A list of table names * @return array An array of fields by table */ function getTableFields( $tables ) { $result = array(); foreach ($tables as $tblval) { $this->setQuery( 'SHOW FIELDS FROM ' . $tblval ); $this->query(); $fields = $this->loadObjectList(); foreach ($fields as $field) { $result[$tblval][$field->Field] = preg_replace("/[(0-9)]/",'', $field->Type ); } } return $result; } function displayLogged () { echo count($this->_log).' queries executed'; echo '<pre>'; foreach ($this->_log as $k=>$sql) { echo $k+1 . "\n" . $sql . '<hr />'; } } /* Helper method - maybe should go into database itself */ function doSQL ($sql) { $this->setQuery($sql); if (!$this->query()) { echo "<script> alert('".$this->getErrorMsg()."'); window.history.go(-1); </script>\n"; exit(); } } /* Helper method - maybe could go into database itself */ function &doSQLget ($sql, $classname) { $this->setQuery($sql); $rows = $this->loadObjectList(); $target = get_class_vars($classname); if ($rows) { foreach ($rows as $row) { $next =& new $classname(0); foreach ($target as $field=>$value) { if (isset($row->$field)) $next->$field = $row->$field; } $result[] = $next; } } else $result = array(); return $result; } } class mamboDatabase extends database { function mamboDatabase () { $host = mamboCore::get('mosConfig_host'); $user = mamboCore::get('mosConfig_user'); $pw = mamboCore::get('mosConfig_password'); $db = mamboCore::get('mosConfig_db'); $prefix = mamboCore::get('mosConfig_dbprefix'); parent::database($host, $user, $pw, $db, $prefix); } function &getInstance () { static $instance; if (!is_object($instance)) $instance = new mamboDatabase(); return $instance; } } /** * mosDBTable Abstract Class. * @abstract * @package Mambo * @subpackage Database * * Parent classes to all database derived objects. Customisation will generally * not involve tampering with this object. * @package Mambo * @author Andrew Eddie <eddieajau@users.sourceforge.net */ class mosDBTable { /** @var string Name of the table in the db schema relating to child class */ var $_tbl = ''; /** @var string Name of the primary key field in the table */ var $_tbl_key = ''; /** @var string Error message */ var $_error = ''; /** @var mosDatabase Database connector */ var $_db = null; /** * Object constructor to set table and key field * * Can be overloaded/supplemented by the child class * @param string $table name of the table in the db schema relating to child class * @param string $key name of the primary key field in the table */ function mosDBTable( $table, $key, &$db ) { $this->_tbl = $table; $this->_tbl_key = $key; $this->_db =& $db; } /** * @return bool True if DB query failed. Sets the error message */ function queryTestFailure () { if ($this->_db->query()) return false; $this->_error = $this->_db->getErrorMsg(); return true; } /** * Filters public properties * @access protected * @param array List of fields to ignore */ function filter( $ignoreList=null ) { $callcheck = array('InputFilter', 'process'); if (!is_callable($callcheck)) require_once(mamboCore::get('mosConfig_absolute_path').'/includes/phpinputfilter/class.inputfilter.php'); // specific filters $iFilter =& new InputFilter(); if (is_array($ignoreList)) foreach ($this->getPublicProperties() as $k) { if (!in_array($k, $ignoreList)) $this->$k = $iFilter->process($this->$k); } else foreach ($this->getPublicProperties() as $k) $this->$k = $iFilter->process($this->$k); } /** * @return string Returns the error message */ function getError() { return $this->_error; } /** * Gets the value of the class variable * @param string The name of the class variable * @return mixed The value of the class var (or null if no var of that name exists) */ function get( $_property ) { if(isset( $this->$_property )) return $this->$_property; else return null; } /** * Returns an array of public properties * @return array */ function getPublicProperties() { static $cache = null; if (is_null( $cache )) { $cache = array(); foreach (get_class_vars( get_class( $this ) ) as $key=>$val) { if (substr( $key, 0, 1 ) != '_') { $cache[] = $key; } } } return $cache; } /** * Checks if this object lacks the property given by the parameter * @param string The name of the property * @return bool */ function lacks( $property ) { $thisclass = strtolower(get_class($this)); if (!array_key_exists( $property, get_class_vars($thisclass) )) { $this->_error = "WARNING: $thisclass does not support $property."; return true; } return false; } /** * Set the value of the class variable * @param string The name of the class variable * @param mixed The value to assign to the variable */ function set( $_property, $_value ) { $this->$_property = $_value; } /** * binds a named array/hash to this object * * can be overloaded/supplemented by the child class * @param array $hash named array * @return null|string null is operation was satisfactory, otherwise returns an error */ function bind( $array, $ignore="" ) { if (is_array($array)) return database::mosBindArrayToObject($array, $this, $ignore); $this->_error = strtolower(get_class( $this ))."::bind failed."; return false; } /** * binds an array/hash to this object * @param int $oid optional argument, if not specifed then the value of current key is used * @return any result from the database operation */ function load( $oid=null ) { $k = $this->_tbl_key; if ($oid !== null) $this->$k = $oid; if ($this->$k === null) return false; $this->_db->setQuery("SELECT * FROM $this->_tbl WHERE $this->_tbl_key='".$this->$k."'" ); return $this->_db->loadObject($this); } /** * generic check method * * can be overloaded/supplemented by the child class * @return boolean True if the object is ok */ function check() { return true; } /** * Inserts a new row if id is zero or updates an existing row in the database table * * Can be overloaded/supplemented by the child class * @param boolean If false, null object variables are not updated * @return null|string null if successful otherwise returns and error message */ function store( $updateNulls=false ) { $k = $this->_tbl_key; global $migrate; if( $this->$k && !$migrate) $ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls ); else $ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key ); if( !$ret ) { $this->_error = strtolower(get_class( $this ))."::store failed <br />" . $this->_db->getErrorMsg(); return false; } else return true; } /** * Determine from the direction parameter which operator and order to use in SQL */ function orderCodes ($direction) { if ($direction < 0) { $relation = '<'; $ordering = ' ORDER BY ordering DESC'; } elseif ($direction > 0) { $relation = '>'; $ordering = ' ORDER BY ordering ASC'; } else { $relation = '='; $ordering = ''; } return array ($relation, $ordering); } /** */ function move( $direction, $where='' ) { $k = $this->_tbl_key; list ($relation, $ordering) = $this->orderCodes($direction); $sql = "SELECT $this->_tbl_key, ordering FROM $this->_tbl WHERE ordering $relation $this->ordering"; $sql .= ($where ? "\n AND $where" : '').$ordering.' LIMIT 1'; $this->_db->setQuery( $sql ); $row = null; if ($this->_db->loadObject($row)) { $sql = "UPDATE $this->_tbl SET ordering='$row->ordering' WHERE $this->_tbl_key='".$this->$k."'"; $this->_db->doSQL($sql); } $sql = "UPDATE $this->_tbl SET ordering='$this->ordering' WHERE $this->_tbl_key='".$row->$k."'"; if ($row) $this->ordering = $row->ordering; $this->_db->doSQL($sql); } /** * Compacts the ordering sequence of the selected records * @param string Additional where query to limit ordering to a particular subset of records */ function updateOrder( $where='' ) { if ($this->lacks('ordering')) return false; $k = $this->_tbl_key; if ($this->_tbl == "#__content_frontpage") $order2 = ", content_id DESC"; else $order2 = ""; $sql = "SELECT $k, ordering FROM $this->_tbl " . ($where ? "\nWHERE $where" : '') . "\nORDER BY ordering$order2"; $this->_db->setQuery($sql); if (!$rows = $this->_db->loadObjectList()) { $this->_error = $this->_db->getErrorMsg(); return false; } $neworder = max(min($this->ordering, count($rows)), 1); $i = 1; foreach ($rows as $row) { $key = $row->$k; if ($i == $neworder) $i++; if ($key == $this->$k) { $i--; $ordering = $neworder; } else $ordering = $i; $sql = "UPDATE $this->_tbl SET ordering=$ordering WHERE $k = $key "; $this->_db->doSQL($sql); $i++; } return true; } /** * Default delete method * * can be overloaded/supplemented by the child class * @return true if successful otherwise returns and error message */ function delete( $oid=null ) { $k = $this->_tbl_key; if ($oid) $this->$k = intval( $oid ); $this->_db->setQuery( "DELETE FROM $this->_tbl WHERE $this->_tbl_key = '".$this->$k."'" ); if ($this->queryTestFailure()) return false; return true; } function checkout( $who, $oid=null ) { if ($this->lacks('checked_out')) return false; $k = $this->_tbl_key; if ($oid !== null) $this->$k = $oid; $time = date( "%Y-%m-%d H:i:s" ); if (intval( $who )) { // new way of storing editor, by id $this->_db->setQuery( "UPDATE $this->_tbl" . "\nSET checked_out='$who', checked_out_time='$time'" . "\nWHERE $this->_tbl_key='".$this->$k."'" ); } else { // old way of storing editor, by name $this->_db->setQuery( "UPDATE $this->_tbl" . "\nSET checked_out='1', checked_out_time='$time', editor='".$who."' " . "\nWHERE $this->_tbl_key='".$this->$k."'" ); } return $this->_db->query(); } function checkin( $oid=null ) { if ($this->lacks('checked_out')) return false; $k = $this->_tbl_key; if ($oid !== null) $this->$k = $oid; $time = date("H:i:s"); $this->_db->setQuery( "UPDATE $this->_tbl" . "\nSET checked_out='0', checked_out_time='0000-00-00 00:00:00'" . "\nWHERE $this->_tbl_key='".$this->$k."'" ); return $this->_db->query(); } function hit( $oid=null ) { $k = $this->_tbl_key; if ($oid !== null) $this->$k = intval( $oid ); $key = $this->$k; $this->_db->setQuery( "UPDATE $this->_tbl SET hits=(hits+1) WHERE $this->_tbl_key='$key'" ); $this->_db->query(); if (mamboCore::get('mosConfig_enable_log_items')) { $now = date( "Y-m-d" ); $this->_db->setQuery( "SELECT hits" . "\nFROM #__core_log_items" . "\nWHERE time_stamp='$now' AND item_table='$this->_tbl' AND item_id='$key'" ); $hits = intval( $this->_db->loadResult() ); if ($hits) $this->_db->setQuery( "UPDATE #__core_log_items SET hits=(hits+1)" . "\nWHERE time_stamp='$now' AND item_table='$this->_tbl' AND item_id='".$this->$k."'" ); else $this->_db->setQuery( "INSERT INTO #__core_log_items VALUES" . "\n('$now','$this->_tbl','".$this->$k."','1')" ); $this->_db->query(); } } /** * Generic save function * @param array Source array for binding to class vars * @param string Filter for the order updating * @returns TRUE if completely successful, FALSE if partially or not succesful. */ function save( $source, $order_filter ) { if (!$this->bind($_POST) OR !$this->check() OR !$this->store()OR !$this->checkin()) return false; $filter_value = $this->$order_filter; $this->updateOrder( $order_filter ? "`$order_filter`='$filter_value'" : "" ); $this->_error = ''; return true; } /** * Generic Publish/Unpublish function * @param array An array of id numbers * @param integer 0 if unpublishing, 1 if publishing * @param integer The id of the user performnig the operation */ function publish_array( $cid=null, $publish=1, $myid=0 ) { if (!is_array( $cid ) OR count( $cid ) < 1) { $this->_error = "No items selected."; return false; } $cids = implode( ',', $cid ); $this->_db->setQuery( "UPDATE $this->_tbl SET published='$publish'" . "\nWHERE $this->_tbl_key IN ($cids) AND (checked_out=0 OR checked_out='$myid')" ); if ($this->queryTestFailure()) return false; if (count( $cid ) == 1) $this->checkin( $cid[0] ); return true; } /** * Export item list to xml * @param boolean Map foreign keys to text values */ function toXML( $mapKeysToText=false ) { $xml = '<record table="' . $this->_tbl . '"'; if ($mapKeysToText) $xml .= ' mapkeystotext="true"'; $xml .= '>'; foreach (get_object_vars($this) as $k => $v) { if ($v === null OR is_array($v) OR is_object($v)) continue; if ($k[0] == '_') continue; // internal field $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>'; } $xml .= '</record>'; return $xml; } } /** * Abstract class for classes where the objects of the class can be relatively easily * stored in a single database table. Can usually be adapted to more complex cases. * Requires child classes to implement: tableName(), notSQL(). * tableName() must return the name of the database table, using #__ in the usual Mambo way * notSQL() must return an array of strings, where each string is the name of a * variable that is NOT in the database table, or is not written explicitly, * e.g. the auto-increment key. If this is the ONLY non-SQL field, then the * child class need not implement it, as that it is already in the abstract class. * Child classes may implement timeStampField, in which case it must return the name * of a field that will have a timestamp placed in it whenever the DB is written. */ class mosDBTableEntry { /** @var int ID for file record in database */ var $id = 0; var $database = ''; function mosDBTableEntry () { die ('Cannot instantiate mosDBTableEntry'); } function getDatabase () { if (!is_object($this->database)) $this->database = mamboDatabase::getInstance(); return $this->database; } /* Stores all POST data where the name matches an object variable name */ function addPostData () { foreach (get_class_vars(get_class($this)) as $field=>$value) { if ($field!='id' AND isset($_POST[$field])) { $this->$field = trim($_POST[$field]); } } $this->forceBools(); } /* Provided in case child class does not implement it. Can force any values */ /* within some limited range. In particular, can force bools to be 0 or 1 */ function forceBools () { return; } /* Updates an existing DB entry with the object's current values */ function updateObjectDB () { $this->prepareValues(); $database = $this->getDatabase(); $database->doSQL($this->updateSQL()); } /* Deletes the current object from the DB */ function delete () { $table = $this->tableName(); $sql = "DELETE FROM $table WHERE id=$this->id"; $database = $this->getDatabase(); $database->doSQL($sql); } /* Provided in case the child class does not provide a method for timeStampField */ function timeStampField () { return ''; } /* Provides SQL for updating the DB with the contents of the current object */ function updateSQL () { $tabname = $this->tableName(); $sql = "UPDATE $tabname SET %s WHERE id=$this->id"; $exclude = $this->notSQL(); foreach (get_class_vars(get_class($this)) as $field=>$value) { if (!in_array($field,$exclude)) $setter[] = $field."='".$this->$field."'"; } $timestamp = $this->timeStampField(); if ($timestamp) $setter[] = $timestamp."='".date('Y-m-d H:i:s')."'"; return sprintf($sql,implode(',', $setter)); } /* Default method for identifying fields not to be written to the DB */ /* The child classes may override this and return more items in the array */ function notSQL () { return array ('id'); } /* Provides SQL to insert the current object into the DB */ function insertSQL () { $tabname = $this->tableName(); $sql = "INSERT INTO $tabname (%s) VALUES (%s)"; $exclude = $this->notSQL(); foreach (get_class_vars(get_class($this)) as $field=>$value) { if (!in_array($field,$exclude)) { $infields[] = $field; $values[] = "'".$this->$field."'"; } } $timestamp = $this->timeStampField(); if ($timestamp) { $infields[] = $timestamp; $values[] = "'".date('Y-m-d H:i:s')."'"; } return sprintf($sql, implode(',', $infields), implode(',', $values)); } /* Copies any matching fields from some arbitrary object into the current object */ function setValues (&$anObject) { foreach (get_class_vars(get_class($this)) as $field=>$value) { if ($field != 'id' AND isset($anObject->$field)) $this->$field = $anObject->$field; } } /* Ensures values can safely be written to DB; assumes magic quotes forced off */ function prepareValues () { $database = $this->getDatabase(); foreach (get_class_vars(get_class($this)) as $field=>$value) { if (!is_numeric($this->$field)) $this->$field = $database->getEscaped($this->$field); } } /* Takes some arbitrary SELECT type SQL and places the first or only result into the current object */ function readDataBase($sql) { $database = $this->getDatabase(); $database->setQuery( $sql ); if (!$database->loadObject($this)) $this->id = 0; } } /** * 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 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( $dummy ) { $database = mamboDatabase::getInstance(); $this->mosDBTable( '#__users', 'id', $database ); } /** * 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 ); } /** * Validation and filtering * @return boolean True is satisfactory */ function check() { $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 $this->_db->setQuery( "SELECT COUNT(id) FROM #__users " . "\nWHERE LOWER(username)=LOWER('$this->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 $migrate; if( $this->id AND !$migrate) $ret = $this->_db->updateObject( $this->_tbl, $this, $this->id, $updateNulls ); else $ret = $this->_db->insertObject( $this->_tbl, $this, $this->id ); if ($ret) return true; $this->_error = "mosUser::store failed <br />" . $this->_db->getErrorMsg(); return false; } function delete($oid=null) { 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; } } /** * 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=null; /** * 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); } /** * Singleton get instance * @param object the mainframe instance (if called internally) * Note that because of the need for creation parameters, this cannot * be called successfully unless the mainframe object is already created */ function &getInstance () { static $mainframe; if (func_num_args()) { $args =& func_get_args(); $mainframe = $args[0]; } if (isset($mainframe)) $result =& $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 ) { list($name, $content) = $this->_tidyMetaData($name, $content); $tag = $this->_getMetaTag($name); 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[] = '<title>'.$this->_head['title'].'</title>'; foreach ($this->_head['meta'] as $name=>$meta) { if ($meta[1]) $head[] = $meta[1]; $head[] = '<meta name="' . $name . '" content="' . $meta[0] . '" />'; 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 (isset($_REQUEST[$req_name])) $this->setUserState($var_name, $_REQUEST[$req_name]); elseif (isset($var_default) AND !isset($this->userstate[$var_name])) $this->setUserState($var_name, $var_default); return $this->getUserState($var_name); } /** * 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 (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 <img> tag if ($type) $image = '<img src="'. $image .'" alt="'. $alt .'" align="'. $align .'" name="'. $name .'" border="0" />'; 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'); 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 ($option) $path = $base."/modules/$option.xml"; else $path = $base.'/modules/custom.xml'; return $this->tryFiles ($path); case 'mod1_xml': if ($option) $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/comonents/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)"; 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(); } } /** * @return correct Itemid for Content Item */ function getItemid ($id, $typed=1, $link=1, $bs=1, $bc=1, $gbs=1) { $configuration = mamboCore::getMamboCore(); return $configuration->getItemid($id, $typed, $link, $bs, $bc, $gbs); } } /** * 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 string */ var $time=null; /** @var string */ var $userid=0; /** @var string */ var $usertype=null; /** @var string */ var $username=''; /** @var time */ var $gid=0; /** @var int */ var $guest=1; /** @var string */ var $_session_cookie=null; /** * @param database A database connector object */ function mosSession( &$db ) { $database = mamboDatabase::getInstance(); $this->mosDBTable( '#__session', 'session_id', $database ); $this->time = time(); } function &getCurrent () { static $currentSession; if (!is_object($currentSession)) { $currentSession = new mosSession($dummy); $currentSession->purge(intval(mamboCore::get('mosConfig_lifetime'))); $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. $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 <br />" . $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 <br />" . $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( $inc=1800 ) { $past = time() - $inc; $query = "DELETE FROM $this->_tbl" . "\nWHERE (time < $past)"; $this->_db->setQuery($query); return $this->_db->query(); } } /** * 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<div class=\"profiler\">$this->prefix %.3f $label</div>", $this->getmicrotime() - $this->start ); } function getmicrotime(){ list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } } if (!isset($adminside)) $adminside = 0; if (!isset($indextype)) $indextype = 1; $_VERSION =& new version(); $version = $_VERSION->PRODUCT .' '. $_VERSION->RELEASE .'.'. $_VERSION->DEV_LEVEL .' ' . $_VERSION->DEV_STATUS .' [ '.$_VERSION->CODENAME .' ] '. $_VERSION->RELDATE .' ' . $_VERSION->RELTIME .' '. $_VERSION->RELTZ; $configuration =& mamboCore::getMamboCore(); $configuration->handleGlobals(); if (phpversion() < '4.2.0') require_once( $configuration->rootPath() . '/includes/compat.php41x.php' ); if (phpversion() < '4.3.0') require_once( $configuration->rootPath() . '/includes/compat.php42x.php' ); @set_magic_quotes_runtime( 0 ); if (@$mosConfig_error_reporting === 0) error_reporting( 0 ); elseif (@$mosConfig_error_reporting > 0) error_reporting( $mosConfig_error_reporting ); $local_backup_path = $configuration->rootPath().'/administrator/backups'; $media_path = $configuration->rootPath().'/media/'; $image_path = $configuration->rootPath().'/images/stories'; $image_size = 100; /** retrieve all possible request string (or form) arguments */ $type = mosGetParam($_REQUEST, 'type', 1); $no_html = mosGetParam( $_REQUEST, 'no_html', 0 ); $act = mosGetParam( $_REQUEST, 'act', '' ); $do_pdf = mosGetParam( $_REQUEST, 'do_pdf', 0 ); $pop = mosGetParam( $_REQUEST, 'pop', 0 ); $id = mosGetParam( $_REQUEST, 'id', 0 ); $task = mosGetParam($_REQUEST, 'task', ''); $act = strtolower(mosGetParam($_REQUEST, 'act', '')); $section = mosGetParam($_REQUEST, 'section', ''); $no_html = strtolower(mosGetParam($_REQUEST, 'no_html', '')); $database = mamboDatabase::getInstance(); $database->debug(mamboCore::get('mosConfig_debug')); if ($adminside) { $option = strtolower(mosGetParam($_REQUEST,'option','com_admin')); require_once($configuration->rootPath().'/includes/gacl.class.php' ); require_once($configuration->rootPath().'/includes/gacl_api.class.php' ); $acl = new gacl_api(); if ($option == 'login') { require_once($configuration->rootPath().'/includes/authenticator.php'); $authenticator = mamboAuthenticator::getInstance(); $my = $authenticator->loginAdmin($acl); } else { session_name(md5(mamboCore::get('mosConfig_live_site'))); session_start(); if ($option == 'logout') { require($configuration->rootPath().'/administrator/logout.php'); exit(); } else { require_once($configuration->rootPath().'/administrator/includes/admin.php'); $my = checkAdminSession($database); if ($option == 'simple_mode') $admin_mode = 'on'; elseif ($option == 'advanced_mode') $admin_mode = 'off'; else $admin_mode = mosGetParam($_SESSION, 'simple_editing', ''); $_SESSION['simple_editing'] = mosGetParam($_POST, 'simple_editing', $admin_mode); } } $mainframe =& new mosMainFrame($database, $option, '..', true); if ($my) { require_once( $configuration->rootPath().'/includes/mambo.php' ); require_once ($configuration->rootPath().'/includes/mambofunc.php'); require_once ($configuration->rootPath().'/includes/mamboHTML.php'); require_once( $configuration->rootPath().'/administrator/includes/mosAdminMenus.php'); require_once( $configuration->rootPath().'/includes/mamboxml.php' ); $_MAMBOTS = mosMambotHandler::getInstance(); // start the html output if ($no_html) { if ($path = $mainframe->getPath( "admin" )) require $path; exit(); } $configuration->initGzip(); require_once($configuration->rootPath().'/administrator/includes/admin.php'); if ($adminside != 3) { $path = $configuration->rootPath().'/administrator/templates/'.$mainframe->getTemplate().'/index.php'; require_once($path); $configuration->doGzip(); } } else { $configuration->initGzip(); $path = $configuration->rootPath().'/administrator/templates/'.$mainframe->getTemplate().'/login.php'; require_once( $path ); $configuration->doGzip(); } } else { $sefcode = $configuration->rootPath().'/components/com_sef/sef.php'; if (file_exists($sefcode)) require_once($sefcode); else require_once($configuration->rootPath().'/includes/sef.php'); $urlerror = 0; if (mamboCore::get('mosConfig_sef') AND $indextype == 3) { $sef = mosSEF::getInstance(); $urlerror = $sef->sefRetrieval(mamboCore::get('mosConfig_register_globals')); $indextype = 1; $configuration->handleGlobals(); } $option = $configuration->determineOptionAndItemid(); $Itemid = $configuration->get('Itemid'); $mainframe =& new mosMainFrame($database, $option, '.'); $session = mosSession::getCurrent(); if ($option == 'login') $configuration->handleLogin($session); elseif ($option == 'logout') $configuration->handleLogout($session); $my =& new mosUser($database); $my->getSessionData(); $configuration->offlineCheck($my, $database); $gid = intval( $my->gid ); // gets template for page $cur_template = $mainframe->getTemplate(); require_once( $configuration->rootPath().'/includes/frontend.php' ); require_once( $configuration->rootPath().'/includes/mambo.php' ); require_once ($configuration->rootPath().'/includes/mambofunc.php'); require_once ($configuration->rootPath().'/includes/mamboHTML.php'); require_once( $configuration->rootPath().'/includes/mamboxml.php' ); if ($indextype == 2 AND $do_pdf == 1 ) { include_once('includes/pdf.php'); exit(); } /** detect first visit */ $mainframe->detect(); /** @global mosPlugin $_MAMBOTS */ $_MAMBOTS = mosMambotHandler::getInstance(); require_once( $configuration->rootPath().'/editor/editor.php' ); require_once( $configuration->rootPath() . '/includes/gacl.class.php' ); require_once( $configuration->rootPath() . '/includes/gacl_api.class.php' ); $acl = new gacl_api(); /** @global A places to store information from processing of the component */ $_MOS_OPTION = array(); ob_start(); if (!$urlerror AND $path = $mainframe->getPath( 'front' )) { $menuhandler = mosMenuHandler::getInstance(); $ret = $menuhandler->menuCheck($Itemid, $option, $task, $gid); $menuhandler->setPathway($Itemid); if ($ret) require_once( $path ); else mosNotAuth(); } else { header ("HTTP/1.0 404 Not Found"); include ($configuration->rootPath().'/page404.php'); } $_MOS_OPTION['buffer'] = ob_get_contents(); ob_end_clean(); $configuration->initGzip(); $configuration->standardHeaders(); if ($indextype == 1) { // loads template file if ( !file_exists( 'templates/'. $cur_template .'/index.php' ) ) { echo _TEMPLATE_WARN . $cur_template; } else { require_once( 'templates/'. $cur_template .'/index.php' ); $mambothandler = mosMambotHandler::getInstance(); $mambothandler->loadBotGroup('system'); $mambothandler->trigger('afterTemplate', array($configuration)); echo "<!-- ".time()." -->"; } } elseif ($indextype == 2) { if ( $no_html == 0 ) { // needed to seperate the ISO number from the language file constant _ISO $iso = split( '=', _ISO ); // xml prolog echo '<?xml version="1.0" encoding="'. $iso[1] .'"?' .'>'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="templates/<?php echo $cur_template;?>/css/template_css.css" type="text/css" /> <meta http-equiv="Content-Type" content="text/html; <?php echo _ISO; ?>" /> <meta name="robots" content="noindex, nofollow"> </head> <body class="contentpane"> <?php mosMainBody(); ?> </body> </html> <?php } else { mosMainBody(); } } $configuration->doGzip(); } // displays queries performed for page if ($configuration->get('mosConfig_debug')) $database->displayLogged(); ?>
| ViewVC Help | |
| Powered by ViewVC 1.0.0 |

