<?php
// Sonderzeichen tauschen
function modrewrite_changecase($output) {
	$output = strtolower(trim($output));
	$in = array("![ÄÆäæ]!", "![ÀÁÂÃÅàáâãå]!", "![ÖöØø]!", "![ÒÓÔÕòóôõ]!", "![Üü]!", "![ÙÚÛùúû]!", "![ÈÉÊËèéêë]!", "![ÌÍÎÏ]!", "![Ýý]!", "![Çç]!", "![ÐðþÞ]!", "![Ññ]!", "![Šš]!", "![Žž]!", "!ß!", "!&!", "!¡!", "!§!", "!€!", "!¥!", "!£!", "![\"\'\?\s]!", "![,:<>@\[\]\{-\`ƒ-‰‹‘-•˜›¡¤¦¨-¿]!");
    $out = array('ae', 'a', 'oe', 'o', 'ue', 'u', 'e', 'i', 'y', 'c', 'th', 'n', 's', 'z', 'ss', 'und', '!', 'paragraph', 'euro', 'yen', 'pound', '_', '');
	$output = preg_replace($in, $out, $output);
	return $output;
}

// con_tree um 'modrewrite_name' erweitern & passende idcat zurückgeben
function modrewrite_get_idcat($path) {
	global $con_tree, $catlist, $cfg_client, $rewrite_sid, $sess, $dedi_rewrite, $tree, $tmp_tree;

	$tree = explode('/', $path);
	for ($i=0, $x=count($catlist); $i<=$x; $i++) {
		$tmp_tree[0]['modrewrite_name'] = modrewrite_get_lang_name();
                 $tmp_tree[$catlist[$i]]['modrewrite_name'] = $tmp_tree[$con_tree[$catlist[$i]]['parent']]['modrewrite_name'].modrewrite_changecase($con_tree[$catlist[$i]]['name']).'/';
		if ($path == $tmp_tree[$catlist[$i]]['modrewrite_name'] || $path.'/' == $tmp_tree[$catlist[$i]]['modrewrite_name']) $idcat = $catlist[$i];
	}
	if (isset($idcat)) return $idcat;
}

// passende idcatside zurückgeben
function modrewrite_get_idcatside($page, $idcat='0') {
	global $con_side, $con_tree, $cfg_client;

	// Dateiname aus Pfad auslesen - muß doch auch einfacher gehen
	if (is_array($con_side)) {
		while (list($id, $entry) = each($con_side)) {
			$tmp_name = ($con_side[$id]['is_start'] == '1') ? 'index' : modrewrite_changecase($entry['name']);
			if ($idcat == $entry['idcat'] && $page == $tmp_name) $idcatside = $id;
			$con_side[$id]['modrewrite_name'] = $tmp_name;
		}
	}
	if (isset($idcatside)) return $idcatside;
}

// Name der Sprache suchen
function modrewrite_get_lang_name() {
	global $db, $dedi_db, $cfg_client, $lang;

	# könnte eingespart werden, gleich bei den Rechten mit einlesen
	if (!isset($cfg_client['lang'])) {
		$sql  = "SELECT name
			FROM ".$dedi_db['lang']."
			WHERE idlang = '$lang'
			LIMIT 0, 1";
		$db->query($sql);
		$db->next_record();
		$cfg_client['lang'] = $db->f('name');
	}
	return modrewrite_changecase($cfg_client['lang']).'/';
}

