<?php
/******************************************************************************
 @Author:     Björn Brockmann, Paul Eppner (paul@twomoons.de)
                              Sven Bräutigam, Jürgen Brändle
 @Homepage    http://www.der-dirigent.de
******************************************************************************/

function fire_event($event, $args) {
        global $dedi_events, $val_ct, $db, $dedi_db, $client, $lang, $perm, $sess, $cfg_client, $cfg_dedi;

        if (!is_object($dedi_event)) {
                include_once $cfg_dedi['dedi_path']. 'inc/class.dedi_event.php';
                $dedi_events = &new dedi_event($val_ct);
        }
        $dedi_events -> fire($event, $args);
}

function html_entity_decode_compatible($string) {
        $trans_tbl = get_html_translation_table (HTML_ENTITIES);
        $trans_tbl = array_flip ($trans_tbl);
        return strtr ($string, $trans_tbl);
}

function make_string_dump($tmp = '') {
        $tmp = str_replace('\\', '\\\\', $tmp);
        $tmp = str_replace('\'', '\\\'', $tmp);
        $tmp = str_replace(array('\x00', '\x0a', '\x0d', '\x1a'), array('\0', '\n', '\r', '\Z'), $tmp);
        return $tmp;
}

function extract_dedi_tags($in, $sort='') {
        //alle DEDI Tags extrahieren
        //Hinterher befindet sich in
        //$matches[0][x] -> der gesamte Tag
        //$matches[2][x] -> alle Attribute
        //$matches[3][x] -> Content zwischen <dedi></dedi>
        preg_match_all ('/<dedi:(mod|lay) ([^>]*)\/?>([^<\/]*<\/dedi>)?/i',$in, $matches);
        $match_count = count($matches[0]);

        //Attribute filtern
        if($match_count) {
                for ($i=0; $i< $match_count; $i++) {
                        $attributes = $matches[2][$i];
                        $preg = '/(([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*)'."([ \\n\\t\\r]+)?(=([ \\n\\t\\r]+)?(\"[^\"]*\"|'[^']*'|[^ \\n\\t\\r]*))?/";
                        if (preg_match_all($preg, $attributes, $regs)) {
                                $valCounter = 0;
                                for ($counter=0; $counter<count($regs[1]); $counter++) {
                                        $name = $regs[1][$counter];
                                        $check = $regs[0][$counter];
                                        $value = $regs[7][$valCounter];
                                        if (trim($name) == trim($check)) $arrAttr[] = strtoupper(trim($name));
                                        else {
                                                if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'") $value = substr($value, 1, -1);
                                                $arrAttr[strtolower(trim($name))] = trim($value);
                                                $valCounter++;
                                        }
                                }

                                // Alle Attribute für returnwert aufbereiten
//                                $arrAttr['id'] = sprintf("%01d",$arrAttr['id']);
                                if ($sort == 'type') {
                                        //$out[type][id][attributekey] = attributevalue
                                        $out[$arrAttr['type']][$arrAttr['id']] = $arrAttr;
                                        $out[$arrAttr['type']][$arrAttr['id']]['in_tag'] = $matches[3][$i];
                                } else {
                                        //$out[$i][attributekey] = attributevalue
                                        $out[$i] = $arrAttr;
                                        $out[$i]['full_tag'] = $matches[0][$i];
                                        $out[$i]['in_tag'] = $matches[3][$i];
                                }
                                unset($arrAttr);
                        }
                }
                return $out;
        } else return false;
}


function check_cache_is_expired($timestamp) {
        global $db, $dedi_db, $idcatside;

        // Wenn timestamp <= aktuelle Zeit, Cache ist abgelaufen
        if ($timestamp <= time()) {
                $sql = "UPDATE ".$dedi_db['code']." SET changed='1' WHERE idcatside = $idcatside";
                $db->query($sql);
            // Delete Content Cache
        $db->delete_cache('frontend_content');
    }
}


