[ Index ]

PHP Cross Reference of Mambo 4.6.5

[ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

/includes/ -> core.classes.php (source)

   1  <?php
   2  /**
   3  * @package Mambo
   4  * @author Mambo Foundation Inc see README.php
   5  * @copyright (C) 2000 - 2009 Mambo Foundation Inc.
   6  * See COPYRIGHT.php for copyright notices and details.
   7  * @license GNU/GPL Version 2, see LICENSE.php
   8  *
   9  * Redistributions of files must retain the above copyright notice.
  10  *
  11  * Mambo is free software; you can redistribute it and/or
  12  * modify it under the terms of the GNU General Public License
  13  * as published by the Free Software Foundation; version 2 of the License.
  14  */
  15  
  16  /**
  17  * Mambo basic error object
  18  */
  19  define ('_MOS_ERROR_INFORM', 0);
  20  define ('_MOS_ERROR_WARN', 1);
  21  define ('_MOS_ERROR_SEVERE', 2);
  22  define ('_MOS_ERROR_FATAL', 3);
  23  
  24  /**
  25   * Enter description here...
  26   *
  27   */
  28  class mosError {
  29      /**
  30       * Enter description here...
  31       *
  32       * @var unknown_type
  33       */
  34      var $text = '';
  35      /**
  36       * Enter description here...
  37       *
  38       * @var unknown_type
  39       */
  40      var $level = 0;
  41  
  42      /**
  43       * Enter description here...
  44       *
  45       * @param unknown_type $text
  46       * @param unknown_type $level
  47       * @return mosError
  48       */
  49      function mosError ($text='', $level=_MOS_ERROR_INFORM) {
  50          $this->text = $text;
  51          $this->level = $level;
  52      }
  53  }
  54  
  55  /**
  56  * Mambo group of errors for some particular operation
  57  */
  58  class mosErrorSet {
  59      /**
  60       * Enter description here...
  61       *
  62       * @var unknown_type
  63       */
  64      var $errors = array();
  65      /**
  66       * Enter description here...
  67       *
  68       * @var unknown_type
  69       */
  70      var $maxlevel = 0;
  71  
  72      // Parameter is an error object
  73      /**
  74       * Enter description here...
  75       *
  76       * @param unknown_type $error
  77       */
  78      function addError ($error) {
  79          $this->errors[] = $error;
  80          if ($error->level > $this->maxlevel) $this->maxlevel = $error->level;
  81      }
  82  
  83      /**
  84       * Enter description here...
  85       *
  86       * @param unknown_type $text
  87       * @param unknown_type $level
  88       */
  89      function addErrorDetails ($text='', $level=_MOS_ERROR_INFORM) {
  90          $error = new mosError($text, $level);
  91          $this->addError($error);
  92      }
  93  
  94      /**
  95       * Enter description here...
  96       *
  97       * @return unknown
  98       */
  99      function &getErrors () {
 100          return $this->errors;
 101      }
 102  
 103      /**
 104       * Enter description here...
 105       *
 106       * @return unknown
 107       */
 108      function getMaxLevel () {
 109          return $this->maxlevel;
 110      }
 111  
 112      /**
 113       * Enter description here...
 114       *
 115       * @return unknown
 116       */
 117      function getCount () {
 118          return count($this->errors);
 119      }
 120  
 121      /**
 122       * Enter description here...
 123       *
 124       * @param unknown_type $errorset
 125       */
 126      function mergeAnother ($errorset) {
 127          $this->errors = array_merge($this->errors, $errorset->errors);
 128      }
 129  
 130  }
 131  
 132  
 133  /* This is the new error handler to store errors in the database
 134  class mosErrorHandler {
 135  var $types = array (
 136  E_STRICT => 'Strict check',
 137  E_USER_WARNING => 'User Warning',
 138  E_USER_NOTICE => 'User Notice',
 139  E_WARNING => 'Warning',
 140  E_NOTICE => 'Notice',
 141  E_CORE_WARNING => 'Core Warning',
 142  E_COMPILE_WARNING => 'Compile Warning',
 143  E_USER_ERROR => 'User Error',
 144  E_ERROR => 'Error',
 145  E_PARSE => 'Parse error',
 146  E_CORE_ERROR => 'Core Error',
 147  E_COMPILE_ERROR => 'Compile Error'
 148  );
 149  
 150  function mosErrorHandler () {
 151  set_error_handler(array(&$this, 'handler'));
 152  }
 153  
 154  function handler ($errno, $errstr, $errfile, $errline, $errcontext) {
 155  if ($errno = E_STRICT) return;
 156  $string = $this->types[$errno].': '.$errstr.' in '.$errfile.' at '.$errline;
 157  $database =& mamboDatabase::getInstance();
 158  if (eregi('^(sql)$', $errstr)) {
 159  $extra = $database->getErrorMsg();
 160  }
 161  if (function_exists('debug_backtrace')) {
 162  foreach(debug_backtrace() as $back) {
 163  if (@$back['file']) {
 164  $extra .= "\n".$back['file'].':'.$back['line'];
 165  }
 166  }
 167  }
 168  $database->setQuery("DELETE FROM #__errors WHERE file=$errfile AND line=$errline AND number=$errno");
 169  $database->query();
 170  $database->setQuery("INSERT INTO #__errors VALUES (0, $errno, '$errfile', $errline, '$string', '$extra')");
 171  $database->query();
 172  }
 173  }
 174  */
 175  
 176  /**
 177   * Enter description here...
 178   *
 179   */
 180  class mamboCore {
 181      /**
 182       * Enter description here...
 183       *
 184       * @var unknown_type
 185       */
 186      var $rootPath = '';
 187      /**
 188       * Enter description here...
 189       *
 190       * @var unknown_type
 191       */
 192      var $Itemid = 0;
 193      /**
 194       * Enter description here...
 195       *
 196       * @var unknown_type
 197       */
 198      var $option = '';
 199      /**
 200       * Enter description here...
 201       *
 202       * @var unknown_type
 203       */
 204      var $subdirectory;
 205      /**
 206       * Enter description here...
 207       *
 208       * @var unknown_type
 209       */
 210      var $current_user = null;
 211      /**
 212       * Enter description here...
 213       *
 214       * @var unknown_type
 215       */
 216      var $do_gzip_compress = false;
 217      /**
 218       * Enter description here...
 219       *
 220       * @var unknown_type
 221       */
 222      var $init_errorlevel = 0;
 223  
 224      /**
 225       * Enter description here...
 226       *
 227       * @return mamboCore
 228       */
 229      function mamboCore () {
 230          global $adminside;
 231          $this->init_errorlevel = error_reporting(0);
 232          //$this->rootPath = str_replace('\\', '/', realpath(str_replace('includes', '', dirname(__FILE__))));
 233          $this->rootPath = str_replace('\\', '/',str_replace('includes', '', dirname(__FILE__)));
 234          $this->checkConfig();
 235          $this->Itemid = (int)mosGetParam($_REQUEST, 'Itemid', 0);
 236          $this->getConfig();
 237          $this->fixLanguage();
 238          @set_magic_quotes_runtime( 0 );
 239          if (@$this->mosConfig_error_reporting > 0 OR @$this->mosConfig_error_reporting ===0) error_reporting($this->mosConfig_error_reporting);
 240          else error_reporting($this->init_errorlevel);
 241      }
 242  
 243      /**
 244       * Enter description here...
 245       *
 246       * @return unknown
 247       */
 248      function &getMamboCore () {
 249          static $instance;
 250          if (!is_object($instance)) $instance = new mamboCore();
 251          return $instance;
 252      }
 253  
 254      /**
 255       * Enter description here...
 256       *
 257       * @return unknown
 258       */
 259      function rootPath () {
 260          //if (realpath($this->rootPath) === false) die ('Invalid program load path');
 261          if (file_exists($this->rootPath) === false) die ('Invalid program load path');
 262          return $this->rootPath;
 263      }
 264  
 265      /**
 266       * Enter description here...
 267       *
 268       * @param unknown_type $property
 269       * @return unknown
 270       */
 271      function get ($property) {
 272          $config =& mamboCore::getMamboCore();
 273          if ($property == 'mosConfig_absolute_path') {
 274              //if (realpath($config->mosConfig_absolute_path) === false) die ('Invalid program load path');
 275              if (file_exists($config->mosConfig_absolute_path) === false) die ('Invalid program load path');
 276              else return $config->rootPath;
 277          }
 278          if (isset($config->$property)) return $config->$property;
 279          trigger_error("Invalid property ($property) requested from mamboCore");
 280          return null;
 281      }
 282  
 283      /**
 284       * Enter description here...
 285       *
 286       * @param unknown_type $property
 287       * @return unknown
 288       */
 289      function is_set ($property) {
 290          $config =& mamboCore::getMamboCore();
 291          return isset($config->$property);
 292      }
 293  
 294      /**
 295       * Enter description here...
 296       *
 297       * @param unknown_type $property
 298       * @param unknown_type $value
 299       * @return unknown
 300       */
 301      function set ($property, $value) {
 302          $config =& mamboCore::getMamboCore();
 303          $config->$property = $value;
 304          $GLOBALS[$property] = $value;
 305          return $value;
 306      }
 307  
 308      /**
 309       * Enter description here...
 310       *
 311       */
 312      function checkConfig () {
 313          // checks for configuration file, if none found loads installation page
 314          if (!file_exists($this->rootPath.'/configuration.php') OR filesize($this->rootPath.'/configuration.php') < 10 ) {
 315              header( 'Location: installation/index.php' );
 316              exit();
 317          }
 318      }
 319  
 320      /**
 321       * Enter description here...
 322       *
 323       */
 324      function getConfig () {
 325          global $adminside;
 326          $code = '';
 327          $f = @fopen($this->rootPath.'/configuration.php','rb');
 328          if ($f) {
 329              while ($f AND !feof($f)) {
 330                  $line = fgets($f);
 331                  $altered = preg_replace('/^\$/', '$this->', $line);
 332                  if ($altered != $line) $code .= $altered;
 333              }
 334          }
 335          else {
 336              #header( 'Location: installation/index.php' );
 337              exit();
 338          }
 339          fclose($f);
 340          eval($code);
 341  
 342          $origin = array_pop(debug_backtrace());
 343          // Find the PHP script at the start, with a fix for Windows slashes
 344          $absolutepath = str_replace('\\', '/', $origin['file']);
 345          $localpath = $_SERVER['PHP_SELF'];
 346          $userdir= '';
 347          if (strpos($localpath,'~') !== false){
 348              $userdir = substr($localpath, 0, strpos(substr($localpath,1),'/')+1);
 349              $localpath = substr($localpath,strpos(substr($localpath,1),'/')+1);
 350          }
 351          $docroot = substr($absolutepath,0,strpos($absolutepath,$localpath));
 352          $mamboroot = str_replace('\\', '/', rtrim($this->rootPath, '\/'));
 353          $this->subdirectory = $userdir . substr($mamboroot, strlen($docroot));
 354  
 355          $scheme = isset($_SERVER['HTTP_SCHEME']) ? $_SERVER['HTTP_SCHEME'] : ((isset($_SERVER['HTTPS']) AND strtolower($_SERVER['HTTPS'] != 'off')) ? 'https' : 'http');
 356          if (isset($_SERVER['HTTP_HOST'])) {
 357              $withport = explode(':', $_SERVER['HTTP_HOST']);
 358              $servername = $withport[0];
 359              if (isset($withport[1])) $port = ':'.$withport[1];
 360          }
 361          elseif (isset($_SERVER['SERVER_NAME'])) $servername = $_SERVER['SERVER_NAME'];
 362          else trigger_error(T_('Impossible to determine the name of this server'), E_USER_ERROR);
 363          if (!isset($port) AND !empty($_SERVER['SERVER_PORT'])) $port = ':'.$_SERVER['SERVER_PORT'];
 364          if (isset($port)) {
 365              if (($scheme == 'http' AND $port == ':80') OR ($scheme == 'https' AND $port == ':443')) $port = '';
 366          }
 367          else $port = '';
 368          $afterscheme = '://'.$servername.$port.$this->subdirectory;
 369          //$this->mosConfig_live_site = $this->mosConfig_secure_site = $scheme.$afterscheme;
 370          $this->mosConfig_unsecure_site = 'http'.$afterscheme;
 371          $this->mosConfig_absolute_path = $this->rootPath;
 372          preg_match_all('/\$this\-\>([A-Za-z_][A-Za-z0-9_]*)/', $code, $matches);
 373          foreach ($matches[1] as $match) $GLOBALS[$match] = $this->$match;
 374          if (!isset($this->mosConfig_register_globals)) {
 375              $this->mosConfig_register_globals = 0;
 376              $GLOBALS['mosConfig_register_globals'] = 0;
 377          }
 378  
 379      }
 380  
 381      /**
 382       * Enter description here...
 383       *
 384       * @return unknown
 385       */
 386      function getFavIcon () {
 387          // favourites icon
 388          if (!isset($this->mosConfig_favicon)) $this->mosConfig_favicon = 'favicon.ico';
 389          if (!file_exists($this->rootPath.'/images/'.$this->mosConfig_favicon)) $this->mosConfig_favicon = 'favicon.ico';
 390          return $this->mosConfig_live_site.'/images/'.$this->mosConfig_favicon;
 391      }
 392  
 393      /**
 394       * Enter description here...
 395       *
 396       * @param unknown_type $user
 397       * @param unknown_type $database
 398       */
 399  function offlineCheck (&$user, &$database) {
 400      global $adminside;
 401          if (($this->mosConfig_offline && !$adminside) OR file_exists($this->rootPath.'/installation/index.php')) {
 402              require_once($this->rootPath().'/administrator/includes/admin.php');
 403              session_start();
 404              $session =& mosSession::getCurrent();
 405              if (!isset($_SESSION['initiated'])) { 
 406                  session_regenerate_id(true); 
 407                  $_SESSION['initiated'] = true; 
 408              } 
 409              $my =& new mosUser();
 410              $my->getSessionData();
 411              if (mosSession::validate($my)) return;
 412              include("$this->mosConfig_absolute_path/offline.php");
 413              exit();
 414          }
 415      }
 416  
 417      function loadLanguage(){
 418          if (!mosGetParam($_REQUEST, 'lang'));
 419      else $this->mosConfig_locale = mosGetParam($_REQUEST, 'lang', $this->mosConfig_locale);
 420          $language =& new mamboLanguage($this->mosConfig_locale, $this->rootPath.'/language/');
 421          $languages = $language->getLanguages();
 422          $charset = $language->get('charset');
 423          $dateformat = $language->get('dateformat');
 424          $this->mosConfig_lang = $language->get('lang');
 425          $this->current_language = $language;
 426          if (!defined('_ISO')) DEFINE('_ISO','charset='.$charset);
 427          header('Content-type: text/html; '._ISO);
 428          if (!defined('_DATE_FORMAT_LC')) DEFINE('_DATE_FORMAT_LC', $dateformat); //Uses PHP's strftime Command Format
 429          if (!defined('_DATE_FORMAT_LC2')) DEFINE('_DATE_FORMAT_LC2', $dateformat);
 430  
 431          #error_reporting(E_ALL)        ;
 432          ##########  DEPRECATED ############
 433          if (isset($this->mosConfig_lang) AND $this->mosConfig_lang);
 434          else $this->set('mosConfig_lang', 'english');
 435          $language_file = "$this->mosConfig_absolute_path/language/$this->mosConfig_lang.php";
 436          if (file_exists($language_file)) require_once ($language_file);
 437          else require_once ("$this->mosConfig_absolute_path/language/english.php");
 438          ###################################
 439      }
 440      /**
 441       * Enter description here...
 442       *
 443       */
 444      function fixLanguage () {
 445          require_once($this->mosConfig_absolute_path.'/includes/phpgettext/phpgettext.class.php');
 446          require_once($this->mosConfig_absolute_path.'/includes/phpgettext/error.php');
 447          require_once($this->mosConfig_absolute_path.'/includes/mambofunc.php');
 448          require_once($this->mosConfig_absolute_path.'/includes/mambolanguage.class.php');
 449      }
 450  
 451      /**
 452       * Enter description here...
 453       *
 454       */
 455  	function handleGlobals () {
 456          $superglobals = array($_SERVER, $_ENV, $_FILES, $_COOKIE, $_POST, $_GET);
 457          if (isset( $_SESSION )) array_unshift ( $superglobals , $_SESSION );
 458  
 459          // Emulate register_globals on
 460          if (!ini_get('register_globals') && $this->mosConfig_register_globals) {
 461              while(list($key,$value)=each($_GET)) {
 462                  if (!isset($GLOBALS[$key])) $GLOBALS[$key]=$value;
 463              }
 464              while(list($key,$value)=each($_POST)) {
 465                  if (!isset($GLOBALS[$key])) $GLOBALS[$key]=$value;
 466              }
 467          }
 468          // Emulate register_globals off
 469          elseif (ini_get('register_globals') && !$this->mosConfig_register_globals) {
 470              foreach ( $superglobals as $superglobal ) {
 471                  foreach ( $superglobal as $key => $value) {
 472                      unset( $GLOBALS[$key]);
 473                      unset( $GLOBALS[$key]);
 474                  }
 475              }
 476          }
 477      }
 478  
 479      /**
 480       * Enter description here...
 481       *
 482       * @return unknown
 483       */
 484      function determineOptionAndItemid () {
 485          $this->Itemid = (int)mosGetParam($_REQUEST, 'Itemid', 0);
 486          if ($option = strtolower(mosGetParam($_REQUEST, 'option')));
 487          else {
 488              $menuhandler =& mosMenuHandler::getInstance();
 489              $menus =& $menuhandler->getByParentOrder($this->Itemid, 'mainmenu');
 490              if (count($menus)) {
 491                  $this->Itemid = $menus[0]->id;
 492                  $_REQUEST['Itemid'] = $this->Itemid;
 493                  $link = $menus[0]->link;
 494                  $pos = strpos( $link, '?' );
 495                  if ($pos !== false) $link = substr( $link, $pos+1 ). '&Itemid='.$this->Itemid;
 496                  parse_str( $link, $temp );
 497                  /** this is a patch, need to rework when globals are handled better */
 498                  foreach ($temp as $k=>$v) $_GET[$k] = $_REQUEST[$k] = $v;
 499                  if (isset($temp['option'])) $option = $temp['option'];
 500                  else return '';             
 501              }
 502          }
 503          /** patch to lessen the impact on templates */
 504          if ($option == 'search') $option = 'com_search';
 505          // checking if we can find the Itemid thru the component
 506          if ($this->Itemid === 0) {
 507              if ( $option == 'com_content') {
 508                  require_once($this->rootPath().'/components/com_content/content.class.php');
 509                  $handler =& contentHandler::getInstance();
 510                  $this->Itemid = (int)$handler->getItemid(mosGetParam($_REQUEST, 'id', 0 ));
 511                  $_REQUEST['Itemid'] = $this->Itemid;
 512              }
 513              else {
 514                  $menuhandler =& mosMenuHandler::getInstance();
 515                  $this->Itemid = $menuhandler->getIdLikeLink("index.php?option=$option");
 516                  if ($this->Itemid === 0) {
 517                      $menuhandler =& mosMenuHandler::getInstance();
 518                      $menus =& $menuhandler->getByParentOrder($this->Itemid, 'mainmenu');
 519                  }
 520              }
 521          }
 522          return trim(htmlspecialchars($option));
 523      }
 524  
 525      /**
 526       * Enter description here...
 527       *
 528       * @param unknown_type $url
 529       * @param unknown_type $msg
 530       */
 531      function redirect ($url, $msg='') {
 532          $callcheck = array('InputFilter', 'process');
 533          if (!is_callable($callcheck)) require_once(mamboCore::get('mosConfig_absolute_path').'/includes/phpInputFilter/class.inputfilter.php');
 534          // specific filters
 535          $iFilter =& new InputFilter();
 536          $url = $iFilter->process( $url );
 537          $message = trim($iFilter->process($msg));
 538          if ($iFilter->badAttributeValue(array('href', $url))) $url = mamboCore::get('mosConfig_live_site');
 539          if ($message) {
 540              if (strpos($url, '?')) $url .= '&mosmsg='.urlencode($message);
 541              else $url .= '?mosmsg='.urlencode($message);
 542          }
 543          $url = preg_replace("/[\n]|[\r]/",'',$url);
 544          if (headers_sent()) echo "<script>document.location.href='$url';</script>\n";
 545          else {
 546              @ob_end_clean(); // clear output buffer
 547              header( "Location: $url" );
 548          }
 549          exit();
 550      }
 551  
 552      /**
 553       * Enter description here...
 554       *
 555       * @param unknown_type $text
 556       */
 557      function logMessage ($text) {
 558          // JS Popup message
 559          if (mosGetParam( $_POST, 'message', 0 )) {
 560              ?>
 561              <script type="text/javascript">
 562              <!--//
 563              alert( "<?php echo $text; ?>" );
 564              //-->
 565              </script>
 566              <?php
 567          }
 568          if ($return = mosGetParam( $_REQUEST, 'return', '' )) {
 569              $this->redirect( $return );
 570          }
 571          else {
 572              $this->redirect( $this->mosConfig_live_site.'/index.php' );
 573          }
 574      }
 575  
 576      /**
 577       * Enter description here...
 578       *
 579       */
 580      function handleLogin () {
 581          require_once($this->rootPath().'/includes/authenticator.php');
 582          $authenticator =& mamboAuthenticator::getInstance();
 583          $loggedin = $authenticator->loginUser();
 584          if ($loggedin) $this->logMessage(T_('You have Logged In succesfully'));
 585          else mamboCore::redirect('index.php');
 586      }
 587  
 588      /**
 589       * Enter description here...
 590       *
 591       */
 592      function handleLogout () {
 593          require_once($this->rootPath().'/includes/authenticator.php');
 594          $authenticator =& mamboAuthenticator::getInstance();
 595          $authenticator->logoutUser();
 596          $this->logMessage(T_('You have Logged Out successfully'));
 597      }
 598  
 599      /**
 600       * Enter description here...
 601       *
 602       */
 603      function standardHeaders () {
 604          header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
 605          header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
 606          header( 'Cache-Control: no-store, no-cache, must-revalidate' );
 607          header( 'Cache-Control: post-check=0, pre-check=0', false );
 608          header( 'Pragma: no-cache' );
 609          $mambothandler =& mosMambotHandler::getInstance();
 610          $mambothandler->loadBotGroup('system');
 611          $mambothandler->trigger('onHeaders', array($this));
 612      }
 613  
 614      /**
 615       * Enter description here...
 616       *
 617       */
 618      function initGzip() {
 619          $this->do_gzip_compress = FALSE;
 620          //zlib.output_compression and ob_gzhandler don't get along well so we'll check to make
 621          //that zlib.output_compression is not enable in the php.ini before turning on ob_gzhandler
 622          if ( $this->mosConfig_gzip == 1 AND (int)ini_get('zlib.output_compression') != 1 ) {
 623              $phpver = phpversion();
 624              $useragent = mosGetParam( $_SERVER, 'HTTP_USER_AGENT', '' );
 625              $canZip = mosGetParam( $_SERVER, 'HTTP_ACCEPT_ENCODING', '' );
 626  
 627              if ( $phpver >= '4.0.4pl1' AND
 628              ( strpos($useragent,'compatible') !== false ||
 629              strpos($useragent,'Gecko')      !== false
 630              )
 631              ) {
 632                  if ( extension_loaded('zlib') ) {
 633                      ob_start( 'ob_gzhandler' );
 634                      return;
 635                  }
 636              } else if ( $phpver > '4.0' ) {
 637                  if ( strpos($canZip,'gzip') !== false ) {
 638                      if (extension_loaded( 'zlib' )) {
 639                          $this->do_gzip_compress = TRUE;
 640                          ob_start();
 641                          ob_implicit_flush(0);
 642  
 643                          header( 'Content-Encoding: gzip' );
 644                          return;
 645                      }
 646                  }
 647              }
 648          }
 649          ob_start();
 650      }
 651  
 652      /**
 653      * Perform GZIP
 654      */
 655      function doGzip() {
 656          if ( $this->do_gzip_compress ) {
 657              /**
 658              *Borrowed from php.net!
 659              */
 660              $gzip_contents = ob_get_contents();
 661              ob_end_clean();
 662  
 663              $gzip_size = strlen($gzip_contents);
 664              $gzip_crc = crc32($gzip_contents);
 665  
 666              $gzip_contents = gzcompress($gzip_contents, 9);
 667              $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
 668  
 669              echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
 670              echo $gzip_contents;
 671              echo pack('V', $gzip_crc);
 672              echo pack('V', $gzip_size);
 673          } else {
 674              ob_end_flush();
 675          }
 676      }
 677  
 678      /**
 679       * Enter description here...
 680       *
 681       * @param unknown_type $separator
 682       * @param unknown_type $field
 683       * @return unknown
 684       */
 685      function getLastPart ($separator, $field) {
 686          $parts = explode($separator, $field);
 687          return $parts[count($parts)-1];
 688      }
 689  
 690      /**
 691       * Enter description here...
 692       *
 693       * @param unknown_type $separator
 694       * @param unknown_type $field
 695       * @return unknown
 696       */
 697      function allButLast ($separator, $field) {
 698          $lastSize = strlen(mamboCore::getLastPart($separator,$field));
 699          return substr($field, 0, strlen($field)-$lastSize);
 700      }
 701  
 702  }
 703  
 704  
 705  /**
 706  * Sorts an Array of objects
 707  */
 708  class mosObjectSorter {
 709      /**
 710       * Enter description here...
 711       *
 712       * @var unknown_type
 713       */
 714      var $_keyname = '';
 715      /**
 716       * Enter description here...
 717       *
 718       * @var unknown_type
 719       */
 720      var $_direction = 0;
 721      /**
 722       * Enter description here...
 723       *
 724       * @var unknown_type
 725       */
 726      var $_object_array = array();
 727  
 728      /**
 729       * Enter description here...
 730       *
 731       * @param unknown_type $a
 732       * @param unknown_type $k
 733       * @param unknown_type $sort_direction
 734       * @return mosObjectSorter
 735       */
 736      function mosObjectSorter (&$a, $k, $sort_direction=1) {
 737          $this->_keyname = $k;
 738          $this->_direction = $sort_direction;
 739          $this->_object_array =& $a;
 740          $this->sort();
 741      }
 742  
 743      /**
 744       * Enter description here...
 745       *
 746       * @param unknown_type $a
 747       * @param unknown_type $b
 748       * @return unknown
 749       */
 750      function mosObjectCompare (&$a, &$b) {
 751          $key = $this->_keyname;
 752          if ($a->$key > $b->$key) return $this->_direction;
 753          if ($a->$key < $b->$key) return -$this->_direction;
 754          return 0;
 755      }
 756  
 757      /**
 758       * Enter description here...
 759       *
 760       */
 761      function sort () {
 762          usort($this->_object_array, array($this,'mosObjectCompare'));
 763      }
 764  
 765  }
 766  
 767  /**
 768  * Pathway handler
 769  * @package Mambo
 770  */
 771  class mosPathway {
 772      /** @var array Names for display in pathway */
 773      var $_names = null;
 774      /** @var array URLs for links from pathway */
 775      var $_urls = null;
 776  
 777      /**
 778      * Constructor
 779      */
 780      function mosPathway () {
 781          $menuhandler =& mosMenuHandler::getInstance();
 782          $menus =& $menuhandler->getByParentOrder(0,'mainmenu');
 783          $home = $menus[0];
 784          $this->_names[] = $home->name;
 785          $this->_urls[] = sefRelToAbs($home->link."&Itemid=$home->id");
 786      }
 787  
 788      /**
 789      * Singleton accessor
 790      */
 791      function &getInstance () {
 792          static $instance;
 793          if (!is_object($instance)) $instance = new mosPathway();
 794          return $instance;
 795      }
 796  
 797      /**
 798      * Add an item to the pathway
 799      */
 800      function addItem ($name, $givenurl) {
 801          $last = count($this->_names) - 1;
 802          if (!$name) return;
 803          $url = sefRelToAbs($givenurl);
 804          if ($name == $this->_names[$last] AND $url == $this->_urls[$last]) return;
 805          $this->_names[$last+1] = $name;
 806          $this->_urls[$last+1] = $url;
 807      }
 808  
 809      /**
 810       * Enter description here...
 811       *
 812       */
 813      function reduceToOne () {
 814          for ($i = count($this->_names) - 1; $i > 0; $i--) {
 815              unset($this->_names[$i]);
 816              unset($this->_urls[$i]);
 817          }
 818      }
 819  
 820      /**
 821      * Make a pathway string for display
 822      */
 823      function makePathway () {
 824          $mainframe =& mosMainFrame::getInstance();
 825          $customs = $mainframe->getCustomPathWay();
 826          $last = count($this->_names) - 1;
 827          if (($last == 0) AND (count($customs) == 0)) return '';
 828          $result = "<span class='pathway'>";
 829          $config =& mamboCore::getMamboCore();
 830          $rootpath = $config->rootPath();
 831          $imgPath =  'templates/'.$mainframe->getTemplate().'/images/arrow.png';
 832          if (file_exists( "$rootpath/$imgPath" )) $img = "<img src='$config->mosConfig_live_site/$imgPath' border='0' alt='arrow' />";
 833          else {
 834              $imgPath = '/images/M_images/arrow.png';
 835              if (file_exists( "$rootpath/$imgPath" )) $img = "<img src='$config->mosConfig_live_site/images/M_images/arrow.png' alt='arrow' />";
 836              else $img = '&gt;';
 837          }
 838          $uri =& mosUriHelper::getInstance();
 839          foreach ($this->_names as $i=>$name) {
 840              $uri->setUri($this->_urls[$i]);
 841              if ($i === $last AND count($customs) == 0) $result .= "$name</span>";
 842              elseif (strstr($uri->get('task'), 'view')) $result .= ""; 
 843              else {
 844                  $sefurl = sefRelToAbs($this->_urls[$i]);
 845                  $result .= "<a href='$sefurl' class='pathway'>$name</a>";
 846                  $result .= "&nbsp;$img&nbsp;";
 847              }
 848          }
 849          foreach ($customs as $custom) $result .= $custom;
 850          if (count($customs)) $result .= '</span>';
 851          return $result;
 852      }
 853  
 854  }
 855  
 856  /**
 857  * Module database table class
 858  * @package Mambo
 859  */
 860  class mosMenu extends mosDBTable {
 861      /** @var int Primary key */
 862      var $id=null;
 863      /** @var string */
 864      var $menutype=null;
 865      /** @var string */
 866      var $name=null;
 867      /** @var string */
 868      var $link=null;
 869      /** @var int */
 870      var $type=null;
 871      /** @var int */
 872      var $published=null;
 873      /** @var int */
 874      var $componentid=null;
 875      /** @var int */
 876      var $parent=null;
 877      /** @var int */
 878      var $sublevel=null;
 879      /** @var int */
 880      var $ordering=null;
 881      /** @var boolean */
 882      var $checked_out=null;
 883      /** @var datetime */
 884      var $checked_out_time=null;
 885      /** @var boolean */
 886      var $pollid=null;
 887  
 888      /** @var string */
 889      var $browserNav=null;
 890      /** @var int */
 891      var $access=null;
 892      /** @var int */
 893      var $utaccess=null;
 894      /** @var string */
 895      var $params=null;
 896  
 897      /**
 898      * @param database A database connector object
 899      */
 900      function mosMenu() {
 901          $db =& mamboDatabase::getInstance();
 902          $this->mosDBTable( '#__menu', 'id', $db );
 903      }
 904      /**
 905      *    binds an array/hash to this object
 906      *    @param int $oid optional argument, if not specifed then the value of current key is used
 907      *    @return any result from the database operation
 908      */
 909      function load( $oid=null ) {
 910          $k = $this->_tbl_key;
 911          if ($oid !== null) $this->$k = $oid;
 912          if ($this->$k === null) return false;
 913          $menuhandler =& mosMenuHandler::getInstance();
 914          $menu =& $menuhandler->getMenuById($this->$k);
 915          if ($menu) {
 916              foreach (get_object_vars($menu) as $key=>$data) $this->$key = $data;
 917              return true;
 918          }
 919          else return false;
 920      }
 921  
 922  }
 923  
 924  /**
 925  * File Manager including safe mode provision?
 926  * @package Mambo
 927  */
 928  class mosFileManager {
 929  
 930      /**
 931      * Singleton accessor
 932      */
 933      function &getInstance () {
 934          static $instance;
 935          if (!is_object($instance)) $instance = new mosFileManager();
 936          return $instance;
 937      }
 938  
 939      /**
 940       * Enter description here...
 941       *
 942       * @param unknown_type $file
 943       * @return unknown
 944       */
 945      function deleteFile ($file) {
 946          if (file_exists($file)) {
 947              @chmod($file, 0644);
 948              return unlink($file);
 949          }
 950          return true;
 951      }
 952  
 953      /**
 954       * Enter description here...
 955       *
 956       * @param unknown_type $dir
 957       * @return unknown
 958       */
 959      function deleteDirectory ($dir) {
 960          if (file_exists($dir)) {
 961              if (is_dir($dir)) {
 962                  @chmod($dir, 0755);
 963                  return rmdir($dir);
 964              }
 965              return false;
 966          }
 967          return true;
 968      }
 969  
 970      /**
 971       * Enter description here...
 972       *
 973       * @param unknown_type $fileSysObject
 974       */
 975      function setPermissions ($fileSysObject) {
 976          if (file_exists($fileSysObject))  {
 977              if (is_dir($fileSysObject)) $perms = mamboCore::get('mosConfig_dirperms');
 978              else $perms = mamboCore::get('mosConfig_fileperms');
 979              if ($perms) {
 980                  $origmask = @umask(0);
 981                  $mode = octdec($perms);
 982                  @chmod($fileSysObject, $mode);
 983                  @umask($origmask);
 984              }
 985          }
 986      }
 987  
 988      /**
 989       * Enter description here...
 990       *
 991       * @param unknown_type $dir
 992       * @return unknown
 993       */
 994      function makeDirectory ($dir) {
 995          $perms = mamboCore::get('mosConfig_dirperms');
 996          $origmask = @umask(0);
 997          if ($perms) $result = @mkdir($dir, octdec($perms));
 998          else $result = @mkdir($dir, 0755);
 999          if ($result) $this->setPermissions($dir);
1000          @umask($origmask);
1001          return $result;
1002      }
1003  
1004  
1005      /**
1006       * Enter description here...
1007       *
1008       * @param unknown_type $dir
1009       * @param unknown_type $onlyCheck
1010       * @return unknown
1011       */
1012      function createDirectory ($dir, $onlyCheck=false) {
1013          if (file_exists($dir)) {
1014              if (is_dir($dir) AND is_writable($dir)) return true;
1015              else return false;
1016          }
1017          list($upDirectory, $count) = $this->containingDirectory($dir);
1018          if ($count > 1 AND !file_exists($upDirectory) AND !($result = $this->createDirectory($upDirectory, $onlyCheck))) return false;
1019          if ($onlyCheck AND isset($result)) return true;
1020          if (!is_dir($upDirectory) OR !is_writable($upDirectory)) return false;
1021          if ($onlyCheck) return true;
1022          else return $this->makeDirectory($dir);
1023      }
1024  
1025      /**
1026       * Enter description here...
1027       *
1028       * @param unknown_type $dir
1029       * @return unknown
1030       */
1031      function containingDirectory ($dir) {
1032          $dirs = preg_split('*[/|\\\]*', $dir);
1033          for ($i = count($dirs)-1; $i >= 0; $i--) {
1034              $text = trim($dirs[$i]);
1035              unset($dirs[$i]);
1036              if ($text) break;
1037          }
1038          $result2 = count($dirs);
1039          $result1 = implode('/',$dirs).($result2 > 1 ? '' : '/');
1040          return array($result1, $result2);
1041      }
1042  
1043      /**
1044       * Enter description here...
1045       *
1046       * @param unknown_type $from
1047       * @param unknown_type $to
1048       * @return unknown
1049       */
1050      function simpleCopy ($from, $to) {
1051          if (@copy($from, $to)) {
1052              $this->setPermissions($to);
1053              return true;
1054          }
1055          else return false;
1056      }
1057  
1058      /**
1059       * Enter description here...
1060       *
1061       * @param unknown_type $from
1062       * @param unknown_type $to
1063       * @return unknown
1064       */
1065      function forceCopy ($from, $to) {
1066          $todir = dirname($to);
1067          if (!file_exists($todir)) $this->createDirectory($todir);
1068          if (!file_exists($todir)) return false;
1069          $name = basename($from);
1070          $this->deleteFile($to.$name);
1071          return $this->simpleCopy ($from, $to);
1072      }
1073  
1074      /**
1075       * Enter description here...
1076       *
1077       * @param unknown_type $from
1078       * @param unknown_type $to
1079       * @return unknown
1080       */
1081      function lightCopy ($from, $to) {
1082          $name = basename($from);
1083          if (file_exists($to.$name)) return false;
1084          $todir = dirname($to);
1085          if (!file_exists($todir)) $this->createDirectory($todir);
1086          if (!file_exists($todir)) return false;
1087          return $this->simpleCopy ($from, $to);
1088      }
1089  
1090      /**
1091       * Enter description here...
1092       *
1093       * @param unknown_type $to
1094       * @return unknown
1095       */
1096      function acceptCopy ($to) {
1097          $todir = dirname($to);
1098          return $this->createDirectory($todir, true);
1099      }
1100  
1101  
1102      /**
1103      * Function to strip additional / or \ in a path name
1104      * @param string The path
1105      * @param boolean Add trailing slash
1106      */
1107      function mosPathName($p_path, $p_addtrailingslash=true) {
1108          if (substr(PHP_OS, 0, 3) == 'WIN')    {
1109              $retval = str_replace( '/', '\\', $p_path );
1110              if ($p_addtrailingslash AND substr( $retval, -1 ) != '\\') $retval .= '\\';
1111              // Remove double \\
1112              $retval = str_replace( '\\\\', '\\', $retval );
1113          }
1114          else {
1115              $retval = str_replace( '\\', '/', $p_path );
1116              if ($p_addtrailingslash AND substr( $retval, -1 ) != '/') $retval .= '/';
1117              // Remove double //
1118              $retval = str_replace('//','/',$retval);
1119          }
1120          return $retval;
1121      }
1122  
1123      /**
1124      * Chmods files and directories recursively to mos global permissions. Available from 4.5.2 up.
1125      * @param path The starting file or directory (no trailing slash)
1126      * @param filemode Integer value to chmod files. NULL = dont chmod files.
1127      * @param dirmode Integer value to chmod directories. NULL = dont chmod directories.
1128      * @return TRUE=all succeeded FALSE=one or more chmods failed
1129      */
1130      function mosChmod($path)
1131      {
1132          $fileperms = mamboCore::get('mosConfig_fileperms');
1133          if ($fileperms != '') $filemode = octdec($fileperms);
1134          else $filemode = null;
1135          $dirperms = mamboCore::get('mosConfig_dirperms');
1136          if ($dirperms != '') $dirmode = octdec($dirperms);
1137          else $dirmode = null;
1138          if (isset($filemode) OR isset($dirmode))
1139          return $this->mosChmodRecursive($path, $filemode, $dirmode);
1140          return true;
1141      } // mosChmod
1142  
1143      /**
1144      * Chmods files and directories recursively to given permissions. Available from 4.5.2 up.
1145      * @param path The starting file or directory (no trailing slash)
1146      * @param filemode Integer value to chmod files. NULL = dont chmod files.
1147      * @param dirmode Integer value to chmod directories. NULL = dont chmod directories.
1148      * @return TRUE=all succeeded FALSE=one or more chmods failed
1149      */
1150      function mosChmodRecursive($path, $filemode=NULL, $dirmode=NULL) {
1151          $ret = true;
1152          if (is_dir($path)) {
1153              $topdir =& new mosDirectory($path);
1154              $files =& $topdir->listFiles ('', 'file', true, true);
1155              $dirs =& $topdir->listFiles ('', 'dir', true, true);
1156          }
1157          else {
1158              $files = array($path);
1159              $dirs = array();
1160          }
1161          if (isset($filemode)) foreach ($files as $file) $ret = @chmod($file, $filemode) ? $ret : false;
1162          if (isset($dirmode)) foreach ($dirs as $dir) $ret = @chmod($dir, $dirmode) ? $ret : false;
1163          return $ret;
1164      }
1165  
1166  }
1167  
1168  /**
1169   * Enter description here...
1170   *
1171   */
1172  class mosDirectory {
1173      /**
1174       * Enter description here...
1175       *
1176       * @var unknown_type
1177       */
1178      var $path = '';
1179  
1180      /**
1181       * Enter description here...
1182       *
1183       * @param unknown_type $path
1184       * @return mosDirectory
1185       */
1186      function mosDirectory ($path) {
1187          $path = str_replace('\\', '/', $path);
1188          if (substr($path,-1,1) == '/') $this->path = $path;
1189          else $this->path = $path.'/';
1190      }
1191  
1192      /**
1193       * Enter description here...
1194       *
1195       * @param unknown_type $type
1196       * @param unknown_type $recurse
1197       * @param unknown_type $fullpath
1198       * @return unknown
1199       */
1200      function &listAll ($type='file', $recurse=false, $fullpath=false) {
1201          $results = array();
1202          if ($dir = @opendir($this->path)) {
1203              while (false !== ($file = readdir($dir))) {
1204                  if ($file == '.' OR $file == '..') continue;
1205                  if (is_dir($this->path.$file)) {
1206                      if ($recurse) {
1207                          $subdir = new mosDirectory($this->path.$file);
1208                          $results = array_merge($results, $subdir->listAll($type, $recurse, $fullpath));
1209                          unset($subdir);
1210                      }
1211                      if ($type == 'file') continue;
1212                  }
1213                  elseif ($type == 'dir') continue;
1214                  if ($fullpath) $results[] = $this->path.$file;
1215                  else $results[] = $file;
1216              }
1217              closedir($dir);
1218          }
1219      asort($results);
1220          return $results;
1221      }
1222  
1223      /**
1224       * Enter description here...
1225       *
1226       * @return unknown
1227       */
1228      function soleDir () {
1229          $found = '';
1230          if ($dir = @opendir($this->path)) {
1231              while (false !== ($file = readdir($dir))) {
1232                  if ($file == '.' OR $file == '..') continue;
1233                  if (is_dir($this->path.$file)) {
1234                      if ($found) return '';
1235                      else $found = $file;
1236                  }
1237                  else return '';
1238              }
1239              closedir($dir);
1240          }
1241          return $found;
1242      }
1243  
1244      /**
1245       * Enter description here...
1246       *
1247       */
1248      function deleteAll () {
1249          if (!file_exists($this->path)) return;
1250          $subdirs =& $this->listAll ('dir', false, true);
1251          foreach ($subdirs as $subdir) {
1252              $subdirectory = new mosDirectory($subdir);
1253              $subdirectory->deleteAll();
1254              unset($subdirectory);
1255          }
1256          $filemanager =& mosFileManager::getInstance();
1257          $files =& $this->listAll ('file', false, true);
1258          foreach ($files as $file) $filemanager->deleteFile($file);
1259          $filemanager->deleteDirectory($this->path);
1260      }
1261  
1262      /**
1263       * Enter description here...
1264       *
1265       * @return unknown
1266       */
1267      function createFresh () {
1268          $this->deleteAll();
1269          $filemanager =& mosFileManager::getInstance();
1270          $filemanager->createDirectory($this->path);
1271          return true;
1272      }
1273  
1274      /**
1275       * Enter description here...
1276       *
1277       */
1278      function createIfNeeded () {
1279          if (!file_exists($this->path)) {
1280              $filemanager =& mosFileManager::getInstance();
1281              $filemanager->createDirectory($this->path);
1282          }
1283      }
1284  
1285      /**
1286       * Enter description here...
1287       *
1288       * @param unknown_type $pattern
1289       * @param unknown_type $type
1290       * @param unknown_type $recurse
1291       * @param unknown_type $fullpath
1292       * @return unknown
1293       */
1294      function &listFiles ($pattern='', $type='file', $recurse=false, $fullpath=false) {
1295          $results = array();
1296          $all =& $this->listAll($type, $recurse, $fullpath);
1297          foreach ($all as $file) {
1298              $name = basename($file);
1299              if ($pattern AND !preg_match( "/$pattern/", $name )) continue;
1300              if (($name != 'index.html') AND ($name[0] != '.')) $results[] = $file;
1301          }
1302          return $results;
1303      }
1304  
1305      /**
1306       * Enter description here...
1307       *
1308       * @return unknown
1309       */
1310      function getSize () {
1311          $totalsize = 0;
1312          $files =& $this->listFiles();
1313          foreach ($files as $file) $totalsize += filesize($this->path.$file);
1314          return $totalsize;
1315      }
1316  
1317  }
1318  
1319  
1320  /**
1321  * Menu handler
1322  * @package Mambo
1323  */
1324  class mosMenuHandler {
1325      /** @var array Menu objects currently available */
1326      var $_menus = null;
1327      /** @var array Counts of menu items by type and published status */
1328      var $_counts = null;
1329      /** @var array Access to stored menu objects by ID */
1330      var $_idlinks = null;
1331      /** @var array Items that may be useful for setting Itemid */
1332      var $_byParentOrder = null;
1333  
1334      /**
1335      * Constructor
1336      */
1337      function mosMenuHandler() {
1338          $database =& mamboDatabase::getInstance();
1339          $sql = "SELECT * FROM #__menu ORDER BY name";
1340          $this->_menus =& $database->doSQLget($sql, 'mosMenu');
1341          if (!$this->_menus) $this->_menus = array();
1342          foreach ($this->_menus as $key=>$menu) {
1343              $this->_idlinks[$menu->id] = $key;
1344              if ($menu->published == 1) $this->_byParentOrder[$menu->parent][$menu->ordering][$menu->menutype] = $key;
1345              if (isset($this->_counts[$menu->menutype][$menu->published])) $this->_counts[$menu->menutype][$menu->published]++;
1346              else $this->_counts[$menu->menutype][$menu->published] = 1;
1347          }
1348          if ($this->_byParentOrder) {
1349              foreach ($this->_byParentOrder as $parent=>$outer) ksort($this->_byParentOrder[$parent]);
1350              ksort($this->_byParentOrder);
1351          }
1352      }
1353      /**
1354      * Singleton accessor
1355      */
1356      function &getInstance () {
1357          static $instance;
1358          if (!is_object($instance)) $instance = new mosMenuHandler();
1359          return $instance;
1360      }
1361  
1362      /**
1363       * Enter description here...
1364       *
1365       * @param unknown_type $id
1366       * @return unknown
1367       */
1368      function &getMenuByID ($id) {
1369          if (isset($this->_idlinks[$id])) {
1370              $key = $this->_idlinks[$id];
1371              $result = $this->_menus[$key];
1372          }
1373          else $result = null;
1374          return $result;
1375      }
1376  
1377      /**
1378       * Enter description here...
1379       *
1380       * @param unknown_type $type
1381       * @param unknown_type $published
1382       * @return unknown
1383       */
1384      function getMenuCount ($type, $published) {
1385          if (isset($this->_counts[$type][$published])) return $this->_counts[$type][$published];
1386          else return 0;
1387      }
1388  
1389      /**
1390       * Enter description here...
1391       *
1392       * @param unknown_type $types
1393       * @return unknown
1394       */
1395      function &getMenusByType ($types) {
1396          $checker = explode(',', $types);
1397          $result = null;
1398          foreach ($this->_menus as $menu) {
1399              if (in_array($menu->type, $checker)) $result[] = $menu;
1400          }
1401          return $result;
1402      }
1403  
1404      /**
1405       * Enter description here...
1406       *
1407       * @return unknown
1408       */
1409      function &getMenuTypes () {
1410          $types = array();
1411          foreach ($this->_menus as $menu) {
1412              if (!isset($types[$menu->menutype])) $types[$menu->menutype] = 0;
1413              $types[$menu->menutype]++;
1414          }
1415          return $types;
1416      }
1417  
1418      /**
1419       * Enter description here...
1420       *
1421       * @param unknown_type $type
1422       * @param unknown_type $link
1423       * @return unknown
1424       */
1425      function getIDByTypeLink ($type, $link) {
1426          foreach ($this->_menus as $menu) {
1427              if ($menu->published == 1 AND ($type == '*' OR $menu->type == $type) AND $menu->link == $link) return $menu->id;
1428          }
1429          return null;
1430      }
1431  
1432      /**
1433       * Enter description here...
1434       *
1435       * @param unknown_type $link
1436       * @return unknown
1437       */
1438      function getIDLikeLink ($link) {
1439          $exact = $this->getIdByTypeLink('*', $link);
1440          if ($exact !== null) return $exact;
1441          foreach ($this->_menus as $menu) {
1442              if ($menu->published == 1 AND strpos($menu->link,$link) === 0) return $menu->id;
1443          }
1444          return 0;
1445      }
1446  
1447      /**
1448       * Enter description here...
1449       *
1450       * @param unknown_type $type
1451       * @param unknown_type $componentid
1452       * @return unknown
1453       */
1454      function getIDByTypeCid ($type, $componentid) {
1455          foreach ($this->_menus as $menu) {
1456              if ($menu->published == 1 AND $menu->type == $type AND $menu->componentid == $componentid) return $menu->id;
1457          }
1458          return null;
1459      }
1460  
1461      function getSectionItemId($sectionid, $gbs = 1){
1462          static $__sectionsItemds;
1463         
1464          if (isset($__sectionsItemids[$sectionid])) return $__sectionsItemids[$sectionid];
1465          
1466          $_Itemid = null;
1467          if ($_Itemid == null ) {
1468              // Search in sections
1469              $_Itemid = $this->getIDByTypeCid ('content_section', $sectionid);
1470          }
1471          if ($_Itemid == null ) {
1472              // Search in sections
1473              $_Itemid = $this->getIDByTypeCid ('content_blog_section', $sectionid);
1474          }
1475  
1476          if ($_Itemid == null  && $gbs) {
1477              // Search in global blog section
1478              $_Itemid = $this->getIDByTypeCid('content_blog_section', 0);
1479          }
1480          if ($_Itemid != null) $__sectionsItemids[$sectionid] = $_Itemid;
1481          return $_Itemid;
1482      }
1483  
1484      function getCategoryItemId($catid){
1485          static $__categoriesItemids;
1486  
1487          if (isset($__categoriesItemids[$catid])) return $__categoriesItemids[$catid];
1488          
1489          $_Itemid = null;
1490          if ($_Itemid == null) {
1491              // Search in blog categories
1492              $_Itemid = $this->getIDByTypeCid ('content_blog_category', $catid);
1493          }
1494          if ($_Itemid == null) {
1495              // Search in categories
1496              $_Itemid = $this->getIDByTypeCid ('content_category', $catid);
1497          }
1498  
1499          if ($_Itemid != null) $__categoriesItemids[$catid] = $_Itemid;
1500  
1501          return $_Itemid;
1502      }
1503      
1504      /**
1505       * Enter description here...
1506       *
1507       * @return unknown
1508       */
1509      function getGlobalBlogSectionCount () {
1510          $count = 0;
1511          foreach ($this->_menus as $menu) {
1512              if ($menu->type == 'content_blog_section' AND $menu->published == 1 AND $menu->componentid == 0) $count++;
1513          }
1514          return $count;
1515      }
1516  
1517      /**
1518       * Enter description here...
1519       *
1520       * @param unknown_type $Itemid
1521       * @param unknown_type $type
1522       * @param unknown_type $id
1523       * @param unknown_type $catid
1524       * @return unknown
1525       */
1526      function getContentItemid ($Itemid, $type, $id, $catid=0) {
1527          if ($Itemid) return $Itemid;
1528          foreach ($this->_menus as $menu) {
1529              if (strpos($menu->link,'index.php?option=com_content') === false AND strpos($menu->link,'index.php?option=content') === false) continue;
1530              if (strpos($menu->link, $type) === false) continue;
1531              if ($catid) {
1532                  if (strpos($menu->link, "&id=$catid") === false) continue;
1533                  if (strpos($menu->link, "&sectionid=$id") === false) continue;
1534              }
1535              elseif (strpos($menu->link, "&id=$id") === false) continue;
1536              return $menu->id;
1537          }
1538          return 0;
1539      }
1540  
1541      /**
1542       * Enter description here...
1543       *
1544       * @return unknown
1545       */
1546      function getBestQueryMatch () {
1547          parse_str($_SERVER['QUERY_STRING'], $qitems);
1548          if (!isset($qitems['option'])) return 0;
1549          $failures = 999;
1550          $best = 0;
1551          foreach ($this->_menus as $menu) {
1552              $split = explode('?', $menu->link);
1553              if (isset($split[1])) parse_str($split[1], $mitems);
1554              else continue;
1555              if (!isset($mitems['option']) OR $mitems['option'] != $qitems['option']) continue;
1556              $thisfail = 0;
1557              foreach ($mitems as $key=>$mitem) if (!isset($qitems[$key]) OR $mitem != $qitems[$key]) $thisfail++;
1558              if ($thisfail < $failures) {
1559                  $best = $menu->id;
1560                  $failures = $thisfail;
1561              }
1562          }
1563          return $best;
1564      }
1565  
1566  
1567      /**
1568       * Enter description here...
1569       *
1570       * @param unknown_type $link
1571       * @return unknown
1572       */
1573      function &maxAccessLink ($link) {
1574          $selected = null;
1575          $access = 0;
1576          foreach ($this->_menus as $key=>$menu) {
1577              if (strpos($menu->link,$link) === 0 AND $menu->access > $access) {
1578                  $access = $menu->access;
1579                  $selected =& $this->_menus[$key];
1580              }
1581          }
1582          return $selected;
1583      }
1584  
1585      /**
1586       * Enter description here...
1587       *
1588       * @param unknown_type $Itemid
1589       * @param unknown_type $menutype
1590       * @param unknown_type $maxaccess
1591       * @param unknown_type $noparent
1592       * @return unknown
1593       */
1594      function &getByParentOrder ($Itemid, $menutype, $maxaccess=0, $noparent=false) {
1595          $result = array();
1596          if ($this->_byParentOrder !== null) {
1597              foreach ($this->_byParentOrder as $parent=>$outer) {
1598                  foreach ($outer as $ordering=>$inner) {
1599                      foreach ($inner as $mtype=>$last) {
1600                          $key = $this->_byParentOrder[$parent][$ordering][$mtype];
1601                          $menu = $this->_menus[$key];
1602                          if ($menutype AND $mtype != $menutype) continue;
1603                          if ($Itemid AND $Itemid != $menu->id) continue;
1604                          if ($menu->access > $maxaccess) continue;
1605                          if ($noparent AND $parent != 0) continue;
1606                          $result[] = $this->_menus[$key];
1607                      }
1608                  }
1609              }
1610          }
1611          if ($Itemid == 0 && !count($result)){
1612              $result[0] = new stdclass;
1613              $result[0]->id = 1;
1614              $result[0]->link = 'index.php?option=com_frontpage';
1615              $result[0]->parent = 0;
1616              $result[0]->type = 'components';
1617              $result[0]->browserNav = 0;
1618              $result[0]->name = 'Home';
1619          }
1620          return $result;
1621      }
1622  
1623      /**
1624       * Enter description here...
1625       *
1626       * @param unknown_type $Itemid
1627       */
1628      function setPathway ($Itemid) {
1629          if ($Itemid) {
1630              $menu =& $this->getMenuByID($Itemid);
1631              if (!$menu) return;
1632              if ($menu->parent) $this->setPathway($menu->parent);
1633              $pathway =& mosPathway::getInstance();
1634              $pathway->addItem($menu->name, $menu->link."&Itemid=$Itemid");
1635          }
1636      }
1637  
1638      /**
1639      * Checks whether a menu option is within the users access level
1640      * @param int Item id number
1641      * @param string The menu option
1642      * @param int The users group ID number
1643      * @param database A database connector object
1644      * @return boolean True if the visitor's group at least equal to the menu access
1645      */
1646      function menuCheck( $Itemid, $menu_option, $task, $gid ) {
1647          // Construct a link to this component - if no menu for it, assume it is OK
1648          $dblink="index.php?option=$menu_option";
1649          if ($this->getIDLikeLink($dblink) == 0) return true;
1650          if ($Itemid) {
1651              $menu =& $this->getMenuByID($Itemid);
1652              if (!$menu) return false;
1653              if (strpos($menu->link,$dblink) ===0) {
1654                  $access = $menu->access;
1655              } elseif ($menu_option == 'com_content' AND $Itemid == 1) {
1656                  return true;
1657              }
1658          }
1659          if (!isset($access)) {
1660              if ($task!='') $dblink .= "&task=$task";
1661              $menu =& $this->maxAccessLink($dblink);
1662              if (isset($menu)) {
1663                  $access = $menu->access;
1664                  mamboCore::set('Itemid', $menu->id);
1665              }
1666          }
1667          return isset($access) ? $access <= $gid : false;
1668      }
1669  
1670      /**
1671       * Enter description here...
1672       *
1673       * @param unknown_type $mitem
1674       * @param unknown_type $level
1675       * @param unknown_type $params
1676       * @param unknown_type $Itemid
1677       * @return unknown
1678       */
1679      function mosGetMenuLink( &$mitem, $level=0, &$params, $Itemid ) {
1680          $txt = '';
1681  
1682          switch ($mitem->type) {
1683              case 'separator':
1684              case 'component_item_link':
1685              break;
1686              case 'content_item_link':
1687              $temp = split("&task=view&id=", $mitem->link);
1688              if (isset($temp[1])) {
1689                  require_once(mamboCore::get('mosConfig_absolute_path').'/components/com_content/content.class.php');
1690                  $handler =& contentHandler::getInstance();
1691                  $mitem->link .= '&Itemid='.$handler->getItemid($temp[1]);
1692              }
1693              break;
1694              case 'url':
1695              $link = strtolower($mitem->link);
1696              if (substr($link,0,10) == 'index.php?' AND strpos($link,'itemid=') === false) $mitem->link .= '&Itemid='. $mitem->id;
1697              break;
1698              case 'content_typed':
1699              default:
1700              $mitem->link .= '&Itemid='.$mitem->id;
1701              break;
1702          }
1703          // Active Menu highlighting
1704          if ( $Itemid == $mitem->id ) $id = 'id="active_menu'.$params->get( 'class_sfx' ).'"';
1705          else $id = '';
1706          $mitem->link = ampReplace( $mitem->link );
1707          if (strcasecmp(substr($mitem->link,0,4), 'http')) $mitem->link = sefRelToAbs( $mitem->link );
1708          if ($level > 0) $menuclass = 'sublevel';
1709          else $menuclass = 'mainlevel';
1710          $menuclass .= $params->get( 'class_sfx');
1711  
1712          switch ($mitem->browserNav) {
1713              // cases are slightly different
1714              case 1:
1715              // open in a new window
1716              $txt = '<a href="'. $mitem->link .'" target="_blank" class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</a>';
1717              break;
1718  
1719              case 2:
1720              // open in a popup window
1721              $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";
1722              break;
1723  
1724              case 3:
1725              // don't link it
1726              $txt = '<span class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</span>';
1727              break;
1728  
1729              default:    // formerly case 2
1730              // open in parent window
1731              $txt = '<a href="'. $mitem->link .'" class="'. $menuclass .'" '. $id .'>'. $mitem->name .'</a>';
1732              break;
1733          }
1734  
1735          if ( $params->get( 'menu_images' ) ) {
1736              $menu_params =& new mosParameters( $mitem->params );
1737              $menu_image = $menu_params->def( 'menu_image', -1 );
1738              if ($menu_image AND $menu_image <> '-1') {
1739                  $image = '<img src="'. mamboCore::get('mosConfig_live_site') .'/images/stories/'. $menu_image .'" border="0" alt="'. $mitem->name .'"/>';
1740                  if ( $params->get('menu_images_align')) $txt = $txt .' '. $image;
1741                  else $txt = $image .' '. $txt;
1742              }
1743          }
1744          return $txt;
1745      }
1746  
1747      /**
1748      * Vertically Indented Menu
1749      */
1750      function mosShowVIMenu(  &$params ) {
1751          global $my, $cur_template, $Itemid;
1752          if (mamboCore::get('mosConfig_shownoauth')) $maxaccess = 9999999;
1753          else $maxaccess = $my->getAccessGid();
1754          $rows =& $this->getByParentOrder(0, $params->get('menutype'), $maxaccess);
1755          foreach ($rows as $i=>$row) $crosslink[$row->id] = $i;
1756          // indent icons
1757          $base = mamboCore::get('mosConfig_live_site');
1758          switch ( $params->get( 'indent_image' ) ) {
1759              case '1':
1760              // Default images
1761              for ( $i = 1; $i < 7; $i++ ) {
1762                  $img[$i] = "<img src=\"$base/images/M_images/indent$i.png\" alt=\"indent$i\" />";
1763              }
1764              break;
1765              case '2':
1766              // Use Params
1767              for ( $i = 1; $i < 7; $i++ ) {
1768                  $parm = $params->get('indent_image'. $i);
1769                  if ($parm == '-1' ) $img[$i] = NULL;
1770                  else $img[$i] = "<img src=\"$base/images/M_images/$parm\" alt=\"indent$i\" />";
1771              }
1772              break;
1773              case '3':
1774              // None
1775              for ( $i = 1; $i < 7; $i++ ) $img[$i] = NULL;
1776              break;
1777              default:
1778              // Template
1779              $imgpath = $base.'/templates/'. $cur_template .'/images';
1780              for ( $i = 1; $i < 7; $i++ ) {
1781                  $img[$i] = "<img src=\"$base/templates/$cur_template/images/indent$i.png\" alt=\"indent$i\" />";
1782              }
1783              break;
1784          }
1785  
1786          $indents = array(
1787          // block prefix / item prefix / item suffix / block suffix
1788          array( '<table width="100%" border="0" cellpadding="0" cellspacing="0">', '<tr align="left"><td>' , '</td></tr>', '</table>' ),
1789          array( '', '<div style="padding-left: 4px">'. $img[1] , '</div>', '' ),
1790          array( '', '<div style="padding-left: 8px">'. $img[2] , '</div>', '' ),
1791          array( '', '<div style="padding-left: 12px">'. $img[3] , '</div>', '' ),
1792          array( '', '<div style="padding-left: 16px">'. $img[4] , '</div>', '' ),
1793          array( '', '<div style="padding-left: 20px">'. $img[5] , '</div>', '' ),
1794          array( '', '<div style="padding-left: 24px">'. $img[6] , '</div>', '' ),
1795          );
1796  
1797          // establish the hierarchy of the menu
1798          $children = array();
1799          // first pass - collect children
1800          foreach ($rows as $v ) $children[$v->parent][] = $v;
1801          // second pass - collect 'open' menus
1802          $open = array( $Itemid );
1803          for ($i = 0; $i < 20 AND isset($crosslink[$open[$i]]) AND isset($rows[$crosslink[$open[$i]]]); $i++) {
1804              $next = $rows[$crosslink[$open[$i]]]->parent;
1805              if ($next) $open[$i+1] = $next;
1806              else break;
1807          }
1808  
1809          $this->mosRecurseVIMenu( 0, 0, $children, $open, $indents, $params );
1810  
1811      }
1812  
1813      /**
1814      * Utility function to recursively work through a vertically indented
1815      * hierarchial menu
1816      */
1817      function mosRecurseVIMenu( $id, $level, &$children, &$open, &$indents, &$params ) {
1818          global $Itemid;
1819          if (@$children[$id]) {
1820              $n = min( $level, count($indents )-1);
1821              echo "\n".$indents[$n][0];
1822              foreach ($children[$id] as $row) {
1823                  echo "\n".$indents[$n][1];
1824                  echo $this->mosGetMenuLink( $row, $level, $params, $Itemid );
1825                  // show menu with menu expanded - submenus visible
1826                  if ($params->get('expand_menu') OR in_array($row->id, $open)) $this->mosRecurseVIMenu( $row->id, $level+1, $children, $open, $indents, $params );
1827                  echo $indents[$n][2];
1828              }
1829              echo "\n".$indents[$n][3];
1830          }
1831      }
1832  
1833      /**
1834      * Draws a horizontal 'flat' style menu (very simple case)
1835      */
1836      function mosShowHFMenu(  &$params, $style=0 ) {
1837          global $my, $cur_template, $Itemid;
1838  
1839          if (mamboCore::get('mosConfig_shownoauth')) $maxaccess = 9999999;
1840          else $maxaccess = $my->getAccessGid();
1841          $rows =& $this->getByParentOrder(0, $params->get('menutype'), $maxaccess, true);
1842  
1843          $links = array();
1844          foreach ($rows as $row) $links[] = $this->mosGetMenuLink( $row, 0, $params, $Itemid );
1845          $menuclass = 'mainlevel'. $params->get( 'class_sfx' );
1846          if (count( $links )) {
1847              if ($style == 1) {
1848                  echo '<ul id="'. $menuclass .'">';
1849                  foreach ($links as $link) echo '<li>' . $link . '</li>';
1850                  echo '</ul>';
1851              }
1852              else {
1853                  echo '<table width="100%" border="0" cellpadding="0" cellspacing="1">';
1854                  echo '<tr>';
1855                  echo '<td nowrap="nowrap">';
1856                  echo '<span class="'. $menuclass .'"> '. $params->get( 'end_spacer' ) .' </span>';
1857                  echo implode( '<span class="'. $menuclass .'"> '. $params->get( 'spacer' ) .' </span>', $links );
1858                  echo '<span class="'. $menuclass .'"> '. $params->get( 'end_spacer' ) .' </span>';
1859                  echo '</td></tr>';
1860                  echo '</table>';
1861              }
1862          }
1863      }
1864  }
1865  
1866  /**
1867  * Plugin handler
1868  * @package Mambo
1869  */
1870  class mosMambotHandler {
1871      /** @var array An array of functions in event groups */
1872      var $_events=null;
1873      /** @var array An array of lists */
1874      var $_lists=null;
1875      /** @var array An array of mambots */
1876      var $_bots=null;
1877      /** @var array An array of bools showing if corresponding bot is registered */
1878      var $_registered=array();
1879      /** @var int Index of the mambot being loaded */
1880      var $_loading=null;
1881  
1882      /**
1883      * Constructor
1884      */
1885      function mosMambotHandler() {
1886          $my = mamboCore::is_set('currentUser') ? mamboCore::get('currentUser') : null;
1887          $gid = $my ? $my->gid : 0;
1888          $this->_events = array();
1889          $database =& mamboDatabase::getInstance();
1890          $database->setQuery( "SELECT folder, element, published, params, CONCAT_WS('/',folder,element) AS lookup"
1891          . "\nFROM #__mambots"
1892          . "\nWHERE published >= 1 AND access <= $gid"
1893          . "\nORDER BY ordering"
1894          );
1895          $this->_bots = $database->loadObjectList();
1896          if (!$this->_bots) $this->_bots = array();
1897      }
1898      /**
1899      * Singleton accessor
1900      */
1901      function &getInstance () {
1902          static $instance;
1903          if (!is_object($instance)) $instance = new mosMambotHandler();
1904          return $instance;
1905      }
1906      /**
1907      * Register a class-type mambot, provided it has a perform method
1908      * - can register for multiple events if desired
1909      * @param object The mambot object
1910      * @param mixed string or array of strings - the mambot events to be registered
1911      * @param int the subscript for use in the main array of mambots
1912      */
1913      function _botRegister (&$botObject, &$selected, $i) {
1914          $function = array(&$botObject, 'perform');
1915          if (!is_callable($function)) return;
1916          if (is_array($selected)) foreach ($selected as $select) $this->_botRegister($botObject, $select);
1917          $this->_events[$selected][] = array ($function, $i);
1918          $this->_registered[$i] = true;
1919      }
1920  
1921      /**
1922      * Loads all the bot files for a particular group
1923      * @param string The group name, relates to the sub-directory in the mambots directory
1924      */
1925      function loadBotGroup( $group ) {
1926          global $_MAMBOTS;
1927          $group = trim( $group );
1928          $total = 0;
1929          $basepath = mamboCore::get('mosConfig_absolute_path');
1930          foreach ($this->_bots as $i=>$bot) {
1931              if ($bot->folder != $group OR isset($this->_registered[$i])) continue;
1932              $path = "$basepath/mambots/$bot->folder/$bot->element.php";
1933              if (file_exists( $path )) {
1934                  $this->_loading = $i;
1935                  require_once( $path );
1936                  if (!isset($this->_registered[$i])) {
1937                      $botclass = str_replace('.','_',$bot->element);
1938                      if (class_exists($botclass)) {
1939                          $newbot = new $botclass();
1940                          if (