<?php
/**
 * SEF module for Joomla!
 *
 * @author      $Author: michal $
 * @copyright   ARTIO s.r.o., http://www.artio.cz
 * @package     JoomSEF
 * @version     $Name$, ($Revision: 4994 $, $Date: 2005-11-03 20:50:05 +0100 (??t, 03 XI 2005) $)
 */

// Security check to ensure this file is being included by a parent file.
if (!defined('_VALID_MOS')) die('Direct Access to this location is not allowed.');

global $_SEF_SPACE, $lowerCase;

/**
 * SEF Component class.
 *
 */
class sef_component
{

    /**
     * Enter description here...
     *
     * @param  array $url_array
     * @param  int $pos
     * @return string
     */
    function revert(&$url_array, $pos)
    {
        global $_SEF_SPACE;

        $QUERY_STRING = '';

        if (strcspn ($url_array[1], ',') == strlen($url_array[1])) {
            // This is a nocache url
            $x = 0;
            $c = count($url_array);
            while ($x < $c) {
                if (isset($url_array[$x]) && $url_array[$x] != '' && isset($url_array[$x + 1]) && $url_array[$x + 1] != '') {
                    $_GET[$url_array[$x]] = $_REQUEST[$url_array[$x]] = $url_array[$x + 1];
                    $QUERY_STRING .= '&'.$url_array[$x].'='.$url_array[$x + 1];
                }
                $x += 2;
            }
        }
        else {
            //This is a default mambo SEF url for a component
            foreach($url_array as $value) {
                $temp = explode(',', $value);
                if (isset($temp[0]) && $temp[0] != '' && isset($temp[1]) && $temp[1] != '') {
                    $_GET[$temp[0]] = $_REQUEST[$temp[0]] = $temp[1];
                    $QUERY_STRING .= "&$temp[0]=$temp[1]";
                }
            }
        }
        return str_replace('&option', 'option', $QUERY_STRING);
    }
}

/**
 * SEF content class.
 *
 */
class sef_content
{

    /**
     * Enter description here...
     *
     * @param  array $url_array
     * @param  int $pos
     * @return string
     */
    function revert(&$url_array, $pos)
    {
        $_GET['option'] = $_REQUEST['option'] = $option = 'com_content';
        $c = count(array_filter($url_array)) - strval($pos);

        switch ($c) {
            //$option/$task/$sectionid/$id/$Itemid/$limit/$limitstart
            case 7: {
                $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];
                break;
            }
            // $option/$task/$id/$Itemid/$limit/$limitstart
            case 6: {
                $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];
                break;
            }
            // $option/$task/$sectionid/$id/$Itemid
            case 5: {
                $task = $url_array[$pos + 1];
                $sectionid = $url_array[$pos + 2];
                $id = $url_array[$pos + 3];
                $Itemid = $url_array[$pos + 4];
                break;
            }
            // $option/$task/$id/$Itemid
            case 4: {
                $task = $url_array[$pos + 1];
                $id = $url_array[$pos + 2];
                $Itemid = $url_array[$pos + 3];
                break;

            }
            // $option/$task/$id
            case 3: {
                $task = $url_array[$pos + 1];
                $id = $url_array[$pos + 2];
                break;

            }
            // $option/$task
            case 2: {
                $task = $url_array[$pos + 1];
            }
        }
        //$QUERY_STRING = "option=com_content&task=$task&sectionid=$sectionid&id=$id&Itemid=$Itemid&limit=$limit&limitstart=$limitstart";
        $_GET['task'] = $_REQUEST['task'] = $task;
        $QUERY_STRING = "option=com_content&task=$task";
        if (@$sectionid) {
            $_GET['sectionid'] = $_REQUEST['sectionid'] = $sectionid;
            $QUERY_STRING .= "&sectionid=$sectionid";
        }
        if (@$id) {
            $_GET['id'] = $_REQUEST['id'] = $id;
            $QUERY_STRING .= "&id=$id";
        }
        if (@$Itemid) {
            $_GET['Itemid'] = $_REQUEST['Itemid'] = $Itemid;
            $QUERY_STRING .= "&Itemid=$Itemid";
        }
        if (@$limit) {
            $_GET['limit'] = $_REQUEST['limit'] = $limit;
            $_GET['limitstart'] = $_REQUEST['limitstart'] = $limitstart;
            $QUERY_STRING .= "&limit=$limit&limitstart=$limitstart";
        }
        return $QUERY_STRING;
    }

}

