<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// ######################## SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// ##################### DEFINE IMPORTANT CONSTANTS #######################
define('CVS_REVISION', '$RCSfile$ - $Revision: 29067 $');
define('NOZIP', 1);

// #################### PRE-CACHE TEMPLATES AND DATA ######################
$phrasegroups = array('thread', 'threadmanage', 'prefix');
$specialtemplates = array();

// ########################## REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/functions_databuild.php');
require_once(DIR . '/includes/adminfunctions_prefix.php');

@set_time_limit(0);

// ######################## CHECK ADMIN PERMISSIONS #######################
if (!can_administer('canadminthreads'))
{
	print_cp_no_permission();
}

$vbulletin->input->clean_array_gpc('r', array(
	'forumid' => TYPE_INT,
	'pollid'  => TYPE_INT,
));

// ############################# LOG ACTION ###############################
log_admin_action(iif(!empty($vbulletin->GPC['forumid']), "forum id = " . $vbulletin->GPC['forumid'], iif(!empty($vbulletin->GPC['pollid']), "poll id = " . $vbulletin->GPC['pollid'])));

// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################
if ($_POST['do'] != 'saverelatedwords')
{
	print_cp_header($vbphrase['autotaggerfromcontentandtitle_enhanced_tags']);
}

// ########################################################################

if ($_POST['do'] == 'taginsert' OR $_REQUEST['do'] == 'tags')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'pagenumber' => TYPE_UINT,
		'sort'       => TYPE_NOHTML
	));
}

// ########################################################################

if ($_POST['do'] == 'taginsert' OR $_REQUEST['do'] == 'tags' OR $_POST['do'] == 'saverelatedwords') {
	$vbulletin->input->clean_array_gpc('r', array(
		'pagenumber' => TYPE_UINT,
		'sort'       => TYPE_NOHTML
	));
}

// ########################################################################

