Location: PHPKode > projects > Joomla SEF / SEO - extending OpenSEF > sef.functions.php
<?php
/**
 * @package OpenSEF for Joomla!
 * @copyright (c) 2005 The OpenSEF Project (www.opensef.org)
 * @copyright (c) 2004-2005 Xaneon Development (www.xaneon.com)
 * @license GPL http://www.gnu.org/copyleft/gpl.html
 *
 * These are default implementations for the core functions of OpenSEF; it
 * might be called the OpenSEF Core API. It's expected that any code which
 * needs to make use of OpenSEF's functionality will include this file.
 *
 * Note that this is designed in a fashion which allows site admins and 3PD
 * developers to develop their own add-ons that extend or replace the OpenSEF
 * core, or do additional URL handling according to fully custom rules.
 *
 * To override the default implementation of an OpenSEF core function, just
 * create a new core extension file and implement a identically named function
 * there. Your core extension will take precedence over the functions defined
 * here.
 *
 */

/** Ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct access to this location is not allowed.' );

if (!function_exists( 'sefLoadSecurityHandler' )) {
  /**
   * Load Securityhandler, for further versions
   *
     * @param object $db the database connection object
     * @param object $config an instance of JosOpenSEFConfig
     * @param object $site an instance of JosOpenSEFSite
   * @return handler
   */
  function sefLoadSecurityHandler( &$db, &$config, &$site ) {
    if (!defined( '_SECURITY_HANDLER' ))
    require_once( 'core/sef.security.php' ); // Default security handler
    $className = constant( '_SECURITY_HANDLER' );
    $securityHandler =& new $className( $db, $config, $site );
    $securityHandler->setDebug( !empty( $config->debug ) );
    return $securityHandler;
  }
}

if (!function_exists( 'sefLoadResolver' )) {
  /**
   * Load the Resolver
   *
   * @param object $db the database connection object
     * @param object $config an instance of JosOpenSEFConfig
     * @param object $site an instance of JosOpenSEFSite
   * @return resolver
   */
  function sefLoadResolver( &$db, &$config, &$site ) {
    if (!defined( '_SEF_RESOLVER' ))
    require_once( 'core/sef.resolver.php' ); // Default resolver
    $className = constant( '_SEF_RESOLVER' );
    $resolver =& new $className( $db, $config, $site );
    $resolver->setDebug( !empty( $config->debug ) );
    return $resolver;
  }
}

if (!function_exists( 'sefLoadRewriter' )) {
  /**
   * Load Rewriter
   *
     * @param object $db the database connection object
     * @param object $config an instance of JosOpenSEFConfig
     * @param object $site an instance of JosOpenSEFSite
   * @return rewriter
   */
  function sefLoadRewriter( &$db, &$config, &$site ) {
    if (!defined( '_SEF_REWRITER' ))
    require_once( 'core/sef.rewriter.php' ); // Default rewrite
    $className = constant( '_SEF_REWRITER' );
    $rewriter =& new $className( $db, $config, $site );
    $rewriter->setDebug( !empty( $config->debug ) );
    return $rewriter;
  }
}

if (!function_exists( 'sefLoadAutoMapper' )) {
  /**
   * Load Automapper
   *
   * @param object $db the database connection object
     * @param object $config an instance of JosOpenSEFConfig
     * @param object $site an instance of JosOpenSEFSite
   * @return automapper
   */
  function sefLoadAutoMapper( &$db, &$config, &$site ) {
    if (!defined( '_SEF_AUTOMAPPER' ))
    require_once( 'core/sef.mapper.php' ); // Default auto-mapper
    $className = constant( '_SEF_AUTOMAPPER' );
    $autoMapper =& new $className( $db, $config, $site );
    $autoMapper->setDebug( !empty( $config->debug ) );
    return $autoMapper;
  }
}

if (!function_exists( 'sefLoadExtension' )) {
  /**
   * Load the sef_ext.php files if exist
   *
   * @param string $component
   * @return boole
   */
  function sefLoadExtension( $component ) {
    global $sefConfig;
    // TODO: PHP5 will have autoloading support, probably rendering this
    // function pretty much obsolete if we can take advantage of it.
    if ($component=="poll" or $component=="contact") {
      $component="onfly";
    }

    if (class_exists( 'sef_' . $component ))
    return true; // Already loaded

    $path = $GLOBALS['mosConfig_absolute_path'];
    $paths = array(
    "$path/administrator/components/com_sef/extensions/sef_ext.$component.php",
    "$path/administrator/components/com_$component/sef_ext.php",
    "$path/components/com_$component/sef_ext.php",
    "$path/administrator/components/com_sef/core/sef.$component.php",
    );
    // We check whether the file exists, is readable, that it's not empty,
    // and then after loading that the class really exists; this is pretty
    // fail-safe and will move on to the next possible file if one doesn't
    // satisfy any of these conditions.
    // Performance note: PHP caches the results of calling file_exists,
    // is_readable, etc., meaning the tests will be quite cheap in practice.
    $debug = !empty( $sefConfig->debug );
    if ($component=="poll") {
      $component="onfly_poll";
    }
    if ($component=="contact") {
      $component="onfly_contact";
    }
    foreach ($paths as $path) {
      if (file_exists( $path ) && is_readable( $path ) && filesize( $path ) > 0) {
        if (!$debug) ob_start();
        @include_once( $path );
        if (!$debug) ob_end_clean();
        if (class_exists( 'sef_' . $component ))
        return true;
      }
    }
    return false;
  }
}