class sef_404
{

    /**
     * Create a SEF URL.
     *
     * @param  string $string
     * @param  array $vars
     * @return string
     */
    function create($string, &$vars)
    {
        global $database, $sefConfig;

        $debug = 0;

        $index = str_replace($GLOBALS['mosConfig_live_site'], '', $_SERVER['PHP_SELF']);
        $base  = dirname($index);
        $base .= ($base == '/') ? '' : '/';

        // In vars zitten de $option enzo.
        extract($vars);

        if ($debug) {
            $debug_string = $string;
            $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404'][$debug_string]['VARS'] = $vars;
        }

        // Plug-in system.
        if (file_exists($GLOBALS['mosConfig_absolute_path'].'/components/com_sef/sef_ext/'.$option.'.php')) {
            include($GLOBALS['mosConfig_absolute_path'].'/components/com_sef/sef_ext/'.$option.'.php');
        }
        else {
            $title = array();
            $title[] = getMenuTitle($option, @$task);
            $title[] = '/';
            $string = sef_404::sefGetLocation($string, $title, @$task, @$limit, @$limitstart, @$lang);
        }
        return $string;
    }

    /**
     * Return reverted URL in Joomla format.
     *
     * @param  array $url_array
     * @param  int $pos
     * @return string
     */
    function revert(&$url_array, $pos)
    {
        global $database, $sefConfig, $mosConfig_MetaDesc, $mosConfig_MetaKeys;

        $debug = 0;

        $QUERY_STRING = '';

        $req = str_replace('option/', '', implode('/', $url_array));
        if ($debug) $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404']['INITIAL_REQ'] = $req;

        // Removed by michal
        // This was causing problems with custom redirects.
        // verify trailing slash and default filename if there is one
        /*if (!eregi($sefConfig->addFile.'$', $req) && !eregi($sefConfig->suffix.'$', $req)) {
            //if there should be a filename add it on
            $req = $req.$sefConfig->addFile;
        }
        if (!eregi('/'.$sefConfig->addFile.'$', $req) && !eregi($sefConfig->suffix.'$', $req)) {
            //no suffix or filename entered so make sure there is a slash
            if (eregi($sefConfig->addFile.'$', $req)) $req = substr($req, 0, strlen($req) - strlen($sefConfig->addFile)).'/'.$sefConfig->addFile;
        }*/
        //$req = str_replace('//', '/', $req);

        if ($debug) $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404']['REQ'] = $req;
        //$sql="SELECT oldurl, newurl FROM #__redirection WHERE oldurl LIKE '".$req."' LIMIT 1";
        $sql = "SELECT * FROM #__redirection WHERE oldurl = '".$req."' LIMIT 1";
        $database->setQuery($sql);

        if ($database->loadObject($row) === true) {
            // use the cached url
            $string = $row->newurl;
            // update the count
            //$database->setQuery("UPDATE #__redirection SET cpt=(cpt+1) WHERE `newurl` LIKE '".$row->newurl."'");
            $database->setQuery("UPDATE #__redirection SET cpt=(cpt+1) WHERE `newurl` = '".$row->newurl."'");
            $database->query();
            $string = str_replace( '&amp;', '&', $string );
            $QUERY_STRING = str_replace('index.php?', '', $string);
            parse_str($QUERY_STRING, $vars);
            // $QUERY_STRING = str_replace( '&', '&amp;', $QUERY_STRING);
            if ($debug) {
                $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404']['QUERY_STRING'] = $QUERY_STRING;
                $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404']['VARS']= $vars;
            }
            $_GET = array_merge($_GET, $vars);
            $_REQUEST = array_merge($_REQUEST, $vars);

            // Add metatags
            if ($row->metatitle)  $GLOBALS['sefMetaTags']['title'] = $row->metatitle;
            if ($row->metadesc)   $GLOBALS['sefMetaTags']['metadesc'] = $row->metadesc;
            if ($row->metakey)    $GLOBALS['sefMetaTags']['metakey'] = $row->metakey;
            if ($row->metalang)   $GLOBALS['sefMetaTags']['lang'] = $row->metalang;
            if ($row->metarobots) $GLOBALS['sefMetaTags']['robots'] = $row->metarobots;
            if ($row->metagoogle) $GLOBALS['sefMetaTags']['googlebot'] = $row->metagoogle;
        }
        return $QUERY_STRING;
    }

