<?php
/**************************************************
  Coppermine Plugin - Search Album
  *************************************************
  Copyright (c) 2005 Paul Van Rompay
  *************************************************
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
***************************************************/

if (!defined('IN_COPPERMINE')) die('Not in Coppermine...');

// ------------------------------------------------------------------------------------------------
// Add filters - process search album and add to search results page
// ------------------------------------------------------------------------------------------------
$thisplugin->add_filter('thumb_caption_search','searchalbum_addresults');
$thisplugin->add_filter('thumb_caption_lastalb','searchalbum_hijacklastalb');
$thisplugin->add_filter('post_breadcrumb','searchalbum_hijacklastalbname');
$thisplugin->add_filter('page_html','searchalbum_replace_search_form');

// ------------------------------------------------------------------------------------------------
// Add actions
// ------------------------------------------------------------------------------------------------
$thisplugin->add_action('plugin_install','searchalbum_install');
$thisplugin->add_action('plugin_configure','searchalbum_configure');
$thisplugin->add_action('plugin_uninstall','searchalbum_uninstall');
$thisplugin->add_action('page_start','searchalbum_pagestart');

// ------------------------------------------------------------------------------------------------
// Install Plugin
// ------------------------------------------------------------------------------------------------
function searchalbum_install() 
{
	global $CONFIG, $lang_plugin_searchalbum_config;
	require ('plugins/search_album/include/init.inc.php');
	
	if ($_POST['submit']==$lang_plugin_searchalbum_config['button_done']) {
		return true;
	} else {
		return 1;
	}
}

// ------------------------------------------------------------------------------------------------
// Configure Plugin
// ------------------------------------------------------------------------------------------------
function searchalbum_configure() 
{
	global $CONFIG, $lang_plugin_searchalbum, $lang_plugin_searchalbum_config;
	require ('plugins/search_album/include/init.inc.php');

	// delete previous plugin config options if necessary (just in case)
	cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name REGEXP '^plugin_searchalbum_'");

	// insert default parameters into configuration table
	$sql = "INSERT INTO {$CONFIG['TABLE_CONFIG']} (name, value)"
		." VALUES"
		." ('plugin_searchalbum_showempty','1')"
		.",('plugin_searchalbum_showcatname','1')"
		.",('plugin_searchalbum_showalbstats','1')"
		.",('plugin_searchalbum_templatestats','{DATE}<br />{FILES} - {VIEWS}')"
		.",('plugin_searchalbum_statsdatefmt','%B %d, %Y')"
		.",('plugin_searchalbum_onlyalbum','0')";
	cpg_db_query($sql);

	echo <<< EOT
		<h2>{$lang_plugin_searchalbum['install_done']}</h2>
		{$lang_plugin_searchalbum['install_note']}<br />
		<br />
		<form action="{$_SERVER['REQUEST_URI']}" method="post">
		<input type="submit" value="{$lang_plugin_searchalbum_config['button_done']}" name="submit"/>
		</form>
EOT;
}

// ------------------------------------------------------------------------------------------------
// Uninstall Plugin
// ------------------------------------------------------------------------------------------------
function searchalbum_uninstall() 
{
	global $CONFIG;
	cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name REGEXP '^plugin_searchalbum_'");
	return true;
}

// ------------------------------------------------------------------------------------------------
// add config button
// ------------------------------------------------------------------------------------------------
function searchalbum_add_config_button($href,$title,$target,$link)
{
  global $template_gallery_admin_menu;

  $new_template = $template_gallery_admin_menu;
  $button = template_extract_block($new_template,'documentation');
  $params = array(
      '{DOCUMENTATION_HREF}' => $href,
      '{DOCUMENTATION_TITLE}' => $title,
      'target="cpg_documentation"' => $target,
      '{DOCUMENTATION_LNK}' => $link,
   );
   $new_button="<!-- BEGIN $link -->".template_eval($button,$params)."<!-- END $link -->\n";
   template_extract_block($template_gallery_admin_menu,'documentation',"<!-- BEGIN documentation -->" . $button . "<!-- END documentation -->\n" . $new_button);
}