function modrewrite_idcat_to_path($matches) {
	global $con_tree, $cfg_client, $lang, $sess, $rewrite_sid, $tree, $tmp_tree;

	if (!empty($matches[2])) $matches[2] = ','.substr($matches[2], 1, strlen($matches[2])-2);
	switch ($cfg_client['url_rewrite']) {
         	case '1':
			if ($matches[3] == '&amp;' || $matches[3] == '&') $matches[3] = '?';
			if ($lang != $cfg_client['startlang']) $tmp_lang = $lang;

			// Session gewechselt
			$tmp_sid = str_replace('?sid=', '', $sess->url(''));
			if ($tmp_sid != $rewrite_sid && !empty($tmp_sid)) {
				return $cfg_client['modrewrite_path'].$tmp_sid.'/'.$tmp_lang.'cat'.$matches[1].$matches[2].'.html'.$matches[3];
			} else {
				// auf Cookie umschalten
				if (!empty($rewrite_sid) && !empty($_COOKIE['sid'])) {
					return $cfg_client['modrewrite_path'].$tmp_lang.'cat'.$matches[1].$matches[2].'.html'.$matches[3];
				} else return $cfg_client['modrewrite_treepath'].$tmp_lang.'cat'.$matches[1].$matches[2].'.html'.$matches[3];
			}
         	case '2':
			if (!isset($con_tree[$matches[1]]['modrewrite_name'])) {
				// Session gewechselt
				$tmp_sid = str_replace('?sid=', '', $sess->url(''));
				if ($tmp_sid != $rewrite_sid && !empty($tmp_sid)) {
					$con_tree[$matches[1]]['modrewrite_name'] = $cfg_client['modrewrite_path'].$tmp_sid.'/'.$tmp_tree[$matches[1]]['modrewrite_name'];
				} else {
					// auf Cookie umschalten
					if ((!empty($rewrite_sid) && !empty($_COOKIE['sid'])) || isset($dedi_rewrite['start'])) {
		                         	$con_tree[$matches[1]]['modrewrite_name'] = $cfg_client['modrewrite_path'].$tmp_tree[$matches[1]]['modrewrite_name'];
					} else {
						// relativen Pfad zur aktuellen Seite aufbauen
						$tmp_path = explode('/', $tmp_tree[$matches[1]]['modrewrite_name']);
						for ($a=0,$b=count($tree)-1; $a<$b; $a++) if ($tree[$a] != $tmp_path[$a]) break;
						for ($d=0,$z=$b-$a; $d<$z; $d++) $con_tree[$matches[1]]['modrewrite_name'] = $con_tree[$matches[1]]['modrewrite_name'].'../';
						for ($z=count($tmp_path)-1; $a<$z; $a++) if (!empty($tmp_path[$a])) $con_tree[$matches[1]]['modrewrite_name'] = $con_tree[$matches[1]]['modrewrite_name'].$tmp_path[$a].'/';
					}
				}
			}
			if ($matches[3] == '&amp;' || $matches[3] == '&') $matches[3] = '?';
			return $con_tree[$matches[1]]['modrewrite_name'].'index'.$matches[2].'.html'.$matches[3];
         	default:
			if (!empty($matches[2]) && $matches[2] != ',') {
				$tmp_matches[2] = explode(',', $matches[2]);
				if (is_array($tmp_matches[2])) {
					unset($matches[2]);
					for ($a=2,$b=count($tmp_matches[2]); $a<$b; $a++) $matches[2] = $matches[2].','.$tmp_matches[2][$a];
                                         $matches[2] = '&amp;get_'.$tmp_matches[2][1].'='.substr($matches[2], 1);
				} else unset($matches[2]);
                         }
			if ($matches[3] == '?' || $matches[3] == '&') $matches[3] = '&amp;';
			if ($lang != $cfg_client['startlang']) {
                         	return $sess->url($cfg_client['modrewrite_path'].$cfg_client['contentfile'].'?lang='.$lang.'&idcat='.$matches[1].$matches[2]).$matches[3];
			} else return $sess->url($cfg_client['modrewrite_path'].$cfg_client['contentfile'].'?idcat='.$matches[1].$matches[2]).$matches[3];
         }
}