    /**
     * Get SEF titles of content items.
     *
     * @param  string $task
     * @param  int $id
     * @return string
     */
    function getContentTitles($task, $id)
    {
        global $database, $sefConfig;

        $title = array();
        // JF translate extension.
        $jfTranslate = $sefConfig->translateNames ? ', `id`' : '';

        switch ($task) {
            case 'section':
            case 'blogsection': {
                if (isset($id)) $sql = "SELECT title AS section$jfTranslate FROM #__sections WHERE id = $id";
                break;
            }
            case 'category':
            case 'blogcategory':
                if (isset($id)) {
                    if ($sefConfig->showSection || !$sefConfig->showCat) {
                        $sql = 'SELECT s.title AS section'.($jfTranslate ? ', s.id' : '')
                        .($sefConfig->showCat ? ', c.title AS category'.($jfTranslate ? ', c.id' : '') : '')
                        .' FROM #__categories as c '
                        .'LEFT JOIN #__sections AS s ON c.section = s.id '
                        .'WHERE c.id = '.$id;
                    }
                    else $sql = "SELECT title AS category$jfTranslate FROM #__categories WHERE id = $id";
                }
                break;
            case 'view':
                if (isset($id)) {
                    if ($sefConfig->useAlias) {
                        // verify title alias is not empty
                        $database->setQuery("SELECT title_alias$jfTranslate FROM #__content WHERE id = $id");
                        $title_field = $database->loadResult() ? 'title_alias' : 'title';
                    }
                    else $title_field = 'title';
                    if ($sefConfig->showSection || !$sefConfig->showCat) {
                        $sql = 'SELECT '.($sefConfig->showSection ? 's.title AS section'.($jfTranslate ? ', s.id AS section_id' : '').', ' : '').
                        ($sefConfig->showCat ? 'c.title AS category'.($jfTranslate ? ', c.id AS category_id' : '').', ' : '').
                        'a.'.$title_field.' AS title'.($jfTranslate ? ', a.id' : '').' FROM #__content as a'.
                        ' LEFT JOIN #__sections AS s ON a.sectionid = s.id '.
                        ($sefConfig->showCat ? ' LEFT JOIN #__categories AS c ON a.catid = c.id ' : '').
                        ' WHERE a.id = '.$id;
                    }
                    else {
                        $sql = 'SELECT '.($sefConfig->showCat ? 'c.title AS category'.($jfTranslate ? ', c.id AS category_id' : '').', ' : '')
                        .'a.'.$title_field.' AS title'.($jfTranslate ? ', a.id' : '').' FROM #__content as a'.
                        ($sefConfig->showCat ? ' LEFT JOIN #__categories AS c ON a.catid = c.id ' : '').
                        ' WHERE a.id = '.$id;
                    }
                }
                break;
            default:
                $sql = '';
        }

        if ($sql) {
            $row = null;
            $database->setQuery($sql);
            $database->loadObject($row);

            if (isset($row->section)) {
                $title[] = $row->section;
                if ($task == 'section') $title[] = '/';
            }
            if (isset($row->category)) {
                $title[] = $row->category;
                if ($task == 'category') $title[] = '/';
            }
            if (isset($row->title)) $title[] = $row->title;
        }
        return $title;
    }

