<?php
// +-------------------------------------------------------------+
// | HiveMail version 1.3.1
// +-------------------------------------------------------------+
// | HIVEMAIL IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than Hivemail or if you have otherwise received
// | this software from someone who is not a representative of
// | this organization you are involved in an illegal activity.
// +-------------------------------------------------------------+
// | $RCSfile: phrase.php,v $ - $Revision: 1.4.2.1 $
// | $Date: 2004/08/18 15:47:07 $ - $Author: tubedogg $
// +-------------------------------------------------------------+

error_reporting(E_ALL & ~E_NOTICE);
require_once('./global.php');
cp_header(' &raquo; Language &raquo; Phrases');

if (is_array($submit)) {
	foreach($submit as $key => $bobo) {
		$goto_page = $key;
	}
	if (empty($goto_page) and !empty($pagenumber)) {
		$goto_page = $pagenumber;
	}
}

// ############################################################################
// Set the default cmd
default_var($cmd, 'modify');
if ($cmd == 'add') {
	$cmd = 'edit';
}
if ($cmd == 'addgroup') {
	$cmd = 'editgroup';
}

// ############################################################################
// Create a new phrase or update an existing one
if ($_POST['cmd'] == 'update') {
	cp_nav('phrasemodify');
	if (empty($aphrase['variable']) or empty($aphrase['value'])) {
		adminlog($variable, false);
		cp_error('The phrase must have a variable and default text.');
	} else {
		if (empty($variable)) {
			$checkphrase = $DB_site->query_first("SELECT * FROM hive_phrase WHERE variable = '".addslashes($aphrase['variable'])."'");
			if (!empty($checkphrase)) {
				cp_error('The phrase variable you entered already exists. Please choose a unique variable.');
			}
			$word = 'created';
		}
		if ($oldphraseareaid != $aphrase['phraseareaid'] and !empty($variable)) {
			$DB_site->query("
				UPDATE hive_phrase
				SET phraseareaid = $aphrase[phraseareaid]
				WHERE phraseareaid = $oldphraseareaid AND variable = '".iif(empty($variable), $aphrase['variable'], $variable)."'
			");
			$phraseareaid = $aphrase['phraseareaid'];
		}
		ksort($e);
		//print_array($e); print_array($t); print_array($aphrase); exit;

		foreach ($e as $languageid => $valuetext) {
			if ($languageid < 1) {
				if (empty($variable)) {
					$templangid = iif($masterinsert == 1 and defined('HIVE_DEV') and HIVE_DEV == true, -1, 0);
					$DB_site->auto_query('phrase', array('phraseareaid' => $aphrase['phraseareaid'], 'languageid' => $templangid, 'variable' => $aphrase['variable'], 'value' => $aphrase['value']));
					unset($templangid);
				} else {
					if ((defined('HIVE_DEV') and HIVE_DEV == true) or $languageid == 0) {
						if (stripslashes($valuetext) != $aphrase['value'] or $variable != $aphrase['variable']) {
							$DB_site->auto_query('phrase', array('phraseareaid' => $aphrase['phraseareaid'], 'variable' => $aphrase['variable'], 'value' => $aphrase['value']), "variable = '$variable' AND languageid = $languageid");
						}
					}
				}
			} elseif (!empty($variable)) {
				if (empty($valuetext)) {
					continue;
				}
				if (empty($t["$languageid"])) {
					$DB_site->query("
						DELETE FROM hive_phrase
						WHERE variable = '$variable' AND languageid = $languageid
					");
				} elseif ($valuetext != $t["$languageid"]) {
					$DB_site->auto_query('phrase', array('value' => $t["$languageid"]), "variable = '$variable' AND languageid = $languageid");
				}
			}
			unset($t["$languageid"]);
		}
		if (is_array($t)) {
			foreach ($t as $languageid => $valuetext) {
				if (!empty($valuetext)) {
					$DB_site->auto_query('phrase', array('phraseareaid' => $aphrase['phraseareaid'], 'variable' => $aphrase['variable'], 'value' => $valuetext, 'languageid' => $languageid));
				}
			}
		}

		require_once('../includes/functions_template.php');
		rebuild_language(-1);

		adminlog(iif(empty($variable), $aphrase['variable'], $variable), true);
		cp_redirect('The phrase and its\' translation(s) have been '.iif($word == 'created', 'created', 'updated'), 'phrase.php?cmd=modify'.iif($phraseareaid, "&phraseareaid=$phraseareaid").iif(empty($variable), "&phraseareaid=$aphrase[phraseareaid]").iif($perpage, "&perpage=$perpage").iif($pagenumber, "&pagenumber=$pagenumber"));
	}
}

// ############################################################################
// Create a new phrase or update an existing one
if ($cmd == 'edit') {
	cp_nav('phrasemodify');
	startform('phrase.php', 'update', '', array('aphrase_variable' => 'variable', 'aphrase_value' => 'default text'));

	$aphrase = $DB_site->query_first("SELECT * FROM hive_phrase WHERE variable = '".addslashes($variable)."' AND languageid = -1 or languageid = 0");
	adminlog($variable);
	if (empty($variable)) {
		$aphrase = array(
			'variable' => '',
			'value' => '',
			'languageid' => iif(defined('HIVE_DEV') and HIVE_DEV == true, -1, 0),
		);
		$variable = '';
		starttable('Create New Phrase');
	} else {
		starttable('Translate Phrase "'.$aphrase['variable'].'"');
		$translations = $DB_site->query("
			SELECT *
			FROM hive_phrase
			WHERE variable = '".addslashes($variable)."'
			AND languageid > 0
		");
		while ($trans = $DB_site->fetch_array($translations)) {
			$translation["$trans[languageid]"] = $trans['value'];
		}			
	}

	$alllangs = $DB_site->query("
		SELECT *
		FROM hive_language
		ORDER BY languageid
	");

	hiddenfield('variable', $variable);
	hiddenfield('pagenumber', $pagenumber);
	hiddenfield('perpage', $perpage);
	hiddenfield('oldphraseareaid', $aphrase['phraseareaid']);
	hiddenfield('phraseareaid', $phraseareaid);
	hiddenfield('e['.$aphrase['languageid'].']', addslashes($aphrase['value']));
	if (defined('HIVE_DEV') and HIVE_DEV == true and empty($variable)) {
		radiofield('<b>Insert into master language</b>:', 'masterinsert');
	}
	if (defined('HIVE_DEV') and HIVE_DEV == true or $aphrase['languageid'] == 0) {
		tableselect('<b>Phrase Group</b>:', 'aphrase[phraseareaid]', 'phrasegroup', iif(empty($variable), $phraseareaid, $aphrase['phraseareaid']));
	} else {
		hiddenfield('aphrase[phraseareaid]', $aphrase['phraseareaid']);
	}
	inputfield('<b>Variable</b>:', 'aphrase[variable]', $aphrase['variable'], 35, '', true, true, false, false, false, iif($aphrase['languageid'] == 0 or (defined('HIVE_DEV') and HIVE_DEV == true), false, true));
	textarea('<b>Default Text</b>:', 'aphrase[value]', $aphrase['value'], 7, 35, true, iif($aphrase['languageid'] == 0 or (defined('HIVE_DEV') and HIVE_DEV == true), false, true));
	endtable();

	starttable('Translations');
	textrow('For each language, you can specify a translation for this phrase. If you do not enter a translation, the default text (found above) will be used.');
	while ($alang = $DB_site->fetch_array($alllangs)) {
		hiddenfield('e['.$alang['languageid'].']', iif(!empty($translation["$alang[languageid]"]), addslashes($translation["$alang[languageid]"]), ''));
		textarea('<b>'.$alang['title'].'</b>:<br /><br />', 't['.$alang['languageid'].']', $translation["$alang[languageid]"]);
	}

	if (empty($variable)) {
		endform('Create Phrase');
	} else {
		endform('Save Translations', 'Reset Fields');
	}
	endtable();
}

// ############################################################################
// Save all phrases from a language at once
if ($cmd == 'massupdate') {
	cp_nav('phrasemodify');
	$language = getinfo('language', $languageid, true);

	ksort($e);
	foreach ($e as $var => $val) {
		if (($val == $t["$var"] or empty($t["$var"])) and $p["$var"] == 1) {
			$DB_site->query("
				DELETE FROM hive_phrase
				WHERE languageid = $languageid
				AND variable = '$var'
			");
			unset($t["$var"]);
			continue;
		} elseif ($val == $t["$var"] or empty($t["$var"])) {
			unset($t["$var"]);
			continue;
		}
		if (empty($t["$var"])) {
			unset($t["$var"]);
		}
	}
	foreach ($t as $var => $val) {
		if ($p["$var"] == 1) {
			$DB_site->auto_query('phrase', array('value' => $val), "languageid = $languageid and variable = '$var'");
		} else {
			$DB_site->auto_query('phrase', array('phraseareaid' => $gid["$var"], 'languageid' => $languageid, 'variable' => $var, 'value' => $val));
		}
	}

	require_once('../includes/functions_template.php');
	rebuild_language($languageid);

	if (!empty($goto_page)) {
		adminlog($languageid, true);
		cp_redirect('The page has been successfully saved. You will now be redirected to the new page you selected.', 'phrase.php?cmd=massmodify&languageid='.$languageid.iif($phraseareaid, "&phraseareaid=$phraseareaid").'&perpage=15&pagenumber='.$goto_page);
	} else {
		adminlog($languageid, true);
		cp_redirect('The page has been successfully saved.', 'phrase.php?cmd=massmodify&languageid='.$languageid.iif($phraseareaid, "&phraseareaid=$phraseareaid"));
	}
}

// ############################################################################
// Translate all phrases from a language at once
if ($cmd == 'massmodify') {
	cp_nav('phrasemodify');
	adminlog();
	if (empty($languageid)) {
		cp_error('No language was specified.');
	}
	$language = getinfo('language', $languageid);
	if (!empty($phraseareaid) and $phraseareaid != -1) {
		$phrasegroup = $DB_site->query_first("SELECT * FROM hive_phrasegroup WHERE phraseareaid = $phraseareaid");
		if (empty($phrasegroup)) {
			$phraseareaid = '';
		}
	} else {
		$phraseareaid = '';
	}

	$cells = array(
		'Variable',
		'Default Text',
		$language['title'].' Text',
	);

	// Pagination
	$perpage = 15;
	$link = "phrase.php";
	$pagenav = paginate('phrase', $link, "WHERE (languageid = -1 OR languageid = 0)".iif($phraseareaid, " AND phraseareaid = $phraseareaid"), true);

	startform('phrase.php', 'massmodify', '', array(), false, '', '_self', 'get');
	starttable('Choose Language & Phrase Group', '600');
	tableselect('Language', 'languageid', 'language', $languageid);
	tableselect('Phrase Group', 'phraseareaid', 'phrasegroup', $phraseareaid, '1 = 1', false, '', 'title', 'phraseareaid');
	endform('Switch Language/Phrase Group');
	endtable();

	$allphrases = $DB_site->query("
		SELECT *
		FROM hive_phrase
		WHERE (languageid = -1 OR languageid = 0)
		".iif($phraseareaid, "AND phraseareaid = $phraseareaid")."
		ORDER BY variable
		LIMIT ".($limitlower-1).", $perpage
	");
	while ($ap = $DB_site->fetch_array($allphrases)) {
		$toget[] = $ap['variable'];
		$defphrase["$ap[variable]"] = $ap['value'];
		$defphrasegroups["$ap[variable]"] = $ap['phraseareaid'];
	}

	$toget = "'".implode("','", $toget)."'";
	$customphrases = $DB_site->query("
		SELECT *
		FROM hive_phrase
		WHERE languageid = $languageid
		AND variable IN ($toget)
	");
	while ($cust = $DB_site->fetch_array($customphrases)) {
		$custphrase["$cust[variable]"] = $cust['value'];
	}

	startform('phrase.php', 'massupdate');
	hiddenfield('languageid', $languageid);
	hiddenfield('pagenumber', $pagenumber);
	if ($phraseareaid) {
		hiddenfield('phraseareaid', $phraseareaid);
	}

	starttable($language['title'].' Phrase Translation', '600', true, 3);
	tablehead($cells);
	foreach ($defphrase as $var => $val) {
		hiddenfield("gid[$var]", $defphrasegroups["$var"]);
		if (isset($custphrase["$var"]) and !empty($custphrase["$var"])) {
			$langval = $custphrase["$var"];
			hiddenfield("p[$var]", 1);
		} else {
			$langval = $val;
		}
		tablerow(array("<b>$var</b>", textarea('-', "e[$var]", $val, 7, 30, true, true, false, false), textarea('-', "t[$var]", $langval, 7, 30, true, false, false, false)));
	}
	textrow($pagenav, 3, 'right');
	endform('Save Changes', 'Reset Fields', '', '', 3);
	endtable();
}

// ############################################################################
// List the phrases
if ($cmd == 'modify') {
	cp_nav('phrasemodify');
	adminlog();
	if (empty($phraseareaid) or $phraseareaid == -1) {
		$aphrasegroup['title'] = 'All';
		$phraseareaid = '';
		$tabletitle = "All Phrase Groups";
	} else {
		$aphrasegroup = getinfo('phrasegroup', $phraseareaid, false, false);
		$tabletitle = "'$aphrasegroup[title]' Phrase Group (ID: $phraseareaid)";
	}
	$cells = array(
		'Variable',
	);
	$alllangs = $DB_site->query('
		SELECT *
		FROM hive_language
		ORDER BY languageid
	');
	while ($alang = $DB_site->fetch_array($alllangs)) {
		$cells[] = $alang['title'];
		$langs[] = $alang['languageid'];
	}
	$cells[] = '&nbsp;';

	// Pagination
	$perpage = 15;
	$link = "phrase.php?cmd=modify".iif($phraseareaid, "&phraseareaid=$phraseareaid");
	$pagenav = paginate('phrase', $link, "WHERE (languageid = -1 OR languageid = 0)".iif($phraseareaid, " AND phraseareaid = ".intval($phraseareaid)));

	$phrasegroups = $DB_site->query("
		SELECT *
		FROM hive_phrasegroup
		ORDER BY phraseareaid
	");
	starttable('Choose Phrase Group', '550');
	$pgtable = "<select name=\"phrasegroups\" onchange=\"location = 'phrase.php?cmd=modify&phraseareaid='+this.options[this.selectedIndex].value+'".iif($pagenumber, "&pagenumber=$pagenumber").iif($perpage, "&perpage=$perpage")."';\">\n<option value=\"-1\">-- All Groups --</option>\n";
	while ($phrasegroup = $DB_site->fetch_array($phrasegroups)) {
		$pgtable .= "<option value=\"$phrasegroup[phraseareaid]".iif($phrasegroup['phraseareaid'] == $phraseareaid, ' selected="selected"')."\">$phrasegroup[title]</option>\n";
	}
	$pgtable .= "</select>\n";
	tablerow(array('center' => $pgtable));
	endtable();

	starttable($tabletitle, '550');
	tablehead($cells);

	$phrasevars = $DB_site->query("
		SELECT *
		FROM hive_phrase
		WHERE (languageid = -1 OR languageid = 0)
		".iif($phraseareaid, 'AND phraseareaid = '.intval($phraseareaid))."
		ORDER BY variable
		LIMIT ".($limitlower-1).", $perpage
	");
	$toget = array();
	$pagephrase = array();
	while ($tempphrase = $DB_site->fetch_array($phrasevars)) {
		$toget[] = $tempphrase['variable'];
		$pagephrase[] = $tempphrase;
	}
	$toget = "'".implode("','", $toget)."'";
	$alllangphrases = $DB_site->query("
		SELECT *
		FROM hive_phrase
		WHERE variable IN ($toget)
		AND languageid <> -1
		ORDER BY variable, languageid
	");
	while ($tempphrase = $DB_site->fetch_array($alllangphrases)) {
		$bphrase["$tempphrase[variable]"]["$tempphrase[languageid]"] = 1;
	}

	foreach ($pagephrase as $aphrase) {
		$cells = array(
			$aphrase['variable'],			
		);
		foreach ($langs as $langid) {
			$cells["center_$aphrase[variable]_$langid"] = '<img src="../misc/cp_images/'.iif(!empty($bphrase["$aphrase[variable]"]["$langid"]), 'small_check.gif" title="This phrase has been translated into this language"', 'small_x.gif" title="This phrase has not been translated into this language"').' border="0" />';
		}
		$cells[] = makelink('translate', 'phrase.php?cmd=edit'.iif(!empty($phraseareaid), '&phraseareaid='.$phraseareaid).iif(!empty($perpage), '&perpage='.$perpage).iif(!empty($pagenumber), '&pagenumber='.$pagenumber).'&variable='.$aphrase['variable']) . iif($aphrase['languageid'] == 0 or (defined('HIVE_DEV') and HIVE_DEV == true), '-' . makelink('remove', 'phrase.php?cmd=remove&variable='.$aphrase['variable']));
		tablerow($cells);
	}
	tablehead(array("$pagenav&nbsp;"), count($cells));
	endtable();

	button('', 'Create New Phrase', "window.location='phrase.php?cmd=add".iif(!empty($phraseareaid), '&phraseareaid='.$phraseareaid)."'", true);

	starttable('Legend', '550');
	tablerow(array('<img src="../misc/cp_images/small_check.gif" border="0" />&nbsp;Phrase has been translated into this language<br /><img src="../misc/cp_images/small_x.gif" border="0" />&nbsp;Phrase has not been translated into this language'));
	endtable();
}

// ############################################################################
// Remove phrase
if ($_POST['cmd'] == 'kill') {
	cp_nav('phrasemodify');

	$DB_site->query("
		DELETE FROM hive_phrase
		WHERE variable = '".addslashes($variable)."'
	");

	adminlog($variable, true, 'kill');
	cp_redirect('The phrase and all translation(s) have been removed.', 'phrase.php?cmd=modify&phraseareaid='.$phraseareaid);
}

// ############################################################################
// Remove phrase
if ($cmd == 'remove') {
	cp_nav('phrasemodify');
	$aphrase = $DB_site->query_first("SELECT * FROM hive_phrase WHERE variable = '".addslashes($variable)."' AND languageid = -1 OR languageid = 0");
	if (empty($aphrase)) {
		adminlog($variable, false);
		cp_error('The phrase variable you specified does not exist.');
	} elseif ($aphrase['languageid'] != 0 and (!defined('HIVE_DEV') or HIVE_DEV != true)) {
		adminlog($variable, false);
		cp_error('You cannot remove a phrase from the master language.');
	}

	adminlog($variable);
	startform('phrase.php', 'kill', 'Are you sure you want to remove this phrase?');
	starttable('Remove phrase "'.$variable.'"');
	textrow('Are you <b>sure</b> you want to remove this phrase? This action will also remove all translations of this phrase. This procedure <b>cannot</b> be reversed!<br /><br /><b>Phrase text</b>:<br />'.$aphrase['value']);
	hiddenfield('variable', $variable);
	hiddenfield('phraseareaid', iif(!empty($phraseareaid), $phraseareaid, $aphrase['phraseareaid']));
	endform('Remove Phrase', '', 'Go Back');
	endtable();
}

// ############################################################################
// Off limits!
if (!defined('HIVE_DEV') or HIVE_DEV != true) {
	cp_footer();
	exit;
}

// ############################################################################
// Update phrase group or insert new one
if ($cmd == 'updategroup') {
	cp_nav('phrasegroupmodify');

	if ($phraseareaid == 0) {
		$DB_site->auto_query('phrasegroup', $phrasegroup);
	} else {
		$DB_site->auto_query('phrasegroup', $phrasegroup, "phrasegroupid = $phrasegroupid");
	}

	adminlog($phrasegroupid, true);
	cp_redirect('The phrase group has been '.iif($phrasegroupid == 0, 'created', 'updated').' successfully.', 'phrase.php?cmd=modifygroup');
}

// ############################################################################
// Edit phrase group or create new one
if ($cmd == 'editgroup') {
	cp_nav('phrasegroupmodify');
	startform('phrase.php', 'updategroup', '', array('phrasegroup_title' => 'title'), true);

	$phrasegroup = getinfo('phrasegroup', $phrasegroupid, false, false);
	adminlog($phrasegroupid);
	if ($phrasegroup === false) {
		$phrasegroup = array(
			'title' => '',
		);
		$phrasegroupid = 0;
		$areaid = $DB_site->query_first("
			SELECT max(phraseareaid) AS newid
			FROM hive_phrasegroup
		");
		$phrasegroup['phraseareaid'] = ($areaid['newid']+1);
		starttable('Create New Phrase Group');
	} else {
		starttable('Update Phrase Group "'.$phrasegroup['title'].'" (ID: '.$phrasegroupid.')');
	}

	hiddenfield('phrasegroupid', $phrasegroupid);
	inputfield('<b>Phrase Area ID</b>:', 'phrasegroup[phraseareaid]', $phrasegroup['phraseareaid']);
	inputfield('<b>Title</b>:', 'phrasegroup[title]', $phrasegroup['title']);

	if ($phrasegroupid == 0) {
		endform('Create Phrase Group');
	} else {
		endform('Update Phrase Group');
	}
	endtable();
}

// ############################################################################
// List phrase groups
if ($cmd == 'modifygroup') {
	cp_nav('phrasegroupmodify');
	adminlog();
	$cells = array(
		'Group ID',
		'Area ID',
		'Title',
		'Options'
	);
	$aphrasegroups = $DB_site->query('
		SELECT *
		FROM hive_phrasegroup
	');
	if ($DB_site->num_rows($aphrasegroups) < 1) {
		starttable('Error', '450');
		tablehead($cells);
		textrow('No phrase groups found', count($cells), 1);
	} else {
		starttable('Existing Phrase Groups', '450');
		tablehead($cells);
		while ($aphrasegroup = $DB_site->fetch_array($aphrasegroups)) {
			$cells = array(
				$aphrasegroup['phrasegroupid'],
				$aphrasegroup['phraseareaid'],
				$aphrasegroup['title'],
				makelink('edit', "phrase.php?cmd=editgroup&phrasegroupid=$aphrasegroup[phrasegroupid]") . '-' . makelink('remove', "phrase.php?cmd=removegroup&phrasegroupid=$aphrasegroup[phrasegroupid]")
			);
			tablerow($cells);
		}
	}
	emptyrow(count($cells));
	endtable();

	button('', 'Create New Phrase Group', "window.location='phrase.php?cmd=addgroup'", true);
}

// ############################################################################
// Remove phrase group
if ($_POST['cmd'] == 'killgroup') {
	cp_nav('phrasegroupmodify');

	$DB_site->query("
		DELETE FROM hive_phrasegroup
		WHERE phrasegroupid = $phrasegroupid
	");
	$DB_site->query("
		UPDATE hive_phrasegroup
		SET phraseareaid = 1
		WHERE phraseareaid = $phraseareaid
	");

	adminlog($phrasegroupid, true, 'killgroup');
	cp_redirect('The phrase group has been removed and all phrases from it assigned to the global group.', 'phrase.php?cmd=modifygroup');
}

// ############################################################################
// Remove phrase group
if ($cmd == 'removegroup') {
	cp_nav('phrasegroupmodify');
	if ($phrasegroupid == 1) {
		adminlog($phrasegroupid, false);
		cp_error('You cannot remove the Global phrase group.');
	}
	$aphrasegroup = getinfo('phrasegroup', $phrasegroupid);

	adminlog($phrasegroupid);
	startform('phrase.php', 'killgroup', 'Are you sure you want to remove this phrase group?');
	starttable('Remove phrase group "'.$aphrasegroup['title'].'" (ID: '.$phrasegroupid.')');
	textrow('Are you <b>sure</b> you want to remove this phrase group? This procedure <b>cannot</b> be reversed!<br /><br />Phrases from this group will be assigned to the global group.');
	hiddenfield('phrasegroupid', $phrasegroupid);
	hiddenfield('phraseareaid', $aphrasegroup['phraseareaid']);
	endform('Remove Phrase Group', '', 'Go Back');
	endtable();
}

cp_footer();
?>