function change_code_status($list, $status, $type='idcode') {
        global $db, $dedi_db, $lang, $cfg_client;

        if (!is_array($list)) $list = explode(',',$list);
        if ($list['0'] != '') {
                switch($type) {
                        case 'idcode':
                                if ($cfg_client['publish'] == '1') $status = '2';
                                $sql = "UPDATE $dedi_db[code] SET changed='$status' WHERE idcode IN(".implode(',', $list).")";
                                break;

                        case 'idcatside':
                                if ($cfg_client['publish'] == '1') $status = '2';
                                $sql = "UPDATE $dedi_db[code] SET changed='$status' WHERE idlang='$lang' AND idcatside IN(".implode(',', $list).")";
                                break;

                        case 'publish':
                                $sql = "UPDATE $dedi_db[code] SET changed='$status' WHERE idlang='$lang' AND changed='2' AND idcatside IN(".implode(',', $list).")";
                                break;
                }
                $db->query($sql);
        // Delete Content Cache
        $db->delete_cache('frontend_content');
        }
}

function get_languages_by_client($client) {
        global $db, $dedi_db;

        $sql = "SELECT idlang FROM $dedi_db[clients_lang] WHERE idclient='$client'";
        $db->query($sql);
        while($db->next_record()) $list[]=$db->f('idlang');
        return $list;
}

function browse_layout_for_containers($idlay) {
        global $db, $dedi_db;

        $sql = "SELECT code FROM $dedi_db[lay] WHERE idlay='$idlay'";
        $db->query($sql);
        $db->next_record();
        $list_tmp = extract_dedi_tags($db->f('code'));
        if (is_array($list_tmp)) {
                // Container sortieren
                foreach($list_tmp as $container) {
                        if ($container['id']) {
                                $list['id'][] = $container['id'];
                                if ($container['title']) $list[$container['id']]['title'] = $container['title'];
                        }
                }
        }
        return $list;
}

function browse_template_for_module($idtpl, $idtplconf) {
        global $db, $dedi_db;

        if ($idtpl == '0') {
                $sql = "SELECT idtpl FROM $dedi_db[tpl_conf] WHERE idtplconf='$idtplconf'";
                $db->query($sql);
                $db->next_record();
                $idtpl = $db->f('idtpl');
        }
        $sql = "SELECT A.idcontainer, A.container, A.idmod, B.name, B.input, B.output, C.config, C.view, C.edit FROM $dedi_db[container] A LEFT JOIN $dedi_db[mod] B USING(idmod) LEFT JOIN $dedi_db[container_conf] C ON A.idcontainer=C.idcontainer WHERE A.idtpl='$idtpl' AND C.idtplconf='$idtplconf'";
        $db->query($sql);
        while ($db->next_record()) {
                $cont_loop = $db->f('container');
                $list['id'][] = $cont_loop;
                $list[$cont_loop] = array('idcontainer'=>$db->f('idcontainer'),
                                                                  'idmod'      =>$db->f('idmod'),
                                                                  'modname'    =>$db->f('name'),
                                                                  'input'      =>$db->f('input'),
                                                                  'output'     =>$db->f('output'),
                                                                  'config'     =>$db->f('config'),
                                                                  'view'       =>$db->f('view'),
                                                                  'edit'       =>$db->f('edit'));
        }
        return $list;
}

function get_idtplconf_by_using_type($list, $type) {
        global $db, $dedi_db, $cfg_client;

        if (!is_array($list) && $list != '') $list = explode(',',$list);
        if (is_array($list)) {
                switch($type) {
                        case 'lay':
                                $sql = "SELECT idtplconf FROM $dedi_db[tpl] A, $dedi_db[tpl_conf] B WHERE (A.idlay=''";
                                foreach ($list as $value) $sql .=" OR A.idlay='$value'";
                                $sql .= ") AND A.idtpl=B.idtpl";
                                break;
                        case 'mod':
                                $sql = "SELECT DISTINCT B.idtplconf FROM $dedi_db[tpl] A LEFT JOIN $dedi_db[tpl_conf] B USING(idtpl) LEFT JOIN $dedi_db[container_conf] C USING(idtplconf) LEFT JOIN $dedi_db[container] D USING(idcontainer) WHERE (D.idmod=''";
                                foreach ($list as $value) $sql .=" OR D.idmod='$value'";
                                $sql .= ")";
                                break;
                        case 'tpl':
                                $sql = "SELECT idtplconf FROM $dedi_db[tpl_conf] WHERE (idtpl=''";
                                foreach ($list as $value) $sql .=" OR idtpl='$value'";
                                $sql .= ")";
                                break;
                 }
                $db->query($sql);
                while ($db->next_record()) $tmp[] = $db->f('idtplconf');
                return $tmp;
        }
}

