<?php
//
// DeDi-TinyMCE2 sub-function
// Patch-Version 1.1 build 16052006
// implemented / parts coded by tXz (Alexander M. Korn)
// www.tiefeXzeitlos.de
//
function _type_form_tinymce($formname, $content, $type_config) {
	$content = type_form_dedilinks_to_templinks($content);
	global $db, $dedi_db, $idlay, $dedi_lang, $mod_lang, $perm, $catlist,$con_side, $client, $catlist_level,$cfg_dedi, $cfg_client, $lang, $sess, $idcatside, $entry;
	// get stylesheet-files for this page (code taken from project's inc/frontend.php)
	// have to use absolute urls, because stylesheets are not relative to codebase
	$sql = "SELECT C.filetype, D.dirname, B.filename FROM $dedi_db[lay_upl] AS A LEFT JOIN $dedi_db[upl] AS B USING(idupl) LEFT JOIN $dedi_db[filetype] C on B.idfiletype=C.idfiletype left join $dedi_db[directory] D ON B.iddirectory=D.iddirectory WHERE idlay='$idlay'";
	$db->query($sql);
	while ($db->next_record()) if ($db->f('filetype') == 'css') $tinystylefiles .= $cfg_client['htmlpath'].$db->f('dirname').$db->f('filename').",";
	// get the style-classes
	if (!empty($type_config['selectablestyles'])) {
		$style_array = _type_get_stylelist($type_config['selectablestyles']);
		$c = count($style_array);
		if ($c > 0) {
			for($i=0; $i<$c; $i++)
			{
				$tinystyles .= $style_array[$i]['autodesc'] .'='. $style_array[$i]['name'] ;
				if ($i<$c-1) $tinystyles .=';';
			}
		}
	}

	// get internal sites
	$sql = "SELECT A.name, B.idcat, B.parent, B.sortindex FROM $dedi_db[cat_lang] AS A LEFT JOIN $dedi_db[cat] AS B USING(idcat) WHERE B.idclient='$client' AND A.idlang='$lang' ORDER BY B.parent, B.sortindex";
	$db->query($sql);
	while ($db->next_record()) {
		$ordner[$db->f('idcat')] = $db->f('name');
		$tlo_tree[$db->f('parent')][$db->f('sortindex')] = $db->f('idcat');
	}
	// tree_level_order_light();
	$sql = "SELECT D.idcatside, D.idcat, D.sortindex, D.is_start, F.title FROM $dedi_db[cat_side] AS D LEFT JOIN $dedi_db[side] AS E USING(idside) LEFT JOIN $dedi_db[side_lang] AS F USING(idside) WHERE E.idclient='$client' AND F.idlang='$lang' ORDER BY D.idcatside";
	$db->query($sql);
	while ($db->next_record()) {
		$seiten[$db->f('idcat')][$db->f('idcatside')]['name'] = $db->f('title');
		$seiten[$db->f('idcat')][$db->f('idcatside')]['idcatside'] = $db->f('idcatside');
		$seiten[$db->f('idcat')][$db->f('idcatside')]['is_start'] = $db->f('is_start');
		if ($db->f('is_start') == 1){ $seiten['start'][$db->f('idcat')] = $db->f('idcatside'); }
		if (!is_array($seiten['sortarray'][$db->f('idcat')])){$seiten['sortarray'][$db->f('idcat')] = array(); }
			array_push($seiten['sortarray'][$db->f('idcat')],$db->f('sortindex'));
	}
	$baum = array();
	foreach($catlist as $a){
		$temp['id'] = $seiten['start'][$a];
		$temp['name'] = $ordner[$a];
		$temp['level'] = $catlist_level[$a];
		array_push($baum, $temp);
		if(is_array($seiten[$a])) {
			array_multisort($seiten['sortarray'][$a] , SORT_ASC , $seiten[$a] , SORT_ASC);
			foreach(array_keys($seiten[$a]) as $b) {
			//if($seiten['start'][$a] != $b) {
				$temp['id'] = $seiten[$a][$b]['idcatside'];
				$temp['name'] = $seiten[$a][$b]['name'];
				$temp['level'] = $catlist_level[$a] + 1;
				array_push($baum, $temp);
			//}
			}
		}
	}
	// script-array inhalt erzeugen
	foreach($baum as $a)
		if ($con_link_intern != $a['id'] && $a['id']!=""){
			$tinylinktitle=str_repeat('&nbsp;',$a['level']).$a['name'];
			if (strlen($tinylinktitle)>60) $tinylinktitle=str_chop($tinylinktitle);
			$tinylinksarray[]= "['" . $tinylinktitle . "','" .  "http://dedi'+'link/idcatside=".$a['id']."']";
		}
	$tinylinks=implode(',',$tinylinksarray);

	//Standardfiletypes laden, wenn keine anderen angegeben, defaults laden
	$ft = strtolower(trim($type_config['imagefiletypes']));
	$filetypes = ( empty($ft) || $ft == 'true' ) ? 'jpg,jpeg,gif,png': $ft;

	$filetypes_s = $type_config['imagefiletypes'];
	$filetypes_s = str_replace(' ', '', $filetypes_s);
	$filetypes_s = ( empty($filetypes_s) || $filetypes_s == 'true' ) ? 'jpg,jpeg,gif,png': $filetypes_s;
	$filetypes = explode(',', $filetypes_s);

	$folders_s = $type_config['imagefolders'];
	$folders = explode(',', $folders_s);

	$sql = "SELECT iddirectory, parentid, name FROM ".$dedi_db['directory']." WHERE idclient=".$client." AND dirname NOT LIKE('cms/%') ORDER BY dirname";
	$db -> query($sql);

	$tree = array();
	while($db -> next_record()) {
		if($perm->have_perm(1, 'folder', $db->f('iddirectory'))) {
			$tree[$db->f('parentid')][] = $db->f('iddirectory');
			$folder[$db->f('iddirectory')] = str_replace("'", "\\'", $db->f('name'));
		};
	}
	
	$allfolders=array();
	foreach($folders as $a){
		$allfolders[]=$a;
		if($type_config['imagesubfolders']=='true') {
			if (is_array($tree[$a]))
				foreach($tree[$a] as $b) {
					$allfolders[]=$b;
					if (is_array($tree[$b])) foreach($tree[$b] as $c) $allfolders[]=$c;
				}
		}
	}
		
	$sql = "SELECT A.idupl idupl, A.filename filename, A.iddirectory iddirectory, A.titel titel, A.pictwidth width, A.pictheight height, B.filetype as filetype, C.dirname as directory FROM ".$dedi_db['upl']." AS A, ".$dedi_db['filetype']." AS B, ".$dedi_db['directory']." AS C WHERE A.idclient=".$client." AND C.idclient=".$client." AND A.idfiletype = B.idfiletype AND B.filetype IN ('".join($filetypes, "','")."') AND C.iddirectory = A.iddirectory ORDER BY directory,filename";
	$db -> query($sql);
	$files = array();
	while($db -> next_record()) {
		if($perm->have_perm( 17, 'file', $db->f('idupl'), $db->f('iddirectory'))) {
			if (in_array($db->f('iddirectory'),$allfolders) || empty($type_config['imagefolders'])) {
				$image_array[] = array(
					'name'		=> str_replace("'", "\\'", $db->f('filename')),
					'title'		=> str_replace("'", "\\'", $db->f('titel')),
					'dir'		=> $db->f('directory'), 
				);
			}
		}
	}

	// generate tiny images script-array
	if (is_array($image_array)) {
		foreach($image_array as $a) {
			$tinyimagetitle=$a['dir'].$a['name'];
			if (!empty($a['title'])) $tinyimagetitle.=" (".$a['title'].")";
			if (strlen($tinyimagetitle)>60) $tinyimagetitle=str_chop($tinyimagetitle);	
			if ($a['name']!="")	$tinyimagesarray[]= "['".$tinyimagetitle."','".$cfg_client["upl_htmlpath"].$a['dir'].$a['name']."']";
		}
		$tinyimages=implode(',',$tinyimagesarray);
	} else $tinyimages="";

	// get the doctype from the default layout
	preg_match( '/((<!DOCTYPE)[^>]*(>))/mi', $cfg_client['default_layout'], $doctype);
	$tinydoctype = str_replace( chr(13), '', str_replace( chr(10), '', $doctype[0]));

	// get the dedi-ui-language - dirty methode ... but the only way ... 
	$tinylanguage=strtolower(substr($cfg_dedi['backend_lang'],0,2));
	// no supported language > English
	if ($tinylanguage!="de" && $tinylanguage!="en" && $tinylanguage!="fr") $tinylanguage="en";

	unset($plugins_array);
	if (empty($type_config['features']) || $type_config['features'] == 'true') {
		$buttons1 = 'fullscreen,separator,print,separator,undo,redo,separator,cut,copy,paste,pastetext,pasteword,separator,search,replace,separator,charmap,separator,advhr,separator,anchor,link,unlink,separator,image,separator,table,visualaid,separator,removeformat,cleanup,separator,code';
		$buttons2 = 'styleselect,styleprops,formatselect,bold,italic,underline,strikethrough,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,liststyle,separator,indent,outdent,separator,forecolor,backcolor';
		$plugins = 'contextmenu,table,paste,searchreplace,print,fullscreen,advhr,advimage,advlink,style';
	} else {
		// is wysiwyg2, let the user choose what he wants to see!
		// add support for dedi-tags:
		$features = str_replace(' ', '', strtolower($type_config['features']) );
		$features = explode(',', $features);
		$itemset = 'false';
		if (in_array('popupeditor', $features) ) {
			$itemset = 'true';
			$components[] = 'fullscreen';
			$plugins_array[] ='fullscreen';
			$components[] = 'separator';
		}
		if (in_array('print', $features) ) {
			$itemset = 'true';
			$components[] = 'print';
			$plugins_array[] ='print';
			$components[] = 'separator';
		}
		// senseless > why wysiwyg?
		/*
		if (in_array('preview', $features) ) {
			$components[] = 'preview';
			$components[] = 'separator';
		}
		*/
		if (in_array('undo', $features)) {
			$itemset = 'true';
			$components[] = 'undo';
			$components[] = 'redo';
			$components[] = 'separator';
		}
		if (in_array('clipboardtools', $features) ) {
			$itemset = 'true';
			$components[] = 'cut';
			$components[] = 'copy';
			$components[] = 'paste';
			$components[] = 'pastetext';
			$components[] = 'pasteword';
			$plugins_array[] = 'paste';
			$components[] = 'separator';
		}
		if (in_array('search', $features)) {
			$itemset = 'true';
			$components[] = 'search';
			$components[] = 'replace';
			$plugins_array[] ='searchreplace';
			$components[] = 'separator';
		}
		if (in_array('specialchars', $features)) {
			$itemset = 'true';
			$components[] = 'charmap';
			$components[] = 'separator';
		}
		if (in_array('hr', $features)) {
			$itemset = 'true';
			$components[] = 'advhr';
			$plugins_array[] ='advhr';
			$components[] = 'separator';
		}
		if(in_array('file', $features) || in_array('link', $features)) {
			$itemset = 'true';
			$components[] = 'anchor';
			$components[] = 'link';
			$components[] = 'unlink';
			$plugins_array[] ='advlink';
			$components[] = 'separator';
		}
		if (in_array('image', $features)) {
			$itemset = 'true';
			$components[] = 'image';
			$plugins_array[] ='advimage';
			$components[] = 'separator';
		}
		if (in_array('table', $features)) {
			$itemset = 'true';
			$components[] = 'table';
			$components[] = 'visualaid';
			$plugins_array[] ='table';
			$components[] = 'separator';
		}
		if (in_array('striptag', $features)) {
			$itemset = 'true';
			$components[] = 'removeformat';
			$components[] = 'cleanup';
			$components[] = 'separator';
		}
		if (in_array('htmlmode', $features) || in_array('changemode', $features)) {
			$itemset = 'true';
			$components[] = 'code';
			$components[] = 'separator';
		}
		if ($itemset == 'true')	$components[]='dynlinebreak';
		$itemset = 'false';
		if (in_array('styles', $features)) {
			if (!empty($type_config['selectablestyles']))	$components[] = 'styleselect';
			 $components[] = 'styleprops';
			 $plugins_array[] ='style';
		}
		//if (in_array('font', $features)) $components[] = 'fontselect';
		//if (in_array('fontsize', $features)) $components[] = 'fontsizeselect';
		if (in_array('fontsize', $features) || in_array('font', $features)) $components[] = 'formatselect';
		if (in_array('bold', $features)) {
			$itemset = 'true';
			$components[] = 'bold';
		}
		if (in_array('italic', $features)) {
			$itemset = 'true';
			$components[] = 'italic';
		}
		if (in_array('underline', $features)) {
			$itemset = 'true';
			$components[] = 'underline';
		}
		if (in_array('strikethrough', $features)) {
			$itemset = 'true';
			$components[] = 'strikethrough';
		}
		if (in_array('subscript', $features)) {
			$itemset = 'true';
			$components[] = 'sub';
		}
		if (in_array('superscript', $features)) {
			$itemset = 'true';
			$components[] = 'sup';
		}
		if ($itemset == 'true') $components[] = 'separator';
		$itemset = 'false';

		if (in_array('align', $features)) {
			$components[] = 'justifyleft';
			$components[] = 'justifycenter';
			$components[] = 'justifyright';
			$components[] = 'justifyfull';
			$components[] = 'separator';
		}
		if (in_array('list', $features)) {
			$components[] = 'bullist';
			$components[] = 'numlist';
			$components[] = 'liststyle';
			$components[] = 'separator';
		}

		if( in_array('indent', $features) ) {
			$components[] = 'indent';
			$components[] = 'outdent';
			$components[] = 'separator';
		}
		$itemset = 'false';
		if (in_array('fontcolor', $features)) {
			$itemset = 'true';
			$components[] = 'forecolor';
		}
		if (in_array('backgroundcolor', $features)) {
			$itemset = 'true';
			$components[] = 'backcolor';
		}
		if ($itemset == 'true') $components[] = 'separator';
		$itemset = 'false';
		
		// needed?
		unset($buttons1,$buttons2);
		// populate toolbars ...
		// the code splits on the pre-defined items position
		// decides if a split is needed due to the overall number of items
		// and it ereases separators at the end of the button line(s)		
		//
		// dynlinebreak = there is one item in the "first line"
		if (array_search('dynlinebreak',$components)) {
			$buttonsarray1=array_slice($components,0,array_search('dynlinebreak',$components));
			$buttonsarray2=array_slice($components,array_search('dynlinebreak',$components)+1);
			// count items
			$buttonsarray1length=count($buttonsarray1);
			$buttonsarray2length=count($buttonsarray2);
			// "2 lines" are only needed if too much items ... 
			if ($buttonsarray1length+$buttonsarray2length<30) {
				// ok merge the formerly splittet components
				// we could take the $components array too, but in this way the 'dynlinebreak' is allready ereased ;)
				$buttonsarray1=array_merge($buttonsarray1,$buttonsarray2);
				// second array no longer needed - length to zero = no "second line"
				$buttonsarray2length=0;
				// new length new calculation
				$buttonsarray1length=count($buttonsarray1);
			}
			// prevent seperator at the end
			if ($buttonsarray1[$buttonsarray1length-1]=='separator') $buttonsarray1=array_slice($buttonsarray1,0,$buttonsarray1length-1);
			// implode to tinymce button string - line 1
			$buttons1=implode(',',$buttonsarray1);
			// are there relly items of the "second line"?
			if ($buttonsarray2length>0) {
				// prevent seperator at the end
				if ($buttonsarray2[$buttonsarray2length-1]=='separator') $buttonsarray2=array_slice($buttonsarray2,0,$buttonsarray2length-1);
				// implode to tinymce button string - line 2
				$buttons2=implode(',',$buttonsarray2);
			// no "second line" > empty string = second tiny line off
			} else $buttons2="";
		// no dynlinebreak found ... only items of the "second line"
		} else {
			// how many items
			$buttonsarraylength=count($components);
			// are there really any items of the "second line"
			if ($buttonsarraylength>0) {
				// prevent seperator at the end
				if ($components[$buttonsarraylength-1]=='separator') $components=array_slice($components,0,$buttonsarraylength-1);
				// implode to tinymce button string - line 2
				$buttons1=implode(',',$components);
			// if there's really nothing
			} else $buttons1="";
		}
		if (empty($plugins_array))
			$plugins="";
		else {
			$plugins_array[] ='contextmenu';
			$plugins=implode(',',$plugins_array);
		}
	}
	// output tinyMCE
	$out = '<td>';
	// tinyMCE HTML code
	$out .= '<script language="javascript" type="text/javascript" src="'.$cfg_client['htmlpath'].'cms/tinymce/tiny_mce_gzip.php"></script>';
	$out .= '<script language="JavaScript" type="text/javascript">';
	$out .= 'tinyMCE.init({';
	$out .= 'document_base_url:"'.$cfg_client['htmlpath'].'index.php",';
	$out .= 'doctype :"'.addslashes($tinydoctype).'",';
	$out .= 'mode : "specific_textareas",';
	$out .= 'elements : "text",';
	$out .= 'theme : "advanced",';
	$out .= 'language : "'.$tinylanguage.'",';
	// total <br/> mode on applet setting '5'
	if ($cfg_client['wysiwyg_applet']=='5') {
		$out .= 'force_p_newlines : false,';
		$out .= 'force_br_newlines: true,';
		$out .= 'convert_newlines_to_brs : true,';
	}
	$out .= 'convert_fonts_to_spans : true,';
	$out .= 'plugins : "'.$plugins.'",';
	$out .= 'theme_advanced_buttons1 :"'.$buttons1.'",';
	$out .= 'theme_advanced_buttons2 :"'.$buttons2.'",';
	$out .= 'theme_advanced_buttons3 :"",';
	$out .= 'theme_advanced_toolbar_location : "top",';
	$out .= 'theme_advanced_toolbar_align : "left",';
	$out .= 'relative_urls : true,';
	//$out .= 'convert_urls : true,';
	$out .= 'auto_cleanup_word : true,';
	// wysiwyg only ... show all
	if (empty($type_config['features']) || $type_config['features'] == 'true') {
		$out .= 'content_css : "' . $tinystylefiles .$cfg_client['htmlpath'].'cms/tinymce/content_overwrite.css'.'",';
		$out .= 'theme_advanced_styles : "'.$tinystyles.'",';
		$out .= 'debug : false });';
		$out .= ' var tinyMCELinkList = new Array('.$tinylinks.');';
		$out .= ' var tinyMCEImageList = new Array('.$tinyimages.');';
	} else {
	// wysiwyg2 only ... show only selected
		if (in_array('styles', $features) && !empty($type_config['selectablestyles'])){
			$out .= 'content_css : "' . $tinystylefiles.$cfg_client['htmlpath'].'cms/tinymce/content_overwrite.css'.'",';
			$out .= 'theme_advanced_styles : "'.$tinystyles.'",';
		}
		$out .= 'debug : false });';
		if(in_array('file', $features) || in_array('link', $features))
			$out .= ' var tinyMCELinkList = new Array('.$tinylinks.');';
		if (in_array('image', $features)) 
			$out .= ' var tinyMCEImageList = new Array('.$tinyimages.');';
	}
	$out .= '</script>';
	$out .= '<textarea mce_editable="true" name="'.$formname.'" cols="80" rows="20" wrap="virtual" id="'.$formname.'" style="width:644px;height:300px;">'.$content.'</textarea>';
	$out .= "</td>";
	return $out;
}
/**
* Chop a string into a smaller string.
*
* @author      Aidan Lister <aidan@php.net>
* @version     1.1.0
* @link        http://aidanlister.com/repos/v/function.str_chop.php
* @param       mixed  $string   The string you want to shorten
* @param       int    $length   The length you want to shorten the string to
* @param       bool   $center   If true, chop in the middle of the string
* @param       mixed  $append   String appended if it is shortened
*/
function str_chop($string, $length = 60, $center = true, $append = null)
{
	 // Set the default append string
	 if ($append === null) {
			 $append = ($center === true) ? ' ... ' : ' ...';
	 }

	 // Get some measurements
	 $len_string = strlen($string);
	 $len_append = strlen($append);

	 // If the string is longer than the maximum length, we need to chop it
	 if ($len_string > $length) {
			 // Check if we want to chop it in half
			 if ($center === true) {
					 // Get the lengths of each segment
					 $len_start = $length / 2;
					 $len_end = $len_start - $len_append;

					 // Get each segment
					 $seg_start = substr($string, 0, $len_start);
					 $seg_end = substr($string, $len_string - $len_end, $len_end);

					 // Stick them together
					 $string = $seg_start . $append . $seg_end;
			 } else {
					 // Otherwise, just chop the end off
					 $string = substr($string, 0, $length - $len_append) . $append;
			 }
	 }
	 return $string;
}
?>