<?php

	/**
	 * Modul der die Produkte als eingene Artikeltypen speichert
	 */
	class wpsg_mod_produktartikel extends wpsg_mod_basic 
	{
		
		var $lizenz = 1;
		var $id = 15;
		var $hilfeURL = 'http://wpshopgermany.de/?p=2496';
		var $version = "9.9.9";
		var $free = false;
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('ProduktArtikel', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Produkte sind ein eigener Wordpress Artikeltyp und erscheinen so als Artikel und in der Suche.', 'wpsg');
									
		} // public function __construct()
		
		public function init()
		{
			
			add_action('init', array($this, 'create_wpsg_post_types'));			
			 			
		} // public function init()

		public function wpsg_enqueue_scripts() 
		{ 
					
			if (is_admin()) return;
			
			if (	(	$this->shop->get_option('wpsg_mod_produktartikel_facebook') == '1' ||
						$this->shop->get_option('wpsg_mod_produktartikel_google') == '1' ||
						$this->shop->get_option('wpsg_mod_produktartikel_twitter') == '1') &&
					$this->shop->get_option('wpsg_mod_produktartikel_noJS') != '1')
			{
					
				wp_enqueue_script('wpsg_mod_produktartikel_social', WPSG_URL_CONTENT.'plugins/wpshopgermany/lib/socialshareprivacy/jquery.socialshareprivacy.js');
						
			}
			
		} // public function wpsg_enqueue_scripts()
		
		public function install() 
		{ 
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			// Standard Path Key setzen
			if ($this->shop->get_option('wpsg_mod_produktartikel_pathkey') === false || $this->shop->get_option('wpsg_mod_produktartikel_pathkey') == '')
			{
				
				$this->shop->update_option('wpsg_mod_produktartikel_pathkey', 'produkte');
				
			}			
			
			$this->shop->checkDefault('wpsg_mod_produktartikel_showui', '0');
			$this->shop->checkDefault('wpsg_mod_produktartikel_showHome', '0');
			$this->shop->checkDefault('wpsg_mod_produktartikel_showCategory', '1');
			$this->shop->checkDefault('wpsg_mod_produktartikel_showFeed', '0');
			$this->shop->checkDefault('wpsg_mod_produktartikel_showSearch', '0');
						
			/*
			 * Posts Tabelle erweitern
			 */ 
			$sql = "CREATE TABLE ".$this->shop->prefix."posts (
		   		wpsg_produkt_id INT(11) NOT NULL,
		   		KEY wpsg_produkt_id (`wpsg_produkt_id`)
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
   	   	 
   			dbDelta($sql);
   			
		} 
		
		public function the_excerpt(&$content) 
		{ 
			
			global $post;

			if (get_post_type($post) == $this->shop->get_option('wpsg_mod_produktartikel_pathkey'))
			{
				
				$produkt_id = $post->wpsg_produkt_id;
				$content = $this->shop->renderProdukt($produkt_id);
				
			}
			
		} // public function the_excerpt(&$content)
		
		public function content_filter(&$content)
		{
						
			global $post;
						
			// Artikel ist ein Produkt, hier das Rendern des Templates übernehmen
			if (get_post_type($post) == $this->shop->get_option('wpsg_mod_produktartikel_pathkey'))
			{
				 
				$produkt_id = $post->wpsg_produkt_id;  
				$content = $this->shop->renderProdukt($produkt_id);
				
				return -2;
				
			}
						
		} // public function content_filter()
		 
		public function pre_get_posts(&$query) 
		{
 
			if (wpsg_isSizedInt($this->shop->get_option('wpsg_mod_produktartikel_onlyMainQuery')) && !$query->is_main_query()) return;
			
			if ($this->shop->get_option('wpsg_mod_produktartikel_showHome') == '1' && is_home())
			{

				$this->setPostType($query);
				 
			}
			
			if ($this->shop->get_option('wpsg_mod_produktartikel_showCategory') == '1' && is_category())
			{
												
				$this->setPostType($query);
				 
			}
			
			if ($this->shop->get_option('wpsg_mod_produktartikel_showFeed') == '1' && is_feed()) 
			{
				
				$this->setPostType($query);
				 
			}
			
			if ($this->shop->get_option('wpsg_mod_produktartikel_showSearch') == '1' && is_search())
			{
				
				$this->setPostType($query);
				 
			} 
			
			if (is_single() && $query->is_main_query())
			{
				
				$this->setPostType($query);
				
			}
			
		} // public function pre_get_posts(&$query)
		
		public function settings_edit()
		{
			
			// Verfügbare Produkttemplates
			$this->shop->view['arTemplates'] = $this->shop->loadProduktTemplates();
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/settings_edit.phtml');
			
		}

		public function settings_save() 
		{
			
			global $wpdb;
			
			$this->shop->update_option('wpsg_mod_produktartikel_showHome', $_REQUEST['wpsg_mod_produktartikel_showHome']);
			$this->shop->update_option('wpsg_mod_produktartikel_showCategory', $_REQUEST['wpsg_mod_produktartikel_showCategory']);
			$this->shop->update_option('wpsg_mod_produktartikel_showFeed', $_REQUEST['wpsg_mod_produktartikel_showFeed']);
			$this->shop->update_option('wpsg_mod_produktartikel_showSearch', $_REQUEST['wpsg_mod_produktartikel_showSearch']);
			$this->shop->update_option('wpsg_mod_produktartikel_onlyMainQuery', $_REQUEST['wpsg_mod_produktartikel_onlyMainQuery']);
						
			$this->shop->update_option('wpsg_mod_produktartikel_hometemplate', $_REQUEST['wpsg_mod_produktartikel_hometemplate']);
			$this->shop->update_option('wpsg_mod_produktartikel_listtemplate', $_REQUEST['wpsg_mod_produktartikel_listtemplate']);
			$this->shop->update_option('wpsg_mod_produktartikel_searchtemplate', $_REQUEST['wpsg_mod_produktartikel_searchtemplate']);			
			$this->shop->update_option('wpsg_mod_produktartikel_facebook', $_REQUEST['wpsg_mod_produktartikel_facebook']);
			$this->shop->update_option('wpsg_mod_produktartikel_google', $_REQUEST['wpsg_mod_produktartikel_google']);
			$this->shop->update_option('wpsg_mod_produktartikel_twitter', $_REQUEST['wpsg_mod_produktartikel_twitter']);
			
			$this->shop->update_option('wpsg_mod_produktartikel_showui', $_REQUEST['wpsg_mod_produktartikel_showui']);
			$this->shop->update_option('wpsg_mod_produktartikel_postthumbnail', $_REQUEST['wpsg_mod_produktartikel_postthumbnail']);
			
			$pathkey_alt = $this->shop->get_option('wpsg_mod_produktartikel_pathkey');
			$pathkey_new = $this->shop->clear($_REQUEST['wpsg_mod_produktartikel_pathkey']);
			
			if ($pathkey_alt != $_REQUEST['wpsg_mod_produktartikel_pathkey'] && $pathkey_new != '')
			{
				
				$this->db->UpdateQuery($this->shop->prefix."posts", array(
					'post_type' => wpsg_q($pathkey_new)
				), "`post_type` = '".wpsg_q($pathkey_alt)."'");
				
				$this->shop->update_option('wpsg_mod_produktartikel_pathkey', $pathkey_new);
				
				$this->shop->addBackendMessage(__('Path Key erfolgreich geändert. Die Produkt URLs haben sich geändert!', 'wpsg'));
				
			}
			else if (trim($_REQUEST['wpsg_mod_produktartikel_pathkey']) == '')
			{
				
				$this->shop->addBackendError(__('Der Path Key darf nicht leer sein!', 'wpsg'));
				
			}
			
			$this->create_wpsg_post_types();
			flush_rewrite_rules();
			
		} // public function settings_save()
		
		public function admin_includes() 
		{ 

			echo wpsg_drawForm_Checkbox('wpsg_mod_produktartikel_noJS', __('Socialshareprivacy nicht einbinden (Produktartikel)', 'wpsg'), $this->shop->get_option('wpsg_mod_produktartikel_noJS'), array(
				'hint' => wpsg_translate('nohspc_'.__('Ist diese Option aktiv, so wird die benötigte JavaScript Bibliothek <u>nicht</u> eingebunden, auch wenn die Optionen im <a href="#1#">Produktartikelmodul</a> aktiv sind.', 'wpsg'), WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Admin&action=module&modul=wpsg_mod_produktartikel')
			));
			
		} // function admin_includes()
		
		public function admin_includes_save() 
		{ 
			
			$this->shop->update_option('wpsg_mod_produktartikel_noJS', $_REQUEST['wpsg_mod_produktartikel_noJS']);
			
		} // function admin_includes_save()
		 
		public function produkt_copy(&$produkt_id, &$copy_id)
		{ 
			
			global $current_user;
			
			$product_source = $this->shop->cache->loadProduct($produkt_id);
			$product_target = $this->shop->cache->loadProduct($copy_id);
			
			$post_content = $this->shop->renderProdukt($copy_id);
			
			$post_data = $this->db->fetchRow("
				SELECT 
					`id`, `comment_status`, `menu_order`
				FROM 
					`".$this->shop->prefix."posts` 
				WHERE 
					`wpsg_produkt_id` = '".wpsg_q($produkt_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
						
			$data = array(
				"post_title" => wpsg_q($product_target['name']), 
				'post_author' => $current_user->ID,
				'post_content' => wpsg_q($post_content),
				"post_type" => wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey')),
				"wpsg_produkt_id" => wpsg_q($copy_id),
				"comment_status" => wpsg_q($post_data['comment_status']),
				"post_name" => wpsg_q($this->shop->clear($product_target['name'])),
				"menu_order" => wpsg_q($post_data['menu_order']),
				"post_modified" => "NOW()",
				"post_modified_gmt" => "NOW()",
				'post_date' => 'NOW()'
			);
			 
			$post_id = $this->db->ImportQuery($this->shop->prefix.'posts', $data);
			
			$this->updatePostThumbnail($copy_id);
			
			// Taxonomie mit kopieren
			$this->db->Query("DELETE FROM `".$this->shop->prefix."term_relationships` WHERE `object_id` = '".wpsg_q($post_id)."'");
			
			$arTaxOriginalProduct = $this->db->fetchAssocField("SELECT `term_taxonomy_id` FROM `".$this->shop->prefix."term_relationships` WHERE `object_id` = '".wpsg_q($post_data['id'])."' ");
			
			foreach ($arTaxOriginalProduct as $term_taxonomy_id)
			{
				
				$this->db->ImportQuery($this->shop->prefix.'term_relationships', array(
					'object_id' => wpsg_q($post_id),
					'term_taxonomy_id' => wpsg_q($term_taxonomy_id),
					'term_order' => '0'
				));
				
				$count = $this->db->fetchOne("SELECT COUNT(*) FROM `".$this->shop->prefix."term_relationships` WHERE `term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."'");
				
				$this->db->UpdateQuery($this->shop->prefix."term_taxonomy", array(
					'count' => wpsg_q($count)
				), "`term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."'");
				
			}
			 			
		} // public function produkt_copy(&$produkt_id, &$copy_id)
		
		public function produkt_edit(&$data)
		{

			global $wpdb;
			 
			$data = wpsg_array_merge($data, (array)$this->db->fetchRow("
				SELECT
					`id` AS `post_id`,
					`comment_status`,
					`menu_order`,
					`post_name`
				FROM	
					`".$this->shop->prefix."posts`
				WHERE
					`wpsg_produkt_id` = '".wpsg_q($data['id'])."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			")); 
			
		} // public function produkt_edit(&$data)
		
		public function produkt_del($produkt_id) 
		{ 
			
			global $wpdb;
			
			$post_id = $this->db->fetchOne("
				SELECT 
					`id` 
				FROM 
					`".$this->shop->prefix."posts` 
				WHERE 
					`wpsg_produkt_id` = '".wpsg_q($produkt_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
			
			$this->db->Query("DELETE FROM `".$this->shop->prefix."posts` WHERE `wpsg_produkt_id` = '".wpsg_q($produkt_id)."'");
			
			$this->db->Query("DELETE FROM `".$this->shop->prefix."term_relationships` WHERE `object_id` = '".wpsg_q($post_id)."'");
			
			$this->db->Query("DELETE FROM `".$this->shop->prefix."postmeta` WHERE `post_id` = '".wpsg_q($post_id)."'");
			
			$this->updateTaxonomieCount();
			
		} // public function produkt_del($produkt_id)
		
		public function wp_head() 
		{ 
			
			global $post;
			
			if (is_single($post) && get_post_type($post) == $this->shop->get_option('wpsg_mod_produktartikel_pathkey'))
			{
								
				$produkt_id = $post->wpsg_produkt_id;
				
				$this->shop->view['data'] = $this->shop->loadProduktArray($produkt_id);
				$this->shop->view['data']['url'] = '';
				$this->getProduktlink($produkt_id, $this->shop->view['data']['url']);
				
				$this->shop->view['data']['beschreibung'] = preg_replace("/\r|\n/", "", wpsg_hspc(strip_tags($this->shop->view['data']['beschreibung'])));				
				
				if ($this->shop->hasMod('wpsg_mod_produktbilder'))
				{
					
					$arBilder = $this->shop->callMod('wpsg_mod_produktbilder', 'getProduktBilder', array($produkt_id)); 

					if (sizeof($arBilder) > 0) $this->shop->view['data']['bilder'] = $arBilder;
					
				}
				
				if ($this->shop->get_option('wpsg_mod_produktartikel_facebook') == '1')
				{
					$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/header_facebook.phtml');
				}
				if ($this->shop->get_option('wpsg_mod_produktartikel_google') == '1')
				{
					$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/header_google.phtml');
				} 		
				
			}
						
		} // public function wp_head()
		
		public function produkt_edit_sidebar(&$produkt_data) 
		{ 
			
			if (isset($_REQUEST['wpsg_lang'])) return;
			
			$this->shop->view['data'] = $produkt_data;
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/produkt_edit_sidebar.phtml');
						
		} // public function produkt_edit_sidebar(&$produkt_data)
		
		public function produkt_edit_allgemein(&$produkt_data) { 
		
			$this->shop->view['data'] = $produkt_data;
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/produkt_edit_allgemein.phtml');
			
		} // public function produkt_edit_allgemein(&$produkt_data)
				
		public function produkt_save_translation(&$produkt_id, &$trans_id)
		{
					
			// Da sich die Übersetzung geändert hat muss das Produkt erneut gespeichert werden
			$this->produkt_save($produkt_id);
			 
		} // public function produkt_save_translation(&$produkt_id, &$trans_id)
		
		public function produkt_save(&$produkt_id) 
		{ 

			global $wpdb, $current_user;
			
			// Prüfen ob ein Post zu diesem Artikel existiert
			$post_id = $this->db->fetchOne("
				SELECT 
					`id` 
				FROM 
					`".$this->shop->prefix."posts` 
				WHERE 
					`wpsg_produkt_id` = '".wpsg_q($produkt_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
			 			
			$produkt = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'");
			
			// Sollte der Path leer sein dann den Produktnamen nehmen
			if (trim($_REQUEST['wpsg_mod_produktartikel']['path']) == '')
			{
				$_REQUEST['wpsg_mod_produktartikel']['path'] = $_REQUEST['name'];
			}
			 
			$arLanguages = $this->shop->getStoreLanguages();
			if (wpsg_isSizedArray($arLanguages) && sizeof($arLanguages) > 1)
			{

				$post_title = '';
				$post_content = '';
				
				// Titel der Übersetzten Produkte heraussuchen
				foreach ($arLanguages as $l)
				{
					
					$produkt_trans = $this->db->fetchRow("SELECT `id`, `name` FROM `".WPSG_TBL_PRODUCTS."` WHERE `lang_locale` = '".wpsg_q($l['locale'])."' AND `lang_parent` = '".wpsg_q($produkt_id)."'");
					
					if ($produkt_trans['id'] > 0) // Übersetzung existiert					{
					{
						$post_title .= '<!--:'.$l['lang'].'-->'.$produkt_trans['name'].'<!--:-->';
						$post_content .= '<!--:'.$l['lang'].'-->'.$this->shop->renderProdukt($produkt_id, false, $l['locale']).'<!--:-->';						
					}
					else // Übersetzung existiert nicht, hier trage ich einfach den Originaltext ein
					{
						$post_title .= '<!--:'.$l['lang'].'-->'.$produkt['name'].'<!--:-->';
						$post_content .= '<!--:'.$l['lang'].'-->'.$this->shop->renderProdukt($produkt_id).'<!--:-->';
					}
					
				}
				
			}
			else
			{
				
				$post_title = $_REQUEST['name'];
				$post_content = $this->shop->renderProdukt($produkt_id);
				
			}
			
			$data = array(
				"post_title" => wpsg_q($post_title), 
				'post_author' => $current_user->ID,				
				'post_content' => wpsg_q($post_content),
				"post_type" => wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey')),
				"wpsg_produkt_id" => wpsg_q($produkt_id),
				"comment_status" => wpsg_q(((wpsg_isSizedInt($_REQUEST['wpsg_mod_produktartikel']['kommentare']))?'open':'closed')),
				"menu_order" => wpsg_q($_REQUEST['wpsg_produktartikel_menuorder']),
				"post_modified" => "NOW()",
				"post_modified_gmt" => "NOW()"
			);
			 
			if ($post_id <= 0)
			{
				
				$data['post_date'] = $produkt['cdate'];
				$post_id = $this->db->ImportQuery($this->shop->prefix.'posts', $data);
				 				
			}
			else
			{
								
				$this->db->UpdateQuery($this->shop->prefix.'posts', $data, "`id` = '".wpsg_q($post_id)."'");
				
			}
			
			// Pathkey
			$data = array();
			$data['post_name'] = wpsg_q($this->shop->clear($_REQUEST['wpsg_mod_produktartikel']['path'], $post_id));
			$this->db->UpdateQuery($this->shop->prefix.'posts', $data, "`id` = '".wpsg_q($post_id)."'");
			
			// Kategorie speichern			
			if (!wpsg_isSizedString($_REQUEST['wpsg_lang']))
			{
			
				// Die Kategorie darf nur beim speichern in der Originalsprache gesetzt werden!
				
				// Alte Zuordnung löschen
				$this->db->Query("DELETE FROM `".$this->shop->prefix."term_relationships` WHERE `object_id` = '".wpsg_q($post_id)."'");
				
				// Neue Zuordnung speichern
				foreach ((array)$_REQUEST['post_category'] as $c)
				{
					
					$term_taxonomy_id = $this->db->fetchOne("SELECT `term_taxonomy_id` FROM `".$this->shop->prefix."term_taxonomy` WHERE `term_id` = '".wpsg_q($c)."'");
					
					$this->db->ImportQuery($this->shop->prefix.'term_relationships', array(
						'object_id' => wpsg_q($post_id),
						'term_taxonomy_id' => wpsg_q($term_taxonomy_id),
						'term_order' => '0'
					));
					
					$count = $this->db->fetchOne("SELECT COUNT(*) FROM `".$this->shop->prefix."term_relationships` WHERE `term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."'");
					
					$this->db->UpdateQuery($this->shop->prefix."term_taxonomy", array(
						'count' => wpsg_q($count)
					), "`term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."'");
					
				}
				
				$this->updateTaxonomieCount();
				
			}
			
			$this->updatePostThumbnail($produkt_id);
						
			flush_rewrite_rules();
			
		} // public function produkt_save($produkt_id)
		
		public function create_wpsg_post_types()
		{
		 
			$show_ui = false;
			
			if ($this->shop->get_option('wpsg_mod_produktartikel_showui') == '1') $show_ui = true;
					
			register_post_type($this->shop->get_option('wpsg_mod_produktartikel_pathkey'),
				array(
					'public' => true, // steht auf "true", damit andere Module/ Plugins diesen Posttype "sehen" können
					'publicly_queryable' => false,
					'labels' => array(
						'name' => __('wpShopGermany Produkte', 'wpsg')
					),
					'query_var' => false,
					'rewrite' => array('slug' => $this->shop->get_option('wpsg_mod_produktartikel_pathkey')),
					'show_ui' => $show_ui,
 					'show_in_menu' => true,
					'taxonomies' => array('category'),
					'supports' => array('title', 'editor', 'thumbnail')
				)
			); 
						
		} // public function create_wpsg_post_types()

		public function getProduktlink($produkt_id, &$url) 
		{ 

			$produkt_id = $this->shop->getProduktId($produkt_id);
			
			$post_id = $this->db->fetchOne("
				SELECT 
					`id` 
				FROM 
					`".$this->shop->prefix."posts` 
				WHERE 
					`wpsg_produkt_id` = '".wpsg_q($produkt_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");

			// Wenn kein Post gefunden abbrechen, sonst gibt es die URL der Startseite und die alternative URL Bildung über den Warenkorb funktioniert nicht.
			if ($post_id <= 0) return;
			
			$url = get_permalink($post_id);
			
			if (function_exists('qtrans_convertURL'))
			{
				
				$url = qtrans_convertURL($url);
				
			}
			
			return -1;
			
		} // public function getProduktlink($produkt_id)
		
		public function renderProdukt_templateSelect(&$produkt_data, &$template_file) 
		{ 
			 
			if ($GLOBALS['wp_the_query']->is_category && $this->shop->get_option('wpsg_mod_produktartikel_listtemplate') != '-1' && $this->shop->get_option('wpsg_mod_produktartikel_listtemplate') != false)
			{
				
				$template_file = WPSG_PATH_PRODUKTTEMPLATES.$this->shop->get_option('wpsg_mod_produktartikel_listtemplate'); 
				
			}
			else if ($GLOBALS['wp_the_query']->is_search && $this->shop->get_option('wpsg_mod_produktartikel_searchtemplate') != '-1' && $this->shop->get_option('wpsg_mod_produktartikel_searchtemplate') != false)
			{
				
				$template_file = WPSG_PATH_PRODUKTTEMPLATES.$this->shop->get_option('wpsg_mod_produktartikel_searchtemplate'); 
				
			} 
			else if ($GLOBALS['wp_the_query']->is_home && $this->shop->get_option('wpsg_mod_produktartikel_hometemplate') != '-1' && $this->shop->get_option('wpsg_mod_produktartikel_hometemplate') != false)
			{
				
				$template_file = WPSG_PATH_PRODUKTTEMPLATES.$this->shop->get_option('wpsg_mod_produktartikel_hometemplate');
				
			}
			 
		} // public function renderProdukt_templateSelect(&$produkt_data, &$template_file)
		
		public function loadProduktArray(&$produkt_data) 
		{ 

			global $wpdb;

			$product_id = $this->shop->getProduktId($produkt_data['id']);
			
			$post_id = $this->db->fetchOne("
				SELECT 
					`id` 
				FROM 
					`".$this->shop->prefix."posts` 
				WHERE 
					`wpsg_produkt_id` = '".wpsg_q($product_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
			
			$post_data = $this->db->fetchRow("
				SELECT
					`id`, `menu_order`
				FROM
					`".$this->shop->prefix."posts`
				WHERE
					`wpsg_produkt_id` = '".wpsg_q($product_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
 
			$post_id = $post_data['id'];
			
			$arCat = $this->db->fetchOne("
				SELECT 
					GROUP_CONCAT(DISTINCT `term_taxonomy_id`)
				FROM
					".$this->shop->prefix."term_relationships
				WHERE
					`object_id` = '".wpsg_q($post_id)."'
			");
			
			if (wpsg_isSizedInt($post_id) && wpsg_isSizedString(get_permalink($post_id)))
			{

				$produkt_data = wpsg_array_merge($produkt_data, array(
					'post_id' => $post_id,
					'pos' => $post_data['menu_order'], 
					'url' => get_permalink($post_id),
					'arCat' => $arCat	
				));
				
			}
			
		} // public function loadProduktArray(&$produkt_data)
		
		/* Modulfunktionen */
		
		private function updateTaxonomieCount()
		{
			
			$arTermTaxonomyID = $this->db->fetchAssocField("SELECT `term_taxonomy_id` FROM `".$this->shop->prefix."term_taxonomy` ");
			
			foreach ($arTermTaxonomyID as $term_taxonomy_id)
			{

				$count = $this->db->fetchOne("SELECT COUNT(*) FROM `".$this->shop->prefix."term_relationships` WHERE `term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."'");
				
				$this->db->UpdateQuery($this->shop->prefix.'term_taxonomy', array(
					'count' => wpsg_q($count)			
				), " `term_taxonomy_id` = '".wpsg_q($term_taxonomy_id)."' ");
				
			}
			
		} // private function updateTaxonomieCount()
		
		/**
		 * Aktualisiert das Post Thumbnail (Beitragsbild)
		 * in dem zum Produkt gehörendem Beitrag
		 */
		public function updatePostThumbnail($product_id)
		{
						
			// Wenn das Produktbildermodul inaktiv ist, muss ich hier nichts machen
			// Oder wenn Option nicht aktiv
			if (!$this->shop->hasMod('wpsg_mod_produktbilder') || !wpsg_isSizedInt($this->shop->get_option('wpsg_mod_produktartikel_postthumbnail'))) return;
			
			$post_id = $this->getPostIdFromProductId($product_id);
			
			if ($post_id !== false)
			{
				
				// ID des bestehenden POST Thumbnail
				$post_thumbnail_id = get_post_thumbnail_id($post_id);
				
				// Die Bilder müssen in extra Ordner liegen, da Wordpress auch die skallierten Bilder dort ablegt
				$path_post_thumbnail = $this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($product_id)).'posthumbnail/';

				// Ordner für die Thumbnails löschen, er beinhaltet die skallierten alten Bilder und wird wieder angelegt sofern ein Bild existiert
				wpsg_rrmdir($path_post_thumbnail);
				
				// Eventuell bestehendes Thumbnail löschen
				if (wpsg_isSizedInt($post_thumbnail_id))
				{
					
					delete_post_thumbnail($post_id);
					wp_delete_attachment($post_thumbnail_id);
					
				}
				
				$arBilder = $this->shop->callMod('wpsg_mod_produktbilder', 'getProduktBilder', array($product_id));
				 
				if (wpsg_isSizedArray($arBilder))
				{
					
					$img_file = array_shift($arBilder);
					
					$filename = $this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($product_id)).$img_file;
					
					if (!file_exists($path_post_thumbnail)) mkdir($path_post_thumbnail, 0777, true);
				
					if (file_exists($path_post_thumbnail))
					{
						 
						copy($filename, $path_post_thumbnail.$img_file);
						
						if (file_exists($path_post_thumbnail.$img_file))
						{
						
							$filetype = wp_check_filetype($img_file, null);
					
							$fileurl = $this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($product_id, true)).'posthumbnail/'.$img_file;
							 
							$attachment = array(
								'guid' => $fileurl,
								'post_mime_type' => $filetype['type'],
								'post_title' => preg_replace('/\.[^.]+$/', '', basename($img_file)),
								'post_content' => '',
								'post_status' => 'inherit'
							);
	
							$attach_id = wp_insert_attachment($attachment, $path_post_thumbnail.$img_file, $post_id);
							
							// Meta Daten schreiben
							require_once(ABSPATH.'wp-admin/includes/image.php');
								
							$attach_data = wp_generate_attachment_metadata($attach_id, $path_post_thumbnail.$img_file);
							wp_update_attachment_metadata($attach_id, $attach_data);
							
							set_post_thumbnail($post_id, $attach_id);
							
						}
					}
						 					
				}
												
			}
			
		} // private function updatePostThumbnail($product_id)
		
		/**
		 * Gibt die Post_ID anhand einer ProduktID zurück.
		 * Wird kein Post gefunden, so wird false zurückgegeben
		 */
		private function getPostIdFromProductId($product_id)
		{
			
			$post_id = $this->db->fetchOne("
				SELECT
					`id`
				FROM
					`".$this->shop->prefix."posts`
				WHERE
					`wpsg_produkt_id` = '".wpsg_q($product_id)."' AND
					`post_type` = '".wpsg_q($this->shop->get_option('wpsg_mod_produktartikel_pathkey'))."'
			");
			
			if (wpsg_isSizedInt($post_id)) return $post_id;
			else return false;				
			
		} // private function getPostIdFromProductId($product_id)
		
		/**
		 * Fügt die Abfrage für den PostType an den Wordpress Query
		 */
		private function setPostType($query)
		{
			
			$post_type = $query->get('post_type');

			if ($post_type == '' || !wpsg_isSizedArray($post_type))
			{

				$postType = array(
					'post',
					'page',
					'attachment',
					$this->shop->get_option('wpsg_mod_produktartikel_pathkey')
				);
				
				if (is_string($post_type) && strlen($post_type) > 0)
				{
					$postType[] = $post_type;
				}
				
				$query->set('post_type', $postType);
				
			}
			else
			{
				
				$post_type[] = $this->shop->get_option('wpsg_mod_produktartikel_pathkey');
				
				$query->set('post_type', $post_type);
				
			}
			
		} // private function setPostType($query)
				
		/**
		 * Wird vom Produkttemplate aufgerufen um die Social Media Links einzubinden
		 */
		public function socialIntegration($produkt_id)
		{
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_produktartikel/produkt.phtml');
			
		} // public function socialIntegration($produkt_id)
		
		/**
		 * Gibt einen Array mit Kategorien zurück
		 */
		public function getCategorySelectArray($ref = 0, $ebene = 0, &$arReturn = array())
		{
			
			global $wpdb;
			
			$arCat = $this->db->fetchAssoc("
				SELECT 
					T.`term_id`, T.`name` 
				FROM 
					`".$this->shop->prefix."term_taxonomy` AS TT
						LEFT JOIN `".$this->shop->prefix."terms` AS T ON (T.`term_id` = TT.`term_id`)
				WHERE 
					TT.`parent` = '".wpsg_q($ref)."' AND 
					TT.`taxonomy` = 'category ' AND
					T.`term_id` > 0
				ORDER BY
					T.`name` ASC
			");

			foreach ($arCat as $c)
			{

				$cat_name = '';				
				for ($i = 0; $i < $ebene; $i ++) $cat_name .= '-';				
				$cat_name .= $c['name'];
				
				$arReturn[$c['term_id']] = $cat_name;
				
				$this->getCategorySelectArray($c['term_id'], $ebene + 1, $arReturn);
				
			}
			
			return $arReturn;
			
		} // public function getCategorySelectArray($ref = 0)
	
	} // class wpsg_mod_produktartikel extends wpsg_mod_basic

?>