function modrewrite_idcatside_to_path($matches) {
	global $con_side, $con_tree, $cfg_client, $lang, $sess, $rewrite_sid, $tree, $tmp_tree;

	if (!empty($matches[2])) $matches[2] = ','.substr($matches[2], 1, strlen($matches[2])-2);
	switch ($cfg_client['url_rewrite']) {
         	case '1':
			if ($matches[3] == '&amp;' || $matches[3] == '&') $matches[3] = '?';
			if ($lang != $cfg_client['startlang']) $tmp_lang = $lang;

			// Session gewechselt
			$tmp_sid = str_replace('?sid=', '', $sess->url(''));
			if ($tmp_sid != $rewrite_sid && !empty($tmp_sid)) {
				return $cfg_client['modrewrite_path'].$tmp_sid.'/'.$tmp_lang.'side'.$matches[1].$matches[2].'.html'.$matches[3];
			} else {
				// auf Cookie umschalten
				if (!empty($rewrite_sid) && !empty($_COOKIE['sid'])) {
					return $cfg_client['modrewrite_path'].$tmp_lang.'side'.$matches[1].$matches[2].'.html'.$matches[3];
				} else return $cfg_client['modrewrite_treepath'].$tmp_lang.'side'.$matches[1].$matches[2].'.html'.$matches[3];
			}
         	case '2':
			if (!isset($con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'])) {
				// Session gewechselt
				$tmp_sid = str_replace('?sid=', '', $sess->url(''));
				if ($tmp_sid != $rewrite_sid && !empty($tmp_sid)) {
					$con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'] = $cfg_client['modrewrite_path'].$tmp_sid.'/'.$tmp_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'];
				} else {
					// auf Cookie umschalten
					if ((!empty($rewrite_sid) && !empty($_COOKIE['sid'])) || isset($dedi_rewrite['start'])) {
		                         	$con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'] = $cfg_client['modrewrite_path'].$tmp_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'];
					} else {
						// relativen Pfad zur aktuellen Seite aufbauen
						$tmp_path = explode('/', $tmp_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name']);
						for ($a=0,$b=count($tree)-1; $a<$b; $a++) if ($tree[$a] != $tmp_path[$a]) break;
						for ($d=0,$z=$b-$a; $d<$z; $d++) $con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'] = $con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'].'../';
						for ($z=count($tmp_path)-1; $a<$z; $a++) if (!empty($tmp_path[$a])) $con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'] = $con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'].$tmp_path[$a].'/';
					}
				}
                         }
			if ($matches[3] == '&amp;' || $matches[3] == '&') $matches[3] = '?';
			return $con_tree[$con_side[$matches[1]]['idcat']]['modrewrite_name'].$con_side[$matches[1]]['modrewrite_name'].$matches[2].'.html'.$matches[3];
         	default:
			if (!empty($matches[2]) && $matches[2] != ',') {
				$tmp_matches[2] = explode(',', $matches[2]);
				if (is_array($tmp_matches[2])) {
					unset($matches[2]);
					for ($a=2,$b=count($tmp_matches[2]); $a<$b; $a++) $matches[2] = $matches[2].','.$tmp_matches[2][$a];
                                         $matches[2] = '&amp;get_'.$tmp_matches[2][1].'='.substr($matches[2], 1);
				} else unset($matches[2]);
                         }
			if ($matches[3] == '?' || $matches[3] == '&') $matches[3] = '&amp;';
			if ($lang != $cfg_client['startlang']) {
                         	return $sess->url($cfg_client['modrewrite_path'].$cfg_client['contentfile'].'?lang='.$lang.'&idcatside='.$matches[1].$matches[2]).$matches[3];
			} else return $sess->url($cfg_client['modrewrite_path'].$cfg_client['contentfile'].'?idcatside='.$matches[1].$matches[2]).$matches[3];
         }
}

function modrewrite_contentfile_idcat($matches) {
	$tmp_matches[1] = $matches[2];
	$tmp_matches[3] = $matches[3];
	return modrewrite_idcat_to_path($tmp_matches);
}

function modrewrite_contentfile_idcatside($matches) {
	$tmp_matches[1] = $matches[2];
	$tmp_matches[3] = $matches[3];
	return modrewrite_idcatside_to_path($tmp_matches);
}

function modrewrite_root($matches) {
	global $lang, $cfg_client;

	if ($matches[1] == '&amp;' || $matches[1] == '&') $matches[1] = '?';
	switch ($cfg_client['url_rewrite']) {
         	case '1':
			return $cfg_client['modrewrite_path'].'index.html'.$matches[1];
         	case '2':
			return $cfg_client['modrewrite_path'].modrewrite_get_lang_name().'index.html'.$matches[1];
         	default:
			return $cfg_client['modrewrite_path'].$cfg_client['contentfile'].$matches[1];
	}
}

function modrewrite_get_values() {
	global $rewrite_values, $rewrite_path, $cfg_client, $_GET;

	if (!empty($rewrite_values) && $rewrite_values != '.html') {
		if (!empty($rewrite_path)) $rewrite_path = $rewrite_path.'.html';
		$rewrite_values = substr($rewrite_values, 0, -5);
		$rewrite_values = explode(',', $rewrite_values);
		if (!empty($rewrite_values['1'])) {
			for ($a=2, $b=count($rewrite_values); $a<$b; $a++) {
				$cfg_client['get'][$rewrite_values['1']][] = $rewrite_values[$a];
			}
                 }
         }
	foreach ($_GET as $key => $value) {
		if (substr($key, 0, 4) == 'get_') {
			$name = substr($key, 4);
                         if (!empty($name)) {
	                 	$cfg_client['get'][$name] = explode(',', $value);
                         }
                 }
         }
}