    /**
	 * Vul in de array $title de onderdelen waaruit de link moet bestaan
	 * Bijvoorbeeld: menuitem, categorie, itemnaam
	 * Deze functie last de boel aan elkaar
	 *
	 * @param  string $url
	 * @param  array $title
	 * @param  string $task
	 * @param  int $limit
	 * @param  int $limitstart
	 * @return string SEF URL
	 */
    function sefGetLocation($url, &$title, $task = null, $limit = null, $limitstart = null, $lang = null)
    {
        global $database, $sefConfig, $mosConfig_lang;

        $debug = 0;

        //shorten the url for storage and for consistancy
        $url = str_replace('&amp;', '&', $url);

        // Get all the titles ready for urls.
        $location = array();
        foreach($title as $titlePart) {
            if (strlen($titlePart) == 0) continue;
            $location[] = titleToLocation($titlePart);
        }

        // Remove unwanted characters.
        $finalstrip = explode('|', $sefConfig->stripthese);
        $takethese = str_replace('|', '', $sefConfig->friendlytrim);

        $imptrim = implode('/', $location);

        if (!is_null($task)) {
            $task = str_replace($sefConfig->replacement.'-'.$sefConfig->replacement, $sefConfig->replacement, $task);
            $task = str_replace($finalstrip, '', $task);
            $task = trim($task,$takethese);
        }

        $imptrim = str_replace($sefConfig->replacement.'-'.$sefConfig->replacement, $sefConfig->replacement, $imptrim);
        $suffixthere = 0;
        if (eregi($sefConfig->suffix.'$', $imptrim)) {
            $suffixthere = strlen($sefConfig->suffix);
        }

        $imptrim = str_replace($finalstrip, $sefConfig->replacement, substr($imptrim, 0, strlen($imptrim) - $suffixthere));
        $imptrim = str_replace($sefConfig->replacement.$sefConfig->replacement, $sefConfig->replacement, ((strlen($imptrim) > 100 - strlen($sefConfig->suffix) - strlen($GLOBALS['mosConfig_live_site'])) ? substr($imptrim, 0, strlen($imptrim) - $suffixthere) : $imptrim));

        $suffixthere = 0;
        if (eregi($sefConfig->suffix.'$', $imptrim)) {
            $suffixthere = strlen($sefConfig->suffix);
        }

        $imptrim = trim(substr($imptrim, 0, strlen($imptrim) - $suffixthere), $takethese);

        $location = str_replace('//', '/', $imptrim.(!is_null($task) ? '/'.$task.$sefConfig->suffix : ''));
        $location = str_replace('//', '/', str_replace('/'.$sefConfig->replacement, '/', $location));

        if ($debug) $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404']['sefGetLocation'][$url] = $location;

        // Attempt to intelligently detect page 0 of multi-page urls.
        // They don't really need to be added.
        if (isset($limitstart) && $limitstart == 0) {
            $url = preg_replace('/\&limit=[0-9]+\&limitstart=0/', '', $url);
        }

        // Let's reorder the variables in non-sef url first so they
        // are in alphabetical order (some components create for
        // the same page urls with different variables order)
        $pos = strpos($url, '?');
        if ($pos) {
            $firstPart = substr($url, 0, $pos + 1);
            $secondPart = substr($url, $pos + 1);
            $urlVars = explode('&', $secondPart);
            sort($urlVars);
            $secondPart = implode('&', $urlVars);
            $url = $firstPart.$secondPart;
        }

        // check for non-sef url first and avoid repeative lookups
        // we only want to look for title variations when adding new
        // this should also help eliminate duplicates.
        $query = "SELECT oldurl FROM #__redirection WHERE newurl = '".$url."'";
        $database->setQuery($query);

        // Found a match, so we are done.
        if (!is_null($realloc = $database->loadResult())) {
            return $realloc;
        }
        // This is new, so we need to insert the new title.
        else {
            $iteration = 1;
            $realloc = null;
            $prevPagenum = null;

            $suffixMust = false;
            if (class_exists('JoomFish')) {
                // Add lang to suffix, if set to.
                if (!$sefConfig->langToPath && isset($lang)) {
                    $suffix = '_'.$lang.$sefConfig->suffix;
                    $suffixMust = true;
                }
            }
            if (!isset($suffix)) $suffix = $sefConfig->suffix;
            $addFile = $sefConfig->addFile;
            if (($pos = strrpos($addFile, '.')) !== false) $addFile = substr($addFile, 0, $pos);

            do {
                // Hier begint de loop met het toevoegen van de component/nummer.html
                // temploc is $location, unless we're on a second or greater iteration,
                // then its $location.$iteration

                if (substr($location, -1) == '/' || strlen($location) == 0) {
                    if ($sefConfig->pagetext) {
                        if (!is_null($limit)) {
                            $pagenum = $limitstart / $limit;
                            $pagenum++;
                            // Make sure we do not end in infite loop here.
                            if ($prevPagenum == $pagenum) $pagenum = $iteration;
                            $prevPagenum = $pagenum;
                        }
                        else $pagenum = $iteration;

                        if (strpos($sefConfig->pagetext, '%s') !== false) {
                            $page = str_replace('%s', $pagenum == 1 ? $addFile : $pagenum, $sefConfig->pagetext).$suffix;
                        }
                        else $page = $sefConfig->pagetext.($pagenum == 1 ? $addFile : $sefConfig->pagerep.$pagenum).$suffix;

                        $temploc = $location.($pagenum == 1 && !$suffixMust ? '' : $page);
                    }
                    else $temploc = $location.($iteration == 1 ? ($suffixMust ? $sefConfig->pagerep.$suffix : '') : $sefConfig->pagerep.$iteration.$suffix);
                }
                elseif ($suffix) {
                    if  ($sefConfig->suffix != '/') {
                        if (eregi($sefConfig->suffix, $location)) {
                            $temploc = preg_replace('/'.$sefConfig->suffix.'/', '', $location).($iteration == 1 ? $suffix : $sefConfig->pagerep.$iteration.$suffix);
                        }
                        else $temploc = $location.($iteration == 1 ? $suffix : $sefConfig->pagerep.$iteration.$suffix);
                    }
                    else $temploc = $location.($iteration == 1 ? $suffix : $sefConfig->pagerep.$iteration.$suffix);
                }
                else $temploc = $location.($iteration == 1 ? ($suffixMust ? $sefConfig->pagerep.$suffix : '') : $sefConfig->pagerep.$iteration.$suffix);

                // Add language to path if set to.
                if (class_exists('JoomFish') && $sefConfig->langToPath && isset($lang)) {
                    $slash = ($temploc != '' && $temploc[0] == '/');
                    $temploc = $lang.($slash || strlen($temploc) > 0  ? '/' : '').$temploc;
                }

                if ($sefConfig->addFile) {
                    if (!eregi($sefConfig->suffix.'$', $temploc) && substr($temploc, -1) == '/') {
                        $temploc .= $sefConfig->addFile;
                    }
                }

                // Convert to lowercase if set to.
                if ($sefConfig->lowerCase) $temploc = strtolower($temploc);

                // see if we have a result for this location
                $sql = "SELECT newurl FROM #__redirection WHERE oldurl = '".$temploc."'";
                $database->setQuery($sql);

                if ($iteration > 9999) {
                    die('Too many pages.');
                }

                if (!is_null($dburl = $database->loadResult())) {
                    if ($dburl == $url) {
                        // found the matching object
                        // it probably should have been found sooner
                        // but is checked again here just for CYA purposes
                        // and to end the loop
                        $realloc = $temploc;
                    }
                    // else, didn't find it, increment and try again
                }
                else {
                    // Title not found, checken op 404's
                    $query = "SELECT `id` FROM #__redirection
					WHERE `oldurl` = '$temploc' AND `newurl` = ''";
                    $database->setQuery($query);
                    $id = $database->loadResult();

                    if (!is_null($id)) {
                        // Er bestaat een 404 pagina voor die geupdate moet worden
                        // Dat komt omdat je op deze pagina bent begonnen terwijl en nog geen sef urls waren
                        $query = "UPDATE #__redirection SET `newurl` = '".addslashes(urldecode($url))."'
						WHERE `id` = '$id'";
                        $database->setQuery($query);
                        
                        // If error occured.
                        if (!$database->query()) var_dump($query);
                    }
                    else {
                        // Save it in the database
                        $query = 'INSERT INTO #__redirection (oldurl, newurl) '.
                        "VALUES ('".$temploc."', '".addslashes(urldecode($url))."')";
                        $database->setQuery($query);
                        
                        // If error occured.
                        if (!$database->query()) var_dump($query);
                    }
                    $realloc = $temploc;
                }
                $iteration++;
            } while (is_null($realloc));
        }
        return $realloc;
    }