if (!function_exists( 'sefRelToAbs' )) {
  /**
   * Rewrite internal URL to OpenSEF URL.
   * Replaces the core Joomla! function in includes/sef.php.
   *
   * @param string $string
   * @return string
   */
  function sefRelToAbs( $string ) {
    global $sefRewriter, $mosConfig_live_site;

    if (!isset( $sefRewriter ) || !is_object( $sefRewriter )) {
      global $database, $sefConfig, $sefSite;
      $sefRewriter = sefLoadRewriter( $database, $sefConfig, $sefSite );
    }
    if (!eregi("^(([^:/?#]+):)",$string) && !strcasecmp(substr($string,0,9),'index.php') ) {
      $string = str_replace( '&amp;', '&', $string );
      $url_array = explode('/', $_SERVER['REQUEST_URI']);
      if (in_array('content', $url_array)) {
        $uri        = explode('content/', $_SERVER['REQUEST_URI']);
        $option       = 'com_content';
        $_GET['option']   = $option;
        $_REQUEST['option'] = $option;
        $pos        = array_search ('content', $url_array);
        $lang = '';
        foreach($url_array as $key=>$value) {
          if ( !strcasecmp(substr($value,0,5),'lang,') ) {
            $temp = explode(',', $value);
            if (isset($temp[0]) && $temp[0] != '' && isset($temp[1]) && $temp[1] != '') {
              $_GET['lang']     = $temp[1];
              $_REQUEST['lang']   = $temp[1];
              $lang         = $temp[1];
            }
            unset($url_array[$key]);
          }
        }
        if (isset($url_array[$pos+8]) && $url_array[$pos+8] != '' && in_array('category', $url_array) && ( strpos( $url_array[$pos+5], 'order,' ) !== false ) && ( strpos( $url_array[$pos+6], 'filter,' ) !== false ) ) {
          $task           = $url_array[$pos+1];
          $sectionid        = $url_array[$pos+2];
          $id           = $url_array[$pos+3];
          $Itemid         = $url_array[$pos+4];
          $order          = str_replace( 'order,', '', $url_array[$pos+5] );
          $filter         = str_replace( 'filter,', '', $url_array[$pos+6] );
          $limit          = $url_array[$pos+7];
          $limitstart       = $url_array[$pos+8];
            $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['sectionid']    = $sectionid;
          $_REQUEST['sectionid']  = $sectionid;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;
          $_GET['order']      = $order;
          $_REQUEST['order']    = $order;
          $_GET['filter']     = $filter;
          $_REQUEST['filter']   = $filter;
          $_GET['limit']      = $limit;
          $_REQUEST['limit']    = $limit;
          $_GET['limitstart']   = $limitstart;
          $_REQUEST['limitstart'] = $limitstart;

          $QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&id=$id&Itemid=$Itemid&order=$order&filter=$filter&limit=$limit&limitstart=$limitstart";
        } else if (isset($url_array[$pos+7]) && $url_array[$pos+7] != '' && ( in_array('archivecategory', $url_array) || in_array('archivesection', $url_array) ) ) {
          $task           = $url_array[$pos+1];
          $sectionid        = $url_array[$pos+2];
          $Itemid         = $url_array[$pos+3];
          $limit          = $url_array[$pos+4];
          $limitstart       = $url_array[$pos+5];
          $year           = $url_array[$pos+6];
          $month          = $url_array[$pos+7];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['id']       = $sectionid;
          $_REQUEST['id']     = $sectionid;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;
          $_GET['limit']      = $limit;
          $_REQUEST['limit']    = $limit;
          $_GET['limitstart']   = $limitstart;
          $_REQUEST['limitstart'] = $limitstart;
          $_GET['year']       = $year;
          $_REQUEST['year']     = $year;
          $_GET['month']      = $month;
          $_REQUEST['month']    = $month;

          $QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&Itemid=$Itemid&limit=$limit&limitstart=$limitstart&year=$year&month=$month";
        } else if (isset($url_array[$pos+7]) && $url_array[$pos+7] != '' && in_array('category', $url_array) && ( strpos( $url_array[$pos+5], 'order,' ) !== false )) {
          $task           = $url_array[$pos+1];
          $sectionid        = $url_array[$pos+2];
          $id           = $url_array[$pos+3];
          $Itemid         = $url_array[$pos+4];
          $order          = str_replace( 'order,', '', $url_array[$pos+5] );
          $limit          = $url_array[$pos+6];
          $limitstart       = $url_array[$pos+7];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['sectionid']    = $sectionid;
          $_REQUEST['sectionid']  = $sectionid;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;
          $_GET['order']      = $order;
          $_REQUEST['order']    = $order;
          $_GET['limit']      = $limit;
          $_REQUEST['limit']    = $limit;
          $_GET['limitstart']   = $limitstart;
          $_REQUEST['limitstart'] = $limitstart;

          $QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&id=$id&Itemid=$Itemid&order=$order&limit=$limit&limitstart=$limitstart";
        } else if (isset($url_array[$pos+6]) && $url_array[$pos+6] != '') {
          $task           = $url_array[$pos+1];
          $sectionid        = $url_array[$pos+2];
          $id           = $url_array[$pos+3];
          $Itemid         = $url_array[$pos+4];
          $limit          = $url_array[$pos+5];
          $limitstart       = $url_array[$pos+6];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['sectionid']    = $sectionid;
          $_REQUEST['sectionid']  = $sectionid;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;
          $_GET['limit']      = $limit;
          $_REQUEST['limit']    = $limit;
          $_GET['limitstart']   = $limitstart;
          $_REQUEST['limitstart'] = $limitstart;

          $QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&id=$id&Itemid=$Itemid&limit=$limit&limitstart=$limitstart";
        } else if (isset($url_array[$pos+5]) && $url_array[$pos+5] != '') {
          $task           = $url_array[$pos+1];
          $id           = $url_array[$pos+2];
          $Itemid         = $url_array[$pos+3];
          $limit          = $url_array[$pos+4];
          $limitstart       = $url_array[$pos+5];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;
          $_GET['limit']      = $limit;
          $_REQUEST['limit']    = $limit;
          $_GET['limitstart']   = $limitstart;
          $_REQUEST['limitstart'] = $limitstart;

          $QUERY_STRING = "option=com_content&task=$task&id=$id&Itemid=$Itemid&limit=$limit&limitstart=$limitstart";
        } else if (isset($url_array[$pos+4]) && $url_array[$pos+4] != '' && ( in_array('archivecategory', $url_array) || in_array('archivesection', $url_array) )) {
          $task           = $url_array[$pos+1];
          $year           = $url_array[$pos+2];
          $month          = $url_array[$pos+3];
          $module         = $url_array[$pos+4];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['year']       = $year;
          $_REQUEST['year']     = $year;
          $_GET['month']      = $month;
          $_REQUEST['month']    = $month;
          $_GET['module']     = $module;
          $_REQUEST['module']   = $module;

          $QUERY_STRING = "option=com_content&task=$task&year=$year&month=$month&module=$module";
        } else if (!(isset($url_array[$pos+5]) && $url_array[$pos+5] != '') && isset($url_array[$pos+4]) && $url_array[$pos+4] != '') {
          $task           = $url_array[$pos+1];
          $sectionid        = $url_array[$pos+2];
          $id           = $url_array[$pos+3];
          $Itemid         = $url_array[$pos+4];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['sectionid']    = $sectionid;
          $_REQUEST['sectionid']  = $sectionid;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;

          $QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&id=$id&Itemid=$Itemid";
        } else if (!(isset($url_array[$pos+4]) && $url_array[$pos+4] != '') && (isset($url_array[$pos+3]) && $url_array[$pos+3] != '')) {
          $task           = $url_array[$pos+1];
          $id           = $url_array[$pos+2];
          $Itemid         = $url_array[$pos+3];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;
          $_GET['Itemid']     = $Itemid;
          $_REQUEST['Itemid']   = $Itemid;

          $QUERY_STRING = "option=com_content&task=$task&id=$id&Itemid=$Itemid";
        } else if (!(isset($url_array[$pos+3]) && $url_array[$pos+3] != '') && (isset($url_array[$pos+2]) && $url_array[$pos+2] != '')) {
          $task           = $url_array[$pos+1];
          $id           = $url_array[$pos+2];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;
          $_GET['id']       = $id;
          $_REQUEST['id']     = $id;

          $QUERY_STRING = "option=com_content&task=$task&id=$id";
        } else if (!(isset($url_array[$pos+2]) && $url_array[$pos+2] != '') && (isset($url_array[$pos+1]) && $url_array[$pos+1] != '')) {
          $task = $url_array[$pos+1];
          $_GET['task']       = $task;
          $_REQUEST['task']     = $task;

          $QUERY_STRING = 'option=com_content&task='. $task;
        }
        if ($lang!='') {
          $QUERY_STRING .= '&lang='. $lang;
        }
        $_SERVER['QUERY_STRING']  = $QUERY_STRING;
        $REQUEST_URI        = $uri[0].'index.php?'.$QUERY_STRING;
        $_SERVER['REQUEST_URI']   = $REQUEST_URI;
        $string = $QUERY_STRING;
      } else if (in_array('component', $url_array)) {
        $uri = explode('component/', $_SERVER['REQUEST_URI']);
        $uri_array = explode('/', $uri[1]);
        $QUERY_STRING = '';
        $path     = $mosConfig_absolute_path .'/components';
        $dirlist  = array();
        if ( is_dir( $path ) ) {
          $base = opendir( $path );
          while (false !== ( $dir = readdir($base) ) ) {
            if (is_dir($path .'/'. $dir) && $dir !== '.' && $dir !== '..' && strtolower($dir) !== 'cvs' && strtolower($dir) !== '.svn') {
              $dirlist[] = $dir;
            }
          }
          closedir($base);
        }
        foreach($uri_array as $value) {
          $temp = explode(',', $value);
          if (isset($temp[0]) && $temp[0]!='' && isset($temp[1]) && $temp[1]!='') {
            $_GET[$temp[0]]   = $temp[1];
            $_REQUEST[$temp[0]] = $temp[1];
            if ( $temp[0] == 'option' ) {
              $check = '';
              if (count( $dirlist )) {
                foreach ( $dirlist as $dir ) {
                  if ( $temp[1] == $dir ) {
                    $check = 1;
                    break;
                  }
                }
              }
              if ( !$check ) {
                header( 'HTTP/1.0 404 Not Found' );
                require_once( $mosConfig_absolute_path . '/templates/404.php' );
                exit( 404 );
              }
            }
            if ( $QUERY_STRING == '' ) {
              $QUERY_STRING .= "$temp[0]=$temp[1]";
            } else {
              $QUERY_STRING .= "&$temp[0]=$temp[1]";
            }
          }
        }
        $_SERVER['QUERY_STRING']  = $QUERY_STRING;
        $REQUEST_URI        = $uri[0].'index.php?'.$QUERY_STRING;
        $_SERVER['REQUEST_URI']   = $REQUEST_URI;
      }
      return $sefRewriter->rewrite( $string );
    } else {
      if ( (strpos( $string, $mosConfig_live_site ) !== 0) ) {
        if (strncmp($string, '/', 1) == 0) {
          $live_site_parts = array();
          eregi("^(https?:[\/]+[^\/]+)(.*$)", $mosConfig_live_site, $live_site_parts);
          $string = $live_site_parts[1] . $string;

        } else if ( ( strpos( $string, 'http' ) !== 0 )
          && ( strpos( $string, 'https' ) !== 0 )
          && ( strpos( $string, 'ftp' ) !== 0 )
          && ( strpos( $string, 'file' ) !== 0 )
          && ( strpos( $string, 'mailto' ) !== 0 )
          && ( strpos( $string, 'javascript' ) !== 0 ) ) {
            $string = $mosConfig_live_site .'/'. $string;
        }
      }
      return $string;
    }
  }
}

