Index

PHP Cross Reference of Joomla! 1.0.12 eCommerce Edition

title

Body

[close]

/includes/ -> joomla.php (source)

   1  <?php
   2  /**
   3  * @version $Id: joomla.php 5866 2006-11-28 01:13:26Z friesengeist $
   4  * @package Joomla
   5  * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
   6  * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
   7  * Joomla! is free software. This version may have been modified pursuant
   8  * to the GNU General Public License, and as distributed it includes or
   9  * is derivative of works licensed under the GNU General Public License or
  10  * other free or open source software licenses.
  11  * See COPYRIGHT.php for copyright notices and details.
  12  */
  13  
  14  // no direct access
  15  defined( '_VALID_MOS' ) or die( 'Restricted access' );
  16  define( '_MOS_MAMBO_INCLUDED', 1 );
  17  
  18  /**
  19   * Page generation time
  20   * @package Joomla
  21   */
  22  class mosProfiler {
  23      /** @var int Start time stamp */
  24      var $start=0;
  25      /** @var string A prefix for mark messages */
  26      var $prefix='';
  27  
  28      /**
  29       * Constructor
  30       * @param string A prefix for mark messages
  31       */
  32  	function mosProfiler( $prefix='' ) {
  33          $this->start = $this->getmicrotime();
  34          $this->prefix = $prefix;
  35      }
  36  
  37      /**
  38       * @return string A format message of the elapsed time
  39       */
  40  	function mark( $label ) {
  41          return sprintf ( "\n<div class=\"profiler\">$this->prefix %.3f $label</div>", $this->getmicrotime() - $this->start );
  42      }
  43  
  44      /**
  45       * @return float The current time in milliseconds
  46       */
  47  	function getmicrotime(){
  48          list($usec, $sec) = explode(" ",microtime());
  49          return ((float)$usec + (float)$sec);
  50      }
  51  }
  52  
  53  if (phpversion() < '4.2.0') {
  54      require_once( dirname( __FILE__ ) . '/compat.php41x.php' );
  55  }
  56  if (phpversion() < '4.3.0') {
  57      require_once( dirname( __FILE__ ) . '/compat.php42x.php' );
  58  }
  59  if (version_compare( phpversion(), '5.0' ) < 0) {
  60      require_once( dirname( __FILE__ ) . '/compat.php50x.php' );
  61  }
  62  
  63  @set_magic_quotes_runtime( 0 );
  64  
  65  if ( @$mosConfig_error_reporting === 0 || @$mosConfig_error_reporting === '0' ) {
  66      error_reporting( 0 );
  67  } else if (@$mosConfig_error_reporting > 0) {
  68      error_reporting( $mosConfig_error_reporting );
  69  }
  70  
  71  require_once ( $mosConfig_absolute_path . '/includes/version.php' );
  72  require_once ( $mosConfig_absolute_path . '/includes/database.php' );
  73  require_once ( $mosConfig_absolute_path . '/includes/gacl.class.php' );
  74  require_once ( $mosConfig_absolute_path . '/includes/gacl_api.class.php' );
  75  require_once ( $mosConfig_absolute_path . '/includes/phpmailer/class.phpmailer.php' );
  76  require_once ( $mosConfig_absolute_path . '/includes/joomla.xml.php' );
  77  require_once ( $mosConfig_absolute_path . '/includes/phpInputFilter/class.inputfilter.php' );
  78  
  79  $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
  80  if ($database->getErrorNum()) {
  81      $mosSystemError = $database->getErrorNum();
  82      $basePath = dirname( __FILE__ );
  83      include $basePath . '/../configuration.php';
  84      include $basePath . '/../offline.php';
  85      exit();
  86  }
  87  $database->debug( $mosConfig_debug );
  88  $acl = new gacl_api();
  89  
  90  // platform neurtral url handling
  91  if ( isset( $_SERVER['REQUEST_URI'] ) ) {
  92      $request_uri = $_SERVER['REQUEST_URI'];
  93  } else {
  94      $request_uri = $_SERVER['SCRIPT_NAME'];
  95      // Append the query string if it exists and isn't null
  96      if ( isset( $_SERVER['QUERY_STRING'] ) && !empty( $_SERVER['QUERY_STRING'] ) ) {
  97          $request_uri .= '?' . $_SERVER['QUERY_STRING'];
  98      }
  99  }
 100  $_SERVER['REQUEST_URI'] = $request_uri;
 101  
 102  // current server time
 103  $now = date( 'Y-m-d H:i', time() );
 104  DEFINE( '_CURRENT_SERVER_TIME', $now );
 105  DEFINE( '_CURRENT_SERVER_TIME_FORMAT', '%Y-%m-%d %H:%M:%S' );
 106  
 107  // Non http/https URL Schemes
 108  $url_schemes = 'data:, file:, ftp:, gopher:, imap:, ldap:, mailto:, news:, nntp:, telnet:, javascript:, irc:, mms:';
 109  DEFINE( '_URL_SCHEMES', $url_schemes );
 110  
 111  // disable strict mode in MySQL 5
 112  if (!defined( '_JOS_SET_SQLMODE' )) {
 113      /** ensure that functions are declared only once */
 114      define( '_JOS_SET_SQLMODE', 1 );
 115  
 116      // if running mysql 5, set sql-mode to mysql40 - thereby circumventing strict mode problems
 117      if ( strpos( $database->getVersion(), '5' ) === 0 ) {
 118          $query = "SET sql_mode = 'MYSQL40'";
 119          $database->setQuery( $query );
 120          $database->query();
 121      }
 122  }
 123  
 124  /**
 125   * @package Joomla
 126   * @abstract
 127   */
 128  class mosAbstractLog {
 129      /** @var array */
 130      var $_log    = null;
 131  
 132      /**
 133       * Constructor
 134       */
 135  	function mosAbstractLog() {
 136          $this->__constructor();
 137      }
 138  
 139      /**
 140       * Generic constructor
 141       */
 142  	function __constructor() {
 143          $this->_log = array();
 144      }
 145  
 146      /**
 147       * @param string Log message
 148       * @param boolean True to append to last message
 149       */
 150  	function log( $text, $append=false ) {
 151          $n = count( $this->_log );
 152          if ($append && $n > 0) {
 153              $this->_log[count( $this->_log )-1] .= $text;
 154          } else {
 155              $this->_log[] = $text;
 156          }
 157      }
 158  
 159      /**
 160       * @param string The glue for each log item
 161       * @return string Returns the log
 162       */
 163  	function getLog( $glue='<br/>', $truncate=9000, $htmlSafe=false ) {
 164          $logs = array();
 165          foreach ($this->_log as $log) {
 166              if ($htmlSafe) {
 167                  $log = htmlspecialchars( $log );
 168              }
 169              $logs[] = substr( $log, 0, $truncate );
 170          }
 171          return  implode( $glue, $logs );
 172      }
 173  }
 174  
 175  /**
 176   * Task routing class
 177   * @package Joomla
 178   * @abstract
 179   */
 180  class mosAbstractTasker {
 181      /** @var array An array of the class methods to call for a task */
 182      var $_taskMap     = null;
 183      /** @var string The name of the current task*/
 184      var $_task         = null;
 185      /** @var array An array of the class methods*/
 186      var $_methods     = null;
 187      /** @var string A url to redirect to */
 188      var $_redirect     = null;
 189      /** @var string A message about the operation of the task */
 190      var $_message     = null;
 191  
 192      // action based access control
 193  
 194      /** @var string The ACO Section */
 195      var $_acoSection         = null;
 196      /** @var string The ACO Section value */
 197      var $_acoSectionValue     = null;
 198  
 199      /**
 200       * Constructor
 201       * @param string Set the default task
 202       */
 203  	function mosAbstractTasker( $default='' ) {
 204          $this->_taskMap = array();
 205          $this->_methods = array();
 206          foreach (get_class_methods( get_class( $this ) ) as $method) {
 207              if (substr( $method, 0, 1 ) != '_') {
 208                  $this->_methods[] = strtolower( $method );
 209                  // auto register public methods as tasks
 210                  $this->_taskMap[strtolower( $method )] = $method;
 211              }
 212          }
 213          $this->_redirect = '';
 214          $this->_message = '';
 215          if ($default) {
 216              $this->registerDefaultTask( $default );
 217          }
 218      }
 219  
 220      /**
 221       * Sets the access control levels
 222       * @param string The ACO section (eg, the component)
 223       * @param string The ACO section value (if using a constant value)
 224       */
 225  	function setAccessControl( $section, $value=null ) {
 226          $this->_acoSection = $section;
 227          $this->_acoSectionValue = $value;
 228      }
 229      /**
 230       * Access control check
 231       */
 232  	function accessCheck( $task ) {
 233          global $acl, $my;
 234  
 235          // only check if the derived class has set these values
 236          if ($this->_acoSection) {
 237              // ensure user has access to this function
 238              if ($this->_acoSectionValue) {
 239                  // use a 'constant' task for this task handler
 240                  $task = $this->_acoSectionValue;
 241              }
 242              return $acl->acl_check( $this->_acoSection, $task, 'users', $my->usertype );
 243          } else {
 244              return true;
 245          }
 246      }
 247  
 248      /**
 249       * Set a URL to redirect the browser to
 250       * @param string A URL
 251       */
 252  	function setRedirect( $url, $msg = null ) {
 253          $this->_redirect = $url;
 254          if ($msg !== null) {
 255              $this->_message = $msg;
 256          }
 257      }
 258      /**
 259       * Redirects the browser
 260       */
 261  	function redirect() {
 262          if ($this->_redirect) {
 263              mosRedirect( $this->_redirect, $this->_message );
 264          }
 265      }
 266      /**
 267       * Register (map) a task to a method in the class
 268       * @param string The task
 269       * @param string The name of the method in the derived class to perform for this task
 270       */
 271  	function registerTask( $task, $method ) {
 272          if (in_array( strtolower( $method ), $this->_methods )) {
 273              $this->_taskMap[strtolower( $task )] = $method;
 274          } else {
 275              $this->methodNotFound( $method );
 276          }
 277      }
 278      /**
 279       * Register the default task to perfrom if a mapping is not found
 280       * @param string The name of the method in the derived class to perform if the task is not found
 281       */
 282  	function registerDefaultTask( $method ) {
 283          $this->registerTask( '__default', $method );
 284      }
 285      /**
 286       * Perform a task by triggering a method in the derived class
 287       * @param string The task to perform
 288       * @return mixed The value returned by the function
 289       */
 290  	function performTask( $task ) {
 291          $this->_task = $task;
 292  
 293          $task = strtolower( $task );
 294          if (isset( $this->_taskMap[$task] )) {
 295              $doTask = $this->_taskMap[$task];
 296          } else if (isset( $this->_taskMap['__default'] )) {
 297              $doTask = $this->_taskMap['__default'];
 298          } else {
 299              return $this->taskNotFound( $this->_task );
 300          }
 301  
 302          if ($this->accessCheck( $doTask )) {
 303              return call_user_func( array( &$this, $doTask ) );
 304          } else {
 305              return $this->notAllowed( $task );
 306          }
 307      }
 308      /**
 309       * Get the last task that was to be performed
 310       * @return string The task that was or is being performed
 311       */
 312  	function getTask() {
 313          return $this->_task;
 314      }
 315      /**
 316       * Basic method if the task is not found
 317       * @param string The task
 318       * @return null
 319       */
 320  	function taskNotFound( $task ) {
 321          echo 'Task ' . $task . ' not found';
 322          return null;
 323      }
 324      /**
 325       * Basic method if the registered method is not found
 326       * @param string The name of the method in the derived class
 327       * @return null
 328       */
 329  	function methodNotFound( $name ) {
 330          echo 'Method ' . $name . ' not found';
 331          return null;
 332      }
 333      /**
 334       * Basic method if access is not permitted to the task
 335       * @param string The name of the method in the derived class
 336       * @return null
 337       */
 338  	function notAllowed( $name ) {
 339          echo _NOT_AUTH;
 340  
 341          return null;
 342      }
 343  }
 344  /**
 345  * Class to support function caching
 346  * @package Joomla
 347  */
 348  class mosCache {
 349      /**
 350      * @return object A function cache object
 351      */
 352      function &getCache(  $group=''  ) {
 353          global $mosConfig_absolute_path, $mosConfig_caching, $mosConfig_cachepath, $mosConfig_cachetime;
 354  
 355          require_once ( $mosConfig_absolute_path . '/includes/joomla.cache.php' );
 356  
 357          $options = array(
 358              'cacheDir'         => $mosConfig_cachepath . '/',
 359              'caching'         => $mosConfig_caching,
 360              'defaultGroup'     => $group,
 361              'lifeTime'         => $mosConfig_cachetime
 362          );
 363          $cache = new JCache_Lite_Function( $options );
 364          return $cache;
 365      }
 366      /**
 367      * Cleans the cache
 368      */
 369  	function cleanCache( $group=false ) {
 370          global $mosConfig_caching;
 371          if ($mosConfig_caching) {
 372              $cache =& mosCache::getCache( $group );
 373              $cache->clean( $group );
 374          }
 375      }
 376  }
 377  /**
 378  * Joomla! Mainframe class
 379  *
 380  * Provide many supporting API functions
 381  * @package Joomla
 382  */
 383  class mosMainFrame {
 384      /** @var database Internal database class pointer */
 385      var $_db                        = null;
 386      /** @var object An object of configuration variables */
 387      var $_config                    = null;
 388      /** @var object An object of path variables */
 389      var $_path                        = null;
 390      /** @var mosSession The current session */
 391      var $_session                    = null;
 392      /** @var string The current template */
 393      var $_template                    = null;
 394      /** @var array An array to hold global user state within a session */
 395      var $_userstate                    = null;
 396      /** @var array An array of page meta information */
 397      var $_head                        = null;
 398      /** @var string Custom html string to append to the pathway */
 399      var $_custom_pathway            = null;
 400      /** @var boolean True if in the admin client */
 401      var $_isAdmin                     = false;
 402  
 403  
 404      /**
 405      * Class constructor
 406      * @param database A database connection object
 407      * @param string The url option
 408      * @param string The path of the mos directory
 409      */
 410  	function mosMainFrame( &$db, $option, $basePath, $isAdmin=false ) {
 411          $this->_db =& $db;
 412  
 413          // load the configuration values
 414          $this->_setTemplate( $isAdmin );
 415          $this->_setAdminPaths( $option, $this->getCfg( 'absolute_path' ) );
 416          if (isset( $_SESSION['session_userstate'] )) {
 417              $this->_userstate =& $_SESSION['session_userstate'];
 418          } else {
 419              $this->_userstate = null;
 420          }
 421          $this->_head = array();
 422          $this->_head['title']     = $GLOBALS['mosConfig_sitename'];
 423          $this->_head['meta']     = array();
 424          $this->_head['custom']     = array();
 425  
 426          //set the admin check
 427          $this->_isAdmin         = (boolean) $isAdmin;
 428  
 429          $now = date( 'Y-m-d H:i:s', time() );
 430          $this->set( 'now', $now );
 431      }
 432  
 433      /**
 434       * Gets the id number for a client
 435       * @param mixed A client identifier
 436       */
 437  	function getClientID( $client ) {
 438          switch ($client) {
 439              case '2':
 440              case 'installation':
 441                  return 2;
 442                  break;
 443  
 444              case '1':
 445              case 'admin':
 446              case 'administrator':
 447                  return 1;
 448                  break;
 449  
 450              case '0':
 451              case 'site':
 452              case 'front':
 453              default:
 454                  return 0;
 455                  break;
 456          }
 457      }
 458  
 459      /**
 460       * Gets the client name
 461       * @param int The client identifier
 462       * @return strint The text name of the client
 463       */
 464  	function getClientName( $client_id ) {
 465           // do not translate
 466          $clients = array( 'site', 'admin', 'installer' );
 467          return mosGetParam( $clients, $client_id, 'unknown' );
 468      }
 469  
 470      /**
 471       * Gets the base path for the client
 472       * @param mixed A client identifier
 473       * @param boolean True (default) to add traling slash
 474       */
 475  	function getBasePath( $client=0, $addTrailingSlash=true ) {
 476          global $mosConfig_absolute_path;
 477  
 478          switch ($client) {
 479              case '0':
 480              case 'site':
 481              case 'front':
 482              default:
 483                  return mosPathName( $mosConfig_absolute_path, $addTrailingSlash );
 484                  break;
 485  
 486              case '2':
 487              case 'installation':
 488                  return mosPathName( $mosConfig_absolute_path . '/installation', $addTrailingSlash );
 489                  break;
 490  
 491              case '1':
 492              case 'admin':
 493              case 'administrator':
 494                  return mosPathName( $mosConfig_absolute_path . '/administrator', $addTrailingSlash );
 495                  break;
 496  
 497          }
 498      }
 499  
 500      /**
 501      * @param string
 502      */
 503  	function setPageTitle( $title=null ) {
 504          if (@$GLOBALS['mosConfig_pagetitles']) {
 505              $title = trim( htmlspecialchars( $title ) );
 506              $title = stripslashes($title);
 507              $this->_head['title'] = $title ? $GLOBALS['mosConfig_sitename'] . ' - '. $title : $GLOBALS['mosConfig_sitename'];
 508          }
 509      }
 510      /**
 511      * @param string The value of the name attibute
 512      * @param string The value of the content attibute
 513      * @param string Text to display before the tag
 514      * @param string Text to display after the tag
 515      */
 516  	function addMetaTag( $name, $content, $prepend='', $append='' ) {
 517          $name = trim( htmlspecialchars( $name ) );
 518          $content = trim( htmlspecialchars( $content ) );
 519          $prepend = trim( $prepend );
 520          $append = trim( $append );
 521          $this->_head['meta'][] = array( $name, $content, $prepend, $append );
 522      }
 523      /**
 524      * @param string The value of the name attibute
 525      * @param string The value of the content attibute to append to the existing
 526      * Tags ordered in with Site Keywords and Description first
 527      */
 528  	function appendMetaTag( $name, $content ) {
 529          $name = trim( htmlspecialchars( $name ) );
 530          $n = count( $this->_head['meta'] );
 531          for ($i = 0; $i < $n; $i++) {
 532              if ($this->_head['meta'][$i][0] == $name) {
 533                  $content = trim( htmlspecialchars( $content ) );
 534                  if ( $content ) {
 535                      if ( !$this->_head['meta'][$i][1] ) {
 536                          $this->_head['meta'][$i][1] = $content ;
 537                      } else {
 538                          $this->_head['meta'][$i][1] = $content .', '. $this->_head['meta'][$i][1];
 539                      }
 540                  }
 541                  return;
 542              }
 543          }
 544          $this->addMetaTag( $name , $content );
 545      }
 546  
 547      /**
 548      * @param string The value of the name attibute
 549      * @param string The value of the content attibute to append to the existing
 550      */
 551  	function prependMetaTag( $name, $content ) {
 552          $name = trim( htmlspecialchars( $name ) );
 553          $n = count( $this->_head['meta'] );
 554          for ($i = 0; $i < $n; $i++) {
 555              if ($this->_head['meta'][$i][0] == $name) {
 556                  $content = trim( htmlspecialchars( $content ) );
 557                  $this->_head['meta'][$i][1] = $content . $this->_head['meta'][$i][1];
 558                  return;
 559              }
 560          }
 561          $this->addMetaTag( $name, $content );
 562      }
 563      /**
 564       * Adds a custom html string to the head block
 565       * @param string The html to add to the head
 566       */
 567  	function addCustomHeadTag( $html ) {
 568          $this->_head['custom'][] = trim( $html );
 569      }
 570      /**
 571      * @return string
 572      */
 573  	function getHead() {
 574          $head = array();
 575          $head[] = '<title>' . $this->_head['title'] . '</title>';
 576          foreach ($this->_head['meta'] as $meta) {
 577              if ($meta[2]) {
 578                  $head[] = $meta[2];
 579              }
 580              $head[] = '<meta name="' . $meta[0] . '" content="' . $meta[1] . '" />';
 581              if ($meta[3]) {
 582                  $head[] = $meta[3];
 583              }
 584          }
 585          foreach ($this->_head['custom'] as $html) {
 586              $head[] = $html;
 587          }
 588          return implode( "\n", $head ) . "\n";
 589      }
 590  
 591  
 592      /**
 593      * @return string
 594      */
 595  	function getPageTitle() {
 596          return $this->_head['title'];
 597      }
 598  
 599      /**
 600      * @return string
 601      */
 602  	function getCustomPathWay() {
 603          return $this->_custom_pathway;
 604      }
 605  
 606  	function appendPathWay( $html ) {
 607          $this->_custom_pathway[] = $html;
 608      }
 609  
 610    /**
 611      * Gets the value of a user state variable
 612      * @param string The name of the variable
 613      */
 614  	function getUserState( $var_name ) {
 615          if (is_array( $this->_userstate )) {
 616              return mosGetParam( $this->_userstate, $var_name, null );
 617          } else {
 618              return null;
 619          }
 620      }
 621      /**
 622      * Gets the value of a user state variable
 623      * @param string The name of the user state variable
 624      * @param string The name of the variable passed in a request
 625      * @param string The default value for the variable if not found
 626      */
 627  	function getUserStateFromRequest( $var_name, $req_name, $var_default=null ) {
 628          if (is_array( $this->_userstate )) {
 629              if (isset( $_REQUEST[$req_name] )) {
 630                  $this->setUserState( $var_name, $_REQUEST[$req_name] );
 631              } else if (!isset( $this->_userstate[$var_name] )) {
 632                  $this->setUserState( $var_name, $var_default );
 633              }
 634  
 635              // filter input
 636              $iFilter = new InputFilter();
 637              $this->_userstate[$var_name] = $iFilter->process( $this->_userstate[$var_name] );
 638  
 639              return $this->_userstate[$var_name];
 640          } else {
 641              return null;
 642          }
 643      }
 644      /**
 645      * Sets the value of a user state variable
 646      * @param string The name of the variable
 647      * @param string The value of the variable
 648      */
 649  	function setUserState( $var_name, $var_value ) {
 650          if (is_array( $this->_userstate )) {
 651              $this->_userstate[$var_name] = $var_value;
 652          }
 653      }
 654      /**
 655      * Initialises the user session
 656      *
 657      * Old sessions are flushed based on the configuration value for the cookie
 658      * lifetime. If an existing session, then the last access time is updated.
 659      * If a new session, a session id is generated and a record is created in
 660      * the jos_sessions table.
 661      */
 662  	function initSession() {
 663          // initailize session variables
 664          $session     =& $this->_session;
 665          $session     = new mosSession( $this->_db );
 666  
 667          // purge expired sessions
 668          $session->purge('core');
 669  
 670          // Session Cookie `name`
 671          $sessionCookieName     = mosMainFrame::sessionCookieName();
 672          // Get Session Cookie `value`
 673          $sessioncookie         = strval( mosGetParam( $_COOKIE, $sessionCookieName, null ) );
 674  
 675          // Session ID / `value`
 676          $sessionValueCheck     = mosMainFrame::sessionCookieValue( $sessioncookie );
 677  
 678          // Check if existing session exists in db corresponding to Session cookie `value`
 679          // extra check added in 1.0.8 to test sessioncookie value is of correct length
 680          if ( $sessioncookie && strlen($sessioncookie) == 32 && $sessioncookie != '-' && $session->load($sessionValueCheck) ) {
 681              // update time in session table
 682              $session->time = time();
 683              $session->update();
 684          } else {
 685              // Remember Me Cookie `name`
 686              $remCookieName = mosMainFrame::remCookieName_User();
 687  
 688              // test if cookie found
 689              $cookie_found = false;
 690              if ( isset($_COOKIE[$sessionCookieName]) || isset($_COOKIE[$remCookieName]) || isset($_POST['force_session']) ) {
 691                  $cookie_found = true;
 692              }
 693  
 694              // check if neither remembermecookie or sessioncookie found
 695              if (!$cookie_found) {
 696                  // create sessioncookie and set it to a test value set to expire on session end
 697                  setcookie( $sessionCookieName, '-', false, '/' );
 698              } else {
 699              // otherwise, sessioncookie was found, but set to test val or the session expired, prepare for session registration and register the session
 700                  $url = strval( mosGetParam( $_SERVER, 'REQUEST_URI', null ) );
 701                  // stop sessions being created for requests to syndicated feeds
 702                  if ( strpos( $url, 'option=com_rss' ) === false && strpos( $url, 'feed=' ) === false ) {
 703                      $session->guest     = 1;
 704                      $session->username     = '';
 705                      $session->time         = time();
 706                      $session->gid         = 0;
 707                      // Generate Session Cookie `value`
 708                      $session->generateId();
 709  
 710                      if (!$session->insert()) {
 711                          die( $session->getError() );
 712                      }
 713  
 714                      // create Session Tracking Cookie set to expire on session end
 715                      setcookie( $sessionCookieName, $session->getCookie(), false, '/' );
 716                  }
 717              }
 718  
 719              // Cookie used by Remember me functionality
 720              $remCookieValue    = strval( mosGetParam( $_COOKIE, $remCookieName, null ) );
 721  
 722              // test if cookie is correct length
 723              if ( strlen($remCookieValue) > 64 ) {
 724                  // Separate Values from Remember Me Cookie
 725                  $remUser    = substr( $remCookieValue, 0, 32 );
 726                  $remPass    = substr( $remCookieValue, 32, 32 );
 727                  $remID        = intval( substr( $remCookieValue, 64  ) );
 728  
 729                  // check if Remember me cookie exists. Login with usercookie info.
 730                  if ( strlen($remUser) == 32 && strlen($remPass) == 32 ) {
 731                      $this->login( $remUser, $remPass, 1, $remID );
 732                  }
 733              }
 734          }
 735      }
 736  
 737      /*
 738      * Function used to conduct admin session duties
 739      * Added as of 1.0.8
 740      * Deperciated 1.1
 741      */
 742  	function initSessionAdmin($option, $task) {
 743          global $_VERSION, $mosConfig_admin_expired;
 744  
 745          // logout check
 746          if ($option == 'logout') {
 747              require $GLOBALS['mosConfig_absolute_path'] .'/administrator/logout.php';
 748              exit();
 749          }
 750  
 751          $site = $GLOBALS['mosConfig_live_site'];
 752  
 753          // check if session name corresponds to correct format
 754          if ( session_name() != md5( $site ) ) {
 755              echo "<script>document.location.href='index.php'</script>\n";
 756              exit();
 757          }
 758  
 759          // restore some session variables
 760          $my             = new mosUser( $this->_db );
 761          $my->id         = intval( mosGetParam( $_SESSION, 'session_user_id', '' ) );
 762          $my->username     = strval( mosGetParam( $_SESSION, 'session_username', '' ) );
 763          $my->usertype     = strval( mosGetParam( $_SESSION, 'session_usertype', '' ) );
 764          $my->gid         = intval( mosGetParam( $_SESSION, 'session_gid', '' ) );
 765          $my->params        = mosGetParam( $_SESSION, 'session_user_params', '' );
 766  
 767          $session_id     = mosGetParam( $_SESSION, 'session_id', '' );
 768          $logintime         = mosGetParam( $_SESSION, 'session_logintime', '' );
 769  
 770          // check to see if session id corresponds with correct format
 771          if ( $session_id == md5( $my->id . $my->username . $my->usertype . $logintime ) ) {
 772              // if task action is to `save` or `apply` complete action before doing session checks.
 773              if ($task != 'save' && $task != 'apply') {
 774                  // test for session_life_admin
 775                  if ( @$GLOBALS['mosConfig_session_life_admin'] ) {
 776                      $session_life_admin = $GLOBALS['mosConfig_session_life_admin'];
 777                  } else {
 778                      $session_life_admin = 1800;
 779                  }
 780  
 781                  // purge expired admin sessions only
 782                  $past = time() - $session_life_admin;
 783                  $query = "DELETE FROM #__session"
 784                  . "\n WHERE time < '" . (int) $past . "'"
 785                  . "\n AND guest = 1"
 786                  . "\n AND gid = 0"
 787                  . "\n AND userid <> 0"
 788                  ;
 789                  $this->_db->setQuery( $query );
 790                  $this->_db->query();
 791  
 792                  // update session timestamp
 793                  $current_time = time();
 794                  $query = "UPDATE #__session"
 795                  . "\n SET time = " . $this->_db->Quote( $current_time )
 796                  . "\n WHERE session_id = " . $this->_db->Quote( $session_id )
 797                  ;
 798                  $this->_db->setQuery( $query );
 799                  $this->_db->query();
 800  
 801                  // set garbage cleaning timeout
 802                  $this->setSessionGarbageClean();
 803  
 804                  // check against db record of session
 805                  $query = "SELECT COUNT( session_id )"
 806                  . "\n FROM #__session"
 807                  . "\n WHERE session_id = " . $this->_db->Quote( $session_id )
 808                  . "\n AND username = ". $this->_db->Quote( $my->username )
 809                  . "\n AND userid = ". intval( $my->id )
 810                  ;
 811                  $this->_db->setQuery( $query );
 812                  $count = $this->_db->loadResult();
 813  
 814                  // if no entry in session table that corresponds boot from admin area
 815                  if ( $count == 0 ) {
 816                      $link     = NULL;
 817  
 818                      if ($_SERVER['QUERY_STRING']) {
 819                          $link = 'index2.php?'. $_SERVER['QUERY_STRING'];
 820                      }
 821  
 822                      // check if site designated as a production site
 823                      // for a demo site disallow expired page functionality
 824                      // link must also be a Joomla link to stop malicious redirection
 825                      if ( $link && strpos( $link, 'index2.php?option=com_' ) === 0 && $_VERSION->SITE == 1 && @$mosConfig_admin_expired === '1' ) {
 826                          $now     = time();
 827  
 828                          $file     = $this->getPath( 'com_xml', 'com_users' );
 829                          $params =& new mosParameters( $my->params, $file, 'component' );
 830  
 831                          // return to expired page functionality
 832                          $params->set( 'expired',         $link );
 833                          $params->set( 'expired_time',     $now );
 834  
 835                          // param handling
 836                          if (is_array( $params->toArray() )) {
 837                              $txt = array();
 838                              foreach ( $params->toArray() as $k=>$v) {
 839                                  $txt[] = "$k=$v";
 840                              }
 841                              $saveparams = implode( "\n", $txt );
 842                          }
 843  
 844                          // save expired page info to user data
 845                          $query = "UPDATE #__users"
 846                          . "\n SET params = ". $this->_db->Quote( $saveparams )
 847                          . "\n WHERE id = " . (int) $my->id
 848                          . "\n AND username = ". $this->_db->Quote( $my->username )
 849                          . "\n AND usertype = ". $this->_db->Quote( $my->usertype )
 850                          ;
 851                          $this->_db->setQuery( $query );
 852                          $this->_db->query();
 853                      }
 854  
 855                      echo "<script>document.location.href='index.php?mosmsg=Admin Session Expired'</script>\n";
 856                      exit();
 857                  } else {
 858                      // load variables into session, used to help secure /popups/ functionality
 859                      $_SESSION['option'] = $option;
 860                      $_SESSION['task']     = $task;
 861                  }
 862              }
 863          } else if ($session_id == '') {
 864              // no session_id as user has not attempted to login, or session.auto_start is switched on
 865              if (ini_get( 'session.auto_start' ) || !ini_get( 'session.use_cookies' )) {
 866                  echo "<script>document.location.href='index.php?mosmsg=You need to login. If PHP\'s session.auto_start setting is on or session.use_cookies setting is off, you may need to correct this before you will be able to login.'</script>\n";
 867              } else {
 868                  echo "<script>document.location.href='index.php?mosmsg=You need to login'</script>\n";
 869              }
 870              exit();
 871          } else {
 872              // session id does not correspond to required session format
 873              echo "<script>document.location.href='index.php?mosmsg=Invalid Session'</script>\n";
 874              exit();
 875          }
 876  
 877          return $my;
 878      }
 879  
 880      /*
 881      * Function used to set Session Garbage Cleaning
 882      * garbage cleaning set at configured session time + 600 seconds
 883      * Added as of 1.0.8
 884      * Deperciated 1.1
 885      */
 886  	function setSessionGarbageClean() {
 887          /** ensure that funciton is only called once */
 888          if (!defined( '_JOS_GARBAGECLEAN' )) {
 889              define( '_JOS_GARBAGECLEAN', 1 );
 890  
 891              $garbage_timeout = $this->getCfg('session_life_admin') + 600;
 892              @ini_set('session.gc_maxlifetime', $garbage_timeout);
 893          }
 894      }
 895  
 896      /*
 897      * Static Function used to generate the Session Cookie Name
 898      * Added as of 1.0.8
 899      * Deperciated 1.1
 900      */
 901  	function sessionCookieName() {
 902          global $mainframe;
 903  
 904          return md5( 'site' . $mainframe->getCfg( 'live_site' ) );
 905      }
 906  
 907      /*
 908      * Static Function used to generate the Session Cookie Value
 909      * Added as of 1.0.8
 910      * Deperciated 1.1
 911      */
 912  	function sessionCookieValue( $id=null ) {
 913          global $mainframe;
 914  
 915          $type         = $mainframe->getCfg( 'session_type' );
 916  
 917          $browser     = @$_SERVER['HTTP_USER_AGENT'];
 918  
 919          switch ($type) {
 920              case 2:
 921              // 1.0.0 to 1.0.7 Compatibility
 922              // lowest level security
 923                  $value             = md5( $id . $_SERVER['REMOTE_ADDR'] );
 924                  break;
 925  
 926              case 1:
 927              // slightly reduced security - 3rd level IP authentication for those behind IP Proxy
 928                  $remote_addr     = explode('.',$_SERVER['REMOTE_ADDR']);
 929                  $ip                = $remote_addr[0] .'.'. $remote_addr[1] .'.'. $remote_addr[2];
 930                  $value             = mosHash( $id . $ip . $browser );
 931                  break;
 932  
 933              default:
 934              // Highest security level - new default for 1.0.8 and beyond
 935                  $ip                = $_SERVER['REMOTE_ADDR'];
 936                  $value             = mosHash( $id . $ip . $browser );
 937                  break;
 938          }
 939  
 940          return $value;
 941      }
 942  
 943      /*
 944      * Static Function used to generate the Rememeber Me Cookie Name for Username information
 945      * Added as of 1.0.8
 946      * Depreciated 1.1
 947      */
 948  	function remCookieName_User() {
 949          $value = mosHash( 'remembermecookieusername'. mosMainFrame::sessionCookieName() );
 950  
 951          return $value;
 952      }
 953  
 954      /*
 955      * Static Function used to generate the Rememeber Me Cookie Name for Password information
 956      * Added as of 1.0.8
 957      * Depreciated 1.1
 958      */
 959  	function remCookieName_Pass() {
 960          $value = mosHash( 'remembermecookiepassword'. mosMainFrame::sessionCookieName() );
 961  
 962          return $value;
 963      }
 964  
 965      /*
 966      * Static Function used to generate the Remember Me Cookie Value for Username information
 967      * Added as of 1.0.8
 968      * Depreciated 1.1
 969      */
 970  	function remCookieValue_User( $username ) {
 971          $value = md5( $username . mosHash( @$_SERVER['HTTP_USER_AGENT'] ) );
 972  
 973          return $value;
 974      }
 975  
 976      /*
 977      * Static Function used to generate the Remember Me Cookie Value for Password information
 978      * Added as of 1.0.8
 979      * Depreciated 1.1
 980      */
 981  	function remCookieValue_Pass( $passwd ) {
 982          $value     = md5( $passwd . mosHash( @$_SERVER['HTTP_USER_AGENT'] ) );
 983  
 984          return $value;
 985      }
 986  
 987      /**
 988      * Login validation function
 989      *
 990      * Username and encoded password is compare to db entries in the jos_users
 991      * table. A successful validation updates the current session record with
 992      * the users details.
 993      */
 994  	function login( $username=null,$passwd=null, $remember=0, $userid=NULL ) {
 995          global $acl, $_VERSION;
 996  
 997          $bypost = 0;
 998  
 999          // if no username and password passed from function, then function is being called from login module/component
1000          if (!$username || !$passwd) {
1001              $username     = stripslashes( strval( mosGetParam( $_POST, 'username', '' ) ) );
1002              $passwd     = stripslashes( strval( mosGetParam( $_POST, 'passwd', '' ) ) );
1003              $passwd     = md5( $passwd );
1004  
1005              $bypost     = 1;
1006  
1007              // extra check to ensure that Joomla! sessioncookie exists
1008              if (!$this->_session->session_id) {
1009                  mosErrorAlert( _ALERT_ENABLED );
1010                  return;
1011              }
1012  
1013              josSpoofCheck(NULL,1);
1014          }
1015  
1016          $row = null;
1017          if (!$username || !$passwd) {
1018              mosErrorAlert( _LOGIN_INCOMPLETE );
1019              exit();
1020          } else {
1021              if ( $remember && strlen($username) == 32 && strlen($passwd) == 32 && $userid ) {
1022              // query used for remember me cookie
1023                  $harden = mosHash( @$_SERVER['HTTP_USER_AGENT'] );
1024  
1025                  $query = "SELECT id, name, username, password, usertype, block, gid"
1026                  . "\n FROM #__users"
1027                  . "\n WHERE id = " . (int) $userid
1028                  ;
1029                  $this->_db->setQuery( $query );
1030                  $this->_db->loadObject($user);
1031  
1032                  $check_username = md5( $user->username . $harden );
1033                  $check_password = md5( $user->password . $harden );
1034  
1035                  if ( $check_username == $username && $check_password == $passwd ) {
1036                      $row = $user;
1037                  }
1038              } else {
1039              // query used for login via login module
1040                  $query = "SELECT id, name, username, password, usertype, block, gid"
1041                  . "\n FROM #__users"
1042                  . "\n WHERE username = ". $this->_db->Quote( $username )
1043                  . "\n AND password = ". $this->_db->Quote( $passwd )
1044                  ;
1045                  $this->_db->setQuery( $query );
1046                  $this->_db->loadObject( $row );
1047              }
1048  
1049              if (is_object($row)) {
1050                  // user blocked from login
1051                  if ($row->block == 1) {
1052                      mosErrorAlert(_LOGIN_BLOCKED);
1053                  }
1054  
1055                  // fudge the group stuff
1056                  $grp = $acl->getAroGroup( $row->id );
1057                  $row->gid = 1;
1058                  if ($acl->is_group_child_of( $grp->name, 'Registered', 'ARO' ) || $acl->is_group_child_of( $grp->name, 'Public Backend', 'ARO' )) {
1059                      // fudge Authors, Editors, Publishers and Super Administrators into the Special Group
1060                      $row->gid = 2;
1061                  }
1062                  $row->usertype = $grp->name;
1063  
1064                  // initialize session data
1065                  $session             =& $this->_session;
1066                  $session->guest     = 0;
1067                  $session->username     = $row->username;
1068                  $session->userid     = intval( $row->id );
1069                  $session->usertype     = $row->usertype;
1070                  $session->gid         = intval( $row->gid );
1071                  $session->update();
1072  
1073                  // check to see if site is a production site
1074                  // allows multiple logins with same user for a demo site
1075                  if ( $_VERSION->SITE ) {
1076                      // delete any old front sessions to stop duplicate sessions
1077                      $query = "DELETE FROM #__session"
1078                      . "\n WHERE session_id != ". $this->_db->Quote( $session->session_id )
1079                      . "\n AND username = ". $this->_db->Quote( $row->username )
1080                      . "\n AND userid = " . (int) $row->id
1081                      . "\n AND gid = " . (int) $row->gid
1082                      . "\n AND guest = 0"
1083                      ;
1084                      $this->_db->setQuery( $query );
1085                      $this->_db->query();
1086                  }
1087  
1088                  // update user visit data
1089                  $currentDate = date("Y-m-d\TH:i:s");
1090  
1091                  $query = "UPDATE #__users"
1092                  . "\n SET lastvisitDate = ". $this->_db->Quote( $currentDate )
1093                  . "\n WHERE id = " . (int) $session->userid
1094                  ;
1095                  $this->_db->setQuery($query);
1096                  if (!$this->_db->query()) {
1097                      die($this->_db->stderr(true));
1098                  }
1099  
1100                  // set remember me cookie if selected
1101                  $remember = strval( mosGetParam( $_POST, 'remember', '' ) );
1102                  if ( $remember == 'yes' ) {
1103                      // cookie lifetime of 365 days
1104                      $lifetime         = time() + 365*24*60*60;
1105                      $remCookieName     = mosMainFrame::remCookieName_User();
1106                      $remCookieValue = mosMainFrame::remCookieValue_User( $row->username ) . mosMainFrame::remCookieValue_Pass( $row->password ) . $row->id;
1107                      setcookie( $remCookieName, $remCookieValue, $lifetime, '/' );
1108                  }
1109                  mosCache::cleanCache();
1110              } else {
1111                  if ( $bypost ) {
1112                      mosErrorAlert(_LOGIN_INCORRECT);
1113                  } else {
1114                      $this->logout();
1115                      mosRedirect('index.php');
1116                  }
1117                  exit();
1118              }
1119          }
1120      }
1121  
1122      /**
1123      * User logout
1124      *
1125      * Reverts the current session record back to 'anonymous' parameters
1126      */
1127  	function logout() {
1128          mosCache::cleanCache();
1129  
1130          $session             =& $this->_session;
1131          $session->guest     = 1;
1132          $session->username     = '';
1133          $session->userid     = '';
1134          $session->usertype     = '';
1135          $session->gid         = 0;
1136  
1137          $session->update();
1138  
1139          // kill remember me cookie
1140          $lifetime         = time() - 86400;
1141          $remCookieName     = mosMainFrame::remCookieName_User();
1142          setcookie( $remCookieName, ' ', $lifetime, '/' );
1143  
1144          @session_destroy();
1145      }
1146  
1147      /**
1148      * @return mosUser A user object with the information from the current session
1149      */
1150  	function getUser() {
1151          global $database;
1152  
1153          $user = new mosUser( $this->_db );
1154  
1155          $user->id             = intval( $this->_session->userid );
1156          $user->username     = $this->_session->username;
1157          $user->usertype     = $this->_session->usertype;
1158          $user->gid             = intval( $this->_session->gid );
1159  
1160          if ($user->id) {
1161              $query = "SELECT id, name, email, block, sendEmail, registerDate, lastvisitDate, activation, params"
1162              . "\n FROM #__users"
1163              . "\n WHERE id = " . (int) $user->id
1164              ;
1165              $database->setQuery( $query );
1166              $database->loadObject( $my );
1167  
1168              $user->params             = $my->params;
1169              $user->name                = $my->name;
1170              $user->email            = $my->email;
1171              $user->block            = $my->block;
1172              $user->sendEmail        = $my->sendEmail;
1173              $user->registerDate        = $my->registerDate;
1174              $user->lastvisitDate    = $my->lastvisitDate;
1175              $user->activation        = $my->activation;
1176          }
1177  
1178          return $user;
1179      }
1180      /**
1181       * @param string The name of the variable (from configuration.php)
1182       * @return mixed The value of the configuration variable or null if not found
1183       */
1184  	function getCfg( $varname ) {
1185          $varname = 'mosConfig_' . $varname;
1186          if (isset( $GLOBALS[$varname] )) {
1187              return $GLOBALS[$varname];
1188          } else {
1189              return null;
1190          }
1191      }
1192  
1193  	function _setTemplate( $isAdmin=false ) {
1194          global $Itemid;
1195          $mosConfig_absolute_path = $this->getCfg( 'absolute_path' );
1196  
1197          if ($isAdmin) {
1198              $query = "SELECT template"
1199              . "\n FROM #__templates_menu"
1200              . "\n WHERE client_id = 1"
1201              . "\n AND menuid = 0"
1202              ;
1203              $this->_db->setQuery( $query );
1204              $cur_template = $this->_db->loadResult();
1205              $path = "$mosConfig_absolute_path/administrator/templates/$cur_template/index.php";
1206              if (!file_exists( $path )) {
1207                  $cur_template = 'joomla_admin';
1208              }
1209          } else {
1210              $assigned = ( !empty( $Itemid ) ? " OR menuid = " . (int) $Itemid : '' );
1211  
1212              $query = "SELECT template"
1213              . "\n FROM #__templates_menu"
1214              . "\n WHERE client_id = 0"
1215              . "\n AND ( menuid = 0 $assigned )"
1216              . "\n ORDER BY menuid DESC"
1217              ;
1218              $this->_db->setQuery( $query, 0, 1 );
1219              $cur_template = $this->_db->loadResult();
1220  
1221              // TemplateChooser Start
1222              $jos_user_template         = strval( mosGetParam( $_COOKIE, 'jos_user_template', '' ) );
1223              $jos_change_template     = strval( mosGetParam( $_REQUEST, 'jos_change_template', $jos_user_template ) );
1224              if ($jos_change_template) {
1225                  // clean template name
1226                  $jos_change_template = preg_replace( '#\W#', '', $jos_change_template );
1227                  if ( strlen( $jos_change_template ) >= 40 ) {
1228                      $jos_change_template = substr($jos_change_template, 0 , 39);
1229                  }
1230  
1231                  // check that template exists in case it was deleted
1232                  if (file_exists( $mosConfig_absolute_path .'/templates/'. $jos_change_template .'/index.php' )) {
1233                      $lifetime         = 60*10;
1234                      $cur_template     = $jos_change_template;
1235                      setcookie( 'jos_user_template', "$jos_change_template", time()+$lifetime);
1236                  } else {
1237                      setcookie( 'jos_user_template', '', time()-3600 );
1238                  }
1239              }
1240              // TemplateChooser End
1241          }
1242  
1243          $this->_template = $cur_template;
1244      }
1245  
1246  	function getTemplate() {
1247          return $this->_template;
1248      }
1249  
1250      /**
1251      * Determines the paths for including engine and menu files
1252      * @param string The current option used in the url
1253      * @param string The base path from which to load the configuration file
1254      */
1255  	function _setAdminPaths( $option, $basePath='.' ) {
1256          $option         = strtolower( $option );
1257  
1258          $this->_path     = new stdClass();
1259  
1260          // security check to disable use of `/`, `\\` and `:` in $options variable
1261          if (strpos($option, '/') !== false || strpos($option, '\\') !== false || strpos($option, ':') !== false) {
1262              mosErrorAlert( 'Restricted access' );
1263              return;
1264          }
1265  
1266          $prefix = substr( $option, 0, 4 );
1267          if ($prefix != 'com_' && $prefix != 'mod_') {
1268              // ensure backward compatibility with existing links
1269              $name     = $option;
1270              $option = "com_$option";
1271          } else {
1272              $name     = substr( $option, 4 );
1273          }
1274  
1275          // components
1276          if (file_exists( "$basePath/templates/$this->_template/components/$name.html.php" )) {
1277              $this->_path->front         = "$basePath/components/$option/$name.php";
1278              $this->_path->front_html     = "$basePath/templates/$this->_template/components/$name.html.php";
1279          } else if (file_exists( "$basePath/components/$option/$name.php" )) {
1280              $this->_path->front         = "$basePath/components/$option/$name.php";
1281              $this->_path->front_html     = "$basePath/components/$option/$name.html.php";
1282          }
1283  
1284          if (file_exists( "$basePath/administrator/components/$option/admin.$name.php" )) {
1285              $this->_path->admin         = "$basePath/administrator/components/$option/admin.$name.php";
1286              $this->_path->admin_html     = "$basePath/administrator/components/$option/admin.$name.html.php";
1287          }
1288  
1289          if (file_exists( "$basePath/administrator/components/$option/toolbar.$name.php" )) {
1290              $this->_path->toolbar             = "$basePath/administrator/components/$option/toolbar.$name.php";
1291              $this->_path->toolbar_html         = "$basePath/administrator/components/$option/toolbar.$name.html.php";
1292              $this->_path->toolbar_default     = "$basePath/administrator/includes/toolbar.html.php";
1293          }
1294  
1295          if (file_exists( "$basePath/components/$option/$name.class.php" )) {
1296              $this->_path->class = "$basePath/components/$option/$name.class.php";
1297          } else if (file_exists( "$basePath/administrator/components/$option/$name.class.php" )) {
1298              $this->_path->class = "$basePath/administrator/components/$option/$name.class.php";
1299          } else if (file_exists( "$basePath/includes/$name.php" )) {
1300              $this->_path->class = "$basePath/includes/$name.php";
1301          }
1302  
1303          if ($prefix == 'mod_' && file_exists("$basePath/administrator/modules/$option.php")) {
1304              $this->_path->admin         = "$basePath/administrator/modules/$option.php";
1305              $this->_path->admin_html     = "$basePath/administrator/modules/mod_$name.html.php";
1306          } else if (file_exists("$basePath/administrator/components/$option/admin.$name.php" )) {
1307              $this->_path->admin         = "$basePath/administrator/components/$option/admin.$name.php";
1308              $this->_path->admin_html     = "$basePath/administrator/components/$option/admin.$name.html.php";
1309          } else {
1310              $this->_path->admin         = "$basePath/administrator/components/com_admin/admin.admin.php";
1311              $this->_path->admin_html     = "$basePath/administrator/components/com_admin/admin.admin.html.php";
1312          }
1313      }
1314      /**
1315      * Returns a stored path variable
1316      *
1317      */
1318  	function getPath( $varname, $option='' ) {
1319          global $mosConfig_absolute_path;
1320          if ($option) {
1321              $temp = $this->_path;
1322              $this->_setAdminPaths( $option, $this->getCfg( 'absolute_path' ) );
1323          }
1324          $result = null;
1325          if (isset( $this->_path->$varname )) {
1326              $result = $this->_path->$varname;
1327          } else {
1328              switch ($varname) {
1329                  case 'com_xml':
1330                      $name = substr( $option, 4 );
1331                      $path = "$mosConfig_absolute_path/administrator/components/$option/$name.xml";
1332                      if (file_exists( $path )) {
1333                          $result = $path;
1334                      } else {
1335                          $path = "$mosConfig_absolute_path/components/$option/$name.xml";
1336                          if (file_exists( $path )) {
1337                              $result = $path;
1338                          }
1339                      }
1340                      break;
1341  
1342                  case 'mod0_xml':
1343                      // Site modules
1344                      if ($option == '') {
1345                          $path = $mosConfig_absolute_path . "/modules/custom.xml";
1346                      } else {
1347                          $path = $mosConfig_absolute_path . "/modules/$option.xml";
1348                      }
1349                      if (file_exists( $path )) {
1350                          $result = $path;
1351                      }
1352                      break;
1353  
1354                  case 'mod1_xml':
1355                      // admin modules
1356                      if ($option == '') {
1357                          $path = $mosConfig_absolute_path . '/administrator/modules/custom.xml';
1358                      } else {
1359                          $path = $mosConfig_absolute_path . "/administrator/modules/$option.xml";
1360                      }
1361                      if (file_exists( $path )) {
1362                          $result = $path;
1363                      }
1364                      break;
1365  
1366                  case 'bot_xml':
1367                      // Site mambots
1368                      $path = $mosConfig_absolute_path . "/mambots/$option.xml";
1369                      if (file_exists( $path )) {
1370                          $result = $path;
1371                      }
1372                      break;
1373  
1374                  case 'menu_xml':
1375                      $path = $mosConfig_absolute_path . "/administrator/components/com_menus/$option/$option.xml";
1376                      if (file_exists( $path )) {
1377                          $result = $path;
1378                      }
1379                      break;
1380  
1381                  case 'installer_html':
1382                      $path = $mosConfig_absolute_path . "/administrator/components/com_installer/$option/$option.html.php";
1383                      if (file_exists( $path )) {
1384                          $result = $path;
1385                      }
1386                      break;
1387  
1388                  case 'installer_class':
1389                      $path = $mosConfig_absolute_path . "/administrator/components/com_installer/$option/$option.class.php";
1390                      if (file_exists( $path )) {
1391                          $result = $path;
1392                      }
1393                      break;
1394              }
1395          }
1396          if ($option) {
1397              $this->_path = $temp;
1398          }
1399          return $result;
1400      }
1401      /**
1402      * Detects a 'visit'
1403      *
1404      * This function updates the agent and domain table hits for a particular
1405      * visitor.  The user agent is recorded/incremented if this is the first visit.
1406      * A cookie is set to mark the first visit.
1407      */
1408  	function detect() {
1409          global $mosConfig_enable_stats;
1410          if ($mosConfig_enable_stats == 1) {
1411              if (mosGetParam( $_COOKIE, 'mosvisitor', 0 )) {
1412                  return;
1413              }
1414              setcookie( 'mosvisitor', 1 );
1415  
1416              if (phpversion() <= '4.2.1') {
1417                  $agent = getenv( 'HTTP_USER_AGENT' );
1418                  $domain = @gethostbyaddr( getenv( "REMOTE_ADDR" ) );
1419              } else {
1420                  if ( isset($_SERVER['HTTP_USER_AGENT']) ) {
1421                      $agent = $_SERVER['HTTP_USER_AGENT'];
1422                  } else {
1423                      $agent = 'Unknown';
1424                  }
1425  
1426                  $domain = @gethostbyaddr( $_SERVER['REMOTE_ADDR'] );
1427              }
1428  
1429              $browser = mosGetBrowser( $agent );
1430  
1431              $query = "SELECT COUNT(*)"
1432              . "\n FROM #__stats_agents"
1433              . "\n WHERE agent = " . $this->_db->Quote( $browser )
1434              . "\n AND type = 0"
1435              ;
1436              $this->_db->setQuery( $query );
1437              if ($this->_db->loadResult()) {
1438                  $query = "UPDATE #__stats_agents"
1439                  . "\n SET hits = ( hits + 1 )"
1440                  . "\n WHERE agent = " . $this->_db->Quote( $browser )
1441                  . "\n AND type = 0"
1442                  ;
1443                  $this->_db->setQuery( $query );
1444              } else {
1445                  $query = "INSERT INTO #__stats_agents"
1446                  . "\n ( agent, type )"
1447                  . "\n VALUES ( " . $this->_db->Quote( $browser ) . ", 0 )"
1448                  ;
1449                  $this->_db->setQuery( $query );
1450              }
1451              $this->_db->query();
1452  
1453              $os = mosGetOS( $agent );
1454  
1455              $query = "SELECT COUNT(*)"
1456              . "\n FROM #__stats_agents"
1457              . "\n WHERE agent = " . $this->_db->Quote( $os )
1458              . "\n AND type = 1"
1459              ;
1460              $this->_db->setQuery( $query );
1461              if ($this->_db->loadResult()) {
1462                  $query = "UPDATE #__stats_agents"
1463                  . "\n SET hits = ( hits + 1 )"
1464                  . "\n WHERE agent = " . $this->_db->Quote( $os )
1465                  . "\n AND type = 1"
1466                  ;
1467                  $this->_db->setQuery( $query );
1468              } else {
1469                  $query = "INSERT INTO #__stats_agents"
1470                  . "\n ( agent, type )"
1471                  . "\n VALUES ( " . $this->_db->Quote( $os ) . ", 1 )"
1472                  ;
1473                  $this->_db->setQuery( $query );
1474              }
1475              $this->_db->query();
1476  
1477              // tease out the last element of the domain
1478              $tldomain = split( "\.", $domain );
1479              $tldomain = $tldomain[count( $tldomain )-1];
1480  
1481              if (is_numeric( $tldomain )) {
1482                  $tldomain = "Unknown";
1483              }
1484  
1485              $query = "SELECT COUNT(*)"
1486              . "\n FROM #__stats_agents"
1487              . "\n WHERE agent = " . $this->_db->Quote( $tldomain )
1488              . "\n AND type = 2"
1489              ;
1490              $this->_db->setQuery( $query );
1491              if ($this->_db->loadResult()) {
1492                  $query = "UPDATE #__stats_agents"
1493                  . "\n SET hits = ( hits + 1 )"
1494                  . "\n WHERE agent = " . $this->_db->Quote( $tldomain )
1495                  . "\n AND type = 2"
1496                  ;
1497                  $this->_db->setQuery( $query );
1498              } else {
1499                  $query = "INSERT INTO #__stats_agents"
1500                  . "\n ( agent, type )"
1501                  . "\n VALUES ( " . $this->_db->Quote( $tldomain ) . ", 2 )"
1502                  ;
1503                  $this->_db->setQuery( $query );
1504              }
1505              $this->_db->query();
1506          }
1507      }
1508  
1509      /**
1510      * @return correct Itemid for Content Item
1511      */
1512  	function getItemid( $id, $typed=1, $link=1, $bs=1, $bc=1, $gbs=1 ) {
1513          global $Itemid;
1514  
1515          $_Itemid = '';
1516  
1517          if ($_Itemid == '' && $typed && $this->getStaticContentCount()) {
1518              $exists = 0;
1519              foreach( $this->get( '_ContentTyped', array() ) as $key => $value ) {
1520                  // check if id has been tested before, if it is pull from class variable store
1521                  if ( $key == $id ) {
1522                      $_Itemid     = $value;
1523                      $exists     = 1;
1524                      break;
1525                  }
1526              }
1527              // if id hasnt been checked before initaite query
1528              if ( !$exists ) {
1529                  // Search for typed link
1530                  $query = "SELECT id"
1531                  . "\n FROM #__menu"
1532                  . "\n WHERE type = 'content_typed'"
1533                  . "\n AND published = 1"
1534                  . "\n AND link = 'index.php?option=com_content&task=view&id=" . (int) $id . "'"
1535                  ;
1536                  $this->_db->setQuery( $query );
1537                  // pull existing query storage into temp variable
1538                  $ContentTyped         = $this->get( '_ContentTyped', array() );
1539                  // add query result to temp array storage
1540                  $ContentTyped[$id]     = $this->_db->loadResult();
1541                  // save temp array to main array storage
1542                  $this->set( '_ContentTyped', $ContentTyped );
1543  
1544                  $_Itemid = $ContentTyped[$id];
1545              }
1546          }
1547  
1548          if ($_Itemid == '' && $link && $this->getContentItemLinkCount()) {
1549              $exists = 0;
1550              foreach( $this->get( '_ContentItemLink', array() ) as $key => $value ) {
1551              // check if id has been tested before, if it is pull from class variable store
1552                  if ( $key == $id ) {
1553                      $_Itemid     = $value;
1554                      $exists     = 1;
1555                      break;
1556                  }
1557              }
1558              // if id hasnt been checked before initaite query
1559              if ( !$exists ) {
1560                  // Search for item link
1561                  $query = "SELECT id"
1562                  ."\n FROM #__menu"
1563                  ."\n WHERE type = 'content_item_link'"
1564                  . "\n AND published = 1"
1565                  . "\n AND link = 'index.php?option=com_content&task=view&id=" . (int) $id . "'"
1566                  ;
1567                  $this->_db->setQuery( $query );
1568                  // pull existing query storage into temp variable
1569                  $ContentItemLink         = $this->get( '_ContentItemLink', array() );
1570                  // add query result to temp array storage
1571                  $ContentItemLink[$id]     = $this->_db->loadResult();
1572                  // save temp array to main array storage
1573                  $this->set( '_ContentItemLink', $ContentItemLink );
1574  
1575                  $_Itemid = $ContentItemLink[$id];
1576              }
1577          }
1578  
1579          if ($_Itemid == '') {
1580              $exists = 0;
1581              foreach( $this->get( '_ContentSection', array() ) as $key => $value ) {
1582              // check if id has been tested before, if it is pull from class variable store
1583                  if ( $key == $id ) {
1584                      $_Itemid     = $value;
1585                      $exists     = 1;
1586                      break;
1587                  }
1588              }
1589              // if id hasnt been checked before initaite query
1590              if ( !$exists ) {
1591                  $query = "SELECT ms.id AS sid, ms.type AS stype, mc.id AS cid, mc.type AS ctype, i.id as sectionid, i.id As catid, ms.published AS spub, mc.published AS cpub"
1592                  . "\n FROM #__content AS i"
1593                  . "\n LEFT JOIN #__sections AS s ON i.sectionid = s.id"
1594                  . "\n LEFT JOIN #__menu AS ms ON ms.componentid = s.id "
1595                  . "\n LEFT JOIN #__categories AS c ON i.catid = c.id"
1596                  . "\n LEFT JOIN #__menu AS mc ON mc.componentid = c.id "
1597                  . "\n WHERE ( ms.type IN ( 'content_section', 'content_blog_section' ) OR mc.type IN ( 'content_blog_category', 'content_category' ) )"
1598                  . "\n AND i.id = " . (int) $id
1599                  . "\n ORDER BY ms.type DESC, mc.type DESC, ms.id, mc.id"
1600                  ;
1601                  $this->_db->setQuery( $query );
1602                  $links = $this->_db->loadObjectList();
1603  
1604                  if (count($links)) {
1605                      foreach($links as $link) {
1606                          if ($link->stype == 'content_section' && $link->sectionid == $id && !isset($content_section) && $link->spub == 1) {
1607                              $content_section = $link->sid;
1608                          }
1609  
1610                          if ($link->stype == 'content_blog_section' && $link->sectionid == $id && !isset($content_blog_section) && $link->spub == 1) {
1611                              $content_blog_section = $link->sid;
1612                          }
1613  
1614                          if ($link->ctype == 'content_blog_category' && $link->catid == $id && !isset($content_blog_category) && $link->cpub == 1) {
1615                              $content_blog_category = $link->cid;
1616                          }
1617  
1618                          if ($link->ctype == 'content_category' && $link->catid == $id && !isset($content_category) && $link->cpub == 1) {
1619                              $content_category = $link->cid;
1620                          }
1621                      }
1622                  }
1623  
1624                  if (!isset($content_section)) {
1625                      $content_section = null;
1626                  }
1627  
1628                  // pull existing query storage into temp variable
1629                  $ContentSection         = $this->get( '_ContentSection', array() );
1630                  // add query result to temp array storage
1631                  $ContentSection[$id]     = $content_section;
1632                  // save temp array to main array storage
1633                  $this->set( '_ContentSection', $ContentSection );
1634  
1635                  $_Itemid = $ContentSection[$id];
1636              }
1637          }
1638  
1639          if ($_Itemid == '') {
1640              $exists = 0;
1641              foreach( $this->get( '_ContentBlogCategory', array() ) as $key => $value ) {
1642                  // check if id has been tested before, if it is pull from class variable store
1643                  if ( $key == $id ) {
1644                      $_Itemid     = $value;
1645                      $exists     = 1;
1646                      break;
1647                  }
1648              }
1649              // if id hasnt been checked before initaite query
1650              if ( !$exists ) {
1651                  if (!isset($content_blog_category)) {
1652                      $content_blog_category = null;
1653                  }
1654  
1655                  // pull existing query storage into temp variable
1656                  $ContentBlogCategory         = $this->get( '_ContentBlogCategory', array() );
1657                  // add query result to temp array storage
1658                  $ContentBlogCategory[$id]     = $content_blog_category;
1659                  // save temp array to main array storage
1660                  $this->set( '_ContentBlogCategory', $ContentBlogCategory );
1661  
1662                  $_Itemid = $ContentBlogCategory[$id];
1663              }
1664          }
1665  
1666          if ($_Itemid == '') {
1667              // ensure that query is only called once
1668              if ( !$this->get( '_GlobalBlogSection' ) && !defined( '_JOS_GBS' ) ) {
1669                  define( '_JOS_GBS', 1 );
1670  
1671                  // Search in global blog section
1672                  $query = "SELECT id "
1673                  . "\n FROM #__menu "
1674                  . "\n WHERE type = 'content_blog_section'"
1675                  . "\n AND published = 1"
1676                  . "\n AND componentid = 0"
1677                  ;
1678                  $this->_db->setQuery( $query );
1679                  $this->set( '_GlobalBlogSection', $this->_db->loadResult() );
1680              }
1681  
1682              $_Itemid = $this->get( '_GlobalBlogSection' );
1683          }
1684  
1685          if ($_Itemid == '') {
1686              $exists = 0;
1687              foreach( $this->get( '_ContentBlogSection', array() ) as $key => $value ) {
1688                  // check if id has been tested before, if it is pull from class variable store
1689                  if ( $key == $id ) {
1690                      $_Itemid     = $value;
1691                      $exists     = 1;
1692                      break;
1693                  }
1694              }
1695              // if id hasnt been checked before initaite query
1696              if ( !$exists ) {
1697                  if (!isset($content_blog_section)) {
1698                      $content_blog_section = null;
1699                  }
1700  
1701                  // pull existing query storage into temp variable
1702                  $ContentBlogSection         = $this->get( '_ContentBlogSection', array() );
1703                  // add query result to temp array storage
1704                  $ContentBlogSection[$id]     = $content_blog_section;
1705                  // save temp array to main array storage
1706                  $this->set( '_ContentBlogSection', $ContentBlogSection );
1707  
1708                  $_Itemid = $ContentBlogSection[$id];
1709              }
1710          }
1711  
1712          if ($_Itemid == '') {
1713              $exists = 0;
1714              foreach( $this->get( '_ContentCategory', array() ) as $key => $value ) {
1715                  // check if id has been tested before, if it is pull from class variable store
1716                  if ( $key == $id ) {
1717                      $_Itemid     = $value;
1718                      $exists     = 1;
1719                      break;
1720                  }
1721              }
1722              // if id hasnt been checked before initaite query
1723              if ( !$exists ) {
1724                  if (!isset($content_category)) {
1725                      $content_category = null;
1726                  }
1727  
1728                  // pull existing query storage into temp variable
1729                  $ContentCategory         = $this->get( '_ContentCategory', array() );
1730                  // add query result to temp array storage
1731                  //$ContentCategory[$id]     = $this->_db->loadResult();
1732                  $ContentCategory[$id]     = $content_category;
1733                  // save temp array to main array storage
1734                  $this->set( '_ContentCategory', $ContentCategory );
1735  
1736                  $_Itemid = $ContentCategory[$id];
1737              }
1738          }
1739  
1740          if ($_Itemid == '') {
1741              // ensure that query is only called once
1742              if ( !$this->get( '_GlobalBlogCategory' ) && !defined( '_JOS_GBC' ) ) {
1743                  define( '_JOS_GBC', 1 );
1744  
1745                  // Search in global blog category
1746                  $query = "SELECT id "
1747                  . "\n FROM #__menu "
1748                  . "\n WHERE type = 'content_blog_category'"
1749                  . "\n AND published = 1"
1750                  . "\n AND componentid = 0"
1751                  ;
1752                  $this->_db->setQuery( $query );
1753                  $this->set( '_GlobalBlogCategory', $this->_db->loadResult() );
1754              }
1755  
1756              $_Itemid = $this->get( '_GlobalBlogCategory' );
1757          }
1758  
1759          if ( $_Itemid != '' ) {
1760          // if Itemid value discovered by queries, return this value
1761              return $_Itemid;
1762          } else if ( $Itemid != 99999999 && $Itemid === 0 ) {
1763          // if queries do not return Itemid value, return Itemid of page - if it is not 99999999
1764              return $Itemid;
1765          }
1766      }
1767  
1768      /**
1769      * @return number of Published Blog Sections
1770      * Kept for Backward Compatability
1771      */
1772  	function getBlogSectionCount( ) {
1773          return 1;
1774      }
1775  
1776      /**
1777      * @return number of Published Blog Categories
1778      * Kept for Backward Compatability
1779      */
1780  	function getBlogCategoryCount( ) {
1781          return 1;
1782      }
1783  
1784      /**
1785      * @return number of Published Global Blog Sections
1786      * Kept for Backward Compatability
1787      */
1788  	function getGlobalBlogSectionCount( ) {
1789          return 1;
1790      }
1791  
1792      /**
1793      * @return number of Static Content
1794      */
1795  	function getStaticContentCount( ) {
1796          // ensure that query is only called once
1797          if ( !$this->get( '_StaticContentCount' ) && !defined( '_JOS_SCC' ) ) {
1798              define( '_JOS_SCC', 1 );
1799  
1800              $query = "SELECT COUNT( id )"
1801              ."\n FROM #__menu "
1802              ."\n WHERE type = 'content_typed'"
1803              ."\n AND published = 1"
1804              ;
1805              $this->_db->setQuery( $query );
1806              // saves query result to variable
1807              $this->set( '_StaticContentCount', $this->_db->loadResult() );
1808          }
1809  
1810          return $this->get( '_StaticContentCount' );
1811      }
1812  
1813      /**
1814      * @return number of Content Item Links
1815      */
1816  	function getContentItemLinkCount( ) {
1817          // ensure that query is only called once
1818          if ( !$this->get( '_ContentItemLinkCount' ) && !defined( '_JOS_CILC' ) ) {
1819              define( '_JOS_CILC', 1 );
1820  
1821              $query = "SELECT COUNT( id )"
1822              ."\n FROM #__menu "
1823              ."\n WHERE type = 'content_item_link'"
1824              ."\n AND published = 1"
1825              ;
1826              $this->_db->setQuery( $query );
1827              // saves query result to variable
1828              $this->set( '_ContentItemLinkCount', $this->_db->loadResult() );
1829          }
1830  
1831          return $this->get( '_ContentItemLinkCount' );
1832      }
1833  
1834      /**
1835      * @param string The name of the property
1836      * @param mixed The value of the property to set
1837      */
1838  	function set( $property, $value=null ) {
1839          $this->$property = $value;
1840      }
1841  
1842      /**
1843      * @param string The name of the property
1844      * @param mixed  The default value
1845      * @return mixed The value of the property
1846      */
1847  	function get($property, $default=null) {
1848          if(isset($this->$property)) {
1849              return $this->$property;
1850          } else {
1851              return $default;
1852          }
1853      }
1854  
1855      /** Is admin interface?
1856       * @return boolean
1857       * @since 1.0.2
1858       */
1859  	function isAdmin() {
1860          return $this->_isAdmin;
1861      }
1862  }
1863  
1864  /**
1865  * Component database table class
1866  * @package Joomla
1867  */
1868  class mosComponent extends mosDBTable {
1869      /** @var int Primary key */
1870      var $id                    = null;
1871      /** @var string */
1872      var $name                = null;
1873      /** @var string */
1874      var $link                = null;
1875      /** @var int */
1876      var $menuid                = null;
1877      /** @var int */
1878      var $parent                = null;
1879      /** @var string */
1880      var $admin_menu_link    = null;
1881      /** @var string */
1882      var $admin_menu_alt        = null;
1883      /** @var string */
1884      var $option                = null;
1885      /** @var string */
1886      var $ordering            = null;
1887      /** @var string */
1888      var $admin_menu_img        = null;
1889      /** @var int */
1890      var $iscore                = null;
1891      /** @var string */
1892      var $params                = null;
1893  
1894      /**
1895      * @param database A database connector object
1896      */
1897  	function mosComponent( &$db ) {
1898          $this->mosDBTable( '#__components', 'id', $db );
1899      }
1900  }
1901  
1902  /**
1903  * Utility class for all HTML drawing classes
1904  * @package Joomla
1905  */
1906  class mosHTML {
1907  	function makeOption( $value, $text='', $value_name='value', $text_name='text' ) {
1908          $obj = new stdClass;
1909          $obj->$value_name = $value;
1910          $obj->$text_name = trim( $text ) ? $text : $value;
1911          return $obj;
1912      }
1913  
1914    function writableCell( $folder, $relative=1, $text='', $visible=1 ) {
1915      $writeable         = '<b><font color="green">Writeable</font></b>';
1916      $unwriteable     = '<b><font color="red">Unwriteable</font></b>';
1917  
1918        echo '<tr>';
1919        echo '<td class="item">';
1920      echo $text;
1921      if ( $visible ) {
1922          echo $folder . '/';
1923      }
1924      echo '</td>';
1925        echo '<td align="left">';
1926      if ( $relative ) {
1927          echo is_writable( "../$folder" )     ? $writeable : $unwriteable;
1928      } else {
1929          echo is_writable( "$folder" )         ? $writeable : $unwriteable;
1930      }
1931      echo '</td>';
1932        echo '</tr>';
1933    }
1934  
1935      /**
1936      * Generates an HTML select list
1937      * @param array An array of objects
1938      * @param string The value of the HTML name attribute
1939      * @param string Additional HTML attributes for the <select> tag
1940      * @param string The name of the object variable for the option value
1941      * @param string The name of the object variable for the option text
1942      * @param mixed The key that is selected
1943      * @returns string HTML for the select list
1944      */
1945  	function selectList( &$arr, $tag_name, $tag_attribs, $key, $text, $selected=NULL ) {
1946          // check if array
1947          if ( is_array( $arr ) ) {
1948              reset( $arr );
1949          }
1950  
1951          $html     = "\n<select name=\"$tag_name\" $tag_attribs>";
1952          $count     = count( $arr );
1953  
1954          for ($i=0, $n=$count; $i < $n; $i++ ) {
1955              $k = $arr[$i]->$key;
1956              $t = $arr[$i]->$text;
1957              $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
1958  
1959              $extra = '';
1960              $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
1961              if (is_array( $selected )) {
1962                  foreach ($selected as $obj) {
1963                      $k2 = $obj->$key;
1964                      if ($k == $k2) {
1965                          $extra .= " selected=\"selected\"";
1966                          break;
1967                      }
1968                  }
1969              } else {
1970                  $extra .= ($k == $selected ? " selected=\"selected\"" : '');
1971              }
1972              $html .= "\n\t<option value=\"".$k."\"$extra>" . $t . "</option>";
1973          }
1974          $html .= "\n</select>\n";
1975  
1976          return $html;
1977      }
1978  
1979      /**
1980      * Writes a select list of integers
1981      * @param int The start integer
1982      * @param int The end integer
1983      * @param int The increment
1984      * @param string The value of the HTML name attribute
1985      * @param string Additional HTML attributes for the <select> tag
1986      * @param mixed The key that is selected
1987      * @param string The printf format to be applied to the number
1988      * @returns string HTML for the select list
1989      */
1990  	function integerSelectList( $start, $end, $inc, $tag_name, $tag_attribs, $selected, $format="" ) {
1991          $start     = intval( $start );
1992          $end     = intval( $end );
1993          $inc     = intval( $inc );
1994          $arr     = array();
1995  
1996          for ($i=$start; $i <= $end; $i+=$inc) {
1997              $fi = $format ? sprintf( "$format", $i ) : "$i";
1998              $arr[] = mosHTML::makeOption( $fi, $fi );
1999          }
2000  
2001          return mosHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
2002      }
2003  
2004      /**
2005      * Writes a select list of month names based on Language settings
2006      * @param string The value of the HTML name attribute
2007      * @param string Additional HTML attributes for the <select> tag
2008      * @param mixed The key that is selected
2009      * @returns string HTML for the select list values
2010      */
2011  	function monthSelectList( $tag_name, $tag_attribs, $selected ) {
2012          $arr = array(
2013              mosHTML::makeOption( '01', _JAN ),
2014              mosHTML::makeOption( '02', _FEB ),
2015              mosHTML::makeOption( '03', _MAR ),
2016              mosHTML::makeOption( '04', _APR ),
2017              mosHTML::makeOption( '05', _MAY ),
2018              mosHTML::makeOption( '06', _JUN ),
2019              mosHTML::makeOption( '07', _JUL ),
2020              mosHTML::makeOption( '08', _AUG ),
2021              mosHTML::makeOption( '09', _SEP ),
2022              mosHTML::makeOption( '10', _OCT ),
2023              mosHTML::makeOption( '11', _NOV ),
2024              mosHTML::makeOption( '12', _DEC )
2025          );
2026  
2027          return mosHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
2028      }
2029  
2030      /**
2031      * Generates an HTML select list from a tree based query list
2032      * @param array Source array with id and parent fields
2033      * @param array The id of the current list item
2034      * @param array Target array.  May be an empty array.
2035      * @param array An array of objects
2036      * @param string The value of the HTML name attribute
2037      * @param string Additional HTML attributes for the <select> tag
2038      * @param string The name of the object variable for the option value
2039      * @param string The name of the object variable for the option text
2040      * @param mixed The key that is selected
2041      * @returns string HTML for the select list
2042      */
2043  	function treeSelectList( &$src_list, $src_id, $tgt_list, $tag_name, $tag_attribs, $key, $text, $selected ) {
2044  
2045          // establish the hierarchy of the menu
2046          $children = array();
2047          // first pass - collect children
2048          foreach ($src_list as $v ) {
2049              $pt = $v->parent;
2050              $list = @$children[$pt] ? $children[$pt] : array();
2051              array_push( $list, $v );
2052              $children[$pt] = $list;
2053          }
2054          // second pass - get an indent list of the items
2055          $ilist = mosTreeRecurse( 0, '', array(), $children );
2056  
2057          // assemble menu items to the array
2058          $this_treename = '';
2059          foreach ($ilist as $item) {
2060              if ($this_treename) {
2061                  if ($item->id != $src_id && strpos( $item->treename, $this_treename ) === false) {
2062                      $tgt_list[] = mosHTML::makeOption( $item->id, $item->treename );
2063                  }
2064              } else {
2065                  if ($item->id != $src_id) {
2066                      $tgt_list[] = mosHTML::makeOption( $item->id, $item->treename );
2067                  } else {
2068                      $this_treename = "$item->treename/";
2069                  }
2070              }
2071          }
2072          // build the html select list
2073          return mosHTML::selectList( $tgt_list, $tag_name, $tag_attribs, $key, $text, $selected );
2074      }
2075  
2076      /**
2077      * Writes a yes/no select list
2078      * @param string The value of the HTML name attribute
2079      * @param string Additional HTML attributes for the <select> tag
2080      * @param mixed The key that is selected
2081      * @returns string HTML for the select list values
2082      */
2083  	function yesnoSelectList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
2084          $arr = array(
2085          mosHTML::makeOption( '0', $no ),
2086          mosHTML::makeOption( '1', $yes ),
2087          );
2088  
2089          return mosHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
2090      }
2091  
2092      /**
2093      * Generates an HTML radio list
2094      * @param array An array of objects
2095      * @param string The value of the HTML name attribute
2096      * @param string Additional HTML attributes for the <select> tag
2097      * @param mixed The key that is selected
2098      * @param string The name of the object variable for the option value
2099      * @param string The name of the object variable for the option text
2100      * @returns string HTML for the select list
2101      */
2102  	function radioList( &$arr, $tag_name, $tag_attribs, $selected=null, $key='value', $text='text' ) {
2103          reset( $arr );
2104          $html = "";
2105          for ($i=0, $n=count( $arr ); $i < $n; $i++ ) {
2106              $k = $arr[$i]->$key;
2107              $t = $arr[$i]->$text;
2108              $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
2109  
2110              $extra = '';
2111              $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
2112              if (is_array( $selected )) {
2113                  foreach ($selected as $obj) {
2114                      $k2 = $obj->$key;
2115                      if ($k == $k2) {
2116                          $extra .= " selected=\"selected\"";
2117                          break;
2118                      }
2119                  }
2120              } else {
2121                  $extra .= ($k == $selected ? " checked=\"checked\"" : '');
2122              }
2123              $html .= "\n\t<input type=\"radio\" name=\"$tag_name\" id=\"$tag_name$k\" value=\"".$k."\"$extra $tag_attribs />";
2124              $html .= "\n\t<label for=\"$tag_name$k\">$t</label>";
2125          }
2126          $html .= "\n";
2127  
2128          return $html;
2129      }
2130  
2131      /**
2132      * Writes a yes/no radio list
2133      * @param string The value of the HTML name attribute
2134      * @param string Additional HTML attributes for the <select> tag
2135      * @param mixed The key that is selected
2136      * @returns string HTML for the radio list
2137      */
2138  	function yesnoRadioList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
2139          $arr = array(
2140              mosHTML::makeOption( '0', $no ),
2141              mosHTML::makeOption( '1', $yes )
2142          );
2143  
2144          return mosHTML::radioList( $arr, $tag_name, $tag_attribs, $selected );
2145      }
2146  
2147      /**
2148      * @param int The row index
2149      * @param int The record id
2150      * @param boolean
2151      * @param string The name of the form element
2152      * @return string
2153      */
2154  	function idBox( $rowNum, $recId, $checkedOut=false, $name='cid' ) {
2155          if ( $checkedOut ) {
2156              return '';
2157          } else {
2158              return '<input type="checkbox" id="cb'.$rowNum.'" name="'.$name.'[]" value="'.$recId.'" onclick="isChecked(this.checked);" />';
2159          }
2160      }
2161  
2162  	function sortIcon( $base_href, $field, $state='none' ) {
2163          global $mosConfig_live_site;
2164  
2165          $alts = array(
2166              'none'     => _CMN_SORT_NONE,
2167              'asc'     => _CMN_SORT_ASC,
2168              'desc'     => _CMN_SORT_DESC,
2169          );
2170          $next_state = 'asc';
2171          if ($state == 'asc') {
2172              $next_state = 'desc';
2173          } else if ($state == 'desc') {
2174              $next_state = 'none';
2175          }
2176  
2177          $html = "<a href=\"$base_href&field=$field&order=$next_state\">"
2178          . "<img src=\"$mosConfig_live_site/images/M_images/sort_$state.png\" width=\"12\" height=\"12\" border=\"0\" alt=\"{$alts[$next_state]}\" />"
2179          . "</a>";
2180          return $html;
2181      }
2182  
2183      /**
2184      * Writes Close Button
2185      */
2186  	function CloseButton ( &$params, $hide_js=NULL ) {
2187          // displays close button in Pop-up window
2188          if ( $params->get( 'popup' ) && !$hide_js ) {
2189              ?>
2190              <script language="javascript" type="text/javascript">
2191              <!--
2192              document.write('<div align="center" style="margin-top: 30px; margin-bottom: 30px;">');
2193              document.write('<a href="#" onclick="javascript:window.close();"><span class="small"><?php echo _PROMPT_CLOSE;?></span></a>');
2194              document.write('</div>');
2195              //-->
2196              </script>
2197              <?php
2198          }
2199      }
2200  
2201      /**
2202      * Writes Back Button
2203      */
2204  	function BackButton ( &$params, $hide_js=NULL ) {
2205          // Back Button
2206          if ( $params->get( 'back_button' ) && !$params->get( 'popup' ) && !$hide_js) {
2207              ?>
2208              <div class="back_button">
2209                  <a href='javascript:history.go(-1)'>
2210                      <?php echo _BACK; ?></a>
2211              </div>
2212              <?php
2213          }
2214      }
2215  
2216      /**
2217      * Cleans text of all formating and scripting code
2218      */
2219  	function cleanText ( &$text ) {
2220          $text = preg_replace( "'<script[^>]*>.*?</script>'si", '', $text );
2221          $text = preg_replace( '/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is', '\2 (\1)', $text );
2222          $text = preg_replace( '/<!--.+?-->/', '', $text );
2223          $text = preg_replace( '/{.+?}/', '', $text );
2224          $text = preg_replace( '/&nbsp;/', ' ', $text );
2225          $text = preg_replace( '/&amp;/', ' ', $text );
2226          $text = preg_replace( '/&quot;/', ' ', $text );
2227          $text = strip_tags( $text );
2228          $text = htmlspecialchars( $text );
2229  
2230          return $text;
2231      }
2232  
2233      /**
2234      * Writes Print icon
2235      */
2236  	function PrintIcon( &$row, &$params, $hide_js, $link, $status=NULL ) {
2237          if ( $params->get( 'print' )  && !$hide_js ) {
2238              // use default settings if none declared
2239              if ( !$status ) {
2240                  $status = 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no';
2241              }
2242  
2243              // checks template image directory for image, if non found default are loaded
2244              if ( $params->get( 'icons' ) ) {
2245                  $image = mosAdminMenus::ImageCheck( 'printButton.png', '/images/M_images/', NULL, NULL, _CMN_PRINT, _CMN_PRINT );
2246              } else {
2247                  $image = _ICON_SEP .'&nbsp;'. _CMN_PRINT. '&nbsp;'. _ICON_SEP;
2248              }
2249  
2250              if ( $params->get( 'popup' ) && !$hide_js ) {
2251                  // Print Preview button - used when viewing page
2252                  ?>
2253                  <script language="javascript" type="text/javascript">
2254                  <!--
2255                  document.write('<td align="right" width="100%" class="buttonheading">');
2256                  document.write('<a href="#" onclick="javascript:window.print(); return false;" title="<?php echo _CMN_PRINT;?>">');
2257                  document.write('<?php echo $image;?>');
2258                  document.write('</a>');
2259                  document.write('</td>');
2260                  //-->
2261                  </script>
2262                  <?php
2263              } else {
2264                  // Print Button - used in pop-up window
2265                  ?>
2266                  <td align="right" width="100%" class="buttonheading">
2267                      <a href="<?php echo $link; ?>" target="_blank" onclick="window.open('<?php echo $link; ?>','win2','<?php echo $status; ?>'); return false;" title="<?php echo _CMN_PRINT;?>">
2268                          <?php echo $image;?></a>
2269                  </td>
2270                  <?php
2271              }
2272          }
2273      }
2274  
2275      /**
2276      * simple Javascript Cloaking
2277      * email cloacking
2278       * by default replaces an email with a mailto link with email cloacked
2279      */
2280  	function emailCloaking( $mail, $mailto=1, $text='', $email=1 ) {
2281          // convert text
2282          $mail             = mosHTML::encoding_converter( $mail );
2283          // split email by @ symbol
2284          $mail            = explode( '@', $mail );
2285          $mail_parts        = explode( '.', $mail[1] );
2286          // random number
2287          $rand            = rand( 1, 100000 );
2288  
2289          $replacement     = "\n <script language='JavaScript' type='text/javascript'>";
2290          $replacement     .= "\n <!--";
2291          $replacement     .= "\n var prefix = '&#109;a' + 'i&#108;' + '&#116;o';";
2292          $replacement     .= "\n var path = 'hr' + 'ef' + '=';";
2293          $replacement     .= "\n var addy". $rand ." = '". @$mail[0] ."' + '&#64;';";
2294          $replacement     .= "\n addy". $rand ." = addy". $rand ." + '". implode( "' + '&#46;' + '", $mail_parts ) ."';";
2295  
2296          if ( $mailto ) {
2297              // special handling when mail text is different from mail addy
2298              if ( $text ) {
2299                  if ( $email ) {
2300                      // convert text
2301                      $text             = mosHTML::encoding_converter( $text );
2302                      // split email by @ symbol
2303                      $text             = explode( '@', $text );
2304                      $text_parts        = explode( '.', $text[1] );
2305                      $replacement     .= "\n var addy_text". $rand ." = '". @$text[0] ."' + '&#64;' + '". implode( "' + '&#46;' + '", @$text_parts ) ."';";
2306                  } else {
2307                      $replacement     .= "\n var addy_text". $rand ." = '". $text ."';";
2308                  }
2309                  $replacement     .= "\n document.write( '<a ' + path + '\'' + prefix + ':' + addy". $rand ." + '\'>' );";
2310                  $replacement     .= "\n document.write( addy_text". $rand ." );";
2311                  $replacement     .= "\n document.write( '<\/a>' );";
2312              } else {
2313                  $replacement     .= "\n document.write( '<a ' + path + '\'' + prefix + ':' + addy". $rand ." + '\'>' );";
2314                  $replacement     .= "\n document.write( addy". $rand ." );";
2315                  $replacement     .= "\n document.write( '<\/a>' );";
2316              }
2317          } else {
2318              $replacement     .= "\n document.write( addy". $rand ." );";
2319          }
2320          $replacement     .= "\n //-->";
2321          $replacement     .= '\n </script>';
2322  
2323          // XHTML compliance `No Javascript` text handling
2324          $replacement     .= "<script language='JavaScript' type='text/javascript'>";
2325          $replacement     .= "\n <!--";
2326          $replacement     .= "\n document.write( '<span style=\'display: none;\'>' );";
2327          $replacement     .= "\n //-->";
2328          $replacement     .= "\n </script>";
2329          $replacement     .= _CLOAKING;
2330          $replacement     .= "\n <script language='JavaScript' type='text/javascript'>";
2331          $replacement     .= "\n <!--";
2332          $replacement     .= "\n document.write( '</' );";
2333          $replacement     .= "\n document.write( 'span>' );";
2334          $replacement     .= "\n //-->";
2335          $replacement     .= "\n </script>";
2336  
2337          return $replacement;
2338      }
2339  
2340  	function encoding_converter( $text ) {
2341          // replace vowels with character encoding
2342          $text     = str_replace( 'a', '&#97;', $text );
2343          $text     = str_replace( 'e', '&#101;', $text );
2344          $text     = str_replace( 'i', '&#105;', $text );
2345          $text     = str_replace( 'o', '&#111;', $text );
2346          $text    = str_replace( 'u', '&#117;', $text );
2347  
2348          return $text;
2349      }
2350  }
2351  
2352  /**
2353  * Category database table class
2354  * @package Joomla
2355  */
2356  class mosCategory extends mosDBTable {
2357      /** @var int Primary key */
2358      var $id                    = null;
2359      /** @var int */
2360      var $parent_id            = null;
2361      /** @var string The menu title for the Category (a short name)*/
2362      var $title                = null;
2363      /** @var string The full name for the Category*/
2364      var $name                = null;
2365      /** @var string */
2366      var $image                = null;
2367      /** @var string */
2368      var $section            = null;
2369      /** @var int */
2370      var $image_position        = null;
2371      /** @var string */
2372      var $description        = null;
2373      /** @var boolean */
2374      var $published            = null;
2375      /** @var boolean */
2376      var $checked_out        = null;
2377      /** @var time */
2378      var $checked_out_time    = null;
2379      /** @var int */
2380      var $ordering            = null;
2381      /** @var int */
2382      var $access                = null;
2383      /** @var string */
2384      var $params                = null;
2385  
2386      /**
2387      * @param database A database connector object
2388      */
2389  	function mosCategory( &$db ) {
2390          $this->mosDBTable( '#__categories', 'id', $db );
2391      }
2392      // overloaded check function
2393  	function check() {
2394          // check for valid name
2395          if (trim( $this->title ) == '') {
2396              $this->_error = "Your Category must contain a title.";
2397              return false;
2398          }
2399          if (trim( $this->name ) == '') {
2400              $this->_error = "Your Category must have a name.";
2401              return false;
2402          }
2403  
2404          // check for existing name
2405          $query = "SELECT id"
2406          . "\n FROM #__categories "
2407          . "\n WHERE name = " . $this->_db->Quote( $this->name )
2408          . "\n AND section = " . $this->_db->Quote( $this->section )
2409          ;
2410          $this->_db->setQuery( $query );
2411  
2412          $xid = intval( $this->_db->loadResult() );
2413          if ($xid && $xid != intval( $this->id )) {
2414              $this->_error = "There is a category already with that name, please try again.";
2415              return false;
2416          }
2417          return true;
2418      }
2419  }
2420  
2421  /**
2422  * Section database table class
2423  * @package Joomla
2424  */
2425  class mosSection extends mosDBTable {
2426      /** @var int Primary key */
2427      var $id                    = null;
2428      /** @var string The menu title for the Section (a short name)*/
2429      var $title                = null;
2430      /** @var string The full name for the Section*/
2431      var $name                = null;
2432      /** @var string */
2433      var $image                = null;
2434      /** @var string */
2435      var $scope                = null;
2436      /** @var int */
2437      var $image_position        = null;
2438      /** @var string */
2439      var $description        = null;
2440      /** @var boolean */
2441      var $published            = null;
2442      /** @var boolean */
2443      var $checked_out        = null;
2444      /** @var time */
2445      var $checked_out_time    = null;
2446      /** @var int */
2447      var $ordering            = null;
2448      /** @var int */
2449      var $access                = null;
2450      /** @var string */
2451      var $params                = null;
2452  
2453      /**
2454      * @param database A database connector object
2455      */
2456  	function mosSection( &$db ) {
2457          $this->mosDBTable( '#__sections', 'id', $db );
2458      }
2459      // overloaded check function
2460  	function check() {
2461          // check for valid name
2462          if (trim( $this->title ) == '') {
2463              $this->_error = "Your Section must contain a title.";
2464              return false;
2465          }
2466          if (trim( $this->name ) == '') {
2467              $this->_error = "Your Section must have a name.";
2468              return false;
2469          }
2470          // check for existing name
2471          $query = "SELECT id"
2472          . "\n FROM #__sections "
2473          . "\n WHERE name = " . $this->_db->Quote( $this->name )
2474          . "\n AND scope = " . $this->_db->Quote( $this->scope )
2475          ;
2476          $this->_db->setQuery( $query );
2477  
2478          $xid = intval( $this->_db->loadResult() );
2479          if ($xid && $xid != intval( $this->id )) {
2480              $this->_error = "There is a section already with that name, please try again.";
2481              return false;
2482          }
2483          return true;
2484      }
2485  }
2486  
2487  /**
2488  * Module database table class
2489  * @package Joomla
2490  */
2491  class mosContent extends mosDBTable {
2492      /** @var int Primary key */
2493      var $id                    = null;
2494      /** @var string */
2495      var $title                = null;
2496      /** @var string */
2497      var $title_alias        = null;
2498      /** @var string */
2499      var $introtext            = null;
2500      /** @var string */
2501      var $fulltext            = null;
2502      /** @var int */
2503      var $state                = null;
2504      /** @var int The id of the category section*/
2505      var $sectionid            = null;
2506      /** @var int DEPRECATED */
2507      var $mask                = null;
2508      /** @var int */
2509      var $catid                = null;
2510      /** @var datetime */
2511      var $created            = null;
2512      /** @var int User id*/
2513      var $created_by            = null;
2514      /** @var string An alias for the author*/
2515      var $created_by_alias    = null;
2516      /** @var datetime */
2517      var $modified            = null;
2518      /** @var int User id*/
2519      var $modified_by        = null;
2520      /** @var boolean */
2521      var $checked_out        = null;
2522      /** @var time */
2523      var $checked_out_time    = null;
2524      /** @var datetime */
2525      var $frontpage_up        = null;
2526      /** @var datetime */
2527      var $frontpage_down        = null;
2528      /** @var datetime */
2529      var $publish_up            = null;
2530      /** @var datetime */
2531      var $publish_down        = null;
2532      /** @var string */
2533      var $images                = null;
2534      /** @var string */
2535      var $urls                = null;
2536      /** @var string */
2537      var $attribs            = null;
2538      /** @var int */
2539      var $version            = null;
2540      /** @var int */
2541      var $parentid            = null;
2542      /** @var int */
2543      var $ordering            = null;
2544      /** @var string */
2545      var $metakey            = null;
2546      /** @var string */
2547      var $metadesc            = null;
2548      /** @var int */
2549      var $access                = null;
2550      /** @var int */
2551      var $hits                = null;
2552  
2553      /**
2554      * @param database A database connector object
2555      */
2556  	function mosContent( &$db ) {
2557          $this->mosDBTable( '#__content', 'id', $db );
2558      }
2559  
2560      /**
2561       * Validation and filtering
2562       */
2563  	function check() {
2564          // filter malicious code
2565          $ignoreList = array( 'introtext', 'fulltext' );
2566          $this->filter( $ignoreList );
2567  
2568          /*
2569          TODO: This filter is too rigorous,
2570          need to implement more configurable solution
2571          // specific filters
2572          $iFilter = new InputFilter( null, null, 1, 1 );
2573          $this->introtext = trim( $iFilter->process( $this->introtext ) );
2574          $this->fulltext =  trim( $iFilter->process( $this->fulltext ) );
2575          */
2576  
2577          if (trim( str_replace( '&nbsp;', '', $this->fulltext ) ) == '') {
2578              $this->fulltext = '';
2579          }
2580  
2581          return true;
2582      }
2583  
2584      /**
2585      * Converts record to XML
2586      * @param boolean Map foreign keys to text values
2587      */
2588  	function toXML( $mapKeysToText=false ) {
2589          global $database;
2590  
2591          if ($mapKeysToText) {
2592              $query = "SELECT name"
2593              . "\n FROM #__sections"
2594              . "\n WHERE id = " . (int) $this->sectionid
2595              ;
2596              $database->setQuery( $query );
2597              $this->sectionid = $database->loadResult();
2598  
2599              $query = "SELECT name"
2600              . "\n FROM #__categories"
2601              . "\n WHERE id = " . (int) $this->catid
2602              ;
2603              $database->setQuery( $query );
2604              $this->catid = $database->loadResult();
2605  
2606              $query = "SELECT name"
2607              . "\n FROM #__users"
2608              . "\n WHERE id = " . (int) $this->created_by
2609              ;
2610              $database->setQuery( $query );
2611              $this->created_by = $database->loadResult();
2612          }
2613  
2614          return parent::toXML( $mapKeysToText );
2615      }
2616  }
2617  
2618  /**
2619  * Module database table class
2620  * @package Joomla
2621  */
2622  class mosMenu extends mosDBTable {
2623      /** @var int Primary key */
2624      var $id                    = null;
2625      /** @var string */
2626      var $menutype            = null;
2627      /** @var string */
2628      var $name                = null;
2629      /** @var string */
2630      var $link                = null;
2631      /** @var int */
2632      var $type                = null;
2633      /** @var int */
2634      var $published            = null;
2635      /** @var int */
2636      var $componentid        = null;
2637      /** @var int */
2638      var $parent                = null;
2639      /** @var int */
2640      var $sublevel            = null;
2641      /** @var int */
2642      var $ordering            = null;
2643      /** @var boolean */
2644      var $checked_out        = null;
2645      /** @var datetime */
2646      var $checked_out_time    = null;
2647      /** @var boolean */
2648      var $pollid                = null;
2649      /** @var string */
2650      var $browserNav            = null;
2651      /** @var int */
2652      var $access                = null;
2653      /** @var int */
2654      var $utaccess            = null;
2655      /** @var string */
2656      var $params                = null;
2657  
2658      /**
2659      * @param database A database connector object
2660      */
2661  	function mosMenu( &$db ) {
2662          $this->mosDBTable( '#__menu', 'id', $db );
2663      }
2664  
2665  	function check() {
2666          $this->id = (int) $this->id;
2667          $this->params = (string) trim( $this->params . ' ' );
2668          return true;
2669      }
2670  }
2671  
2672  /**
2673  * Users Table Class
2674  *
2675  * Provides access to the jos_user table
2676  * @package Joomla
2677  */
2678  class mosUser extends mosDBTable {
2679      /** @var int Unique id*/
2680      var $id                = null;
2681      /** @var string The users real name (or nickname)*/
2682      var $name            = null;
2683      /** @var string The login name*/
2684      var $username        = null;
2685      /** @var string email*/
2686      var $email            = null;
2687      /** @var string MD5 encrypted password*/
2688      var $password        = null;
2689      /** @var string */
2690      var $usertype        = null;
2691      /** @var int */
2692      var $block            = null;
2693      /** @var int */
2694      var $sendEmail        = null;
2695      /** @var int The group id number */
2696      var $gid            = null;
2697      /** @var datetime */
2698      var $registerDate    = null;
2699      /** @var datetime */
2700      var $lastvisitDate    = null;
2701      /** @var string activation hash*/
2702      var $activation        = null;
2703      /** @var string */
2704      var $params            = null;
2705  
2706      /**
2707      * @param database A database connector object
2708      */
2709  	function mosUser( &$database ) {
2710          $this->mosDBTable( '#__users', 'id', $database );
2711      }
2712  
2713      /**
2714       * Validation and filtering
2715       * @return boolean True is satisfactory
2716       */
2717  	function check() {
2718          global $mosConfig_uniquemail;
2719  
2720          // Validate user information
2721          if (trim( $this->name ) == '') {
2722              $this->_error = _REGWARN_NAME;
2723              return false;
2724          }
2725  
2726          if (trim( $this->username ) == '') {
2727              $this->_error = _REGWARN_UNAME;
2728              return false;
2729          }
2730  
2731          // check that username is not greater than 25 characters
2732          $username = $this->username;
2733          if ( strlen($username) > 25 ) {
2734              $this->username = substr( $username, 0, 25 );
2735          }
2736  
2737          // check that password is not greater than 50 characters
2738          $password = $this->password;
2739          if ( strlen($password) > 50 ) {
2740              $this->password = substr( $password, 0, 50 );
2741          }
2742  
2743          if (eregi( "[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", $this->username) || strlen( $this->username ) < 3) {
2744              $this->_error = sprintf( _VALID_AZ09, _PROMPT_UNAME, 2 );
2745              return false;
2746          }
2747  
2748          if ((trim($this->email == "")) || (preg_match("/[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}/", $this->email )==false)) {
2749              $this->_error = _REGWARN_MAIL;
2750              return false;
2751          }
2752  
2753          // check for existing username
2754          $query = "SELECT id"
2755          . "\n FROM #__users "
2756          . "\n WHERE username = " . $this->_db->Quote( $this->username )
2757          . "\n AND id != " . (int)$this->id
2758          ;
2759          $this->_db->setQuery( $query );
2760          $xid = intval( $this->_db->loadResult() );
2761          if ($xid && $xid != intval( $this->id )) {
2762              $this->_error = _REGWARN_INUSE;
2763              return false;
2764          }
2765  
2766          if ($mosConfig_uniquemail) {
2767              // check for existing email
2768              $query = "SELECT id"
2769              . "\n FROM #__users "
2770              . "\n WHERE email = " . $this->_db->Quote( $this->email )
2771              . "\n AND id != " . (int) $this->id
2772              ;
2773              $this->_db->setQuery( $query );
2774              $xid = intval( $this->_db->loadResult() );
2775              if ($xid && $xid != intval( $this->id )) {
2776                  $this->_error = _REGWARN_EMAIL_INUSE;
2777                  return false;
2778              }
2779          }
2780  
2781          return true;
2782      }
2783  
2784  	function store( $updateNulls=false ) {
2785          global $acl, $migrate;
2786          $section_value = 'users';
2787  
2788          $k = $this->_tbl_key;
2789          $key =  $this->$k;
2790          if( $key && !$migrate) {
2791              // existing record
2792              $ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
2793              // syncronise ACL
2794              // single group handled at the moment
2795              // trivial to expand to multiple groups
2796              $groups = $acl->get_object_groups( $section_value, $this->$k, 'ARO' );
2797              $acl->del_group_object( $groups[0], $section_value, $this->$k, 'ARO' );
2798              $acl->add_group_object( $this->gid, $section_value, $this->$k, 'ARO' );
2799  
2800              $object_id = $acl->get_object_id( $section_value, $this->$k, 'ARO' );
2801              $acl->edit_object( $object_id, $section_value, $this->_db->getEscaped( $this->name ), $this->$k, 0, 0, 'ARO' );
2802          } else {
2803              // new record
2804              $ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
2805              // syncronise ACL
2806              $acl->add_object( $section_value, $this->_db->getEscaped( $this->name ), $this->$k, null, null, 'ARO' );
2807              $acl->add_group_object( $this->gid, $section_value, $this->$k, 'ARO' );
2808          }
2809          if( !$ret ) {
2810              $this->_error = strtolower(get_class( $this ))."::store failed <br />" . $this->_db->getErrorMsg();
2811              return false;
2812          } else {
2813              return true;
2814          }
2815      }
2816  
2817  	function delete( $oid=null ) {
2818          global $acl;
2819  
2820          $k = $this->_tbl_key;
2821          if ($oid) {
2822              $this->$k = intval( $oid );
2823          }
2824          $aro_id = $acl->get_object_id( 'users', $this->$k, 'ARO' );
2825  //        $acl->del_object( $aro_id, 'ARO', true );
2826  
2827          $query = "DELETE FROM $this->_tbl"
2828          . "\n WHERE $this->_tbl_key = " . (int) $this->$k
2829          ;
2830          $this->_db->setQuery( $query );
2831  
2832          if ($this->_db->query()) {
2833              // cleanup related data
2834  
2835              // :: private messaging
2836              $query = "DELETE FROM #__messages_cfg"
2837              . "\n WHERE user_id = " . (int) $this->$k
2838              ;
2839              $this->_db->setQuery( $query );
2840              if (!$this->_db->query()) {
2841                  $this->_error = $this->_db->getErrorMsg();
2842                  return false;
2843              }
2844              $query = "DELETE FROM #__messages"
2845              . "\n WHERE user_id_to = " . (int) $this->$k
2846              ;
2847              $this->_db->setQuery( $query );
2848              if (!$this->_db->query()) {
2849                  $this->_error = $this->_db->getErrorMsg();
2850                  return false;
2851              }
2852  
2853              return true;
2854          } else {
2855              $this->_error = $this->_db->getErrorMsg();
2856              return false;
2857          }
2858      }
2859  
2860      /**
2861       * Gets the users from a group
2862       * @param string The value for the group (not used 1.0)
2863       * @param string The name for the group
2864       * @param string If RECURSE, will drill into child groups
2865       * @param string Ordering for the list
2866       * @return array
2867       */
2868  	function getUserListFromGroup( $value, $name, $recurse='NO_RECURSE', $order='name' ) {
2869          global $acl;
2870  
2871          // Change back in
2872          //$group_id = $acl->get_group_id( $value, $name, $group_type = 'ARO');
2873          $group_id = $acl->get_group_id( $name, $group_type = 'ARO');
2874          $objects = $acl->get_group_objects( $group_id, 'ARO', 'RECURSE');
2875  
2876          if (isset( $objects['users'] )) {
2877              mosArrayToInts( $objects['users'] );
2878              $gWhere = '(id =' . implode( ' OR id =', $objects['users'] ) . ')';
2879  
2880              $query = "SELECT id AS value, name AS text"
2881              . "\n FROM #__users"
2882              . "\n WHERE block = '0'"
2883              . "\n AND " . $gWhere
2884              . "\n ORDER BY ". $order
2885              ;
2886              $this->_db->setQuery( $query );
2887              $options = $this->_db->loadObjectList();
2888              return $options;
2889          } else {
2890              return array();
2891          }
2892      }
2893  }
2894  
2895  /**
2896  * Template Table Class
2897  *
2898  * Provides access to the jos_templates table
2899  * @package Joomla
2900  */
2901  class mosTemplate extends mosDBTable {
2902      /** @var int */
2903      var $id                = null;
2904      /** @var string */
2905      var $cur_template    = null;
2906      /** @var int */
2907      var $col_main        = null;
2908  
2909      /**
2910      * @param database A database connector object
2911      */
2912  	function mosTemplate( &$database ) {
2913          $this->mosDBTable( '#__templates', 'id', $database );
2914      }
2915  }
2916  
2917  /**
2918   * Utility function to return a value from a named array or a specified default
2919   * @param array A named array
2920   * @param string The key to search for
2921   * @param mixed The default value to give if no key found
2922   * @param int An options mask: _MOS_NOTRIM prevents trim, _MOS_ALLOWHTML allows safe html, _MOS_ALLOWRAW allows raw input
2923   */
2924  define( "_MOS_NOTRIM", 0x0001 );
2925  define( "_MOS_ALLOWHTML", 0x0002 );
2926  define( "_MOS_ALLOWRAW", 0x0004 );
2927  function mosGetParam( &$arr, $name, $def=null, $mask=0 ) {
2928      static $noHtmlFilter     = null;
2929      static $safeHtmlFilter     = null;
2930  
2931      $return = null;
2932      if (isset( $arr[$name] )) {
2933          $return = $arr[$name];
2934  
2935          if (is_string( $return )) {
2936              // trim data
2937              if (!($mask&_MOS_NOTRIM)) {
2938                  $return = trim( $return );
2939              }
2940  
2941              if ($mask&_MOS_ALLOWRAW) {
2942                  // do nothing
2943              } else if ($mask&_MOS_ALLOWHTML) {
2944                  // do nothing - compatibility mode
2945              } else {
2946                  // send to inputfilter
2947                  if (is_null( $noHtmlFilter )) {
2948                      $noHtmlFilter = new InputFilter( /* $tags, $attr, $tag_method, $attr_method, $xss_auto */ );
2949                  }
2950                  $return = $noHtmlFilter->process( $return );
2951  
2952                  if (empty($return) && is_numeric($def)) {
2953                  // if value is defined and default value is numeric set variable type to integer
2954                      $return = intval($return);
2955                  }
2956              }
2957  
2958              // account for magic quotes setting
2959              if (!get_magic_quotes_gpc()) {
2960                  $return = addslashes( $return );
2961              }
2962          }
2963  
2964          return $return;
2965      } else {
2966          return $def;
2967      }
2968  }
2969  
2970  /**
2971   * Strip slashes from strings or arrays of strings
2972   * @param mixed The input string or array
2973   * @return mixed String or array stripped of slashes
2974   */
2975  function mosStripslashes( &$value ) {
2976      $ret = '';
2977      if (is_string( $value )) {
2978          $ret = stripslashes( $value );
2979      } else {
2980          if (is_array( $value )) {
2981              $ret = array();
2982              foreach ($value as $key => $val) {
2983                  $ret[$key] = mosStripslashes( $val );
2984              }
2985          } else {
2986              $ret = $value;
2987          }
2988      }
2989      return $ret;
2990  }
2991  
2992  /**
2993  * Copy the named array content into the object as properties
2994  * only existing properties of object are filled. when undefined in hash, properties wont be deleted
2995  * @param array the input array
2996  * @param obj byref the object to fill of any class
2997  * @param string
2998  * @param boolean
2999  */
3000  function mosBindArrayToObject( $array, &$obj, $ignore='', $prefix=NULL, $checkSlashes=true ) {
3001      if (!is_array( $array ) || !is_object( $obj )) {
3002          return (false);
3003      }
3004  
3005      $ignore = ' ' . $ignore . ' ';
3006      foreach (get_object_vars($obj) as $k => $v) {
3007          if( substr( $k, 0, 1 ) != '_' ) {            // internal attributes of an object are ignored
3008              if (strpos( $ignore, ' ' . $k . ' ') === false) {
3009                  if ($prefix) {
3010                      $ak = $prefix . $k;
3011                  } else {
3012                      $ak = $k;
3013                  }
3014                  if (isset($array[$ak])) {
3015                      $obj->$k = ($checkSlashes && get_magic_quotes_gpc()) ? mosStripslashes( $array[$ak] ) : $array[$ak];
3016                  }
3017              }
3018          }
3019      }
3020  
3021      return true;
3022  }
3023  
3024  /**
3025  * Utility function to read the files in a directory
3026  * @param string The file system path
3027  * @param string A filter for the names
3028  * @param boolean Recurse search into sub-directories
3029  * @param boolean True if to prepend the full path to the file name
3030  */
3031  function mosReadDirectory( $path, $filter='.', $recurse=false, $fullpath=false  ) {
3032      $arr = array();
3033      if (!@is_dir( $path )) {
3034          return $arr;
3035      }
3036      $handle = opendir( $path );
3037  
3038      while ($file = readdir($handle)) {
3039          $dir = mosPathName( $path.'/'.$file, false );
3040          $isDir = is_dir( $dir );
3041          if (($file != ".") && ($file != "..")) {
3042              if (preg_match( "/$filter/", $file )) {
3043                  if ($fullpath) {
3044                      $arr[] = trim( mosPathName( $path.'/'.$file, false ) );
3045                  } else {
3046                      $arr[] = trim( $file );
3047                  }
3048              }
3049              if ($recurse && $isDir) {
3050                  $arr2 = mosReadDirectory( $dir, $filter, $recurse, $fullpath );
3051                  $arr = array_merge( $arr, $arr2 );
3052              }
3053          }
3054      }
3055      closedir($handle);
3056      asort($arr);
3057      return $arr;
3058  }
3059  
3060  /**
3061  * Utility function redirect the browser location to another url
3062  *
3063  * Can optionally provide a message.
3064  * @param string The file system path
3065  * @param string A filter for the names
3066  */
3067  function mosRedirect( $url, $msg='' ) {
3068  
3069     global $mainframe;
3070  
3071      // specific filters
3072      $iFilter = new InputFilter();
3073      $url = $iFilter->process( $url );
3074      if (!empty($msg)) {
3075          $msg = $iFilter->process( $msg );
3076      }
3077  
3078      if ($iFilter->badAttributeValue( array( 'href', $url ))) {
3079          $url = $GLOBALS['mosConfig_live_site'];
3080      }
3081  
3082      if (trim( $msg )) {
3083           if (strpos( $url, '?' )) {
3084              $url .= '&mosmsg=' . urlencode( $msg );
3085          } else {
3086              $url .= '?mosmsg=' . urlencode( $msg );
3087          }
3088      }
3089  
3090      if (headers_sent()) {
3091          echo "<script>document.location.href='$url';</script>\n";
3092      } else {
3093          @ob_end_clean(); // clear output buffer
3094          header( 'HTTP/1.1 301 Moved Permanently' );
3095          header( "Location: ". $url );
3096      }
3097      exit();
3098  }
3099  
3100  function mosErrorAlert( $text, $action='window.history.go(-1);', $mode=1 ) {
3101      $text = nl2br( $text );
3102      $text = addslashes( $text );
3103      $text = strip_tags( $text );
3104  
3105      switch ( $mode ) {
3106          case 2:
3107              echo "<script>$action</script> \n";
3108              break;
3109  
3110          case 1:
3111          default:
3112              echo "<meta http-equiv=\"Content-Type\" content=\"text/html; "._ISO."\" />";
3113              echo "<script>alert('$text'); $action</script> \n";
3114              //echo '<noscript>';
3115              //mosRedirect( @$_SERVER['HTTP_REFERER'], $text );
3116              //echo '</noscript>';
3117              break;
3118      }
3119  
3120      exit;
3121  }
3122  
3123  function mosTreeRecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 ) {
3124  
3125      if (@$children[$id] && $level <= $maxlevel) {
3126          foreach ($children[$id] as $v) {
3127              $id = $v->id;
3128  
3129              if ( $type ) {
3130                  $pre     = '<sup>L</sup>&nbsp;';
3131                  $spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
3132              } else {
3133                  $pre     = '- ';
3134                  $spacer = '&nbsp;&nbsp;';
3135              }
3136  
3137              if ( $v->parent == 0 ) {
3138                  $txt     = $v->name;
3139              } else {
3140                  $txt     = $pre . $v->name;
3141              }
3142              $pt = $v->parent;
3143              $list[$id] = $v;
3144              $list[$id]->treename = "$indent$txt";
3145              $list[$id]->children = count( @$children[$id] );
3146  
3147              $list = mosTreeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
3148          }
3149      }
3150      return $list;
3151  }
3152  
3153  /**
3154  * Function to strip additional / or \ in a path name
3155  * @param string The path
3156  * @param boolean Add trailing slash
3157  */
3158  function mosPathName($p_path,$p_addtrailingslash = true) {
3159      $retval = "";
3160  
3161      $isWin = (substr(PHP_OS, 0, 3) == 'WIN');
3162  
3163      if ($isWin)    {
3164          $retval = str_replace( '/', '\\', $p_path );
3165          if ($p_addtrailingslash) {
3166              if (substr( $retval, -1 ) != '\\') {
3167                  $retval .= '\\';
3168              }
3169          }
3170  
3171          // Check if UNC path
3172          $unc = substr($retval,0,2) == '\\\\' ? 1 : 0;
3173  
3174          // Remove double \\
3175          $retval = str_replace( '\\\\', '\\', $retval );
3176  
3177          // If UNC path, we have to add one \ in front or everything breaks!
3178          if ( $unc == 1 ) {
3179              $retval = '\\'.$retval;
3180          }
3181      } else {
3182          $retval = str_replace( '\\', '/', $p_path );
3183          if ($p_addtrailingslash) {
3184              if (substr( $retval, -1 ) != '/') {
3185                  $retval .= '/';
3186              }
3187          }
3188  
3189          // Check if UNC path
3190          $unc = substr($retval,0,2) == '//' ? 1 : 0;
3191  
3192          // Remove double //
3193          $retval = str_replace('//','/',$retval);
3194  
3195          // If UNC path, we have to add one / in front or everything breaks!
3196          if ( $unc == 1 ) {
3197              $retval = '/'.$retval;
3198          }
3199      }
3200  
3201      return $retval;
3202  }
3203  
3204  /**
3205  * Class mosMambot
3206  * @package Joomla
3207  */
3208  class mosMambot extends mosDBTable {
3209      /** @var int */
3210      var $id                    = null;
3211      /** @var varchar */
3212      var $name                = null;
3213      /** @var varchar */
3214      var $element            = null;
3215      /** @var varchar */
3216      var $folder                = null;
3217      /** @var tinyint unsigned */
3218      var $access                = null;
3219      /** @var int */
3220      var $ordering            = null;
3221      /** @var tinyint */
3222      var $published            = null;
3223      /** @var tinyint */
3224      var $iscore                = null;
3225      /** @var tinyint */
3226      var $client_id            = null;
3227      /** @var int unsigned */
3228      var $checked_out        = null;
3229      /** @var datetime */
3230      var $checked_out_time    = null;
3231      /** @var text */
3232      var $params                = null;
3233  
3234  	function mosMambot( &$db ) {
3235          $this->mosDBTable( '#__mambots', 'id', $db );
3236      }
3237  }
3238  
3239  /**
3240  * Module database table class
3241  * @package Joomla
3242  */
3243  class mosModule extends mosDBTable {
3244      /** @var int Primary key */
3245      var $id                    = null;
3246      /** @var string */
3247      var $title                = null;
3248      /** @var string */
3249      var $showtitle            = null;
3250      /** @var int */
3251      var $content            = null;
3252      /** @var int */
3253      var $ordering            = null;
3254      /** @var string */
3255      var $position            = null;
3256      /** @var boolean */
3257      var $checked_out        = null;
3258      /** @var time */
3259      var $checked_out_time    = null;
3260      /** @var boolean */
3261      var $published            = null;
3262      /** @var string */
3263      var $module                = null;
3264      /** @var int */
3265      var $numnews            = null;
3266      /** @var int */
3267      var $access                = null;
3268      /** @var string */
3269      var $params                = null;
3270      /** @var string */
3271      var $iscore                = null;
3272      /** @var string */
3273      var $client_id            = null;
3274  
3275      /**
3276      * @param database A database connector object
3277      */
3278  	function mosModule( &$db ) {
3279          $this->mosDBTable( '#__modules', 'id', $db );
3280      }
3281      // overloaded check function
3282  	function check() {
3283          // check for valid name
3284          if (trim( $this->title ) == '') {
3285              $this->_error = "Your Module must contain a title.";
3286              return false;
3287          }
3288  
3289          return true;
3290      }
3291  }
3292  
3293  /**
3294  * Session database table class
3295  * @package Joomla
3296  */
3297  class mosSession extends mosDBTable {
3298      /** @var int Primary key */
3299      var $session_id            = null;
3300      /** @var string */
3301      var $time                = null;
3302      /** @var string */
3303      var $userid                = null;
3304      /** @var string */
3305      var $usertype            = null;
3306      /** @var string */
3307      var $username            = null;
3308      /** @var time */
3309      var $gid                = null;
3310      /** @var int */
3311      var $guest                = null;
3312      /** @var string */
3313      var $_session_cookie    = null;
3314  
3315      /**
3316      * @param database A database connector object
3317      */
3318  	function mosSession( &$db ) {
3319          $this->mosDBTable( '#__session', 'session_id', $db );
3320      }
3321  
3322      /**
3323       * @param string Key search for
3324       * @param mixed Default value if not set
3325       * @return mixed
3326       */
3327  	function get( $key, $default=null ) {
3328          return mosGetParam( $_SESSION, $key, $default );
3329      }
3330  
3331      /**
3332       * @param string Key to set
3333       * @param mixed Value to set
3334       * @return mixed The new value
3335       */
3336  	function set( $key, $value ) {
3337          $_SESSION[$key] = $value;
3338          return $value;
3339      }
3340  
3341      /**
3342       * Sets a key from a REQUEST variable, otherwise uses the default
3343       * @param string The variable key
3344       * @param string The REQUEST variable name
3345       * @param mixed The default value
3346       * @return mixed
3347       */
3348  	function setFromRequest( $key, $varName, $default=null ) {
3349          if (isset( $_REQUEST[$varName] )) {
3350              return mosSession::set( $key, $_REQUEST[$varName] );
3351          } else if (isset( $_SESSION[$key] )) {
3352              return $_SESSION[$key];
3353          } else {
3354              return mosSession::set( $key, $default );
3355          }
3356      }
3357  
3358      /**
3359       * Insert a new row
3360       * @return boolean
3361       */
3362  	function insert() {
3363          $ret = $this->_db->insertObject( $this->_tbl, $this );
3364  
3365          if( !$ret ) {
3366              $this->_error = strtolower(get_class( $this ))."::store failed <br />" . $this->_db->stderr();
3367              return false;
3368          } else {
3369              return true;
3370          }
3371      }
3372  
3373      /**
3374       * Update an existing row
3375       * @return boolean
3376       */
3377  	function update( $updateNulls=false ) {
3378          $ret = $this->_db->updateObject( $this->_tbl, $this, 'session_id', $updateNulls );
3379  
3380          if( !$ret ) {
3381              $this->_error = strtolower(get_class( $this ))."::store failed <br />" . $this->_db->stderr();
3382              return false;
3383          } else {
3384              return true;
3385          }
3386      }
3387  
3388      /**
3389       * Generate a unique session id
3390       * @return string
3391       */
3392  	function generateId() {
3393          $failsafe     = 20;
3394          $randnum     = 0;
3395  
3396          while ($failsafe--) {
3397              $randnum         = md5( uniqid( microtime(), 1 ) );
3398              $new_session_id = mosMainFrame::sessionCookieValue( $randnum );
3399  
3400              if ($randnum != '') {
3401                  $query = "SELECT $this->_tbl_key"
3402                  . "\n FROM $this->_tbl"
3403                  . "\n WHERE $this->_tbl_key = " . $this->_db->Quote( $new_session_id )
3404                  ;
3405                  $this->_db->setQuery( $query );
3406                  if(!$result = $this->_db->query()) {
3407                      die( $this->_db->stderr( true ));
3408                  }
3409  
3410                  if ($this->_db->getNumRows($result) == 0) {
3411                      break;
3412                  }
3413              }
3414          }
3415  
3416          $this->_session_cookie     = $randnum;
3417          $this->session_id         = $new_session_id;
3418      }
3419  
3420      /**
3421       * @return string The name of the session cookie
3422       */
3423  	function getCookie() {
3424          return $this->_session_cookie;
3425      }
3426  
3427      /**
3428       * Purge lapsed sessions
3429       * @return boolean
3430       */
3431  	function purge( $inc=1800, $and='' ) {
3432          global $mainframe;
3433  
3434          if ($inc == 'core') {
3435              $past_logged     = time() - $mainframe->getCfg( 'lifetime' );
3436              $past_guest     = time() - 900;
3437  
3438              $query = "DELETE FROM $this->_tbl"
3439              . "\n WHERE ("
3440              // purging expired logged sessions
3441              . "\n ( time < '" . (int) $past_logged . "' )"
3442              . "\n AND guest = 0"
3443              . "\n AND gid > 0"
3444              . "\n ) OR ("
3445              // purging expired guest sessions
3446              . "\n ( time < '" . (int) $past_guest . "' )"
3447              . "\n AND guest = 1"
3448              . "\n AND userid = 0"
3449              . "\n )"
3450              ;
3451          } else {
3452          // kept for backward compatability
3453              $past = time() - $inc;
3454              $query = "DELETE FROM $this->_tbl"
3455              . "\n WHERE ( time < '" . (int) $past . "' )"
3456              . $and
3457              ;
3458          }
3459          $this->_db->setQuery($query);
3460  
3461          return $this->_db->query();
3462      }
3463  }
3464  
3465  
3466  function mosObjectToArray($p_obj) {
3467      $retarray = null;
3468      if(is_object($p_obj))
3469      {
3470          $retarray = array();
3471          foreach (get_object_vars($p_obj) as $k => $v)
3472          {
3473              if(is_object($v))
3474              $retarray[$k] = mosObjectToArray($v);
3475              else
3476              $retarray[$k] = $v;
3477          }
3478      }
3479      return $retarray;
3480  }
3481  /**
3482  * Checks the user agent string against known browsers
3483  */
3484  function mosGetBrowser( $agent ) {
3485      global $mosConfig_absolute_path;
3486  
3487      require ( $mosConfig_absolute_path .'/includes/agent_browser.php' );
3488  
3489      if (preg_match( "/msie[\/\sa-z]*([\d\.]*)/i", $agent, $m )
3490      && !preg_match( "/webtv/i", $agent )
3491      && !preg_match( "/omniweb/i", $agent )
3492      && !preg_match( "/opera/i", $agent )) {
3493          // IE
3494          return "MS Internet Explorer $m[1]";
3495      } else if (preg_match( "/netscape.?\/([\d\.]*)/i", $agent, $m )) {
3496          // Netscape 6.x, 7.x ...
3497          return "Netscape $m[1]";
3498      } else if ( preg_match( "/mozilla[\/\sa-z]*([\d\.]*)/i", $agent, $m )
3499      && !preg_match( "/gecko/i", $agent )
3500      && !preg_match( "/compatible/i", $agent )
3501      && !preg_match( "/opera/i", $agent )
3502      && !preg_match( "/galeon/i", $agent )
3503      && !preg_match( "/safari/i", $agent )) {
3504          // Netscape 3.x, 4.x ...
3505          return "Netscape $m[1]";
3506      } else {
3507          // Other
3508          $found = false;
3509          foreach ($browserSearchOrder as $key) {
3510              if (preg_match( "/$key.?\/([\d\.]*)/i", $agent, $m )) {
3511                  $name = "$browsersAlias[$key] $m[1]";
3512                  return $name;
3513                  break;
3514              }
3515          }
3516      }
3517  
3518      return 'Unknown';
3519  }
3520  
3521  /**
3522  * Checks the user agent string against known operating systems
3523  */
3524  function mosGetOS( $agent ) {
3525      global $mosConfig_absolute_path;
3526  
3527      require ( $mosConfig_absolute_path .'/includes/agent_os.php' );
3528  
3529      foreach ($osSearchOrder as $key) {
3530          if (preg_match( "/$key/i", $agent )) {
3531              return $osAlias[$key];
3532              break;
3533          }
3534      }
3535  
3536      return 'Unknown';
3537  }
3538  
3539  /**
3540  * @param string SQL with ordering As value and 'name field' AS text
3541  * @param integer The length of the truncated headline
3542  */
3543  function mosGetOrderingList( $sql, $chop='30' ) {
3544      global $database;
3545  
3546      $order = array();
3547      $database->setQuery( $sql );
3548      if (!($orders = $database->loadObjectList())) {
3549          if ($database->getErrorNum()) {
3550              echo $database->stderr();
3551              return false;
3552          } else {
3553              $order[] = mosHTML::makeOption( 1, 'first' );
3554              return $order;
3555          }
3556      }
3557      $order[] = mosHTML::makeOption( 0, '0 first' );
3558      for ($i=0, $n=count( $orders ); $i < $n; $i++) {
3559  
3560          if (strlen($orders[$i]->text) > $chop) {
3561              $text = substr($orders[$i]->text,0,$chop)."...";
3562          } else {
3563              $text = $orders[$i]->text;
3564          }
3565  
3566          $order[] = mosHTML::makeOption( $orders[$i]->value, $orders[$i]->value.' ('.$text.')' );
3567      }
3568      $order[] = mosHTML::makeOption( $orders[$i-1]->value+1, ($orders[$i-1]->value+1).' last' );
3569  
3570      return $order;
3571  }
3572  
3573  /**
3574  * Makes a variable safe to display in forms
3575  *
3576  * Object parameters that are non-string, array, object or start with underscore
3577  * will be converted
3578  * @param object An object to be parsed
3579  * @param int The optional quote style for the htmlspecialchars function
3580  * @param string|array An optional single field name or array of field names not
3581  *                     to be parsed (eg, for a textarea)
3582  */
3583  function mosMakeHtmlSafe( &$mixed, $quote_style=ENT_QUOTES, $exclude_keys='' ) {
3584      if (is_object( $mixed )) {
3585          foreach (get_object_vars( $mixed ) as $k => $v) {
3586              if (is_array( $v ) || is_object( $v ) || $v == NULL || substr( $k, 1, 1 ) == '_' ) {
3587                  continue;
3588              }
3589              if (is_string( $exclude_keys ) && $k == $exclude_keys) {
3590                  continue;
3591              } else if (is_array( $exclude_keys ) && in_array( $k, $exclude_keys )) {
3592                  continue;
3593              }
3594              $mixed->$k = htmlspecialchars( $v, $quote_style );
3595          }
3596      }
3597  }
3598  
3599  /**
3600  * Checks whether a menu option is within the users access level
3601  * @param int Item id number
3602  * @param string The menu option
3603  * @param int The users group ID number
3604  * @param database A database connector object
3605  * @return boolean True if the visitor's group at least equal to the menu access
3606  */
3607  function mosMenuCheck( $Itemid, $menu_option, $task, $gid ) {
3608      global $database, $mainframe;
3609  
3610      if ( $Itemid != '' && $Itemid != 0 && $Itemid != 99999999 ) {
3611          $query = "SELECT *"
3612          . "\n FROM #__menu"
3613          . "\n WHERE id = " . (int) $Itemid
3614          ;
3615      } else {
3616          $dblink = "index.php?option=" . $database->getEscaped( $menu_option );
3617  
3618          if ($task != '') {
3619              $dblink    .= "&task=" . $database->getEscaped( $task );
3620          }
3621  
3622          $query = "SELECT *"
3623          . "\n FROM #__menu"
3624          . "\n WHERE published = 1 AND"
3625          . "\n link LIKE '$dblink%'"
3626          ;
3627      }
3628      $database->setQuery( $query );
3629      $results     = $database->loadObjectList();
3630      $access     = 0;
3631  
3632      foreach ($results as $result) {
3633          $access = max( $access, $result->access );
3634      }
3635  
3636      // save menu information to global mainframe
3637      if(isset($results[0])) {
3638          // loads menu info of particular Itemid
3639          $mainframe->set( 'menu', $results[0] );
3640      } else {
3641          // loads empty Menu info
3642          $mainframe->set( 'menu', new mosMenu($database) );
3643      }
3644  
3645      return ($access <= $gid);
3646  }
3647  
3648  /**
3649  * Returns formated date according to current local and adds time offset
3650  * @param string date in datetime format
3651  * @param string format optional format for strftime
3652  * @param offset time offset if different than global one
3653  * @returns formated date
3654  */
3655  function mosFormatDate( $date, $format="", $offset=NULL ){
3656      global $mosConfig_offset;
3657      if ( $format == '' ) {
3658          // %Y-%m-%d %H:%M:%S
3659          $format = _DATE_FORMAT_LC;
3660      }
3661      if ( is_null($offset) ) {
3662          $offset = $mosConfig_offset;
3663      }
3664      if ( $date && ereg( "([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})", $date, $regs ) ) {
3665          $date = mktime( $regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1] );
3666          $date = $date > -1 ? strftime( $format, $date + ($offset*60*60) ) : '-';
3667      }
3668      return $date;
3669  }
3670  
3671  /**
3672  * Returns current date according to current local and time offset
3673  * @param string format optional format for strftime
3674  * @returns current date
3675  */
3676  function mosCurrentDate( $format="" ) {
3677      global $mosConfig_offset;
3678      if ($format=="") {
3679          $format = _DATE_FORMAT_LC;
3680      }
3681      $date = strftime( $format, time() + ($mosConfig_offset*60*60) );
3682      return $date;
3683  }
3684  
3685  /**
3686  * Utility function to provide ToolTips
3687  * @param string ToolTip text
3688  * @param string Box title
3689  * @returns HTML code for ToolTip
3690  */
3691  function mosToolTip( $tooltip, $title='', $width='', $image='tooltip.png', $text='', $href='#', $link=1 ) {
3692      global $mosConfig_live_site;
3693  
3694      if ( $width ) {
3695          $width = ', WIDTH, \''.$width .'\'';
3696      }
3697      if ( $title ) {
3698          $title = ', CAPTION, \''.$title .'\'';
3699      }
3700      if ( !$text ) {
3701          $image     = $mosConfig_live_site . '/includes/js/ThemeOffice/'. $image;
3702          $text     = '<img src="'. $image .'" border="0" alt="tooltip"/>';
3703      }
3704      $style = 'style="text-decoration: none; color: #333;"';
3705      if ( $href ) {
3706          $style = '';
3707      } else{
3708          $href = '#';
3709      }
3710  
3711      $mousover = 'return overlib(\''. $tooltip .'\''. $title .', BELOW, RIGHT'. $width .');';
3712  
3713      $tip = "<!-- Tooltip -->\n";
3714      if ( $link ) {
3715          $tip .= '<a href="'. $href .'" onmouseover="'. $mousover .'" onmouseout="return nd();" '. $style .'>'. $text .'</a>';
3716      } else {
3717          $tip .= '<span onmouseover="'. $mousover .'" onmouseout="return nd();" '. $style .'>'. $text .'</span>';
3718      }
3719  
3720      return $tip;
3721  }
3722  
3723  /**
3724  * Utility function to provide Warning Icons
3725  * @param string Warning text
3726  * @param string Box title
3727  * @returns HTML code for Warning
3728  */
3729  function mosWarning($warning, $title='Joomla! Warning') {
3730      global $mosConfig_live_site;
3731  
3732      $mouseover     = 'return overlib(\''. $warning .'\', CAPTION, \''. $title .'\', BELOW, RIGHT);';
3733  
3734      $tip         = "<!-- Warning -->\n";
3735      $tip         .= '<a href="javascript:void(0)" onmouseover="'. $mouseover .'" onmouseout="return nd();">';
3736      $tip         .= '<img src="'. $mosConfig_live_site .'/includes/js/ThemeOffice/warning.png" border="0"  alt="warning"/></a>';
3737  
3738      return $tip;
3739  }
3740  
3741  function mosCreateGUID(){
3742      srand((double)microtime()*1000000);
3743      $r = rand();
3744      $u = uniqid(getmypid() . $r . (double)microtime()*1000000,1);
3745      $m = md5 ($u);
3746      return($m);
3747  }
3748  
3749  function mosCompressID( $ID ){
3750      return(Base64_encode(pack("H*",$ID)));
3751  }
3752  
3753  function mosExpandID( $ID ) {
3754      return ( implode(unpack("H*",Base64_decode($ID)), '') );
3755  }
3756  
3757  /**
3758  * Function to create a mail object for futher use (uses phpMailer)
3759  * @param string From e-mail address
3760  * @param string From name
3761  * @param string E-mail subject
3762  * @param string Message body
3763  * @return object Mail object
3764  */
3765  function mosCreateMail( $from='', $fromname='', $subject, $body ) {
3766      global $mosConfig_absolute_path, $mosConfig_sendmail;
3767      global $mosConfig_smtpauth, $mosConfig_smtpuser;
3768      global $mosConfig_smtppass, $mosConfig_smtphost;
3769      global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailer;
3770  
3771      $mail = new mosPHPMailer();
3772  
3773      $mail->PluginDir = $mosConfig_absolute_path .'/includes/phpmailer/';
3774      $mail->SetLanguage( 'en', $mosConfig_absolute_path . '/includes/phpmailer/language/' );
3775      $mail->CharSet     = substr_replace(_ISO, '', 0, 8);
3776      $mail->IsMail();
3777      $mail->From     = $from ? $from : $mosConfig_mailfrom;
3778      $mail->FromName = $fromname ? $fromname : $mosConfig_fromname;
3779      $mail->Mailer     = $mosConfig_mailer;
3780  
3781      // Add smtp values if needed
3782      if ( $mosConfig_mailer == 'smtp' ) {
3783          $mail->SMTPAuth = $mosConfig_smtpauth;
3784          $mail->Username = $mosConfig_smtpuser;
3785          $mail->Password = $mosConfig_smtppass;
3786          $mail->Host     = $mosConfig_smtphost;
3787      } else
3788  
3789      // Set sendmail path
3790      if ( $mosConfig_mailer == 'sendmail' ) {
3791          if (isset($mosConfig_sendmail))
3792              $mail->Sendmail = $mosConfig_sendmail;
3793      } // if
3794  
3795      $mail->Subject     = $subject;
3796      $mail->Body     = $body;
3797  
3798      return $mail;
3799  }
3800  
3801  /**
3802  * Mail function (uses phpMailer)
3803  * @param string From e-mail address
3804  * @param string From name
3805  * @param string/array Recipient e-mail address(es)
3806  * @param string E-mail subject
3807  * @param string Message body
3808  * @param boolean false = plain text, true = HTML
3809  * @param string/array CC e-mail address(es)
3810  * @param string/array BCC e-mail address(es)
3811  * @param string/array Attachment file name(s)
3812  * @param string/array ReplyTo e-mail address(es)
3813  * @param string/array ReplyTo name(s)
3814  * @return boolean
3815  */
3816  function mosMail( $from, $fromname, $recipient, $subject, $body, $mode=0, $cc=NULL, $bcc=NULL, $attachment=NULL, $replyto=NULL, $replytoname=NULL ) {
3817      global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_debug;
3818  
3819      // Allow empty $from and $fromname settings (backwards compatibility)
3820      if ($from == '') {
3821          $from = $mosConfig_mailfrom;
3822      }
3823      if ($fromname == '') {
3824          $fromname = $mosConfig_fromname;
3825      }
3826  
3827      // Filter from, fromname and subject
3828      if (!JosIsValidEmail( $from ) || !JosIsValidName( $fromname ) || !JosIsValidName( $subject )) {
3829          return false;
3830      }
3831  
3832      $mail = mosCreateMail( $from, $fromname, $subject, $body );
3833  
3834      // activate HTML formatted emails
3835      if ( $mode ) {
3836          $mail->IsHTML(true);
3837      }
3838  
3839      if (is_array( $recipient )) {
3840          foreach ($recipient as $to) {
3841              if (!JosIsValidEmail( $to )) {
3842                  return false;
3843              }
3844              $mail->AddAddress( $to );
3845          }
3846      } else {
3847          if (!JosIsValidEmail( $recipient )) {
3848              return false;
3849          }
3850          $mail->AddAddress( $recipient );
3851      }
3852      if (isset( $cc )) {
3853          if (is_array( $cc )) {
3854              foreach ($cc as $to) {
3855                  if (!JosIsValidEmail( $to )) {
3856                      return false;
3857                  }
3858                  $mail->AddCC($to);
3859              }
3860          } else {
3861              if (!JosIsValidEmail( $cc )) {
3862                  return false;
3863              }
3864              $mail->AddCC($cc);
3865          }
3866      }
3867      if (isset( $bcc )) {
3868          if (is_array( $bcc )) {
3869              foreach ($bcc as $to) {
3870                  if (!JosIsValidEmail( $to )) {
3871                      return false;
3872                  }
3873                  $mail->AddBCC( $to );
3874              }
3875          } else {
3876              if (!JosIsValidEmail( $bcc )) {
3877                  return false;
3878              }
3879              $mail->AddBCC( $bcc );
3880          }
3881      }
3882      if ($attachment) {
3883          if (is_array( $attachment )) {
3884              foreach ($attachment as $fname) {
3885                  $mail->AddAttachment( $fname );
3886              }
3887          } else {
3888              $mail->AddAttachment($attachment);
3889          }
3890      }
3891      //Important for being able to use mosMail without spoofing...
3892      if ($replyto) {
3893          if (is_array( $replyto )) {
3894              reset( $replytoname );
3895              foreach ($replyto as $to) {
3896                  $toname = ((list( $key, $value ) = each( $replytoname )) ? $value : '');
3897                  if (!JosIsValidEmail( $to ) || !JosIsValidName( $toname )) {
3898                      return false;
3899                  }
3900                  $mail->AddReplyTo( $to, $toname );
3901              }
3902          } else {
3903              if (!JosIsValidEmail( $replyto ) || !JosIsValidName( $replytoname )) {
3904                  return false;
3905              }
3906              $mail->AddReplyTo($replyto, $replytoname);
3907          }
3908      }
3909  
3910      $mailssend = $mail->Send();
3911  
3912      if( $mosConfig_debug ) {
3913          //$mosDebug->message( "Mails send: $mailssend");
3914      }
3915      if( $mail->error_count > 0 ) {
3916          //$mosDebug->message( "The mail message $fromname <$from> about $subject to $recipient <b>failed</b><br /><pre>$body</pre>", false );
3917          //$mosDebug->message( "Mailer Error: " . $mail->ErrorInfo . "" );
3918      }
3919      return $mailssend;
3920  } // mosMail
3921  
3922  /**
3923   * Checks if a given string is a valid email address
3924   *
3925   * @param    string    $email    String to check for a valid email address
3926   * @return    boolean
3927   */
3928  function JosIsValidEmail( $email ) {
3929      $valid = preg_match( '/^[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}$/', $email );
3930  
3931      return $valid;
3932  }
3933  
3934  /**
3935   * Checks if a given string is a valid (from-)name or subject for an email
3936   *
3937   * @since        1.0.11
3938   * @deprecated    1.5
3939   * @param        string        $string        String to check for validity
3940   * @return        boolean
3941   */
3942  function JosIsValidName( $string ) {
3943      /*
3944       * The following regular expression blocks all strings containing any low control characters:
3945       * 0x00-0x1F, 0x7F
3946       * These should be control characters in almost all used charsets.
3947       * The high control chars in ISO-8859-n (0x80-0x9F) are unused (e.g. http://en.wikipedia.org/wiki/ISO_8859-1)
3948       * Since they are valid UTF-8 bytes (e.g. used as the second byte of a two byte char),
3949       * they must not be filtered.
3950       */
3951      $invalid = preg_match( '/[\x00-\x1F\x7F]/', $string );
3952      if ($invalid) {
3953          return false;
3954      } else {
3955          return true;
3956      }
3957  }
3958  
3959  /**
3960   * Initialise GZIP
3961   */
3962  function initGzip() {
3963      global $mosConfig_gzip, $do_gzip_compress;
3964  
3965      $do_gzip_compress = FALSE;
3966      if ($mosConfig_gzip == 1) {
3967          $phpver     = phpversion();
3968          $useragent     = mosGetParam( $_SERVER, 'HTTP_USER_AGENT', '' );
3969          $canZip     = mosGetParam( $_SERVER, 'HTTP_ACCEPT_ENCODING', '' );
3970  
3971          $gzip_check     = 0;
3972          $zlib_check     = 0;
3973          $gz_check        = 0;
3974          $zlibO_check    = 0;
3975          $sid_check        = 0;
3976          if ( strpos( $canZip, 'gzip' ) !== false) {
3977              $gzip_check = 1;
3978          }
3979          if ( extension_loaded( 'zlib' ) ) {
3980              $zlib_check = 1;
3981          }
3982          if ( function_exists('ob_gzhandler') ) {
3983              $gz_check = 1;
3984          }
3985          if ( ini_get('zlib.output_compression') ) {
3986              $zlibO_check = 1;
3987          }
3988          if ( ini_get('session.use_trans_sid') ) {
3989              $sid_check = 1;
3990          }
3991  
3992          if ( $phpver >= '4.0.4pl1' && ( strpos($useragent,'compatible') !== false || strpos($useragent,'Gecko')    !== false ) ) {
3993              // Check for gzip header or northon internet securities or session.use_trans_sid
3994              if ( ( $gzip_check || isset( $_SERVER['---------------']) ) && $zlib_check && $gz_check && !$zlibO_check && !$sid_check ) {
3995                  // You cannot specify additional output handlers if
3996                  // zlib.output_compression is activated here
3997                  ob_start( 'ob_gzhandler' );
3998                  return;
3999              }
4000          } else if ( $phpver > '4.0' ) {
4001              if ( $gzip_check ) {
4002                  if ( $zlib_check ) {
4003                      $do_gzip_compress = TRUE;
4004                      ob_start();
4005                      ob_implicit_flush(0);
4006  
4007                      header( 'Content-Encoding: gzip' );
4008                      return;
4009                  }
4010              }
4011          }
4012      }
4013      ob_start();
4014  }
4015  
4016  /**
4017  * Perform GZIP
4018  */
4019  function doGzip() {
4020      global $do_gzip_compress;
4021      if ( $do_gzip_compress ) {
4022          /**
4023          *Borrowed from php.net!
4024          */
4025          $gzip_contents = ob_get_contents();
4026          ob_end_clean();
4027  
4028          $gzip_size = strlen($gzip_contents);
4029          $gzip_crc = crc32($gzip_contents);
4030  
4031          $gzip_contents = gzcompress($gzip_contents, 9);
4032          $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
4033  
4034          echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
4035          echo $gzip_contents;
4036          echo pack('V', $gzip_crc);
4037          echo pack('V', $gzip_size);
4038      } else {
4039          ob_end_flush();
4040      }
4041  }
4042  
4043  /**
4044  * Random password generator
4045  * @return password
4046  */
4047  function mosMakePassword($length=8) {
4048      $salt         = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
4049      $makepass    = '';
4050      mt_srand(10000000*(double)microtime());
4051      for ($i = 0; $i < $length; $i++)
4052          $makepass .= $salt[mt_rand(0,61)];
4053      return $makepass;
4054  }
4055  
4056  if (!function_exists('html_entity_decode')) {
4057      /**
4058      * html_entity_decode function for backward compatability in PHP
4059      * @param string
4060      * @param string
4061      */
4062  	function html_entity_decode ($string, $opt = ENT_COMPAT) {
4063  
4064          $trans_tbl = get_html_translation_table (HTML_ENTITIES);
4065          $trans_tbl = array_flip ($trans_tbl);
4066  
4067          if ($opt & 1) { // Translating single quotes
4068              // Add single quote to translation table;
4069              // doesn't appear to be there by default
4070              $trans_tbl["&apos;"] = "'";
4071          }
4072  
4073          if (!($opt & 2)) { // Not translating double quotes
4074              // Remove double quote from translation table
4075              unset($trans_tbl["&quot;"]);
4076          }
4077  
4078          return strtr ($string, $trans_tbl);
4079      }
4080  }
4081  
4082  /**
4083  * Plugin handler
4084  * @package Joomla
4085  */
4086  class mosMambotHandler {
4087      /** @var array An array of functions in event groups */
4088      var $_events            = null;
4089      /** @var array An array of lists */
4090      var $_lists                = null;
4091      /** @var array An array of mambots */
4092      var $_bots                = null;
4093      /** @var int Index of the mambot being loaded */
4094      var $_loading            = null;
4095  
4096      /** Added as of 1.0.8 to ensure queries are only called once **/
4097  
4098      /** @var array An array of the content mambots in the system */
4099      var $_content_mambots    = null;
4100      /** @var array An array of the content mambot params */
4101      var $_content_mambot_params    = array();
4102      /** @var array An array of the content mambot params */
4103      var $_search_mambot_params    = array();
4104  
4105      /**
4106      * Constructor
4107      */
4108  	function mosMambotHandler() {
4109          $this->_events = array();
4110      }
4111      /**
4112      * Loads all the bot files for a particular group
4113      * @param string The group name, relates to the sub-directory in the mambots directory
4114      */
4115  	function loadBotGroup( $group ) {
4116          global $database, $my;
4117  
4118          $group = trim( $group );
4119          if (is_object( $my )) {
4120              $gid = $my->gid;
4121          } else {
4122              $gid = 0;
4123          }
4124  
4125          $group = trim( $group );
4126  
4127          switch ( $group ) {
4128              case 'content':
4129                  if (!defined( '_JOS_CONTENT_MAMBOTS' )) {
4130                      /** ensure that query is only called once */
4131                      define( '_JOS_CONTENT_MAMBOTS', 1 );
4132  
4133                      $query = "SELECT folder, element, published, params"
4134                      . "\n FROM #__mambots"
4135                      . "\n WHERE access <= " . (int) $gid
4136                      . "\n AND folder = 'content'"
4137                      . "\n ORDER BY ordering"
4138                      ;
4139                      $database->setQuery( $query );
4140  
4141                      // load query into class variable _content_mambots
4142                      if (!($this->_content_mambots = $database->loadObjectList())) {
4143                          //echo "Error loading Mambots: " . $database->getErrorMsg();
4144                          return false;
4145                      }
4146                  }
4147  
4148                  // pull bots to be processed from class variable
4149                  $bots = $this->_content_mambots;
4150                  break;
4151  
4152              default:
4153                  $query = "SELECT folder, element, published, params"
4154                  . "\n FROM #__mambots"
4155                  . "\n WHERE published >= 1"
4156                  . "\n AND access <= " . (int) $gid
4157                  . "\n AND folder = " . $database->Quote( $group )
4158                  . "\n ORDER BY ordering"
4159                  ;
4160                  $database->setQuery( $query );
4161  
4162                  if (!($bots = $database->loadObjectList())) {
4163                      //echo "Error loading Mambots: " . $database->getErrorMsg();
4164                      return false;
4165                  }
4166                  break;
4167          }
4168  
4169          // load bots found by queries
4170          $n = count( $bots);
4171          for ($i = 0; $i < $n; $i++) {
4172              $this->loadBot( $bots[$i]->folder, $bots[$i]->element, $bots[$i]->published, $bots[$i]->params );
4173          }
4174  
4175          return true;
4176      }
4177      /**
4178       * Loads the bot file
4179       * @param string The folder (group)
4180       * @param string The elements (name of file without extension)
4181       * @param int Published state
4182       * @param string The params for the bot
4183       */
4184  	function loadBot( $folder, $element, $published, $params='' ) {
4185          global $mosConfig_absolute_path;
4186          global $_MAMBOTS;
4187  
4188          $path = $mosConfig_absolute_path . '/mambots/' . $folder . '/' . $element . '.php';
4189          if (file_exists( $path )) {
4190              $this->_loading = count( $this->_bots );
4191              $bot = new stdClass;
4192              $bot->folder     = $folder;
4193              $bot->element     = $element;
4194              $bot->published = $published;
4195              $bot->lookup     = $folder . '/' . $element;
4196              $bot->params     = $params;
4197              $this->_bots[]     = $bot;
4198  
4199              require_once( $path );
4200  
4201              $this->_loading = null;
4202          }
4203      }
4204      /**
4205      * Registers a function to a particular event group
4206      * @param string The event name
4207      * @param string The function name
4208      */
4209  	function registerFunction( $event, $function ) {
4210          $this->_events[$event][] = array( $function, $this->_loading );
4211      }
4212      /**
4213      * Makes a option for a particular list in a group
4214      * @param string The group name
4215      * @param string The list name
4216      * @param string The value for the list option
4217      * @param string The text for the list option
4218      */
4219  	function addListOption( $group, $listName, $value, $text='' ) {
4220          $this->_lists[$group][$listName][] = mosHTML::makeOption( $value, $text );
4221      }
4222      /**
4223      * @param string The group name
4224      * @param string The list name
4225      * @return array
4226      */
4227  	function getList( $group, $listName ) {
4228          return $this->_lists[$group][$listName];
4229      }
4230      /**
4231      * Calls all functions associated with an event group
4232      * @param string The event name
4233      * @param array An array of arguments
4234      * @param boolean True is unpublished bots are to be processed
4235      * @return array An array of results from each function call
4236      */
4237  	function trigger( $event, $args=null, $doUnpublished=false ) {
4238          $result = array();
4239  
4240          if ($args === null) {
4241              $args = array();
4242          }
4243          if ($doUnpublished) {
4244              // prepend the published argument
4245              array_unshift( $args, null );
4246          }
4247          if (isset( $this->_events[$event] )) {
4248              foreach ($this->_events[$event] as $func) {
4249                  if (function_exists( $func[0] )) {
4250                      if ($doUnpublished) {
4251                          $args[0] = $this->_bots[$func[1]]->published;
4252                          $result[] = call_user_func_array( $func[0], $args );
4253                      } else if ($this->_bots[$func[1]]->published) {
4254                          $result[] = call_user_func_array( $func[0], $args );
4255                      }
4256                  }
4257              }
4258          }
4259          return $result;
4260      }
4261      /**
4262      * Same as trigger but only returns the first event and
4263      * allows for a variable argument list
4264      * @param string The event name
4265      * @return array The result of the first function call
4266      */
4267  	function call( $event ) {
4268          $doUnpublished=false;
4269  
4270          $args =& func_get_args();
4271          array_shift( $args );
4272  
4273          if (isset( $this->_events[$event] )) {
4274              foreach ($this->_events[$event] as $func) {
4275                  if (function_exists( $func[0] )) {
4276                      if ($this->_bots[$func[1]]->published) {
4277                          return call_user_func_array( $func[0], $args );
4278                      }
4279                  }
4280              }
4281          }
4282          return null;
4283      }
4284  }
4285  
4286  /**
4287  * Tab Creation handler
4288  * @package Joomla
4289  */
4290  class mosTabs {
4291      /** @var int Use cookies */
4292      var $useCookies = 0;
4293  
4294      /**
4295      * Constructor
4296      * Includes files needed for displaying tabs and sets cookie options
4297      * @param int useCookies, if set to 1 cookie will hold last used tab between page refreshes
4298      */
4299  	function mosTabs( $useCookies, $xhtml=NULL ) {
4300          global $mosConfig_live_site, $mainframe;
4301  
4302          if ( $xhtml ) {
4303              $mainframe->addCustomHeadTag( '<link rel="stylesheet" type="text/css" media="all" href="includes/js/tabs/tabpane.css" id="luna-tab-style-sheet" />' );
4304          } else {
4305              echo "<link id=\"luna-tab-style-sheet\" type=\"text/css\" rel=\"stylesheet\" href=\"" . $mosConfig_live_site. "/includes/js/tabs/tabpane.css\" />";
4306          }
4307  
4308          echo "<script type=\"text/javascript\" src=\"". $mosConfig_live_site . "/includes/js/tabs/tabpane_mini.js\"></script>";
4309  
4310          $this->useCookies = $useCookies;
4311      }
4312  
4313      /**
4314      * creates a tab pane and creates JS obj
4315      * @param string The Tab Pane Name
4316      */
4317  	function startPane($id){
4318          echo "<div class=\"tab-pane\" id=\"".$id."\">";
4319          echo "<script type=\"text/javascript\">\n";
4320          echo "    var tabPane1 = new WebFXTabPane( document.getElementById( \"".$id."\" ), ".$this->useCookies." )\n";
4321          echo "</script>\n";
4322      }
4323  
4324      /**
4325      * Ends Tab Pane
4326      */
4327  	function endPane() {
4328          echo "</div>";
4329      }
4330  
4331      /*
4332      * Creates a tab with title text and starts that tabs page
4333      * @param tabText - This is what is displayed on the tab
4334      * @param paneid - This is the parent pane to build this tab on
4335      */
4336  	function startTab( $tabText, $paneid ) {
4337          echo "<div class=\"tab-page\" id=\"".$paneid."\">";
4338          echo "<h2 class=\"tab\">".$tabText."</h2>";
4339          echo "<script type=\"text/javascript\">\n";
4340          echo "  tabPane1.addTabPage( document.getElementById( \"".$paneid."\" ) );";
4341          echo "</script>";
4342      }
4343  
4344      /*
4345      * Ends a tab page
4346      */
4347  	function endTab() {
4348          echo "</div>";
4349      }
4350  }
4351  
4352  /**
4353  * Common HTML Output Files
4354  * @package Joomla
4355  */
4356  class mosAdminMenus {
4357      /**
4358      * build the select list for Menu Ordering
4359      */
4360  	function Ordering( &$row, $id ) {
4361          global $database;
4362  
4363          if ( $id ) {
4364              $query = "SELECT ordering AS value, name AS text"
4365              . "\n FROM #__menu"
4366              . "\n WHERE menutype = " . $database->Quote ( $row->menutype )
4367              . "\n AND parent = " . (int) $row->parent
4368              . "\n AND published != -2"
4369              . "\n ORDER BY ordering"
4370              ;
4371              $order = mosGetOrderingList( $query );
4372              $ordering = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"', 'value', 'text', intval( $row->ordering ) );
4373          } else {
4374              $ordering = '<input type="hidden" name="ordering" value="'. $row->ordering .'" />'. _CMN_NEW_ITEM_LAST;
4375          }
4376          return $ordering;
4377      }
4378  
4379      /**
4380      * build the select list for access level
4381      */
4382  	function Access( &$row ) {
4383          global $database;
4384  
4385          $query = "SELECT id AS value, name AS text"
4386          . "\n FROM #__groups"
4387          . "\n ORDER BY id"
4388          ;
4389          $database->setQuery( $query );
4390          $groups = $database->loadObjectList();
4391          $access = mosHTML::selectList( $groups, 'access', 'class="inputbox" size="3"', 'value', 'text', intval( $row->access ) );
4392  
4393          return $access;
4394      }
4395  
4396      /**
4397      * build the select list for parent item
4398      */
4399  	function Parent( &$row ) {
4400          global $database;
4401  
4402          $id = '';
4403          if ( $row->id ) {
4404              $id = "\n AND id != " . (int) $row->id;
4405          }
4406  
4407          // get a list of the menu items
4408          // excluding the current menu item and its child elements
4409          $query = "SELECT m.*"
4410          . "\n FROM #__menu m"
4411          . "\n WHERE menutype = " . $database->Quote( $row->menutype )
4412          . "\n AND published != -2"
4413          . $id
4414          . "\n ORDER BY parent, ordering"
4415          ;
4416          $database->setQuery( $query );
4417          $mitems = $database->loadObjectList();
4418  
4419          // establish the hierarchy of the menu
4420          $children = array();
4421  
4422          if ( $mitems ) {
4423              // first pass - collect children
4424              foreach ( $mitems as $v ) {
4425                  $pt     = $v->parent;
4426                  $list     = @$children[$pt] ? $children[$pt] : array();
4427                  array_push( $list, $v );
4428                  $children[$pt] = $list;
4429              }
4430          }
4431  
4432          // second pass - get an indent list of the items
4433          $list = mosTreeRecurse( 0, '', array(), $children, 20, 0, 0 );
4434  
4435          // assemble menu items to the array
4436          $mitems     = array();
4437          $mitems[]     = mosHTML::makeOption( '0', 'Top' );
4438  
4439          foreach ( $list as $item ) {
4440              $mitems[] = mosHTML::makeOption( $item->id, '&nbsp;&nbsp;&nbsp;'. $item->treename );
4441          }
4442  
4443          $output = mosHTML::selectList( $mitems, 'parent', 'class="inputbox" size="10"', 'value', 'text', $row->parent );
4444  
4445          return $output;
4446      }
4447  
4448      /**
4449      * build a radio button option for published state
4450      */
4451  	function Published( &$row ) {
4452          $published = mosHTML::yesnoRadioList( 'published', 'class="inputbox"', $row->published );
4453          return $published;
4454      }
4455  
4456      /**
4457      * build the link/url of a menu item
4458      */
4459  	function Link( &$row, $id, $link=NULL ) {
4460          global $mainframe;
4461  
4462          if ( $id ) {
4463              switch ($row->type) {
4464                  case 'content_item_link':
4465                  case 'content_typed':
4466                      // load menu params
4467                      $params = new mosParameters( $row->params, $mainframe->getPath( 'menu_xml', $row->type ), 'menu' );
4468  
4469                      if ( $params->get( 'unique_itemid' ) ) {
4470                          $row->link .= '&Itemid='. $row->id;
4471                      } else {
4472                          $temp = split( '&task=view&id=', $row->link);
4473                          $row->link .= '&Itemid='. $mainframe->getItemid($temp[1], 0, 0);
4474                      }
4475  
4476                      $link = $row->link;
4477                      break;
4478  
4479                  default:
4480                      if ( $link ) {
4481                          $link = $row->link;
4482                      } else {
4483                          $link = $row->link .'&amp;Itemid='. $row->id;
4484                      }
4485                      break;
4486              }
4487          } else {
4488              $link = NULL;
4489          }
4490  
4491          return $link;
4492      }
4493  
4494      /**
4495      * build the select list for target window
4496      */
4497  	function Target( &$row ) {
4498          $click[] = mosHTML::makeOption( '0', 'Parent Window With Browser Navigation' );
4499          $click[] = mosHTML::makeOption( '1', 'New Window With Browser Navigation' );
4500          $click[] = mosHTML::makeOption( '2', 'New Window Without Browser Navigation' );
4501          $target = mosHTML::selectList( $click, 'browserNav', 'class="inputbox" size="4"', 'value', 'text', intval( $row->browserNav ) );
4502          return $target;
4503      }
4504  
4505      /**
4506      * build the multiple select list for Menu Links/Pages
4507      */
4508  	function MenuLinks( &$lookup, $all=NULL, $none=NULL, $unassigned=1 ) {
4509          global $database;
4510  
4511          // get a list of the menu items
4512          $query = "SELECT m.*"
4513          . "\n FROM #__menu AS m"
4514          . "\n WHERE m.published = 1"
4515          //. "\n AND m.type != 'separator'"
4516          //. "\n AND NOT ("
4517          //    . "\n ( m.type = 'url' )"
4518          //    . "\n AND ( m.link LIKE '%index.php%' )"
4519          //    . "\n AND ( m.link LIKE '%Itemid=%' )"
4520          //. "\n )"
4521          . "\n ORDER BY m.menutype, m.parent, m.ordering"
4522          ;
4523          $database->setQuery( $query );
4524          $mitems = $database->loadObjectList();
4525          $mitems_temp = $mitems;
4526  
4527          // establish the hierarchy of the menu
4528          $children = array();
4529          // first pass - collect children
4530          foreach ( $mitems as $v ) {
4531              $id = $v->id;
4532              $pt = $v->parent;
4533              $list = @$children[$pt] ? $children[$pt] : array();
4534              array_push( $list, $v );
4535              $children[$pt] = $list;
4536          }
4537          // second pass - get an indent list of the items
4538          $list = mosTreeRecurse( intval( $mitems[0]->parent ), '', array(), $children, 20, 0, 0 );
4539  
4540          // Code that adds menu name to Display of Page(s)
4541          $text_count     = 0;
4542          $mitems_spacer     = $mitems_temp[0]->menutype;
4543          foreach ($list as $list_a) {
4544              foreach ($mitems_temp as $mitems_a) {
4545                  if ($mitems_a->id == $list_a->id) {
4546                      // Code that inserts the blank line that seperates different menus
4547                      if ($mitems_a->menutype != $mitems_spacer) {
4548                          $list_temp[]     = mosHTML::makeOption( -999, '----' );
4549                          $mitems_spacer     = $mitems_a->menutype;
4550                      }
4551  
4552                      // do not display `url` menu item types that contain `index.php` and `Itemid`
4553                      if (!($mitems_a->type == 'url' && strpos($mitems_a->link, 'index.php') !== false && strpos($mitems_a->link, 'Itemid=') !== false)) {
4554                          $text             = $mitems_a->menutype .' | '. $list_a->treename;
4555                          $list_temp[]     = mosHTML::makeOption( $list_a->id, $text );
4556  
4557                          if ( strlen($text) > $text_count) {
4558                              $text_count = strlen($text);
4559                          }
4560                      }
4561                  }
4562              }
4563          }
4564          $list = $list_temp;
4565  
4566          $mitems = array();
4567          if ( $all ) {
4568              // prepare an array with 'all' as the first item
4569              $mitems[] = mosHTML::makeOption( 0, 'All' );
4570              // adds space, in select box which is not saved
4571              $mitems[] = mosHTML::makeOption( -999, '----' );
4572          }
4573          if ( $none ) {
4574              // prepare an array with 'all' as the first item
4575              $mitems[] = mosHTML::makeOption( -999, 'None' );
4576              // adds space, in select box which is not saved
4577              $mitems[] = mosHTML::makeOption( -999, '----' );
4578          }
4579          if ( $unassigned ) {
4580              // prepare an array with 'all' as the first item
4581              $mitems[] = mosHTML::makeOption( 99999999, 'Unassigned' );
4582              // adds space, in select box which is not saved
4583              $mitems[] = mosHTML::makeOption( -999, '----' );
4584          }
4585  
4586          // append the rest of the menu items to the array
4587          foreach ($list as $item) {
4588              $mitems[] = mosHTML::makeOption( $item->value, $item->text );
4589          }
4590          $pages = mosHTML::selectList( $mitems, 'selections[]', 'class="inputbox" size="26" multiple="multiple"', 'value', 'text', $lookup );
4591          return $pages;
4592      }
4593  
4594  
4595      /**
4596      * build the select list to choose a category
4597      */
4598  	function Category( &$menu, $id, $javascript='' ) {
4599          global $database;
4600  
4601          $query = "SELECT c.id AS `value`, c.section AS `id`, CONCAT_WS( ' / ', s.title, c.title) AS `text`"
4602          . "\n FROM #__sections AS s"
4603          . "\n INNER JOIN #__categories AS c ON c.section = s.id"
4604          . "\n WHERE s.scope = 'content'"
4605          . "\n ORDER BY s.name, c.name"
4606          ;
4607          $database->setQuery( $query );
4608          $rows = $database->loadObjectList();
4609          $category = '';
4610          if ( $id ) {
4611              foreach ( $rows as $row ) {
4612                  if ( $row->value == $menu->componentid ) {
4613                      $category = $row->text;
4614                  }
4615              }
4616              $category .= '<input type="hidden" name="componentid" value="'. $menu->componentid .'" />';
4617              $category .= '<input type="hidden" name="link" value="'. $menu->link .'" />';
4618          } else {
4619              $category = mosHTML::selectList( $rows, 'componentid', 'class="inputbox" size="10"'. $javascript, 'value', 'text' );
4620              $category .= '<input type="hidden" name="link" value="" />';
4621          }
4622          return $category;
4623      }
4624  
4625      /**
4626      * build the select list to choose a section
4627      */
4628  	function Section( &$menu, $id, $all=0 ) {
4629          global $database;
4630  
4631          $query = "SELECT s.id AS `value`, s.id AS `id`, s.title AS `text`"
4632          . "\n FROM #__sections AS s"
4633          . "\n WHERE s.scope = 'content'"
4634          . "\n ORDER BY s.name"
4635          ;
4636          $database->setQuery( $query );
4637          if ( $all ) {
4638              $rows[] = mosHTML::makeOption( 0, '- All Sections -' );
4639              $rows = array_merge( $rows, $database->loadObjectList() );
4640          } else {
4641              $rows = $database->loadObjectList();
4642          }
4643  
4644          if ( $id ) {
4645              foreach ( $rows as $row ) {
4646                  if ( $row->value == $menu->componentid ) {
4647                      $section = $row->text;
4648                  }
4649              }
4650              $section .= '<input type="hidden" name="componentid" value="'. $menu->componentid .'" />';
4651              $section .= '<input type="hidden" name="link" value="'. $menu->link .'" />';
4652          } else {
4653              $section = mosHTML::selectList( $rows, 'componentid', 'class="inputbox" size="10"', 'value', 'text' );
4654              $section .= '<input type="hidden" name="link" value="" />';
4655          }
4656          return $section;
4657      }
4658  
4659      /**
4660      * build the select list to choose a component
4661      */
4662  	function Component( &$menu, $id ) {
4663          global $database;
4664  
4665          $query = "SELECT c.id AS value, c.name AS text, c.link"
4666          . "\n FROM #__components AS c"
4667          . "\n WHERE c.link != ''"
4668          . "\n ORDER BY c.name"
4669          ;
4670          $database->setQuery( $query );
4671          $rows = $database->loadObjectList( );
4672  
4673          if ( $id ) {
4674              // existing component, just show name
4675              foreach ( $rows as $row ) {
4676                  if ( $row->value == $menu->componentid ) {
4677                      $component = $row->text;
4678                  }
4679              }
4680              $component .= '<input type="hidden" name="componentid" value="'. $menu->componentid .'" />';
4681          } else {
4682              $component = mosHTML::selectList( $rows, 'componentid', 'class="inputbox" size="10"', 'value', 'text' );
4683          }
4684          return $component;
4685      }
4686  
4687      /**
4688      * build the select list to choose a component
4689      */
4690  	function ComponentName( &$menu, $id ) {
4691          global $database;
4692  
4693          $query = "SELECT c.id AS value, c.name AS text, c.link"
4694          . "\n FROM #__components AS c"
4695          . "\n WHERE c.link != ''"
4696          . "\n ORDER BY c.name"
4697          ;
4698          $database->setQuery( $query );
4699          $rows = $database->loadObjectList( );
4700  
4701          $component = 'Component';
4702          foreach ( $rows as $row ) {
4703              if ( $row->value == $menu->componentid ) {
4704                  $component = $row->text;
4705              }
4706          }
4707  
4708          return $component;
4709      }
4710  
4711      /**
4712      * build the select list to choose an image
4713      */
4714  	function Images( $name, &$active, $javascript=NULL, $directory=NULL ) {
4715          global $mosConfig_absolute_path;
4716  
4717          if ( !$directory ) {
4718              $directory = '/images/stories';
4719          }
4720  
4721          if ( !$javascript ) {
4722              $javascript = "onchange=\"javascript:if (document.forms[0].image.options[selectedIndex].value!='') {document.imagelib.src='..$directory/' + document.forms[0].image.options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
4723          }
4724  
4725          $imageFiles = mosReadDirectory( $mosConfig_absolute_path . $directory );
4726          $images     = array(  mosHTML::makeOption( '', '- Select Image -' ) );
4727          foreach ( $imageFiles as $file ) {
4728              if ( eregi( "bmp|gif|jpg|png", $file ) ) {
4729                  $images[] = mosHTML::makeOption( $file );
4730              }
4731          }
4732          $images = mosHTML::selectList( $images, $name, 'class="inputbox" size="1" '. $javascript, 'value', 'text', $active );
4733  
4734          return $images;
4735      }
4736  
4737      /**
4738      * build the select list for Ordering of a specified Table
4739      */
4740  	function SpecificOrdering( &$row, $id, $query, $neworder=0 ) {
4741          global $database;
4742  
4743          if ( $neworder ) {
4744              $text = _CMN_NEW_ITEM_FIRST;
4745          } else {
4746              $text = _CMN_NEW_ITEM_LAST;
4747          }
4748  
4749          if ( $id ) {
4750              $order = mosGetOrderingList( $query );
4751              $ordering = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"', 'value', 'text', intval( $row->ordering ) );
4752          } else {
4753              $ordering = '<input type="hidden" name="ordering" value="'. $row->ordering .'" />'. $text;
4754          }
4755          return $ordering;
4756      }
4757  
4758      /**
4759      * Select list of active users
4760      */
4761  	function UserSelect( $name, $active, $nouser=0, $javascript=NULL, $order='name', $reg=1 ) {
4762          global $database, $my;
4763  
4764          $and = '';
4765          if ( $reg ) {
4766          // does not include registered users in the list
4767              $and = "\n AND gid > 18";
4768          }
4769  
4770          $query = "SELECT id AS value, name AS text"
4771          . "\n FROM #__users"
4772          . "\n WHERE block = 0"
4773          . $and
4774          . "\n ORDER BY $order"
4775          ;
4776          $database->setQuery( $query );
4777          if ( $nouser ) {
4778              $users[] = mosHTML::makeOption( '0', '- No User -' );
4779              $users = array_merge( $users, $database->loadObjectList() );
4780          } else {
4781              $users = $database->loadObjectList();
4782          }
4783  
4784          $users = mosHTML::selectList( $users, $name, 'class="inputbox" size="1" '. $javascript, 'value', 'text', $active );
4785  
4786          return $users;
4787      }
4788  
4789      /**
4790      * Select list of positions - generally used for location of images
4791      */
4792  	function Positions( $name, $active=NULL, $javascript=NULL, $none=1, $center=1, $left=1, $right=1 ) {
4793          if ( $none ) {
4794              $pos[] = mosHTML::makeOption( '', _CMN_NONE );
4795          }
4796          if ( $center ) {
4797              $pos[] = mosHTML::makeOption( 'center', _CMN_CENTER );
4798          }
4799          if ( $left ) {
4800              $pos[] = mosHTML::makeOption( 'left', _CMN_LEFT );
4801          }
4802          if ( $right ) {
4803              $pos[] = mosHTML::makeOption( 'right', _CMN_RIGHT );
4804          }
4805  
4806          $positions = mosHTML::selectList( $pos, $name, 'class="inputbox" size="1"'. $javascript, 'value', 'text', $active );
4807  
4808          return $positions;
4809      }
4810  
4811      /**
4812      * Select list of active categories for components
4813      */
4814  	function ComponentCategory( $name, $section, $active=NULL, $javascript=NULL, $order='ordering', $size=1, $sel_cat=1 ) {
4815          global $database;
4816  
4817          $query = "SELECT id AS value, name AS text"
4818          . "\n FROM #__categories"
4819          . "\n WHERE section = " . $database->Quote( $section )
4820          . "\n AND published = 1"
4821          . "\n ORDER BY $order"
4822          ;
4823          $database->setQuery( $query );
4824          if ( $sel_cat ) {
4825              $categories[] = mosHTML::makeOption( '0', _SEL_CATEGORY );
4826              $categories = array_merge( $categories, $database->loadObjectList() );
4827          } else {
4828              $categories = $database->loadObjectList();
4829          }
4830  
4831          if ( count( $categories ) < 1 ) {
4832              mosRedirect( 'index2.php?option=com_categories&section='. $section, 'You must create a category first.' );
4833          }
4834  
4835          $category = mosHTML::selectList( $categories, $name, 'class="inputbox" size="'. $size .'" '. $javascript, 'value', 'text', $active );
4836  
4837          return $category;
4838      }
4839  
4840      /**
4841      * Select list of active sections
4842      */
4843  	function SelectSection( $name, $active=NULL, $javascript=NULL, $order='ordering' ) {
4844          global $database;
4845  
4846          $categories[] = mosHTML::makeOption( '0', _SEL_SECTION );
4847          $query = "SELECT id AS value, title AS text"
4848          . "\n FROM #__sections"
4849          . "\n WHERE published = 1"
4850          . "\n ORDER BY $order"
4851          ;
4852          $database->setQuery( $query );
4853          $sections = array_merge( $categories, $database->loadObjectList() );
4854  
4855          $category = mosHTML::selectList( $sections, $name, 'class="inputbox" size="1" '. $javascript, 'value', 'text', $active );
4856  
4857          return $category;
4858      }
4859  
4860      /**
4861      * Select list of menu items for a specific menu
4862      */
4863  	function Links2Menu( $type, $and ) {
4864          global $database;
4865  
4866          $query = "SELECT *"
4867          . "\n FROM #__menu"
4868          . "\n WHERE type = " . $database->Quote( $type )
4869          . "\n AND published = 1"
4870          . $and
4871          ;
4872          $database->setQuery( $query );
4873          $menus = $database->loadObjectList();
4874  
4875          return $menus;
4876      }
4877  
4878      /**
4879       * Select list of menus
4880       * @param string The control name
4881       * @param string Additional javascript
4882       * @return string A select list
4883       */
4884  	function MenuSelect( $name='menuselect', $javascript=NULL ) {
4885          global $database;
4886  
4887          $query = "SELECT params"
4888          . "\n FROM #__modules"
4889          . "\n WHERE module = 'mod_mainmenu'"
4890          ;
4891          $database->setQuery( $query );
4892          $menus = $database->loadObjectList();
4893          $total = count( $menus );
4894          $menuselect = array();
4895          for( $i = 0; $i < $total; $i++ ) {
4896              $params = mosParseParams( $menus[$i]->params );
4897              $menuselect[$i]->value     = $params->menutype;
4898              $menuselect[$i]->text     = $params->menutype;
4899          }
4900          // sort array of objects
4901          SortArrayObjects( $menuselect, 'text', 1 );
4902  
4903          $menus = mosHTML::selectList( $menuselect, $name, 'class="inputbox" size="10" '. $javascript, 'value', 'text' );
4904  
4905          return $menus;
4906      }
4907  
4908      /**
4909      * Internal function to recursive scan the media manager directories
4910      * @param string Path to scan
4911      * @param string root path of this folder
4912      * @param array  Value array of all existing folders
4913      * @param array  Value array of all existing images
4914      */
4915  	function ReadImages( $imagePath, $folderPath, &$folders, &$images ) {
4916          $imgFiles = mosReadDirectory( $imagePath );
4917  
4918          foreach ($imgFiles as $file) {
4919              $ff_     = $folderPath . $file .'/';
4920              $ff     = $folderPath . $file;
4921              $i_f     = $imagePath .'/'. $file;
4922  
4923              if ( is_dir( $i_f ) && $file != 'CVS' && $file != '.svn') {
4924                  $folders[] = mosHTML::makeOption( $ff_ );
4925                  mosAdminMenus::ReadImages( $i_f, $ff_, $folders, $images );
4926              } else if ( eregi( "bmp|gif|jpg|png", $file ) && is_file( $i_f ) ) {
4927                  // leading / we don't need
4928                  $imageFile = substr( $ff, 1 );
4929                  $images[$folderPath][] = mosHTML::makeOption( $imageFile, $file );
4930              }
4931          }
4932      }
4933  
4934      /**
4935      * Internal function to recursive scan the media manager directories
4936      * @param string Path to scan
4937      * @param string root path of this folder
4938      * @param array  Value array of all existing folders
4939      * @param array  Value array of all existing images
4940      */
4941  	function ReadImagesX( &$folders, &$images ) {
4942          global $mosConfig_absolute_path;
4943  
4944          if ( $folders[0]->value != '*0*' ) {
4945              foreach ( $folders as $folder ) {
4946                  $imagePath     = $mosConfig_absolute_path .'/images/stories' . $folder->value;
4947                  $imgFiles     = mosReadDirectory( $imagePath );
4948                  $folderPath = $folder->value .'/';
4949  
4950                  foreach ($imgFiles as $file) {
4951                      $ff     = $folderPath . $file;
4952                      $i_f     = $imagePath .'/'. $file;
4953  
4954                      if ( eregi( "bmp|gif|jpg|png", $file ) && is_file( $i_f ) ) {
4955                          // leading / we don't need
4956                          $imageFile = substr( $ff, 1 );
4957                          $images[$folderPath][] = mosHTML::makeOption( $imageFile, $file );
4958                      }
4959                  }
4960              }
4961          } else {
4962              $folders     = array();
4963              $folders[]     = mosHTML::makeOption( 'None' );
4964          }
4965      }
4966  
4967  	function GetImageFolders( &$temps, $path ) {
4968          if ( $temps[0]->value != 'None' ) {
4969              foreach( $temps as $temp ) {
4970                  if ( substr( $temp->value, -1, 1 ) != '/' ) {
4971                      $temp         = $temp->value .'/';
4972                      $folders[]     = mosHTML::makeOption( $temp, $temp );
4973                  } else {
4974                      $temp         = $temp->value;
4975                      $temp         = ampReplace( $temp );
4976                      $folders[]     = mosHTML::makeOption( $temp, $temp );
4977                  }
4978              }
4979          } else {
4980              $folders[]     = mosHTML::makeOption( 'None Selected' );
4981          }
4982  
4983          $javascript     = "onchange=\"changeDynaList( 'imagefiles', folderimages, document.adminForm.folders.options[document.adminForm.folders.selectedIndex].value, 0, 0);\"";
4984          $getfolders     = mosHTML::selectList( $folders, 'folders', 'class="inputbox" size="1" '. $javascript, 'value', 'text', '/' );
4985  
4986          return $getfolders;
4987      }
4988  
4989  	function GetImages( &$images, $path, $base='/' ) {
4990          if ( is_array($base) && count($base) > 0 ) {
4991              if ( $base[0]->value != '/' ) {
4992                  $base = $base[0]->value .'/';
4993              } else {
4994                  $base = $base[0]->value;
4995              }
4996          } else {
4997              $base = '/';
4998          }
4999  
5000          if ( !isset($images[$base] ) ) {
5001              $images[$base][] = mosHTML::makeOption( '' );
5002          }
5003  
5004          $javascript    = "onchange=\"previewImage( 'imagefiles', 'view_imagefiles', '$path/' )\" onfocus=\"previewImage( 'imagefiles', 'view_imagefiles', '$path/' )\"";
5005          $getimages    = mosHTML::selectList( $images[$base], 'imagefiles', 'class="inputbox" size="10" multiple="multiple" '. $javascript , 'value', 'text', null );
5006  
5007          return $getimages;
5008      }
5009  
5010  	function GetSavedImages( &$row, $path ) {
5011          $images2 = array();
5012  
5013          foreach( $row->images as $file ) {
5014              $temp = explode( '|', $file );
5015              if( strrchr($temp[0], '/') ) {
5016                  $filename = substr( strrchr($temp[0], '/' ), 1 );
5017              } else {
5018                  $filename = $temp[0];
5019              }
5020              $images2[] = mosHTML::makeOption( $file, $filename );
5021          }
5022  
5023          $javascript    = "onchange=\"previewImage( 'imagelist', 'view_imagelist', '$path/' ); showImageProps( '$path/' ); \"";
5024          $imagelist     = mosHTML::selectList( $images2, 'imagelist', 'class="inputbox" size="10" '. $javascript, 'value', 'text' );
5025  
5026          return $imagelist;
5027      }
5028  
5029      /**
5030      * Checks to see if an image exists in the current templates image directory
5031       * if it does it loads this image.  Otherwise the default image is loaded.
5032      * Also can be used in conjunction with the menulist param to create the chosen image
5033      * load the default or use no image
5034      */
5035  	function ImageCheck( $file, $directory='/images/M_images/', $param=NULL, $param_directory='/images/M_images/', $alt=NULL, $name=NULL, $type=1, $align='middle', $title=NULL, $admin=NULL ) {
5036          global $mosConfig_absolute_path, $mosConfig_live_site, $mainframe;
5037  
5038          $cur_template = $mainframe->getTemplate();
5039  
5040          $name     = ( $name     ? ' name="'. $name .'"'     : '' );
5041          $title     = ( $title     ? ' title="'. $title .'"'     : '' );
5042          $alt     = ( $alt     ? ' alt="'. $alt .'"'         : ' alt=""' );
5043          $align     = ( $align     ? ' align="'. $align .'"'     : '' );
5044  
5045          // change directory path from frontend or backend
5046          if ($admin) {
5047              $path     = '/administrator/templates/'. $cur_template .'/images/';
5048          } else {
5049              $path     = '/templates/'. $cur_template .'/images/';
5050          }
5051  
5052          if ( $param ) {
5053              $image = $mosConfig_live_site. $param_directory . $param;
5054              if ( $type ) {
5055                  $image = '<img src="'. $image .'" '. $alt . $name . $align .' border="0" />';
5056              }
5057          } else if ( $param == -1 ) {
5058              $image = '';
5059          } else {
5060              if ( file_exists( $mosConfig_absolute_path . $path . $file ) ) {
5061                  $image = $mosConfig_live_site . $path . $file;
5062              } else {
5063                  // outputs only path to image
5064                  $image = $mosConfig_live_site. $directory . $file;
5065              }
5066  
5067              // outputs actual html <img> tag
5068              if ( $type ) {
5069                  $image = '<img src="'. $image .'" '. $alt . $name . $title . $align .' border="0" />';
5070              }
5071          }
5072  
5073          return $image;
5074      }
5075  
5076      /**
5077      * Checks to see if an image exists in the current templates image directory
5078       * if it does it loads this image.  Otherwise the default image is loaded.
5079      * Also can be used in conjunction with the menulist param to create the chosen image
5080      * load the default or use no image
5081      */
5082  	function ImageCheckAdmin( $file, $directory='/administrator/images/', $param=NULL, $param_directory='/administrator/images/', $alt=NULL, $name=NULL, $type=1, $align='middle', $title=NULL ) {
5083  /*
5084          global $mosConfig_absolute_path, $mosConfig_live_site, $mainframe;
5085  
5086          $cur_template = $mainframe->getTemplate();
5087  
5088          $name     = ( $name     ? ' name="'. $name .'"'     : '' );
5089          $title     = ( $title     ? ' title="'. $title .'"'     : '' );
5090          $alt     = ( $alt     ? ' alt="'. $alt .'"'         : ' alt=""' );
5091          $align     = ( $align     ? ' align="'. $align .'"'     : '' );
5092  
5093          $path     = '/administrator/templates/'. $cur_template .'/images/';
5094  
5095          if ( $param ) {
5096              $image = $mosConfig_live_site. $param_directory . $param;
5097              if ( $type ) {
5098                  $image = '<img src="'. $image .'" '. $alt . $name . $align .' border="0" />';
5099              }
5100          } else if ( $param == -1 ) {
5101              $image = '';
5102          } else {
5103              if ( file_exists( $mosConfig_absolute_path . $path . $file ) ) {
5104                  $image = $mosConfig_live_site . $path . $file;
5105              } else {
5106                  // outputs only path to image
5107                  $image = $mosConfig_live_site. $directory . $file;
5108              }
5109  
5110              // outputs actual html <img> tag
5111              if ( $type ) {
5112                  $image = '<img src="'. $image .'" '. $alt . $name . $title . $align .' border="0" />';
5113              }
5114          }
5115  */
5116          // functionality consolidated into ImageCheck
5117          $image = mosAdminMenus::ImageCheck( $file, $directory, $param, $param_directory, $alt, $name, $type, $align, $title, $admin=1 );
5118  
5119          return $image;
5120      }
5121  
5122  	function menutypes() {
5123          global $database;
5124  
5125          $query = "SELECT params"
5126          . "\n FROM #__modules"
5127          . "\n WHERE module = 'mod_mainmenu'"
5128          . "\n ORDER BY title"
5129          ;
5130          $database->setQuery( $query    );
5131          $modMenus = $database->loadObjectList();
5132  
5133          $query = "SELECT menutype"
5134          . "\n FROM #__menu"
5135          . "\n GROUP BY menutype"
5136          . "\n ORDER BY menutype"
5137          ;
5138          $database->setQuery( $query    );
5139          $menuMenus = $database->loadObjectList();
5140  
5141          $menuTypes = '';
5142          foreach ( $modMenus as $modMenu ) {
5143              $check = 1;
5144              mosMakeHtmlSafe( $modMenu) ;
5145              $modParams     = mosParseParams( $modMenu->params );
5146              $menuType     = @$modParams->menutype;
5147              if (!$menuType) {
5148                  $menuType = 'mainmenu';
5149              }
5150  
5151              // stop duplicate menutype being shown
5152              if ( !is_array( $menuTypes) ) {
5153                  // handling to create initial entry into array
5154                  $menuTypes[] = $menuType;
5155              } else {
5156                  $check = 1;
5157                  foreach ( $menuTypes as $a ) {
5158                      if ( $a == $menuType ) {
5159                          $check = 0;
5160                      }
5161                  }
5162                  if ( $check ) {
5163                      $menuTypes[] = $menuType;
5164                  }
5165              }
5166  
5167          }
5168          // add menutypes from jos_menu
5169          foreach ( $menuMenus as $menuMenu ) {
5170              $check = 1;
5171              foreach ( $menuTypes as $a ) {
5172                  if ( $a == $menuMenu->menutype ) {
5173                      $check = 0;
5174                  }
5175              }
5176              if ( $check ) {
5177                  $menuTypes[] = $menuMenu->menutype;
5178              }
5179          }
5180  
5181          // sorts menutypes
5182          asort( $menuTypes );
5183  
5184          return $menuTypes;
5185      }
5186  
5187      /*
5188      * loads files required for menu items
5189      */
5190  	function menuItem( $item ) {
5191          global $mosConfig_absolute_path;
5192  
5193          $path = $mosConfig_absolute_path .'/administrator/components/com_menus/'. $item .'/';
5194          include_once( $path . $item .'.class.php' );
5195          include_once( $path . $item .'.menu.html.php' );
5196      }
5197  }
5198  
5199  
5200  class mosCommonHTML {
5201  
5202  	function ContentLegend( ) {
5203          ?>
5204          <table cellspacing="0" cellpadding="4" border="0" align="center">
5205          <tr align="center">
5206              <td>
5207              <img src="images/publish_y.png" width="12" height="12" border="0" alt="Pending" />
5208              </td>
5209              <td>
5210              Published, but is <u>Pending</u> |
5211              </td>
5212              <td>
5213              <img src="images/publish_g.png" width="12" height="12" border="0" alt="Visible" />
5214              </td>
5215              <td>
5216              Published and is <u>Current</u> |
5217              </td>
5218              <td>
5219              <img src="images/publish_r.png" width="12" height="12" border="0" alt="Finished" />
5220              </td>
5221              <td>
5222              Published, but has <u>Expired</u> |
5223              </td>
5224              <td>
5225              <img src="images/publish_x.png" width="12" height="12" border="0" alt="Finished" />
5226              </td>
5227              <td>
5228              Not Published
5229              </td>
5230          </tr>
5231          <tr>
5232              <td colspan="8" align="center">
5233              Click on icon to toggle state.
5234              </td>
5235          </tr>
5236          </table>
5237          <?php
5238      }
5239  
5240  	function menuLinksContent( &$menus ) {
5241          ?>
5242          <script language="javascript" type="text/javascript">
5243  		function go2( pressbutton, menu, id ) {
5244              var form = document.adminForm;
5245  
5246              // assemble the images back into one field
5247              var temp = new Array;
5248              for (var i=0, n=form.imagelist.options.length; i < n; i++) {
5249                  temp[i] = form.imagelist.options[i].value;
5250              }
5251              form.images.value = temp.join( '\n' );
5252  
5253              if (pressbutton == 'go2menu') {
5254                  form.menu.value = menu;
5255                  submitform( pressbutton );
5256                  return;
5257              }
5258  
5259              if (pressbutton == 'go2menuitem') {
5260                  form.menu.value     = menu;
5261                  form.menuid.value     = id;
5262                  submitform( pressbutton );
5263                  return;
5264              }
5265          }
5266          </script>
5267          <?php
5268          foreach( $menus as $menu ) {
5269              ?>
5270              <tr>
5271                  <td colspan="2">
5272                  <hr />
5273                  </td>
5274              </tr>
5275              <tr>
5276                  <td width="90px" valign="top">
5277                  Menu
5278                  </td>
5279                  <td>
5280                  <a href="javascript:go2( 'go2menu', '<?php echo $menu->menutype; ?>' );" title="Go to Menu">
5281                  <?php echo $menu->menutype; ?>
5282                  </a>
5283                  </td>
5284              </tr>
5285              <tr>
5286                  <td width="90px" valign="top">
5287                  Link Name
5288                  </td>
5289                  <td>
5290                  <strong>
5291                  <a href="javascript:go2( 'go2menuitem', '<?php echo $menu->menutype; ?>', '<?php echo $menu->id; ?>' );" title="Go to Menu Item">
5292                  <?php echo $menu->name; ?>
5293                  </a>
5294                  </strong>
5295                  </td>
5296              </tr>
5297              <tr>
5298                  <td width="90px" valign="top">
5299                  State
5300                  </td>
5301                  <td>
5302                  <?php
5303                  switch ( $menu->published ) {
5304                      case -2:
5305                          echo '<font color="red">Trashed</font>';
5306                          break;
5307                      case 0:
5308                          echo 'UnPublished';
5309                          break;
5310                      case 1:
5311                      default:
5312                          echo '<font color="green">Published</font>';
5313                          break;
5314                  }
5315                  ?>
5316                  </td>
5317              </tr>
5318              <?php
5319          }
5320          ?>
5321          <input type="hidden" name="menu" value="" />
5322          <input type="hidden" name="menuid" value="" />
5323          <?php
5324      }
5325  
5326  	function menuLinksSecCat( &$menus ) {
5327          ?>
5328          <script language="javascript" type="text/javascript">
5329  		function go2( pressbutton, menu, id ) {
5330              var form = document.adminForm;
5331  
5332              if (pressbutton == 'go2menu') {
5333                  form.menu.value = menu;
5334                  submitform( pressbutton );
5335                  return;
5336              }
5337  
5338              if (pressbutton == 'go2menuitem') {
5339                  form.menu.value     = menu;
5340                  form.menuid.value     = id;
5341                  submitform( pressbutton );
5342                  return;
5343              }
5344          }
5345          </script>
5346          <?php
5347          foreach( $menus as $menu ) {
5348              ?>
5349              <tr>
5350                  <td colspan="2">
5351                  <hr/>
5352                  </td>
5353              </tr>
5354              <tr>
5355                  <td width="90px" valign="top">
5356                  Menu
5357                  </td>
5358                  <td>
5359                  <a href="javascript:go2( 'go2menu', '<?php echo $menu->menutype; ?>' );" title="Go to Menu">
5360                  <?php echo $menu->menutype; ?>
5361                  </a>
5362                  </td>
5363              </tr>
5364              <tr>
5365                  <td width="90px" valign="top">
5366                  Type
5367                  </td>
5368                  <td>
5369                  <?php echo $menu->type; ?>
5370                  </td>
5371              </tr>
5372              <tr>
5373                  <td width="90px" valign="top">
5374                  Item Name
5375                  </td>
5376                  <td>
5377                  <strong>
5378                  <a href="javascript:go2( 'go2menuitem', '<?php echo $menu->menutype; ?>', '<?php echo $menu->id; ?>' );" title="Go to Menu Item">
5379                  <?php echo $menu->name; ?>
5380                  </a>
5381                  </strong>
5382                  </td>
5383              </tr>
5384              <tr>
5385                  <td width="90px" valign="top">
5386                  State
5387                  </td>
5388                  <td>
5389                  <?php
5390                  switch ( $menu->published ) {
5391                      case -2:
5392                          echo '<font color="red">Trashed</font>';
5393                          break;
5394                      case 0:
5395                          echo 'UnPublished';
5396                          break;
5397                      case 1:
5398                      default:
5399                          echo '<font color="green">Published</font>';
5400                          break;
5401                  }
5402                  ?>
5403                  </td>
5404              </tr>
5405              <?php
5406          }
5407          ?>
5408          <input type="hidden" name="menu" value="" />
5409          <input type="hidden" name="menuid" value="" />
5410          <?php
5411      }
5412  
5413  	function checkedOut( &$row, $overlib=1 ) {
5414          $hover = '';
5415          if ( $overlib ) {
5416              $date                 = mosFormatDate( $row->checked_out_time, '%A, %d %B %Y' );
5417              $time                = mosFormatDate( $row->checked_out_time, '%H:%M' );
5418              $checked_out_text     = '<table>';
5419              $checked_out_text     .= '<tr><td>'. $row->editor .'</td></tr>';
5420              $checked_out_text     .= '<tr><td>'. $date .'</td></tr>';
5421              $checked_out_text     .= '<tr><td>'. $time .'</td></tr>';
5422              $checked_out_text     .= '</table>';
5423              $hover = 'onMouseOver="return overlib(\''. $checked_out_text .'\', CAPTION, \'Checked Out\', BELOW, RIGHT);" onMouseOut="return nd();"';
5424          }
5425          $checked             = '<img src="images/checked_out.png" '. $hover .'/>';
5426  
5427          return $checked;
5428      }
5429  
5430      /*
5431      * Loads all necessary files for JS Overlib tooltips
5432      */
5433  	function loadOverlib() {
5434          global  $mosConfig_live_site, $mainframe;
5435  
5436          if ( !$mainframe->get( 'loadOverlib' ) ) {
5437          // check if this function is already loaded
5438              ?>
5439              <script language="javascript" type="text/javascript" src="<?php echo $mosConfig_live_site;?>/includes/js/overlib_mini.js"></script>
5440              <script language="javascript" type="text/javascript" src="<?php echo $mosConfig_live_site;?>/includes/js/overlib_hideform_mini.js"></script>
5441              <?php
5442              // change state so it isnt loaded a second time
5443              $mainframe->set( 'loadOverlib', true );
5444          }
5445      }
5446  
5447  
5448      /*
5449      * Loads all necessary files for JS Calendar
5450      */
5451  	function loadCalendar() {
5452          global  $mosConfig_live_site;
5453          ?>
5454          <link rel="stylesheet" type="text/css" media="all" href="<?php echo $mosConfig_live_site;?>/includes/js/calendar/calendar-mos.css" title="green" />
5455          <!-- import the calendar script -->
5456          <script type="text/javascript" src="<?php echo $mosConfig_live_site;?>/includes/js/calendar/calendar_mini.js"></script>
5457          <!-- import the language module -->
5458          <script type="text/javascript" src="<?php echo $mosConfig_live_site;?>/includes/js/calendar/lang/calendar-en.js"></script>
5459          <?php
5460      }
5461  
5462  	function AccessProcessing( &$row, $i ) {
5463          if ( !$row->access ) {
5464              $color_access = 'style="color: green;"';
5465              $task_access = 'accessregistered';
5466          } else if ( $row->access == 1 ) {
5467              $color_access = 'style="color: red;"';
5468              $task_access = 'accessspecial';
5469          } else {
5470              $color_access = 'style="color: black;"';
5471              $task_access = 'accesspublic';
5472          }
5473  
5474          $href = '
5475          <a href="javascript: void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $task_access .'\')" '. $color_access .'>
5476          '. $row->groupname .'
5477          </a>'
5478          ;
5479  
5480          return $href;
5481      }
5482  
5483  	function CheckedOutProcessing( &$row, $i ) {
5484          global $my;
5485  
5486          if ( $row->checked_out) {
5487              $checked = mosCommonHTML::checkedOut( $row );
5488          } else {
5489              $checked = mosHTML::idBox( $i, $row->id, ($row->checked_out && $row->checked_out != $my->id ) );
5490          }
5491  
5492          return $checked;
5493      }
5494  
5495  	function PublishedProcessing( &$row, $i ) {
5496          $img     = $row->published ? 'publish_g.png' : 'publish_x.png';
5497          $task     = $row->published ? 'unpublish' : 'publish';
5498          $alt     = $row->published ? 'Published' : 'Unpublished';
5499          $action    = $row->published ? 'Unpublish Item' : 'Publish item';
5500  
5501          $href = '
5502          <a href="javascript: void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $task .'\')" title="'. $action .'">
5503          <img src="images/'. $img .'" border="0" alt="'. $alt .'" />
5504          </a>'
5505          ;
5506  
5507          return $href;
5508      }
5509  
5510      /*
5511      * Special handling for newfeed encoding and possible conflicts with page encoding and PHP version
5512      * Added 1.0.8
5513      * Static Function
5514      */
5515  	function newsfeedEncoding( $rssDoc, $text ) {
5516          if (!defined( '_JOS_FEED_ENCODING' )) {
5517          // determine encoding of feed
5518              $feed             = $rssDoc->toNormalizedString(true);
5519              $feed             = strtolower( substr( $feed, 0, 150 ) );
5520              $feedEncoding     = strpos( $feed, 'encoding=&quot;utf-8&quot;' );
5521  
5522              if ( $feedEncoding !== false ) {
5523              // utf-8 feed
5524                  $utf8 = 1;
5525              } else {
5526              // non utf-8 page
5527                  $utf8 = 0;
5528              }
5529  
5530              define( '_JOS_FEED_ENCODING', $utf8 );
5531          }
5532  
5533          if (!defined( '_JOS_SITE_ENCODING' )) {
5534          // determine encoding of page
5535              if ( strpos( strtolower( _ISO ), 'utf' ) !== false ) {
5536              // utf-8 page
5537                  $utf8 = 1;
5538              } else {
5539              // non utf-8 page
5540                  $utf8 = 0;
5541              }
5542  
5543              define( '_JOS_SITE_ENCODING', $utf8 );
5544  
5545          }
5546  
5547          if ( phpversion() >= 5 ) {
5548          // handling for PHP 5
5549              if ( _JOS_FEED_ENCODING ) {
5550              // handling for utf-8 feed
5551                  if ( _JOS_SITE_ENCODING ) {
5552                  // utf-8 page
5553                      $encoding = 'html_entity_decode';
5554                  } else {
5555                  // non utf-8 page
5556                      $encoding = 'utf8_decode';
5557                  }
5558              } else {
5559              // handling for non utf-8 feed
5560                  if ( _JOS_SITE_ENCODING ) {
5561                      // utf-8 page
5562                      $encoding = '';
5563                  } else {
5564                      // non utf-8 page
5565                      $encoding = 'utf8_decode';
5566                  }
5567              }
5568          } else {
5569          // handling for PHP 4
5570              if ( _JOS_FEED_ENCODING ) {
5571              // handling for utf-8 feed
5572                  if ( _JOS_SITE_ENCODING ) {
5573                  // utf-8 page
5574                      $encoding = '';
5575                  } else {
5576                  // non utf-8 page
5577                      $encoding = 'utf8_decode';
5578                  }
5579              } else {
5580              // handling for non utf-8 feed
5581                  if ( _JOS_SITE_ENCODING ) {
5582                  // utf-8 page
5583                      $encoding = 'utf8_encode';
5584                  } else {
5585                  // non utf-8 page
5586                      $encoding = 'html_entity_decode';
5587                  }
5588              }
5589          }
5590  
5591          if ( $encoding ) {
5592              $text = $encoding( $text );
5593          }
5594          $text = str_replace('&apos;', "'", $text);
5595  
5596          return $text;
5597      }
5598  }
5599  
5600  /**
5601  * Sorts an Array of objects
5602  */
5603  function SortArrayObjects_cmp( &$a, &$b ) {
5604      global $csort_cmp;
5605  
5606      if ( $a->$csort_cmp['key'] > $b->$csort_cmp['key'] ) {
5607          return $csort_cmp['direction'];
5608      }
5609  
5610      if ( $a->$csort_cmp['key'] < $b->$csort_cmp['key'] ) {
5611          return -1 * $csort_cmp['direction'];
5612      }
5613  
5614      return 0;
5615  }
5616  
5617  /**
5618  * Sorts an Array of objects
5619  * sort_direction [1 = Ascending] [-1 = Descending]
5620  */
5621  function SortArrayObjects( &$a, $k, $sort_direction=1 ) {
5622      global $csort_cmp;
5623  
5624      $csort_cmp = array(
5625          'key'          => $k,
5626          'direction'    => $sort_direction
5627      );
5628  
5629      usort( $a, 'SortArrayObjects_cmp' );
5630  
5631      unset( $csort_cmp );
5632  }
5633  
5634  /**
5635  * Sends mail to admin
5636  */
5637  function mosSendAdminMail( $adminName, $adminEmail, $email, $type, $title, $author ) {
5638      global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_live_site;
5639  
5640      $subject = _MAIL_SUB." '$type'";
5641      $message = _MAIL_MSG;
5642      eval ("\$message = \"$message\";");
5643  
5644      mosMail($mosConfig_mailfrom, $mosConfig_fromname, $adminEmail, $subject, $message);
5645  }
5646  
5647  /*
5648  * Includes pathway file
5649  */
5650  function mosPathWay() {
5651      global $mosConfig_absolute_path;
5652  
5653      $Itemid = intval( mosGetParam( $_REQUEST, 'Itemid', '' ) );
5654      require_once  ( $mosConfig_absolute_path . '/includes/pathway.php' );
5655  }
5656  
5657  /**
5658  * Displays a not authorised message
5659  *
5660  * If the user is not logged in then an addition message is displayed.
5661  */
5662  function mosNotAuth() {
5663      global $my;
5664  
5665      echo _NOT_AUTH;
5666      if ($my->id < 1) {
5667          echo "<br />" . _DO_LOGIN;
5668      }
5669  }
5670  
5671  /**
5672  * Replaces &amp; with & for xhtml compliance
5673  *
5674  * Needed to handle unicode conflicts due to unicode conflicts
5675  */
5676  function ampReplace( $text ) {
5677      $text = str_replace( '&&', '*--*', $text );
5678      $text = str_replace( '&#', '*-*', $text );
5679      $text = str_replace( '&amp;', '&', $text );
5680      $text = preg_replace( '|&(?![\w]+;)|', '&amp;', $text );
5681      $text = str_replace( '*-*', '&#', $text );
5682      $text = str_replace( '*--*', '&&', $text );
5683  
5684      return $text;
5685  }
5686  /**
5687  * Prepares results from search for display
5688  * @param string The source string
5689  * @param int Number of chars to trim
5690  * @param string The searchword to select around
5691  * @return string
5692  */
5693  function mosPrepareSearchContent( $text, $length=200, $searchword ) {
5694      // strips tags won't remove the actual jscript
5695      $text = preg_replace( "'<script[^>]*>.*?</script>'si", "", $text );
5696      $text = preg_replace( '/{.+?}/', '', $text);
5697  
5698      //$text = preg_replace( '/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is','\2', $text );
5699  
5700      // replace line breaking tags with whitespace
5701      $text = preg_replace( "'<(br[^/>]*?/|hr[^/>]*?/|/(div|h[1-6]|li|p|td))>'si", ' ', $text );
5702  
5703      $text = mosSmartSubstr( strip_tags( $text ), $length, $searchword );
5704  
5705      return $text;
5706  }
5707  
5708  /**
5709  * returns substring of characters around a searchword
5710  * @param string The source string
5711  * @param int Number of chars to return
5712  * @param string The searchword to select around
5713  * @return string
5714  */
5715  function mosSmartSubstr($text, $length=200, $searchword) {
5716    $wordpos = strpos(strtolower($text), strtolower($searchword));
5717    $halfside = intval($wordpos - $length/2 - strlen($searchword));
5718    if ($wordpos && $halfside > 0) {
5719      return '...' . substr($text, $halfside, $length) . '...';
5720    } else {
5721      return substr( $text, 0, $length);
5722    }
5723  }
5724  
5725  /**
5726  * Chmods files and directories recursively to given permissions. Available from 1.0.0 up.
5727  * @param path The starting file or directory (no trailing slash)
5728  * @param filemode Integer value to chmod files. NULL = dont chmod files.
5729  * @param dirmode Integer value to chmod directories. NULL = dont chmod directories.
5730  * @return TRUE=all succeeded FALSE=one or more chmods failed
5731  */
5732  function mosChmodRecursive($path, $filemode=NULL, $dirmode=NULL)
5733  {
5734      $ret = TRUE;
5735      if (is_dir($path)) {
5736          $dh = opendir($path);
5737          while ($file = readdir($dh)) {
5738              if ($file != '.' && $file != '..') {
5739                  $fullpath = $path.'/'.$file;
5740                  if (is_dir($fullpath)) {
5741                      if (!mosChmodRecursive($fullpath, $filemode, $dirmode))
5742                          $ret = FALSE;
5743                  } else {
5744                      if (isset($filemode))
5745                          if (!@chmod($fullpath, $filemode))
5746                              $ret = FALSE;
5747                  } // if
5748              } // if
5749          } // while
5750          closedir($dh);
5751          if (isset($dirmode))
5752              if (!@chmod($path, $dirmode))
5753                  $ret = FALSE;
5754      } else {
5755          if (isset($filemode))
5756              $ret = @chmod($path, $filemode);
5757      } // if
5758      return $ret;
5759  } // mosChmodRecursive
5760  
5761  /**
5762  * Chmods files and directories recursively to mos global permissions. Available from 1.0.0 up.
5763  * @param path The starting file or directory (no trailing slash)
5764  * @param filemode Integer value to chmod files. NULL = dont chmod files.
5765  * @param dirmode Integer value to chmod directories. NULL = dont chmod directories.
5766  * @return TRUE=all succeeded FALSE=one or more chmods failed
5767  */
5768  function mosChmod($path) {
5769      global $mosConfig_fileperms, $mosConfig_dirperms;
5770      $filemode = NULL;
5771      if ($mosConfig_fileperms != '')
5772          $filemode = octdec($mosConfig_fileperms);
5773      $dirmode = NULL;
5774      if ($mosConfig_dirperms != '')
5775          $dirmode = octdec($mosConfig_dirperms);
5776      if (isset($filemode) || isset($dirmode))
5777          return mosChmodRecursive($path, $filemode, $dirmode);
5778      return TRUE;
5779  } // mosChmod
5780  
5781  /**
5782   * Function to convert array to integer values
5783   * @param array
5784   * @param int A default value to assign if $array is not an array
5785   * @return array
5786   */
5787  function mosArrayToInts( &$array, $default=null ) {
5788      if (is_array( $array )) {
5789          foreach( $array as $key => $value ) {
5790              $array[$key] = (int) $value;
5791          }
5792      } else {
5793          if (is_null( $default )) {
5794              $array = array();
5795              return array(); // Kept for backwards compatibility
5796          } else {
5797              $array = array( (int) $default );
5798              return array( $default ); // Kept for backwards compatibility
5799          }
5800      }
5801  }
5802  
5803  /*
5804  * Function to handle an array of integers
5805  * Added 1.0.11
5806  */
5807  function josGetArrayInts( $name, $type=NULL ) {
5808      if ( $type == NULL ) {
5809          $type = $_POST;
5810      }
5811  
5812      $array = mosGetParam( $type, $name, array(0) );
5813  
5814      mosArrayToInts( $array );
5815  
5816      if (!is_array( $array )) {
5817          $array = array(0);
5818      }
5819  
5820      return $array;
5821  }
5822  
5823  /**
5824   * Utility class for helping with patTemplate
5825   */
5826  class patHTML {
5827      /**
5828       * Converts a named array to an array or named rows suitable to option lists
5829       * @param array The source array[key] = value
5830       * @param mixed A value or array of selected values
5831       * @param string The name for the value field
5832       * @param string The name for selected attribute (use 'checked' for radio of box lists)
5833       */
5834  	function selectArray( &$source, $selected=null, $valueName='value', $selectedAttr='selected' ) {
5835          if (!is_array( $selected )) {
5836              $selected = array( $selected );
5837          }
5838          foreach ($source as $i => $row) {
5839              if (is_object( $row )) {
5840                  $source[$i]->selected = in_array( $row->$valueName, $selected ) ? $selectedAttr . '="true"' : '';
5841              } else {
5842                  $source[$i]['selected'] = in_array( $row[$valueName], $selected ) ? $selectedAttr . '="true"' : '';
5843              }
5844          }
5845      }
5846  
5847      /**
5848       * Converts a named array to an array or named rows suitable to checkbox or radio lists
5849       * @param array The source array[key] = value
5850       * @param mixed A value or array of selected values
5851       * @param string The name for the value field
5852       */
5853  	function checkArray( &$source, $selected=null, $valueName='value' ) {
5854          patHTML::selectArray( $source, $selected, $valueName, 'checked' );
5855      }
5856  
5857      /**
5858       * @param mixed The value for the option
5859       * @param string The text for the option
5860       * @param string The name of the value parameter (default is value)
5861       * @param string The name of the text parameter (default is text)
5862       */
5863  	function makeOption( $value, $text, $valueName='value', $textName='text' ) {
5864          return array(
5865              $valueName => $value,
5866              $textName => $text
5867          );
5868      }
5869  
5870      /**
5871       * Writes a radio pair
5872       * @param object Template object
5873       * @param string The template name
5874       * @param string The field name
5875       * @param int The value of the field
5876       * @param array Array of options
5877       * @param string Optional template variable name
5878       */
5879  	function radioSet( &$tmpl, $template, $name, $value, $a, $varname=null ) {
5880          patHTML::checkArray( $a, $value );
5881  
5882          $tmpl->addVar( 'radio-set', 'name', $name );
5883          $tmpl->addRows( 'radio-set', $a );
5884          $tmpl->parseIntoVar( 'radio-set', $template, is_null( $varname ) ? $name : $varname );
5885      }
5886  
5887      /**
5888       * Writes a radio pair
5889       * @param object Template object
5890       * @param string The template name
5891       * @param string The field name
5892       * @param int The value of the field
5893       * @param string Optional template variable name
5894       */
5895  	function yesNoRadio( &$tmpl, $template, $name, $value, $varname=null ) {
5896          $a = array(
5897              patHTML::makeOption( 0, 'No' ),
5898              patHTML::makeOption( 1, 'Yes' )
5899          );
5900          patHTML::radioSet( $tmpl, $template, $name, $value, $a, $varname );
5901      }
5902  }
5903  
5904  /**
5905   * Provides a secure hash based on a seed
5906   * @param string Seed string
5907   * @return string
5908   */
5909  function mosHash( $seed ) {
5910      return md5( $GLOBALS['mosConfig_secret'] . md5( $seed ) );
5911  }
5912  
5913  /**
5914   * Format a backtrace error
5915   * @since 1.0.5
5916   */
5917  function mosBackTrace() {
5918      if (function_exists( 'debug_backtrace' )) {
5919          echo '<div align="left">';
5920          foreach( debug_backtrace() as $back) {
5921              if (@$back['file']) {
5922                  echo '<br />' . str_replace( $GLOBALS['mosConfig_absolute_path'], '', $back['file'] ) . ':' . $back['line'];
5923              }
5924          }
5925          echo '</div>';
5926      }
5927  }
5928  
5929  function josSpoofCheck( $header=NULL, $alt=NULL ) {
5930      $validate     = mosGetParam( $_POST, josSpoofValue($alt), 0 );
5931  
5932      // probably a spoofing attack
5933      if (!$validate) {
5934          header( 'HTTP/1.0 403 Forbidden' );
5935          mosErrorAlert( _NOT_AUTH );
5936          return;
5937      }
5938  
5939      // First, make sure the form was posted from a browser.
5940      // For basic web-forms, we don't care about anything
5941      // other than requests from a browser:
5942      if (!isset( $_SERVER['HTTP_USER_AGENT'] )) {
5943          header( 'HTTP/1.0 403 Forbidden' );
5944          mosErrorAlert( _NOT_AUTH );
5945          return;
5946      }
5947  
5948      // Make sure the form was indeed POST'ed:
5949      //  (requires your html form to use: action="post")
5950      if (!$_SERVER['REQUEST_METHOD'] == 'POST' ) {
5951          header( 'HTTP/1.0 403 Forbidden' );
5952          mosErrorAlert( _NOT_AUTH );
5953          return;
5954      }
5955  
5956      if ($header) {
5957      // Attempt to defend against header injections:
5958          $badStrings = array(
5959              'Content-Type:',
5960              'MIME-Version:',
5961              'Content-Transfer-Encoding:',
5962              'bcc:',
5963              'cc:'
5964          );
5965  
5966          // Loop through each POST'ed value and test if it contains
5967          // one of the $badStrings:
5968          foreach ($_POST as $k => $v){
5969              foreach ($badStrings as $v2) {
5970                  if (is_array($v)) {
5971                      patHTML::_josSpoofCheck($v, $badStrings);
5972                  } else if (strpos( $v, $v2 ) !== false) {
5973                      header( "HTTP/1.0 403 Forbidden" );
5974                      mosErrorAlert( _NOT_AUTH );
5975                      return;
5976                  }
5977              }
5978          }
5979  
5980          // Made it past spammer test, free up some memory
5981          // and continue rest of script:
5982          unset($k, $v, $v2, $badStrings);
5983      }
5984  }
5985  
5986  function _josSpoofCheck($array, $badStrings) {
5987      foreach ($array as $k => $v) {
5988          foreach ($badStrings as $v2) {
5989              if (is_array($v)) {
5990                  patHTML::_josSpoofCheck($v, $badStrings);
5991              } else if (strpos( $v, $v2 ) !== false) {
5992                  header( "HTTP/1.0 403 Forbidden" );
5993                  mosErrorAlert( _NOT_AUTH );
5994                  return;
5995              }
5996          }
5997      }
5998  }
5999  
6000  /**
6001   * Method to determine a hash for anti-spoofing variable names
6002   *
6003   * @return    string    Hashed var name
6004   * @static
6005   */
6006  function josSpoofValue($alt=NULL) {
6007      global $mainframe;
6008  
6009      if ($alt) {
6010          if ( $alt == 1 ) {
6011              $random        = date( 'Ymd' );
6012          } else {
6013              $random        = $alt . date( 'Ymd' );
6014          }
6015      } else {
6016          $random        = date( 'dmY' );
6017      }
6018      // the prefix ensures that the hash is non-numeric
6019      // otherwise it will be intercepted by globals.php
6020      $validate     = 'j' . mosHash( $mainframe->getCfg( 'db' ) . $random );
6021  
6022      return $validate;
6023  }
6024  
6025  // ----- NO MORE CLASSES OR FUNCTIONS PASSED THIS POINT -----
6026  // Post class declaration initialisations
6027  // some version of PHP don't allow the instantiation of classes
6028  // before they are defined
6029  
6030  /** @global mosPlugin $_MAMBOTS */
6031  $_MAMBOTS = new mosMambotHandler();
6032  ?>


Generated: Tue Nov 28 19:30:46 2006          Cross-referenced by PHPXref 0.6