// ------------------------------------------------------------------------------------------------
// add admin button to start of each page
// ------------------------------------------------------------------------------------------------
function searchalbum_pagestart()
{
	global $CONFIG, $lang_plugin_searchalbum;
	require ('plugins/search_album/include/init.inc.php');

	if (GALLERY_ADMIN_MODE) {
		searchalbum_add_config_button('index.php?file=search_album/plugin_config',$lang_plugin_searchalbum['config_title'],'',$lang_plugin_searchalbum['config_button']);
	}

/* 
	// old method of replacing search links
	global $template_sub_menu, $template_sys_menu;

	$template_sub_menu = str_replace('search.php','index.php?file=search_album/search',$template_sub_menu);
	$template_sub_menu = str_replace('{SEARCH_TGT}','index.php?file=search_album/search',$template_sub_menu);
	$template_sys_menu = str_replace('search.php','index.php?file=search_album/search',$template_sys_menu);
	$template_sys_menu = str_replace('{SEARCH_TGT}','index.php?file=search_album/search',$template_sys_menu);
*/
}

// ------------------------------------------------------------------------------------------------
// Replace search link with link to plugin's search form throughout page
// ------------------------------------------------------------------------------------------------
function searchalbum_replace_search_form($html)
{
	global $CONFIG;
	if ($CONFIG['plugin_searchalbum_onlyalbum']) {
		$html = str_replace('search.php','index.php?file=search_album/search_album',$html);
	} else {
		$html = str_replace('search.php','index.php?file=search_album/search',$html);
	}
	$html = str_replace($CONFIG['fullpath'].'images','images',$html);
	return $html;
}

// ------------------------------------------------------------------------------------------------
// Construct WHERE clause for searching keywords in albums
// ------------------------------------------------------------------------------------------------
function searchalbum_sqlwhere() 
{
	global $USER;

	$allowed = array('album_title', 'album_description');

	$type = $_POST['type'] == 'AND' ? " AND " : " OR ";
	if (isset($USER['search']['search'])) {
		$search_string = $USER['search']['search'];
	} else {
		$search_string = '';
	}

	foreach ($allowed as $key) {
		if ((isset($_POST[$key]) == TRUE) || ($_GET['type'] == 'full') || ($_GET['type'] == 'albumonly')) {
			$_POST['params_plugin'][$key] = $_POST[$key];
		}
	}

	if ($search_string && isset($_POST['params_plugin'])) {
		$search_string = strtr($search_string, array('_' => '\_', '%' => '\%'));
		$split_search = explode(' ', $search_string);
		$sections = array();

		foreach($split_search as $word) {
			$word = addslashes($word);
			$fields = array();

			foreach ($_POST['params_plugin'] as $param => $value) {
				if (in_array($param, $allowed)) $fields[] = "a.".str_replace('album_','',$param)." LIKE '%$word%'";
			}
			$sections[] = '(' . implode(' OR ', $fields) . ')';
	        }
		$where = implode($type, $sections);
	} else {
		$where = '';
	}
	return $where;
}

// ------------------------------------------------------------------------------------------------
// Process search album request and add results to search results page
// ------------------------------------------------------------------------------------------------
function searchalbum_addresults($rowset) 
{
	global $CONFIG, $plugin_searchalbum_sqlwhere;

	if ((isset($_POST['plugin_search_album']) || isset($_GET['plugin_search_album'])) && !defined('DISPLAYIMAGE_PHP')) { 

		$plugin_searchalbum_sqlwhere = searchalbum_sqlwhere();

		if ($CONFIG['plugin_searchalbum_showempty']) {

			display_thumbnails('lastalb', 0, 1, $CONFIG['thumbcols'], 1, false);

		} elseif ($plugin_searchalbum_sqlwhere) {

			$query = "SELECT count(aid) as aidcount FROM {$CONFIG['TABLE_ALBUMS']} as a WHERE $plugin_searchalbum_sqlwhere GROUP BY aid";
			$result = cpg_db_query($query);
			$row = mysql_fetch_array($result);
			mysql_free_result($result);
			if($row['aidcount'] > 0) {
				display_thumbnails('lastalb', 0, 1, $CONFIG['thumbcols'], 1, false);
			}

		}
	}

	define('PLUGIN_SEARCH_ALBUM_OUTPUT',true);

	if ($CONFIG['plugin_searchalbum_onlyalbum']) { 
		unset($rowset);  	// unnecessary with definition below, but this makes it very clear
		$rowset = array();
	}

	return $rowset;
}