function modrewrite_path($code) {
	global $cfg_client, $rewrite_path, $idcat, $idcatside, $rewrite_sid;

	// Variablen herausfiltern
	modrewrite_get_values();

	// auf Cookie umschalten
	if (!empty($rewrite_sid)) $cfg_client['modrewrite_spath'] = '../';
	if ($cfg_client['url_rewrite'] == '2' || isset($rewrite_path)) {
		$path = modrewrite_changecase(urldecode($rewrite_path));
		if (strrchr($path, '.') == '.html') {
                 	$page = substr(strrchr($path, '/'), 1);
			$path = str_replace($page, '', $path);
                 	$page = substr($page, 0, -5);
		}
		if (isset($rewrite_path)) for ($i=0, $m=substr_count($rewrite_path, '/'); $i<$m; $i++) $cfg_client['modrewrite_treepath'] = $cfg_client['modrewrite_treepath'].'../';
		$cfg_client['modrewrite_path'] = $cfg_client['modrewrite_spath'].$cfg_client['modrewrite_treepath'];
		$tmp_idcat = modrewrite_get_idcat($path);
		$tmp_idcatside = modrewrite_get_idcatside($page, $tmp_idcat);
		if (empty($idcat) && empty($idcatside)) {
                        	$idcat = $tmp_idcat;
			$idcatside = $tmp_idcatside;
		}
	}
	unset($rewrite_path, $rewrite_sid);
	$cfg_client['modrewrite_path'] = $cfg_client['modrewrite_spath'].$cfg_client['modrewrite_treepath'];
}

function modrewrite_filepath($matches) {
	global $db, $dedi_db, $dedi_file, $cfg_client, $code, $client, $sess;

	if (!isset($dedi_file)) {
		preg_match_all("!http://dedilink/fileid=(\d+)!", $code, $internlinks);
		$sql_links = implode(',', $internlinks[1]);
		if (!empty($sql_links)) {
			# gleich noch auf recht überprüfen
			$sql = "SELECT A.idupl id, A.filename filename,B.dirname dirname
				FROM ".$dedi_db['upl']." as A
				LEFT JOIN ". $dedi_db['directory'] ." as B USING(iddirectory)
				WHERE A.idclient=$client
				AND A.idupl IN ($sql_links)";
			$db->query($sql);
			while($db->next_record()) $dedi_file[$db->f('id')] = $db->f('dirname').$db->f('filename');
		}
	}

	// relativen pfad berechnen
	# $cfg_client['modrewrite_path'] ../ auslesen - relativer pfad zum downloadbereich
	if ($cfg_client['download_control'] == 1) {
		$path = ($cfg_client['url_rewrite'] == 0) ? $sess->url($cfg_client['modrewrite_path'].'cms/inc/download.php?id='.$matches[1]) : $sess->url($cfg_client['upl_htmlpath'].$dedi_file[$matches[1]]);
	} else $path = $cfg_client['upl_htmlpath'].$dedi_file[$matches[1]];
	# wenn path vorhanden relativen pfad davorsetzen dafür upl_htmlpath entfernen! - aktuelle tiefe
	return $path;
}

function modrewrite_replace($output) {
	global $cfg_client, $auth, $idcatside, $rewrite_values;

	// alle relativen Pfade anpassen
	if (!empty($cfg_client['modrewrite_path'])) {
		$in = array("/(src|href|background|action)=([\"\'])(?!\w+:|#|".$cfg_client['contentfile'].")\/?([^\"\']+)([\"\'])/i",
		            "/url\(\s*[\"\']?(?!\w+:|#|".$cfg_client['contentfile'].")\/?([^\"\'\)]+)[\"\']?\s*\)/i");
		$out = array("\\1=\\2".$cfg_client['modrewrite_path']."\\3\\4",
		             "url(".$cfg_client['modrewrite_path']."\\1)");
         	$output = preg_replace($in, $out, $output);
	}

	// Dedilinks ersetzen
	$in = array("'(?<!/)".$cfg_client['contentfile']."\?lang=([1-9][0-9]?)&idcat=([1-9][0-9]*)(&amp;|&|\?)?'",
		    "'(?<!/)".$cfg_client['contentfile']."\?lang=([1-9][0-9]?)&idcatside=([1-9][0-9]*)(&amp;|&|\?)?'",
                     "'(?<!/)".$cfg_client['contentfile']."(&amp;|&|\?)?'",
                     "!http://dedilink/idcat=(\d+)(\[.*\])?(&amp;|&|\?)?!",
	            "!http://dedilink/idcatside=(\d+)(\[.*\])?(&amp;|&|\?)?!",
		    "'http://dedilink/fileid=(\d+)'");
	$out = array("modrewrite_contentfile_idcat",
	             "modrewrite_contentfile_idcatside",
                      "modrewrite_root",
         	     "modrewrite_idcat_to_path",
	             "modrewrite_idcatside_to_path",
                      "modrewrite_filepath");
	foreach ($in as $n => $v) $output = preg_replace_callback($v, $out[$n], $output);

	// Dateilinks ersetzen
	$output = str_replace($cfg_client['htmlpath'], $cfg_client['modrewrite_path'], $output);
	return $output;
}
?>