if (!function_exists( 'sefIsJoomlaSEF' )) {
  /**
   * Determines whether a given URL is in the native Joomla! SEF format.
   *
   * @param string $url
   * @return string
   */
  function sefIsJoomlaSEF( $url ) {
    if ($url[0] == '/') $url = substr( $url, 1 );
    return (eregi( '^content/', $url )
    || eregi( '^worp/', $url )
    || eregi( '^plakat/', $url )
    || eregi( '^weblinks/', $url )
    || eregi( '^newsfeeds/', $url )
    || eregi( '^component/.*option,com_', $url ));
  }
}

if (!function_exists( 'sefIsJoomlaURL' )) {
  /**
   * Determines whether a given URL is an internal Joomla! URL address.
   *
   * @param string $url
   * @return string
   */
  function sefIsJoomlaURL( $url ) {
    if ($url[0] == '/') $url = substr( $url, 1 );
    return (eregi( '^index.php', $url )
    || eregi( '^index2.php', $url ));
  }
}

if (!function_exists( 'sefIsExternalURL' )) {
  /**
   * Determines whether a given URL is a full, absolute URL including the
   * 'http://' prefix.
   *
   * @param string $url
   * @return boole
   */
  function sefIsExternalURL( $url ) {
    return (eregi( '^(http|https|ftp)\://', $url ) ? true : false);
  }
}