// ------------------------------------------------------------------------------------------------
// To display the album search results, we ask for the 'lastalb' meta album above then replace the results here
// ------------------------------------------------------------------------------------------------
function searchalbum_hijacklastalb($rowset) 
{
	global $CONFIG, $USER, $META_ALBUM_SET, $lang_list_albums, $lang_get_pic_data, $lastup_date_fmt;
	global $plugin_searchalbum_sqlwhere, $lang_plugin_searchalbum_stats;
	require ('plugins/search_album/include/init.inc.php');

	if (isset($_POST['plugin_search_album']) || isset($_GET['plugin_search_album'])) { 

		if (!$plugin_searchalbum_sqlwhere) {
			return array();
		}

		$META_ALBUM_SET = str_replace( $CONFIG['TABLE_PICTURES'].".aid" , 'a.aid', $META_ALBUM_SET );
		$query = "SELECT *,a.title AS title,a.aid AS aid,a.description as description,p.ctime as ctime FROM {$CONFIG['TABLE_ALBUMS']} as a LEFT JOIN {$CONFIG['TABLE_PICTURES']} as p ON (a.thumb=p.pid) WHERE ";
		$query .= $plugin_searchalbum_sqlwhere;
		$query .= " $META_ALBUM_SET ORDER BY a.pos";

		$result = cpg_db_query($query);
		$rowset = cpg_db_fetch_rowset($result);
		mysql_free_result($result);
		
		$rowset_nopic = array();
		// for($irow=0;$irow<count($rowset);$irow++) {
		foreach ($rowset as $irow => $value) {
			$row = $rowset[$irow];
			if(($row['pid'] == NULL)&&($row['aid'])) {
				$query_pid = "SELECT MAX(ctime) as maxctime FROM {$CONFIG['TABLE_PICTURES']} WHERE aid={$row['aid']} GROUP BY aid";
				$result_pid = cpg_db_query($query_pid);
				$row_pid = mysql_fetch_array($result_pid);
				mysql_free_result($result_pid);
				$maxctime = $row_pid['maxctime'];
				if ($maxctime) {
					$query_newpic = "SELECT *,a.title AS title,a.description as description,p.ctime as ctime FROM {$CONFIG['TABLE_ALBUMS']} as a,{$CONFIG['TABLE_PICTURES']} as p WHERE (a.aid=p.aid AND p.ctime = $maxctime)";
					$result_newpic = cpg_db_query($query_newpic);
					$rowset_newpic = cpg_db_fetch_rowset($result_newpic);
					$rowset[$irow] = $rowset_newpic[0];
					mysql_free_result($result_newpic);
				} else {
					$cpg_nopic_data = cpg_get_system_thumb('nopic.jpg',10001);
					$cpg_nopic_data['filename'] = 'nopic.jpg';   // basename($cpg_nopic_data['thumb']);
					$cpg_nopic_data['filepath'] = 'images/';     //dirname($cpg_nopic_data['thumb']).'/';
					foreach ($cpg_nopic_data as $key => $value) {
						$rowset[$irow][$key] = $value;
					}
					$rowset[$irow]['caption'] = '<!-- NO PIC --><img src="' . $cpg_nopic_data['thumb'] . '" ' . $cpg_nopic_data['whole'] . ' class="image" border="0" alt="" />';
					$rowset[$irow]['caption_text'] = 'nopic caption';  // required placeholder - is replaced below
					$rowset_nopic[] = $rowset[$irow];
					unset($rowset[$irow]);
				}
			}
		}
		build_caption($rowset,array('ctime'));
		$rowset = array_merge($rowset,$rowset_nopic);
	}


	// Removed next line since caption_text is now only provided by code below (remove previous caption_text)
	// if (($CONFIG['plugin_searchalbum_showcatname']) || ($CONFIG['plugin_searchalbum_showalbstats'])) {

		// Create caption for each album in album search results and 'lastalb' meta-album

		foreach ($rowset as $key => $row) {
			if ($row['caption_text']) {

				// empty caption first since we will replace it here
				$rowset[$key]['caption_text'] = '';

				if ($CONFIG['plugin_searchalbum_showcatname']) {
					if ($row['category'] > FIRST_USER_CAT) {
						$userId = $row['category'] - FIRST_USER_CAT;
						$result = cpg_db_query("SELECT user_name FROM {$CONFIG['TABLE_USERS']} WHERE user_id = '$userId'");
						$row_user = mysql_fetch_array($result);
						mysql_free_result($result);
						$catName = $row_user['user_name']."'s Gallery";
					} elseif ($row['category'] == 0) {
						$catName = "No Category";
					} else {
						$result = cpg_db_query("SELECT name FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid = '".$row['category']."'");
						$row_cat = mysql_fetch_array($result);
						mysql_free_result($result);
						$catName = $row_cat['name'];
					}
					$rowset[$key]['caption_text'] .= '<span class="thumb_title">'.$catName.'</span>';
				}

				$rowset[$key]['caption_text'] .= '<span class="thumb_title">'.$row['title'].'</span>';

				if ($CONFIG['plugin_searchalbum_showalbstats']) {
					$query = "SELECT COUNT(pid) as pic_count, SUM(hits) as hit_count"
						." FROM {$CONFIG['TABLE_PICTURES']} AS p"
						." WHERE p.aid = {$row['aid']} AND p.approved =  'YES'";
					$result = cpg_db_query($query);
					$row_npic = mysql_fetch_array($result);
					mysql_free_result($result);

					if (!$row_npic['hit_count']) { $row_npic['hit_count'] = 0; }
					$albstats_lbl_files = isset($lang_plugin_searchalbum_stats) ? $lang_plugin_searchalbum_stats['stats_files'] : $lang_list_albums['n_pictures'];
					$albstats_lbl_views = isset($lang_plugin_searchalbum_stats) ? $lang_plugin_searchalbum_stats['stats_views'] : $lang_get_pic_data['n_views'];
					$params = array(
						'{DATE}'  => $rowset[$key]['ctime'] ? localised_date($rowset[$key]['ctime'], $CONFIG['plugin_searchalbum_statsdatefmt']) : '',
						'{FILES}' => sprintf($albstats_lbl_files, $row_npic['pic_count']),
						'{VIEWS}' => sprintf($albstats_lbl_views, $row_npic['hit_count']),
					);
					$albstats = template_eval($CONFIG['plugin_searchalbum_templatestats'],$params);

					$rowset[$key]['caption_text'] .= '<span class="thumb_caption"><span class="thumb_stats">'.$albstats.'</span></span>';
				} else {
					$rowset[$key]['caption_text'] .= '<span class="thumb_caption">'.localised_date($row['ctime'], $lastup_date_fmt).'</span>';
				}
			}
		}
	// }
	// see note above about if statement being commented out

	return $rowset;
}

// ------------------------------------------------------------------------------------------------
// To change the title of the album search results, we hijack the 'lastalb' title by replacing it
// ------------------------------------------------------------------------------------------------
function searchalbum_hijacklastalbname() 
{
	global $CONFIG, $USER, $HTML_SUBST, $lang_meta_album_names, $lang_cat_list;
	global $plugin_searchalbum_sqlwhere;

	if (isset($_POST['plugin_search_album']) || isset($_GET['plugin_search_album']) || $_GET['search'] || $_POST['search']) { 
		if (isset($USER['search']['search'])) {
			$search_string = $USER['search']['search'];
		} else {
			$search_string = '';
		}
		$lang_meta_album_names['lastalb'] = $lang_cat_list['albums'].' '.$lang_meta_album_names['search'].' - "'. strtr($search_string, $HTML_SUBST) . '"';
		$lang_meta_album_names['search'] = $lang_cat_list['pictures'].' '.$lang_meta_album_names['search'];
	}
}

// ------------------------------------------------------------------------------------------------
// End of plugin code
// ------------------------------------------------------------------------------------------------

?>