if ($_POST['do'] == 'taginsert')
{
	$vbulletin->input->clean_array_gpc('p', array(
		'tagtext' => TYPE_NOHTML,
		'related_words' => TYPE_NOHTML,
	));

	$tagdm = datamanager_init('tag', $vbulletin, ERRTYPE_ARRAY);
	if ($tagdm->fetch_by_tagtext($vbulletin->GPC['tagtext'])) {
		print_stop_message('tag_exists');
	}
	
	$errors = array();
	$valid = vB_Taggable_Content_Item::filter_tag_list(array($vbulletin->GPC['tagtext']), $errors);

	if ($errors) {
		print_stop_message('generic_error_x', implode('<br /><br />', $errors));
	}

	$related_words = $vbulletin->db->escape_string(strtolower($vbulletin->GPC['related_words']));

	require_once(DIR . '/includes/functions_newpost.php');

	if (!empty($valid))	{
    	$time = TIMENOW;
		$db->query_write("
			INSERT IGNORE INTO " . TABLE_PREFIX . "tag
				(tagtext, dateline, related_words)
			VALUES
				('" . $db->escape_string($valid[0]) . "', " . $time . ", '".$related_words."')
		");
		
		$db->query_write("
			INSERT IGNORE INTO " . TABLE_PREFIX . "tag_proposition
				(tagtext, dateline, status)
			VALUES
				('" . $db->escape_string($valid[0]) . "', " . $time . ", 3)
		");		
	}
/*	oryginal one - ignore it
	if (!empty($valid))
	{
		$tagdm->set('tagtext', $valid[0]);
		$tagdm->set('dateline', TIMENOW);

		if ($tagdm->errors)
		{
			print_stop_message('generic_error_x', implode('<br /><br />', $tagdm->errors));
		}

		$tagdm->save();
	}
*/	

	define('CP_REDIRECT', 'tags_autotaggerfromcontentandtitle.php?do=tags&page=' . $vbulletin->GPC['pagenumber'] . '&sort=' . $vbulletin->GPC['sort']);
	print_stop_message('tag_saved');
}

// ########################################################################
if ($_REQUEST['do'] == 'tags')
{
	if ($vbulletin->GPC['pagenumber'] < 1)
	{
		$vbulletin->GPC['pagenumber'] = 1;
	}

	$column_count = 2;
	$max_per_column = 15;

	$perpage = $column_count * $max_per_column;
	$start = ($vbulletin->GPC['pagenumber'] - 1) * $perpage;

	list($tag_count) = $db->query_first("SELECT COUNT(*) AS total FROM " . TABLE_PREFIX . "tag", DBARRAY_NUM);

	if ($start >= $tag_count)
	{
		$start = max(0, $tag_count - $perpage);
	}

	$tags = $db->query_read("
		SELECT *
		FROM " . TABLE_PREFIX . "tag
		ORDER BY " . ($vbulletin->GPC['sort'] == 'dateline' ? 'dateline DESC' : 'tagtext') . "
		LIMIT $start, $perpage
	");

	print_form_header('tags_autotaggerfromcontentandtitle', 'saverelatedwords', false, true, 'tagsform');
	print_table_header($vbphrase['autotaggerfromcontentandtitle_related_words'], 3);
	if ($db->num_rows($tags))
	{
		$columns = array();
		$counter = 0;

		// build page navigation
		$total_pages = ceil($tag_count / $perpage);
		if ($total_pages > 1)
		{
			$pagenav = '<strong>' . $vbphrase['go_to_page'] . '</strong>';
			for ($thispage = 1; $thispage <= $total_pages; $thispage++)
			{
				if ($thispage == $vbulletin->GPC['pagenumber'])
				{
					$pagenav .= " <strong>[$thispage]</strong> ";
				}
				else
				{
					$pagenav .= " <a href=\"tags_autotaggerfromcontentandtitle.php?$session[sessionurl]do=tags&amp;page=$thispage\" class=\"normal\">$thispage</a> ";
				}
			}

		}
		else
		{
			$pagenav = '';
		}

		if ($vbulletin->GPC['sort'] == 'dateline')
		{
			$sort_link = '<a href="tags_autotaggerfromcontentandtitle.php?do=tags">' . $vbphrase['display_alphabetically'] . '</a>';
		}
		else
		{
			$sort_link = '<a href="tags_autotaggerfromcontentandtitle.php?do=tags&amp;sort=dateline">' . $vbphrase['display_newest'] . '</a>';
		}

		print_description_row(
			"<div style=\"float: $stylevar[left]\">$sort_link</div>$pagenav",
			false, 3, 'thead', 'right'
		);
		print_description_row(
			"<div style=\"float: $stylevar[left]\">".$vbphrase['autotaggerfromcontentandtitle_related_words_description']."</div>",false, 3, 'thead'
		);
		// build columns
		while ($tag = $db->fetch_array($tags))
		{
			$columnid = floor($counter++ / $max_per_column);
			$columns["$columnid"][] = '<div id="tag' . $tag['tagid'] . '" class="alt1" style="float:' . $stylevar[left] . ';clear:' . $stylevar[left] . '">'
          .'<input type="text" name="tag[' . $tag['tagid'] . ']" id="taglist_'. $tag['tagid'] . '" value="'.$tag['related_words'] .'"/>'
          .'<label for="taglist_' . $tag['tagid'] . '">&nbsp;' 
            . $tag['tagtext'] 
          . '</label>'
        .'</div>';
		}

		// make column values printable
		$cells = array();
		for ($i = 0; $i < $column_count; $i++)
		{
			if ($columns["$i"])
			{
				$cells[] = implode("<br />\n", $columns["$i"]);
			}
			else
			{
				$cells[] = '&nbsp;';
			}
		}

		print_column_style_code(array(
			'width: 50%',
			'width: 50%'
		));
		print_cells_row($cells, false, false, -3);

		?>
		<tr>
			<td colspan="<?php echo $column_count; ?>" align="center" class="tfoot">
				<input type="hidden" name="page" value="<?php echo $vbulletin->GPC['pagenumber']; ?>" />
				<input type="hidden" name="sort" value="<?php echo $vbulletin->GPC['sort']; ?>" />
				<input type="submit" value="<?php echo $vbphrase[save]; ?>" id="tag_inlinego" class="button" />
			</td>
		</tr>
		</table>
		</form>
		<?php
	}
	else
	{
		print_description_row($vbphrase['no_tags_defined'], false, 3, '', 'center');
		print_table_footer();
	}

	construct_hidden_code('page', $vbulletin->GPC['pagenumber']);
	construct_hidden_code('sort', $vbulletin->GPC['sort']);

	print_form_header('tags_autotaggerfromcontentandtitle', 'taginsert');
	print_input_row($vbphrase['autotaggerfromcontentandtitle_add_tag'], 'tagtext');
	print_input_row($vbphrase['autotaggerfromcontentandtitle_related_words'], 'related_words');
	print_submit_row();
}

// ########################################################################

if ($_POST['do'] == 'saverelatedwords') {
  $vbulletin->input->clean_array_gpc('p', array(
    'tag'               => TYPE_ARRAY_STR
  ));

  $vbulletin->input->clean_array_gpc('c', array(
    'vbulletin_inlinetag' => TYPE_STR,
  ));

  $taglist = $vbulletin->GPC['tag'];

  if (!empty($vbulletin->GPC['vbulletin_inlinetag']))	{
    $cookielist = explode('-', $vbulletin->GPC['vbulletin_inlinetag']);
    $cookielist = $vbulletin->input->clean($cookielist, TYPE_ARRAY_UINT);

    $taglist = array_unique(array_merge($taglist, $cookielist));
  }

	setcookie('vbulletin_inlinetag', '', TIMENOW - 3600, '/');

	print_cp_header($vbphrase['autotaggerfromcontentandtitle_enhanced_tags']);
	
	if (sizeof($taglist)) {
    echo sizeof($taglist)." tags to update<br/><br/>";

    foreach($taglist as $tagid => $related_words) {
      $related_words = $vbulletin->db->escape_string(strtolower($related_words));
      echo 'Updating tag with id '.$tagid.' related words: '.$related_words.'<br/>';

      $db->query_write("UPDATE " . TABLE_PREFIX . "tag SET related_words='".$related_words."' WHERE tagid=".$tagid);
    }

	}

	define('CP_REDIRECT', 'tags_autotaggerfromcontentandtitle.php?do=tags&page=' . $vbulletin->GPC['pagenumber'] . '&sort=' . $vbulletin->GPC['sort']);
	print_stop_message('tags_edited_successfully');
}

// ########################################################################

print_cp_footer();

?>