if (!function_exists( 'sefRewriteToJoomlaSEF' )) {
  /**
   * Rewrites an internal Joomla! URL into Joomla!'s native SEF format.
   *
   * @param string $url
   * @param string $path
   * @return string
   */
  function sefRewriteToJoomlaSEF( $url, $path = null ) {
    global $sefConfig;
    $component = null;
    // Webuddha 081808 - Fix Component Extraction Issue
    if (ereg( '[\?&]+option=com_([0-9a-zA-Z_\-]+)&{0,1}', $url, $matches ))
      $component = $matches[1];
    // Return Original if component not extracted
    if( is_null($component) ) return $url;
    $menu_id = 0;
    if (ereg( '&Itemid=([0-9]+)', $url, $matches ))
    $menu_id = $matches[1];
    if ($component == 'content') {
      $rewrites = array(
      '#^index\.php\?option=com_content#' => 'content',
      '#&([\w]+)=([\w\d]+)#'  => '/\\2',
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );
    }
    elseif ($component == 'banners') {
      $rewrites = array(
      '#^index\.php\?option=com_banners#' => 'plakat',
      '#&([\w]+)=([\w\d]+)#'  => '/\\2',
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );
    }
    elseif ($component == 'wrapper') {
      $rewrites = array(
      '#^index\.php\?option=com_wrapper#' => 'worp',
      '#&([\w]+)=([\w\d]+)#'  => '/\\2',
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );
    }
    elseif ($component == 'weblinks') {
      $rewrites = array(
      '#^index\.php\?option=com_weblinks#' => 'weblinks',
      '#&([\w]+)=([\w\d]+)#'  => '/\\2',
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );
    }
    elseif ($component == 'newsfeeds') {
      $rewrites = array(
      '#^index\.php\?option=com_newsfeeds#' => 'newsfeeds',
      '#&([\w]+)=([\w\d]+)#'  => '/\\2',
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );

    }
    else {
      $path = ($path ? $path : 'component/option,com_' .
      $component . '/Itemid,' . $menu_id . '/');
      $rewrites = array(
      '#^index\.php#'         => '',
      "#[\?&]+option=com_$component#" => '',
      '#[\?&]+Itemid=([\d]+)#' => '',
      '#\?#'                  => '&',
      '#&([\w]+)=([^&]+)#'    => '/\\1,\\2',
      '#^[/]?#'               => $path, // Consume one slash and prepend component path
      '#([^/])$#'             => '\\1/', // Add trailing slash if necessary
      );
    }
    return preg_replace( array_keys( $rewrites ),
    array_values( $rewrites ), $url );
  }
}