function get_idcode_by_idtplconf($list) {
	global $db, $dedi_db, $cfg_client;

	if (!is_array($list) && $list != '') $list = explode(',',$list);
	if (is_array($list)) {
		if ($cfg_client['publish'] == '1') $changed = "(C.changed='0' OR C.changed='1')";
		else $changed = "(C.changed='0' OR C.changed='2')";
		foreach ($list as $value) {
			$sql = "SELECT idcode FROM $dedi_db[side_lang] A LEFT JOIN $dedi_db[cat_side] B USING(idside) LEFT JOIN $dedi_db[code] C USING(idcatside) WHERE A.idtplconf='$value' AND $changed";
			$db->query($sql);
			while ($db->next_record()) $tmp[] = $db->f('idcode');

			// das Template gehört einem Ordner
			if (!$db->affected_rows()) {
				$sql = "SELECT idcode FROM $dedi_db[cat_lang] A LEFT JOIN $dedi_db[cat_side] B USING(idcat) LEFT JOIN $dedi_db[side_lang] C USING(idside) LEFT JOIN $dedi_db[code] D ON A.idlang=D.idlang WHERE A.idtplconf='$value' AND A.idlang=C.idlang AND C.idtplconf='0' AND B.idcatside=D.idcatside";
				$db->query($sql);
				while ($db->next_record()) $tmp[] = $db->f('idcode');
			}
		}
	}
	return $tmp;
}

function get_idsidelang_by_idtplconf($list) {
        global $db, $dedi_db, $cfg_client;

        if (!is_array($list) && $list != '') $list = explode(',',$list);
        if (is_array($list)) {
                foreach ($list as $value) {
                        $sql = "SELECT idsidelang FROM $dedi_db[side_lang] WHERE idtplconf='$value'";
                        $db->query($sql);
                        while ($db->next_record()) $tmp[] = $db->f('idsidelang');

                        // das Template gehört einem Ordner
                        if (!$db->affected_rows()) {
                                $sql = "SELECT idsidelang FROM $dedi_db[cat_lang] A LEFT JOIN $dedi_db[cat_side] B USING(idcat) LEFT JOIN $dedi_db[side_lang] C USING(idside) WHERE A.idtplconf='$value' AND A.idlang=C.idlang AND C.idtplconf='0'";
                                $db->query($sql);
                                while ($db->next_record()) $tmp[] = $db->f('idsidelang');
                        }
                }
        }
        return $tmp;
}

function set_magic_quotes_gpc(&$code) {
        if (get_magic_quotes_gpc() == 0) $code = addslashes($code);
        if (ini_get(magic_quotes_sybase) != 0) {
                $code = str_replace("''", "'", $code);
                $code = str_replace("\\", "\\\\", $code);
                $code = str_replace("'", "\'", $code);
                $code = str_replace('"', '\"', $code);
        }
}

function dedi_addslashes($code) {
        $code = addslashes($code);
        if (ini_get(magic_quotes_sybase) != 0) {
                $code = str_replace("\\", "\\\\", $code);
                $code = str_replace('"', '\"', $code);
                 $code = str_replace("''", "\'", $code);
        }
        return $code;
}

function dedi_stripslashes($code) {
        if (ini_get(magic_quotes_sybase) != 0) {
                $code = str_replace("\\\\", "\\", $code);
                 $code = str_replace("\'", "'", $code);
                $code = str_replace('\"', '"', $code);
         } else $code = stripslashes($code);
        return $code;
}

function remove_magic_quotes_gpc(&$code) {
        if (get_magic_quotes_gpc() != 0) {
                if (ini_get(magic_quotes_sybase) != 0) {
                        $code = str_replace("\\", "\\\\", $code);
                        $code = str_replace('"', '\"', $code);
                         $code = str_replace("''", "\'", $code);
                }
                 $code = dedi_stripslashes($code);
         }
}

function make_array_to_urlstring($in) {
        if (!is_array($in)) return;
    ksort($in);
    $tmp[] = '';
    // $tmp[] = 0;
    $in = array_diff($in, $tmp);
        foreach($in as $key => $value) {
                if (is_array($value)) {
                        // leere Arrayelemente löschen und in String wandeln
                        $value = array_diff($value, $tmp);
                        if (is_array($value)) $value = implode(',',$value);
        }
                set_magic_quotes_gpc($value);
                $value = urlencode($value);
                $out .= $key.'='.$value.'&';
        }
        $out = preg_replace('/&$/', '', $out);
        return $out;
}