    function getCategories($catid)
    {
        global $debug, $database, $sefConfig;
        $jfTranslate = $sefConfig->translateNames ? ', `id`' : '';

        if (empty($cat_table)) $cat_table = "#__categories";
        if ($debug){$GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404'][$debug_string]['THIS_TASK'] = $this_task; }

        //Als er een categorie in de link staat wordt deze aan title toegevoegd zodat deze
        //In de url wordt opgenomen
        if (isset($catid) && $catid != 0){
            if ($debug){
                $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404'][$debug_string]['CAT_TABLE'] = $cat_table;
                $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404'][$debug_string]['CATID'] = $catid;
            }
            $query = "SELECT name$jfTranslate FROM $cat_table WHERE id = $catid";
            $database->setQuery($query);
            $rows = $database->loadObjectList();

            if ($debug) $GLOBALS['JOOMSEF_DEBUG']['CLASS_SEF_404'][$debug_string][$option] = $rows;

            if ($database->getErrorNum()) die($database->stderr());
            elseif (@count($rows) > 0 && !empty($rows[0]->name)) $title = $rows[0]->name;
        }
        return $title;
    }

}

// Define sef functions for some Joomla! extensions
if (!function_exists('sefencode') && !function_exists('sefdecode')) {

    function sefencode($title) {
        return sef_404::create($title);
    }

    function sefdecode($title) {
        return sef_404::revert($title);
    }

}
?>