if (!function_exists( 'sefRewriteFromJoomlaSEF' )) {
  /**
   * Rewrites a native Joomla! SEF URL into an internal Joomla! URL.
   *
   * @param string $url
   * @return string
   */
  function sefRewriteFromJoomlaSEF( $url ) {
    if ($url[0] == '/') $url = substr( $url, 1 );
    if (ereg( '^content/', $url ) && !ereg( '/category/', $url ) && !ereg( '/blogcategory/', $url )) {
      $rewrites = array(
      '#^content#'           => '',

      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' =>
      '&task=\\1&id=\\2&Itemid=\\3&limit=\\4&limitstart=\\5',

      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' =>
      '&task=\\1&year=\\2&month=\\3&module=\\4',

      '#/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&id=\\2&Itemid=\\3',
      '#/([^/]+)/([^/]+)/#'   => '&task=\\1&id=\\2',
      '#/([^/]+)/#'           => '&task=\\1',
      '#^#'                   => 'index.php?option=com_content',
      );
    }
    elseif (ereg( '^content/', $url ) && ereg( '/blogcategory/', $url ) ) {
      $rewrites = array(
      '#^content#'           => '',

      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' =>
      '&task=\\1&id=\\2&Itemid=\\3&limit=\\4&limitstart=\\5',

      '#/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&id=\\2&Itemid=\\3',
      '#/([^/]+)/([^/]+)/#'   => '&task=\\1&id=\\2',
      '#/([^/]+)/#'           => '&task=\\1',
      '#^#'                   => 'index.php?option=com_content',

      );
    }
    elseif (ereg( '^content/', $url ) && ereg( '/category/', $url ) ) {
      $rewrites = array(
      '#^content#'           => '',

      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' =>
      '&task=\\1&sectionid=\\2&id=\\3&Itemid=\\4&limit=\\5&limitstart=\\6',
      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' =>
      '&task=\\1&sectionid=\\2&id=\\3&Itemid=\\4',
      '#/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&id=\\2&Itemid=\\3',
      '#/([^/]+)/([^/]+)/#'   => '&task=\\1&id=\\2',
      '#/([^/]+)/#'           => '&task=\\1',
      '#^#'                   => 'index.php?option=com_content',

      );
    }
    elseif (ereg( '^plakat/', $url ) ) {
      $rewrites = array(
      '#^plakat#'           => '',
      '#/([^/]+)/([^/]+)/#'   => '&task=\\1&bid=\\2',
      '#/([^/]+)/#'           => '&Itemid=\\1',
      '#^#'                   => 'index.php?option=com_banners',

      );
    }
    elseif (ereg( '^worp/', $url ) ) {
      $rewrites = array(
      '#^worp#'           => '',
      '#/([^/]+)/([^/]+)/#'   => '&catid=\\1&Itemid=\\2',
      '#/([^/]+)/#'           => '&Itemid=\\1',
      '#^#'                   => 'index.php?option=com_wrapper',

      );
    }
    elseif (ereg( '^weblinks/', $url ) ) {
      $rewrites = array(
      '#^weblinks#'           => '',
      '#/([^/]+)/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&catid=\\2&id=\\3&Itemid=\\4',
      '#/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&catid=\\2&id=\\3',
      '#/([^/]+)/([^/]+)/#'   => '&catid=\\1&Itemid=\\2',
      '#/([^/]+)/#'           => '&Itemid=\\1',
      '#^#'                   => 'index.php?option=com_weblinks',

      );
    }
    elseif (ereg( '^newsfeeds/', $url ) ) {
      $rewrites = array(
      '#^newsfeeds#'           => '',
      '#/([^/]+)/([^/]+)/([^/]+)/#' => '&task=\\1&feedid=\\2&Itemid=\\3',
      '#/([^/]+)/([^/]+)/#'   => '&catid=\\1&Itemid=\\2',
      '#/([^/]+)/#'           => '&Itemid=\\1',
      '#^#'                   => 'index.php?option=com_newsfeeds',

      );
    }
    else if (ereg( '^component/', $url )) {
      // Now this is pretty simple. Removed the earlier assumptions about the
      // 'option' parameter being the first, as phpShop among other doesn't
      // stick to any particular convention.
      $rewrites = array(
      '#^component/([^,]+),([^/]+)#' => 'index.php?\\1=\\2',
      '#/([^,]+),([^/]+)#'    => '&\\1=\\2',
      '#/$#'                  => '',
      );
    }
    return preg_replace( array_keys( $rewrites ),
    array_values( $rewrites ), $url );
  }
}