function tree_level_order($node_id, $array, $expanded = 'false', $level = '0') {
        global $tlo_tree, ${$array}, ${$array.'_level'}, $perm, $con_tree, $perm;

        $arr = (is_array($tlo_tree[$node_id])) ? $tlo_tree[$node_id]: array();

        while(list($i) = each($arr))
        {
                $id_loop = $tlo_tree[$node_id][$i];

                //Warum wird hier der perm gecheckt?
                //if ($perm->is_admin() || $perm->test_perm('cat', $id_loop)) {
                        // $perm->test_perm('cat', $id_loop, 7, $con_tree[$id_loop]['visible'])

                ${$array}[] = $id_loop;
                //}

                ${$array.'_level'}[$id_loop] = $level;

                if ($tlo_tree['expanded'] && $expanded == 'false') {

                        if ($tlo_tree['expanded'][$id_loop] == $id_loop || !$perm -> have_perm('0', 'cat', $id_loop)) {
                                tree_level_order($id_loop, $array, $expanded, ($level + 1));
                        }
                }
                else {
                        tree_level_order($id_loop, $array, $expanded, ($level + 1));
                }
        }
        return;
}

// Wird vom dedi:tag Link benutzt bei Auswahl eines Links
// im BearbeitenDialog
function tree_level_order_light($node_id = '0', $level = '0')
{
        global $tlo_tree, $catlist, $catlist_level;

        for ($i=1; !empty($tlo_tree[$node_id][$i]); $i++)
        {
                $catlist[] = $tlo_tree[$node_id][$i];
                $catlist_level[$tlo_tree[$node_id][$i]] = $level;
                tree_level_order_light($tlo_tree[$node_id][$i], ($level + 1));
        }
        return;
}


function make_image ($image = 'space.gif', $description = '', $width = '', $height = '', $popup = '') {
        global $cfg_dedi, $dedi_lang;

        $image_width = (is_numeric($width)) ? ' width="'. $width .'" ': '';
        $image_height = (is_numeric($height)) ? ' height="'. $height .'" ': '';
        $image_popup = ($popup != '') ? ' onmouseover="overlib('.$popup.');" onmouseout="nd();" ' : '';
        $image_final = '<img src="tpl/'.$cfg_dedi['skin'].'/img/'.$image.'" '. $image_width . $image_height . $image_popup .'  border="0">';
        return $image_final;
}

function make_image_link ($url = '#', $image = 'space.gif', $description = '', $width = '', $height = '', $target = '', $popup = '', $anchor ='') {
        global $sess, $cfg_dedi, $dedi_lang;

        return sprintf("<a href=\"".$sess->url($url). $anchor ."\" onMouseOver=\"on('$description');%sreturn true;\" onMouseOut=\"off();%sreturn true;\"%s><img src=\"tpl/".$cfg_dedi['skin']."/img/".$image."\"%s%s border=\"0\"%s></a>", ($popup != '') ? 'overlib('.$popup.');' : '', ($popup != '') ? 'nd();' : '', ($target != '') ? " target=\"$target\"" : '', ($width != '') ? " width=\"$width\"" : '', ($height != '') ? " height=\"$height\"" : '', ($popup == '') ? " alt=\"$description\" title=\"$description\"" : '');
}

function make_image_link2 ($url = '#', $image = 'space.gif', $description = '', $width = '', $height = '', $target = '', $popup = '', $popupheader = '', $class = '', $hash = '', $name = '', $linktext = '', $imgclass = '' ) {
        global $sess, $cfg_dedi, $dedi_lang;

        return sprintf("<a %s%shref=\"".$sess->url($url)."%s\" onMouseOver=\"on('$description');%sreturn true;\" onMouseOut=\"off();%sreturn true;\"%s><img src=\"tpl/".$cfg_dedi['skin']."/img/".$image."\"%s%s border=\"0\"%s%s%s>$linktext</a>", ($name != '') ? 'name="'.$name.'" ' : '', ($class != '') ? 'class="'.$class.'" ' : '', ($hash != '') ? '#'.$hash: '', ($popup != '') ? 'overlib('.$popup.');' : '', ($popup != '') ? 'nd();' : '', ($target != '') ? " target=\"$target\"" : '', ($width != '') ? " width=\"$width\"" : '', ($height != '') ? " height=\"$height\"" : '', ($popup == '') ? " alt=\"$description\"" : '', ($popup == '') ? " title=\"$description\"" : '', ($imgclass != '') ? ' class="'.$imgclass.'" ' : '');
}