if (!function_exists( 'sefEncode' )) {
  /**
   * Encode URLs in sef_ex.php extensions
   *
   * @param string $string
   * @return string
   */
  function sefEncode($string) {
    global $sefConfig;

    if (is_array( $sefConfig->spec_chars_d) && is_array( $sefConfig->config->spec_chars) ) {
      $spec_chars_d = $sefConfig->spec_chars_d;
      $spec_chars = $sefConfig->spec_chars;
      foreach ($spec_chars_d as $i => $spec_char)
      {
        $string = str_replace(stripslashes($spec_char ), stripslashes($spec_chars[$i]), $string);
      }
    }
    $string = urlencode($string);
    $string = eregi_replace("%2F", "%10", $string);
    $string = eregi_replace($sefConfig->encode_space_char, "%11", $string);
    $string = eregi_replace("\+", $sefConfig->encode_space_char, $string);
    $replace = explode(",", $sefConfig->encode_strip_chars );
    foreach ($replace as $value) {
      if ($value != "") {
        $string = eregi_replace(urlencode($value), "", $string );
      }
    }
    if ($sefConfig->encode_lowercase) {
      $string = strtolower($string);
    }
    return $string;
  }
}
if (!function_exists( 'sefDecode' )) {
  /**
   * Decode URLs in sef_ext.php extensions
   *
   * @param string $string
   * @return string
   */
  function sefDecode($string) {
    global $sefConfig;
    $string = eregi_replace($sefConfig->encode_page_suffix, "", $string);
    $string = eregi_replace($sefConfig->encode_space_char, "%20", $string);
    $string = eregi_replace("%11", $sefConfig->encode_space_char, $string);
    $string = eregi_replace("%10", "%2F", $string);
    $string = urldecode($string);
    $string = addslashes($string);
    if (is_array( $sefConfig->spec_chars_d) && is_array( $sefConfig->config->spec_chars) ) {
      $spec_chars_d = $sefConfig->spec_chars_d;
      $spec_chars = $sefConfig->spec_chars;
      foreach ($spec_chars_d as $i => $spec_char) {
        $string = str_replace(stripslashes($spec_chars[$i] ), stripslashes($spec_char), $string);
      }
    }
    return $string;
  }
}


/**
 * Check if used Version oler than the one available for upgrade
 *
 * @param object $upgrader
 * @param string $version
 * @return boole
 */
function opensef_getComponentVersion($upgrader, $version) {
  global $mosConfig_absolute_path, $database, $mainframe;

  $com->oldVersion = $database->loadResult();
  $com->oldVersion = $version;
  $com->module = "com_sef";

  $com->newVersion = $upgrader->get_server_version("com_sef");

  if ($com->newVersion > $com->oldVersion)
  $com->update = true;
  else
  $com->update = false;
  return $com;
}

/**
* Content code
* @package Joomla
* @subpackage Content
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
* Modified by iJoomla.com, published under the name Metataggenerator
* Modified by David Jardin, Achim Raji
* Modified for OpenSEF by Marko "Predator" Schmuck
*/


/**
 * Save Metatag changes
 *
 * @return boole
 */
function metatag_save_manager() {
  global $database,$option2,$cid, $sefConfig;

  $cid    = mosGetParam( $_POST, 'cid', array(0) );
  if (!is_array( $cid )) {
    $cid = array(0);
  }
  $metakey = mosGetParam( $_POST, 'metakey', '' );
  $metadesc = mosGetParam( $_POST, 'metadesc', '' );

  foreach($cid as $key=>$id) {
    $query = "UPDATE #__content"
    . " SET metakey = '".addslashes(stripslashes(@$metakey[$id]))."', metadesc='".addslashes(stripslashes(@$metadesc[$id]))."'"
    . " WHERE id = ".$id." "
    ;
    $database->setQuery( $query );
    if (!$database->query()) {
      echo $database->getErrorMsg();
      exit();
    }
  }
  echo '<h2>'._T( 'META_CHANGES_SUCCESS' ).'</h2>';
  return true;
}

/**
 * Generate keywors for the content
 *
 * @return boole
 */
function metatag_gen_key() {
  global $mosConfig_absolute_path,$database,$option2,$cid, $sefConfig;

  $sectionid  = mosGetParam( $_REQUEST, 'sectionid', 0 );
  $id     = mosGetParam( $_REQUEST, 'id', '' );
  $cid    = mosGetParam( $_POST, 'cid', array(0) );
  if (!is_array( $cid )) {
    $cid = array(0);
  }
  $exclude_key = explode(",",$sefConfig->meta_exclude_key);

  $_POST=array_merge($_GET,$_POST);

  $words = $mosConfig_absolute_path.'/administrator/components/com_sef/includes/seo_words/seo_words_'.$sefConfig->backend_language.'.txt';

  $where=" WHERE 1=1 ";
  if(sizeof($cid)==0) {
    echo "<h2>No content was selected for generating!</h2>";
    return;
  }
  $compare="";
  $fp=fopen($words,'r');
  while(!feof($fp)) $compare.=fread($fp,1024);
  fclose($fp);

  $compare=str_replace("\t"," ",strtolower($compare));
  $compare=explode("\r\n",$compare);

  if($sefConfig->meta_kreplace !=1) $where.=" AND C.metakey=''";

  $where.=" AND ( ";
  foreach($cid as $key=>$value)
  $where.="  C.id='$value' OR ";
  $where.=" C.id=-1) ";

  $query = "SELECT C.id,C.title,C.introtext,C.fulltext"
  ."\n FROM #__content as C"
  . $where;
  $database->setQuery( $query );
  $rows = $database->loadObjectList();

  for($i=0;$i<sizeof($rows);$i++) {
    if(empty($rows[$i]->fulltext))  {
      $content=$rows[$i]->introtext;
      $content=str_replace("&ouml;","�",$content);
      $content=str_replace("&Ouml;","�",$content);
      $content=str_replace("&uuml;","�",$content);
      $content=str_replace("&Uuml;","�",$content);
      $content=str_replace("&auml;","�",$content);
      $content=str_replace("&Auml;","�",$content);
      $content=str_replace("&szlig;","�",$content);
    } else {
      $content=$rows[$i]->fulltext;
      $content=str_replace("&ouml;","�",$content);
      $content=str_replace("&Ouml;","�",$content);
      $content=str_replace("&uuml;","�",$content);
      $content=str_replace("&Uuml;","�",$content);
      $content=str_replace("&auml;","�",$content);
      $content=str_replace("&Auml;","�",$content);
      $content=str_replace("&szlig;","�",$content);
    }
    $keywords=metatag_gen_keyword($content,$_POST,$sefConfig->meta_chars,$compare);
    if($sefConfig->meta_gdesc == 'full') {
      if(!empty($rows[$i]->fulltext))
      $desc_content=substr($rows[$i]->fulltext,0,$sefConfig->meta_gdesc_len);
      elseif($sefConfig->meta_gdesc_opt)
      $desc_content=substr($rows[$i]->introtext,0,$sefConfig->meta_gdesc_len);
    } else {
      if(!empty($rows[$i]->introtext))
      $desc_content=substr($rows[$i]->introtext,0,$sefConfig->meta_gdesc_len);
      elseif($sefConfig->meta_gdesc_opt)
      $desc_content=substr($rows[$i]->fulltext,0,$sefConfig->meta_gdesc_len);
    }
    for($s=0;$s<sizeof($exclude_key);$s++) {
      $desc_content=str_replace($exclude_key[$s]," ",$desc_content);
    }
    $update="metakey = \"" . $keywords."\"";
    $msg="<br><br> Keyword metatags changed for content title <b>".$rows[$i]->title."</b >";;
    if(isset($updatedesc)) {
      $query = "UPDATE #__content"
      . "\n SET ".$updatedesc
      . "\n WHERE id ='".$rows[$i]->id."'"
      ;}
      elseif(isset($update)){$query = "UPDATE #__content"
      . "\n SET ".$update
      . "\n WHERE id ='".$rows[$i]->id."'"
      ;}
      $database->setQuery( $query );
      if (!$database->query()) {
        echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
        exit();
      }
  }
  $msg = _T( 'META_KEY_SUCCESS' );
  echo "<h2>".$msg."</h2>";
  return true;
}

/**
 * Generate Descriptions for the content
 *
 * @return boole
 */
function metatag_gen_desc() {
  global $mosConfig_absolute_path,$database,$option2,$cid,$sefConfig;

  $sectionid  = mosGetParam( $_REQUEST, 'sectionid', 0 );
  $id     = mosGetParam( $_REQUEST, 'id', '' );
  $cid    = mosGetParam( $_POST, 'cid', array(0) );
  if (!is_array( $cid )) {
    $cid = array(0);
  }

  $exclude_key = explode(",",$sefConfig->meta_exclude_key);

  $_POST=array_merge($_GET,$_POST);
  $words = $mosConfig_absolute_path.'/administrator/components/com_sef/includes/seo_words/seo_words_'.$sefConfig->backend_language.'.txt';
  $where=" WHERE 1=1 ";

  if(sizeof($cid)==0) {
    echo "<h2>No content was selected for generating!</h2>";
    return;
  }
  $compare="";
  $fp=fopen($words,'r');
  while(!feof($fp))
  $compare.=fread($fp,1024);
  fclose($fp);

  $compare=str_replace("\t"," ",strtolower($compare));
  $compare=explode("\r\n",$compare);

  if($sefConfig->meta_dreplace != 1 ) $where.=" AND C.metadesc=''";

  $where.=" AND ( ";
  foreach($cid as $key=>$value)
  $where.="  C.id='$value' OR ";
  $where.=" C.id=-1) ";

  $query = "SELECT C.id,C.title,C.introtext,C.fulltext"
  . "\n FROM #__content as C"
  . $where
  ;
  $database->setQuery( $query );
  $rows = $database->loadObjectList();

  for($i=0;$i<sizeof($rows);$i++) {
    if(empty($rows[$i]->fulltext)) {
      $content=$rows[$i]->introtext;
      $content=str_replace("&ouml;","ö",$content);
      $content=str_replace("&Ouml;","Ö",$content);
      $content=str_replace("&uuml;","ü",$content);
      $content=str_replace("&Uuml;","Ü",$content);
      $content=str_replace("&auml;","ä",$content);
      $content=str_replace("&Auml;","Ä",$content);
      $content=str_replace("&szlig;","ß",$content);
    } else {
      $content=$rows[$i]->fulltext;
      $content=str_replace("&ouml;","ö",$content);
      $content=str_replace("&Ouml;","Ö",$content);
      $content=str_replace("&uuml;","ü",$content);
      $content=str_replace("&Uuml;","Ü",$content);
      $content=str_replace("&auml;","ä",$content);
      $content=str_replace("&Auml;","Ä",$content);
      $content=str_replace("&szlig;","ß",$content);
    }

    $keywords=metatag_gen_keyword($content,$_POST,$sefConfig->meta_chars,$compare);

    if($sefConfig->meta_gdesc == 'full' ) {
      if(!empty($rows[$i]->fulltext))
      $desc_content=substr($rows[$i]->fulltext,0,$sefConfig->meta_gdesc_len);
      elseif($sefConfig->meta_gdesc_opt)
      $desc_content=substr($rows[$i]->introtext,0,$sefConfig->meta_gdesc_len);
    } else {
      if(!empty($rows[$i]->introtext))
      $desc_content=substr($rows[$i]->introtext,0,$sefConfig->meta_gdesc_len);
      elseif($sefConfig->meta_gdesc_opt)
      $desc_content=substr($rows[$i]->fulltext,0,$sefConfig->meta_gdesc_len);
    }
    for($s=0;$s<sizeof($exclude_key);$s++) {
      $desc_content=str_replace($exclude_key[$s]," ",$desc_content);
    }

    $desc_content=str_replace("\r\n"," ",$desc_content);
    $desc_content=str_replace("\n"," ",$desc_content);
    $desc_content=str_replace("  "," ",$desc_content);
    $updatedesc="metadesc=\"".addslashes(stripslashes(strip_tags($desc_content)))."\"";
    $msg="<br><br> Description metatags changed for content title <b>".$rows[$i]->title."</b >";

    if(isset($updatedesc)) {
      $query = "UPDATE #__content"
      . "\n SET ".$updatedesc
      . "\n WHERE id ='".$rows[$i]->id."'"
      ;}
      elseif(isset($update)){$query = "UPDATE #__content"
      . "\n SET ".$update
      . "\n WHERE id ='".$rows[$i]->id."'"
      ;}
      $database->setQuery( $query );
      if (!$database->query()) {
        echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
        exit();
      }
  }
  $msg = _T('META_DESC_SUCCESS');
  echo "<h2>".$msg."</h2>";
  return true;
}