function make_image_link3 ($url = '#', $image = 'space.gif', $image1 = 'space.gif', $description = '', $description1 = '', $class = '', $hash = '', $name = '' ) {
        global $sess, $cfg_dedi, $dedi_lang;

        return sprintf("<a %s%shref=\"".$sess->url($url)."%s\" onMouseOver=\"on('$description');return true;\" onMouseOut=\"off();return true;\"><img src=\"tpl/".$cfg_dedi['skin']."/img/".$image."\"  alt=\"$description\" title=\"$description\" border=\"0\" %s></a><a href=\"javascript:history.back()\" onMouseOver=\"on('$description1');return true;\" onMouseOut=\"off();return true;\"><img src=\"tpl/".$cfg_dedi['skin']."/img/".$image1."\" alt=\"$description1\" title=\"$description1\" border=\"0\" %s></a>", ($name != '') ? 'name="'.$name.'" ' : '', ($class != '') ? 'class="'.$class.'" ' : '', ($hash != '') ? '#'.$hash: '', ($class != '') ? 'class="'.$class.'" ' : '', ($class != '') ? 'class="'.$class.'" ' : '');
}

function make_image_link4 ($image = 'space.gif', $image1 = 'space.gif', $description = '', $description1 = '', $class = '', $class1 = '', $backurl = '#', $width = '14', $height = '14' ) {
        global $sess, $cfg_dedi, $dedi_lang;

        return sprintf("<input type=\"image\" %s onMouseOver=\"on('$description');return true;\" onMouseOut=\"off();return true;\"  src=\"tpl/".$cfg_dedi['skin']."/img/".$image."\"  alt=\"$description\" title=\"$description\" border=\"0\" width=\"$width\" height=\"$height\"><a href=\"".$sess->url($backurl)."\" onMouseOver=\"on('$description1');return true;\" onMouseOut=\"off();return true;\"><img %s src=\"tpl/".$cfg_dedi['skin']."/img/".$image1."\" alt=\"$description1\" title=\"$description1\" border=\"0\" width=\"$width\" height=\"$height\"></a>", ($class != '') ? 'class="'.$class.'"' : '', ($class1 != '') ? 'class="'.$class1.'"' : '');
}

function make_image_link5 ($url = '#', $image = 'space.gif', $description = '', $width = '', $height = '', $target = '', $targetpara = '', $popup = '', $popupheader = '', $class = '', $hash = '', $name = '', $linktext = '', $imgclass = '' ) {
        global $sess, $cfg_dedi, $dedi_lang;

        return sprintf("<a %s%shref=\"".$sess->url($url)."%s\" onClick=\"window.open('about:blank','".$target."','".$targetpara."')\"  onMouseOver=\"on('$description');%sreturn true;\" onMouseOut=\"off();%sreturn true;\"%s><img src=\"tpl/".$cfg_dedi['skin']."/img/".$image."\"%s%s border=\"0\"%s%s%s>$linktext</a>", ($name != '')     ? 'name="'.$name.'" ' : '', ($class != '')    ? 'class="'.$class.'" ' : '', ($hash != '')     ? '#'.$hash: '', ($popup != '')    ? 'overlib('.$popup.');' : '', ($popup != '')    ? 'nd();' : '', ($target != '')   ? " target=\"$target\"" : '', ($width != '')    ? " width=\"$width\""       : '', ($height != '')   ? " height=\"$height\""     : '', ($popup == '')    ? " alt=\"$description\""   : '', ($popup == '')    ? " title=\"$description\"" : '', ($imgclass != '') ? ' class="'.$imgclass.'" ' : '');
}

function make_nav_link($class='', $url='#', $mousetext='', $linktext='', $end='&nbsp;' ) {
        global $sess;

        return sprintf("<a %s href=\"%s\" onMouseOver=\"on('%s');return true;\" onMouseOut=\"off();return true;\">%s</a>%s", ($class != '') ? "class=\"$class\"": '' , $sess->url($url), $mousetext, $linktext, $end);
}

// Lädt eine Validator-Klasse für Überprüfungen beim CSS-Editor oder File-Uploads
function get_validator($name) {
        global $cfg_dedi;

        // include validator class and create object
        if (!$cfg_dedi[$name]) $cfg_dedi[$name] = 'class.validator.php';
        include_once($cfg_dedi['dedi_path'].'inc/'.$cfg_dedi[$name]);
        $validator = &new validator();
        return $validator;
}

?>