/**
 * Keyword Generator
 *
 * @param string $content
 * @param global $_POST
 * @param string $chars
 * @param array $compare
 * @return array
 */
function metatag_gen_keyword($content,$_POST,$chars,$compare) {
  global $mosConfig_absolute_path, $sefConfig;

  if($sefConfig->meta_nsep == 'br')
  $nsep="\n";
  else
  $nsep=$sefConfig->meta_nsep;

  $content.="\r\n";
  $content=strip_tags(stripslashes(strtolower($content)));
  $content=str_replace(array("&nbsp;"),array(" "),$content);
  $content=str_replace(array("\n","-"),array(" "," "),$content);
  for($s=0;$s<sizeof($chars);$s++) {
    $content=str_replace($chars[$s]," ",$content);
  }
  $content=html_entity_decode($content);
  $contents=explode(" " ,$content);
  $results=array('','');
  $i=0;
  foreach($contents as $key=>$value) {
    $value=trim($value,"\x00..\x1F");
    $value=str_replace(array("\r"),array(""),$value);
    $value=str_replace(array("\n"),array(""),$value);

    if(!in_array($value,$compare))
    if(strlen($value)>1)
    if(!in_array(array(trim($value),strlen(trim($value))),$results)) {
      $results[$i][0]=$value;
      $results[$i][1]=strlen($value);
      $i++;
    }
  }

  foreach($results as $res)
  $sortAux[] = $res['1'];

  if($sefConfig->meta_nsort == 'SORT_DESC')
  $tp=SORT_DESC;
  elseif($sefConfig->meta_nsort == 'SORT_ASC')
  $tp=SORT_ASC;

  array_multisort($sortAux, $tp, $results);
  $result="";
  for($j=0;$j<=$i;$j++){
    if($j>($sefConfig->meta_nlist -1 ))
    break;
    if($results[$j][0]!="")
    $result.=$results[$j][0].$nsep." ";
  }
  return $result;
}

/**
 * filter categories
 *
 * @param string $query
 * @param string $active
 * @return selectlist
 */
function metatag_filterCategory( $query, $active=NULL ) {
  global $database;

  $categories[] = mosHTML::makeOption( '0', _T('SEL_CATEGORY') );
  $database->setQuery( $query );
  $categories = array_merge( $categories, $database->loadObjectList() );

  $category = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active );

  return $category;
}
function metatag_filterSection( $name, $active=NULL, $javascript=NULL, $order='ordering' ) {
    global $database;

    $categories[] = mosHTML::makeOption( '0', _T('SEL_SECTION') );
    $query = "SELECT id AS value, title AS text"
    . "\n FROM #__sections"
    . "\n WHERE published = 1"
    . "\n ORDER BY $order"
    ;
    $database->setQuery( $query );
    $sections = array_merge( $categories, $database->loadObjectList() );

    $category = mosHTML::selectList( $sections, $name, 'class="inputbox" size="1" '. $javascript, 'value', 'text', $active );

    return $category;
  }
?>
Return current item: Joomla SEF / SEO - extending OpenSEF