<?php
/*======================================================================================
Module:		Articles
Title:		Main class
Version:	0.2.1
Descript.:	An addon module for CMS Made Simple to list articles from different categories (e.g. for shopping, events, blog, ...
Last Mod.:	24.02.2016
Author:		Andi Petzoldt
Profile:	https://plus.google.com/113580733838250075244
Notes:
Licence:	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.
			However, as a special exception to the GPL, this software is distributed
			as an addon module to CMS Made Simple.  You may not use this software
			in any Non GPL version of CMS Made simple, or in any version of CMS
			Made Simple that does not indicate clearly and obviously in its admin
			section that the site was built with CMS Made Simple.
			Find more information about CMS Made Simple on its website:
			http://www.cmsmadesimple.org/
			This program is distributed in the hope that it will be useful,
			but WITHOUT ANY WARRANTY; without even the implied warranty of
			MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
			GNU General Public License for more details.
			You should have received a copy of the GNU General Public License
			along with this program; if not, write to the Free Software
			Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
			Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
======================================================================================*/

// Check authorisation
if (!isset($gCms)) exit;

// force locale date settings
if (isset($GLOBALS['config']['locale'])) setlocale(LC_ALL, $GLOBALS['config']['locale']);


/**
 * Class Articles.
 *
 * This class provides basic functions for the CMSms addon "Articles"
 *
 */
class Articles extends CMSModule{

	// class vars
	private $agCms;
	private $adb;
	private $asmarty;
	private $req_uri;
	private $req_ar_id;
	private $req_cat_id;
	protected $gmode;
	protected $donate;

	/*
	* Constructor function
	*/
	function __construct() {
		// Set gCms
		$this->agCms = cmsms();
		// Set db
		$this->adb = $this->agCms->GetDb();
		// Set smarty
		$this->asmarty = $this->agCms->GetSmarty();
		// Set gmode
		$this->gmode = '';
		// Set Request URI
		$this->req_uri = $_SERVER['REQUEST_URI'];
		while (substr($this->req_uri,-1) == '/') $this->req_uri = substr($this->req_uri,0,-1);
		while (substr($this->req_uri,0,1) == '/') $this->req_uri = substr($this->req_uri,1);
		// Get requested SEO URL and get article- or category ID
		$this->req_ar_id = $this->req_cat_id = 0;
		if ($this->req_uri && $this->GetPreference('seo_use')) {
			$this->req_ar_id = $this->adb->GetOne('SELECT entry_id FROM '.cms_db_prefix().'module_articles_articles WHERE active=1 AND seo_url = ? LIMIT 1', array($this->req_uri));
			if (!$this->req_ar_id) {
				$this->req_ar_id = 0;
				$this->req_cat_id = $this->adb->GetOne('SELECT entry_id FROM '.cms_db_prefix().'module_articles_category WHERE active=1 AND seo_url = ? LIMIT 1', array($this->req_uri));
				if (!$this->req_cat_id) $this->req_cat_id = 0;
			}
		}
		// Check version
		if (!$this->aversion) $this->aversion = $this->adb->GetOne('SELECT version FROM '.cms_db_prefix().'modules WHERE module_name="Articles"', array());
		$this->donate = $this->Lang('donate');
		
		$this->smarty->register_function('gallery_link', array($this,'smarty_function_galleryLink'));
		parent::__construct();
	}

	/**
	* Get the real name of this module.
	* @return string
	*/
	function GetName(){
		return 'Articles';
	}

	/**
	* Get a friendly (translated) name of this module.
	* @return string
	*/
	function GetFriendlyName(){
		return $this->Lang('friendlyname');
	}

	/**
	* Get the version of this module.
	* @return string
	*/
	function GetVersion(){
		return '0.2.1';
	}

	/**
	* Gets a help text for this module.
	* @return string
	*/
	function GetHelp(){
		return $this->Lang('help');
	}

	/**
	* Gets the author of this module
	* @return string
	*/
	function GetAuthor(){
		return 'Andi Petzoldt';
	}

	/**
	* Gets the module authors email address.
	* @return string
	*/
	function GetAuthorEmail(){
		return 'andi@petzoldt.net';
	}

	/**
	* Get the changelog of this module
	* @return string
	*/
	function GetChangeLog(){
		return $this->donate.$this->Lang('changelog');
	}

	/**
	* Init Frontend.
	*/
	public function InitializeFrontend() {
		#$query = 'SELECT news_id,news_url FROM '.cms_db_prefix().'module_news WHERE status = ? AND news_url != ? ORDER BY news_date DESC';
		#$tmp = $this->adb->GetArray($query,array('published',''));
		#if( is_array($tmp) ) {
		#	foreach( $tmp as $one ) {
		#		$parms = array('action'=>'detail','returnid'=>$detailpage,'articleid'=>$one['news_id']);
		#		$route = new CmsRoute($one['news_url'],$this->GetName(),$parms,TRUE);
		#		cms_route_manager::register($route);
		#	}
		#}

		$this->SetParameters();

	}

	/**
	* Init Admin
	*/ 
	public function InitializeAdmin() {
			$this->CreateParameter('mact', 'default', $this->Lang('mact'));
			$this->CreateParameter('inline', '1', $this->Lang('inline'));
			$this->CreateParameter('returnid', '15', $this->Lang('returnid'));
		$this->CreateParameter('template', 'default', $this->Lang('template'));
		$this->CreateParameter('template_cart', 'cart', $this->Lang('template_cart'));
		$this->CreateParameter('template_cartsnippet', 'cartsnippet', $this->Lang('template_cartsnippet'));
		$this->CreateParameter('template_categories', 'categories', $this->Lang('template_categories'));
		$this->CreateParameter('template_articles', 'articles', $this->Lang('template_articles'));
		$this->CreateParameter('template_article', 'article', $this->Lang('template_article'));
		$this->CreateParameter('template_summary', 'summary', $this->Lang('template_summary'));
		$this->CreateParameter('template_ack', 'ack', $this->Lang('template_ack'));
		$this->CreateParameter('email_template_owner', 'email_owner', $this->Lang('email_template_owner'));
		$this->CreateParameter('email_template_customer', 'email_customer', $this->Lang('email_template_customer'));
		$this->CreateParameter('page_cart', '', $this->Lang('page_cart'));
		$this->CreateParameter('page_categories', '', $this->Lang('page_categories'));
		$this->CreateParameter('page_articles', '', $this->Lang('page_articles'));
		$this->CreateParameter('page_article', '', $this->Lang('page_article'));
		$this->CreateParameter('page_summary', '', $this->Lang('page_summary'));
		$this->CreateParameter('page_ack', '', $this->Lang('page_ack'));
		$this->CreateParameter('mode', false, $this->Lang('mode'));
		$this->CreateParameter('forcemode', false, $this->Lang('forcemode'));

		$this->CreateParameter('sortdesc', 'ASC', $this->Lang('sortdesc'));
		$this->CreateParameter('articleslimit', 0, $this->Lang('articleslimit'));
		$this->CreateParameter('cutoff', 0, $this->Lang('cutoff'));
		$this->CreateParameter('pastonly', false, $this->Lang('pastonly'));
		$this->CreateParameter('category', 0, $this->Lang('category'));
		$this->CreateParameter('belongs_to', 0, $this->Lang('belongs_to'));
		$this->CreateParameter('article', 0, $this->Lang('article'));
		$this->CreateParameter('add_to_cart', 0, $this->Lang('add_to_cart'));
		$this->CreateParameter('add_to_cart_x', 0, $this->Lang('add_to_cart_x'));
		$this->CreateParameter('add_to_cart_y', 0, $this->Lang('add_to_cart_y'));
		$this->CreateParameter('articleid', 0, $this->Lang('articleid'));
		$this->CreateParameter('amount', 0, $this->Lang('amount'));
		$this->CreateParameter('article_amount', array(), $this->Lang('amount'));
		$this->CreateParameter('article_delete', array(), $this->Lang('delete'));
		$this->CreateParameter('update_cart', array(), $this->Lang('update'));
		$this->CreateParameter('update_cart_x', 0, $this->Lang('update_cart_x'));
		$this->CreateParameter('update_cart_y', 0, $this->Lang('update_cart_y'));
		$this->CreateParameter('delete_cart', array(), $this->Lang('delete'));
		$this->CreateParameter('delete_cart_x', 0, $this->Lang('delete'));
		$this->CreateParameter('delete_cart_y', 0, $this->Lang('delete'));
		$this->CreateParameter('send_cart', '', $this->Lang('send'));
		$this->CreateParameter('send_cart_x', '', $this->Lang('send'));
		$this->CreateParameter('send_cart_y', '', $this->Lang('send'));
		$this->CreateParameter('send_summary', '', $this->Lang('send'));
		$this->CreateParameter('send_summary_x', '', $this->Lang('send'));
		$this->CreateParameter('send_summary_y', '', $this->Lang('send'));
		$this->CreateParameter('data_change', '', $this->Lang('data_change'));
		$this->CreateParameter('data_change_x', '', $this->Lang('data_change'));
		$this->CreateParameter('data_change_y', '', $this->Lang('data_change'));
		$this->CreateParameter('to_shop', '', $this->Lang('to_shop'));
		$this->CreateParameter('to_shop_x', '', $this->Lang('to_shop'));
		$this->CreateParameter('to_shop_y', '', $this->Lang('to_shop'));
		$this->CreateParameter('seotitle', 0, $this->Lang('seotitle'));
		$this->CreateParameter('seo_url', 0, $this->Lang('seo_url'));
		$this->CreateParameter('gallery_use',0, $this->Lang('use_gallery'));
		$this->CreateParameter('meta_title', 0, $this->Lang('meta_title'));
		$this->CreateParameter('meta_description', 0, $this->Lang('meta_description'));
		$this->CreateParameter('noindex', 0, $this->Lang('noindex'));
		$this->CreateParameter('nofollow', 0, $this->Lang('nofollow'));
		$this->CreateParameter('noarchive', 0, $this->Lang('noarchive'));
		$this->CreateParameter('noodp', 0, $this->Lang('noodp'));
		$this->CreateParameter('notranslate', 0, $this->Lang('notranslate'));
		$this->CreateParameter('aform_salutation', 0, $this->Lang('salutation'));
		$this->CreateParameter('aform_firstname', 0, $this->Lang('firstname'));
		$this->CreateParameter('aform_lastname', 0, $this->Lang('lastname'));
		$this->CreateParameter('aform_org', 0, $this->Lang('org'));
		$this->CreateParameter('aform_tel', 0, $this->Lang('tel'));
		$this->CreateParameter('aform_mail', 0, $this->Lang('mail'));
		$this->CreateParameter('aform_street', 0, $this->Lang('street'));
		$this->CreateParameter('aform_plz', 0, $this->Lang('plz'));
		$this->CreateParameter('aform_city', 0, $this->Lang('city'));
		$this->CreateParameter('aform_country', '', $this->Lang('country'));
		$this->CreateParameter('aform_payment', 0, $this->Lang('payment'));
		$this->CreateParameter('aform_bank', 0, $this->Lang('bank'));
		$this->CreateParameter('aform_blz', 0, $this->Lang('blz'));
		$this->CreateParameter('aform_konto', 0, $this->Lang('konto'));
		$this->CreateParameter('aform_inhaber', 0, $this->Lang('inhaber'));
		$this->CreateParameter('aform_agb', 0, $this->Lang('agb'));
		$this->CreateParameter('aform_newsletter', 0, $this->Lang('newsletter'));
		$this->CreateParameter('aform_notice', 0, $this->Lang('notice'));

	}
	/**
	* Set parameters for this module.
	* @return string
	*/
	public function SetParameters(){
		$this->RegisterModulePlugin();
		#$this->RegisterEvents();

		$this->RestrictUnknownParams();
		#$this->RegisterRoute('/[sS]itemap.xml\/(?P<mode>[0-9]+)$/');

		// Module and Form params
		// $this->CreateParameter('paramName','defaultValue','HelpDescription');
		// CLEAN_TYPE could be CLEAN_NONE / CLEAN_STRING / CLEAN_INT / CLEAN_FLOAT / CLEAN_FILE
		$this->SetParameterType('mact',CLEAN_STRING);
		$this->SetParameterType('inline',CLEAN_INT);
		$this->SetParameterType('returnid',CLEAN_INT);

		$this->SetParameterType('template',CLEAN_STRING);
		$this->SetParameterType('template_cart',CLEAN_STRING);
		$this->SetParameterType('template_cartsnippet',CLEAN_STRING);
		$this->SetParameterType('template_categories',CLEAN_STRING);
		$this->SetParameterType('template_articles',CLEAN_STRING);
		$this->SetParameterType('template_article',CLEAN_STRING);
		$this->SetParameterType('template_summary',CLEAN_STRING);
		$this->SetParameterType('template_ack',CLEAN_STRING);
		$this->SetParameterType('email_template_owner',CLEAN_STRING);
		$this->SetParameterType('email_template_customer',CLEAN_STRING);

		$this->SetParameterType('page_cart',CLEAN_STRING);
		$this->SetParameterType('page_categories',CLEAN_STRING);
		$this->SetParameterType('page_articles',CLEAN_STRING);
		$this->SetParameterType('page_article',CLEAN_STRING);
		$this->SetParameterType('page_summary',CLEAN_STRING);
		$this->SetParameterType('page_ack',CLEAN_STRING);

		$this->SetParameterType('mode',CLEAN_STRING);
		$this->SetParameterType('forcemode',CLEAN_STRING);
		$this->SetParameterType('sortdesc',CLEAN_STRING);
		$this->SetParameterType('articleslimit',CLEAN_INT);
		$this->SetParameterType('cutoff',CLEAN_INT);
		$this->SetParameterType('pastonly',CLEAN_STRING);
		$this->SetParameterType('category',CLEAN_INT);
		$this->SetParameterType('belongs_to',CLEAN_INT);
		$this->SetParameterType('article',CLEAN_INT);
		
		$this->SetParameterType('add_to_cart',CLEAN_STRING);
		$this->SetParameterType('add_to_cart_x',CLEAN_INT);
		$this->SetParameterType('add_to_cart_y',CLEAN_INT);
		$this->SetParameterType('articleid',CLEAN_INT);
		$this->SetParameterType('amount',CLEAN_INT);
		$this->SetParameterType('article_amount',CLEAN_NONE);
		$this->SetParameterType('article_delete',CLEAN_NONE);
		$this->SetParameterType('update_cart',CLEAN_STRING);
		$this->SetParameterType('update_cart_x',CLEAN_INT);
		$this->SetParameterType('update_cart_y',CLEAN_INT);
		$this->SetParameterType('delete_cart',CLEAN_STRING);
		$this->SetParameterType('delete_cart_x',CLEAN_INT);
		$this->SetParameterType('delete_cart_y',CLEAN_INT);
		$this->SetParameterType('send_cart',CLEAN_STRING);
		$this->SetParameterType('send_cart_x',CLEAN_STRING);
		$this->SetParameterType('send_cart_y',CLEAN_STRING);
		$this->SetParameterType('send_summary',CLEAN_STRING);
		$this->SetParameterType('send_summary_x',CLEAN_STRING);
		$this->SetParameterType('send_summary_y',CLEAN_STRING);
		$this->SetParameterType('data_change',CLEAN_STRING);
		$this->SetParameterType('data_change_x',CLEAN_STRING);
		$this->SetParameterType('data_change_y',CLEAN_STRING);
		$this->SetParameterType('to_shop',CLEAN_STRING);
		$this->SetParameterType('to_shop_x',CLEAN_STRING);
		$this->SetParameterType('to_shop_y',CLEAN_STRING);

		$this->SetParameterType('seotitle',CLEAN_STRING);
		$this->SetParameterType('seo_url',CLEAN_STRING);
		$this->SetParameterType('gallery_use',CLEAN_STRING);
		
		$this->SetParameterType('meta_title',CLEAN_STRING);
		$this->SetParameterType('meta_description',CLEAN_STRING);
		$this->SetParameterType('noindex',CLEAN_INT);
		$this->SetParameterType('nofollow',CLEAN_INT);
		$this->SetParameterType('noarchive',CLEAN_INT);
		$this->SetParameterType('noodp',CLEAN_INT);
		$this->SetParameterType('notranslate',CLEAN_INT);

		$this->SetParameterType('aform_salutation',CLEAN_STRING);
		$this->SetParameterType('aform_firstname',CLEAN_STRING);
		$this->SetParameterType('aform_lastname',CLEAN_STRING);
		$this->SetParameterType('aform_org',CLEAN_STRING);
		$this->SetParameterType('aform_tel',CLEAN_STRING);
		$this->SetParameterType('aform_mail',CLEAN_STRING);
		$this->SetParameterType('aform_street',CLEAN_STRING);
		$this->SetParameterType('aform_plz',CLEAN_STRING);
		$this->SetParameterType('aform_city',CLEAN_STRING);
		$this->SetParameterType('aform_country',CLEAN_STRING);
		$this->SetParameterType('aform_payment',CLEAN_STRING);
		$this->SetParameterType('aform_bank',CLEAN_STRING);
		$this->SetParameterType('aform_blz',CLEAN_STRING);
		$this->SetParameterType('aform_konto',CLEAN_STRING);
		$this->SetParameterType('aform_inhaber',CLEAN_STRING);
		$this->SetParameterType('aform_agb',CLEAN_STRING);
		$this->SetParameterType('aform_newsletter',CLEAN_STRING);
		$this->SetParameterType('aform_notice',CLEAN_STRING);

		#$this->RegisterRoute('/[nN]ews\/(?P<articleid>[0-9]+)\/(?P<returnid>[0-9]+)\/(?P<junk>.*?)\/d,(?P<detailtemplate>.*?)$/');
		#$this->RegisterRoute('/[nN]ews\/(?P<articleid>[0-9]+)\/(?P<returnid>[0-9]+)\/(?P<junk>.*?)$/');
		#$this->RegisterRoute('/[nN]ews\/(?P<articleid>[0-9]+)\/(?P<returnid>[0-9]+)$/');

		// Get Preferences
		$urlstart = $this->GetPreference('urlstart') ? $this->GetPreference('urlstart') : 'Articles';
		$mode_categories = $this->GetPreference('mode_categories') ? $this->GetPreference('mode_categories') : 'Categories';
		$mode_articles = $this->GetPreference('mode_articles') ? $this->GetPreference('mode_articles') : 'Articles';
		$mode_article = $this->GetPreference('mode_article') ? $this->GetPreference('mode_article') : 'Article';
		$mode_cart = $this->GetPreference('mode_cart') ? $this->GetPreference('mode_cart') : 'Cart';
		$mode_cartsnippet = $this->GetPreference('mode_cartsnippet') ? $this->GetPreference('mode_cartsnippet') : 'CartSnippet';

		// Register Routes
		// Article Route
		if ($this->GetPreference('seo_use') && (int)$this->req_ar_id>0) {
			// Get Return ID
			$return_id = $this->adb->GetOne('SELECT returnid FROM '.cms_db_prefix().'module_articles_articles WHERE active=1 AND entry_id = ? LIMIT 1', array($this->req_ar_id));
			if (!$return_id) $return_id = $this->adb->GetOne('SELECT C.returnid FROM '.cms_db_prefix().'module_articles_category_articles CA, '.cms_db_prefix().'module_articles_articles A WHERE AC.cat_id=C.entry_id AND C.active=1 AND AC.article_id = ? LIMIT 1', array($this->req_ar_id));
			if (!$return_id) $return_id = $this->GetPreference('returnid');
			// Register Routes
			$this->RegisterRoute('/'.$this->req_url.'(\/)*$/',array('action'=>'default','mode'=>$mode_article,'article'=>$this->req_ar_id,'returnid'=>$return_id));
		// Category Route
		} else if ($this->GetPreference('seo_use') && (int)$this->req_cat_id>0) {
			// Get Return ID
			$return_id = $this->adb->GetOne('SELECT returnid FROM '.cms_db_prefix().'module_articles_category WHERE active=1 AND entry_id = ? LIMIT 1', array($this->req_cat_id));
			if (!$return_id) $return_id = $this->adb->GetOne('SELECT returnid FROM '.cms_db_prefix().'module_articles_category WHERE active=1 AND belongs_to = ? LIMIT 1', array($this->req_cat_id));
			if (!$return_id) $return_id = $this->GetPreference('returnid');
			// Register Routes
			$this->RegisterRoute('/'.$this->req_url.'(\/)*$/',array('action'=>'default','mode'=>$mode_articles,'category'=>$this->req_cat_id,'returnid'=>$return_id));
		// No SEO URL
		} else {
			#$this->RegisterRoute('/'.$urlstart.'\/(?P<category>[0-9]+)\/(?P<junk>.*?)$/',array('action'=>'default','mode'=>'auto','returnid'=>298,'inline'=>1,'mact'=>'cntnt01'));
			if (!isset($returnid) && isset($GLOBALS['returnid'])) $returnid = (int)$GLOBALS['returnid'];
			if (!isset($returnid)) $returnid = $this->GetPreference('returnid');
			#echo "---".'/'.$this->PageID2Url($returnid).'\/(?P<returnid>[0-9]+)\/'.$mode_categories.'$/'."---";
			$this->RegisterRoute('/'.str_replace('/','\/',$this->PageID2Url($returnid)).'\/(?P<returnid>[0-9]+)\/'.$mode_categories.'$/',array('action'=>'default','mode'=>$mode_categories));
			$this->RegisterRoute('/'.str_replace('/','\/',$this->PageID2Url($returnid)).'\/(?P<returnid>[0-9]+)\/'.$mode_articles.'\/(?P<category>[0-9]+)\/(?P<seotitle>.*?)$/',array('action'=>'default','mode'=>$mode_articles));
			$this->RegisterRoute('/'.str_replace('/','\/',$this->PageID2Url($returnid)).'\/(?P<returnid>[0-9]+)\/'.$mode_article.'\/(?P<article>[0-9]+)\/(?P<seotitle>.*?)$/',array('action'=>'default','mode'=>$mode_article));
			$this->RegisterRoute('/'.str_replace('/','\/',$this->PageID2Url($returnid)).'\/(?P<returnid>[0-9]+)\/'.$mode_cart.'$/',array('action'=>'cart','mode'=>$mode_cart));
			$this->RegisterRoute('/'.str_replace('/','\/',$this->PageID2Url($returnid)).'\/(?P<returnid>[0-9]+)\/'.$mode_cartsnippet.'$/',array('action'=>'cart','mode'=>$mode_cartsnippet));
		}

	}

	/**
	* Is this an optional module for CMSms?
	* @return boolean
	*/
	function IsPluginModule(){
		return true;
	}

	/**
	* Has this module an admin
	* @return boolean
	*/
	function HasAdmin(){
		return true;
	}

	/**
	* In which main menu of the backend shall this module be?
	* @return string
	*/
	function GetAdminSection(){
		return 'content';
	}

	/**
	* Get an module description for the backend.
	* @return string
	*/
	function GetAdminDescription(){
		return $this->Lang('moddescription');
	}

	/**
	* Sets the permission for this module.
	* @return string
	*/
	function VisibleToAdminUser(){
	        return $this->CheckPermission('Articles: modify articles');
	}

	/**
	* Shall this module handle events?
	* @return boolean
	*/
	public final function HandlesEvents() {
		return true;
	}

	/**
	* Register Event
	*/
	public final function RegisterEvents(){
		#$this->AddEventHandler( 'Core', 'ContentPostRender', false );
		#$this->AddEventHandler( 'Core', 'ContentPreCompile', false );   --> doesn't work
	}

	/**
	* Run Event
	*/
	public final function DoEvent($originator, $eventname, &$params) {
		// Check event
		#if($originator=='Core' && $eventname=='ContentPostRender'){
			// Check if module was already used
			#if (!$this->mdused) {
				// Set the module used
				#$this->mdused = true;
				// Set content id
				#$this->mdpageid = (int)$this->mdgCms->variables['content_id'];
				// Log visit
				#$log = $this->GetPreference('stats_use') ? $this->PrepareLogVisit() : array();
				// Look for redirect domains
				#$this->RedirectDomain($log);
				// Assign site to smarty template vars
				#$this->mdsmarty->assign('mdsite',$this->mddomain);
				#$this->mdsmarty->assign('mddevsite',$this->mddev ? $this->mddevdomain : '');
			#}
		#}
	}

	/**
	* Get the dependencies for this module.
	* @return array
	*/
	function GetDependencies(){
		return array();
	}

	/**
	* What is the minimum version of CMSms for this module?
	* @return string
	*/
	function MinimumCMSVersion(){
		return "1.10";
	}

	/**
	* Gets a message to display after installing the module
	* @return string
	*/
	function InstallPostMessage(){
		return $this->Lang('postinstall');
	}

	/**
	* Gets a message to disply after uninstalling this module.
	* @return string
	*/
	function UninstallPostMessage(){
		return $this->Lang('postuninstall');
	}

	/**
	* Gets the search result
	* @param integer $returnid Return ID
	* @param integer $articleid Article ID
	* @param string $attr attributes
	* @return string
	*/
	function SearchResult($returnid, $itemid, $attr = '') {
		$result = array();
		if ($attr == 'article') {
			$now = $this->adb->DbTimeStamp(time());
			$zerotime = $this->adb->DbTimeStamp(1);
			$q = "SELECT title,seo_url,returnid FROM ".cms_db_prefix()."module_articles_articles WHERE active=1 AND entry_id = ?";
			$dbresult = $this->adb->Execute( $q, array( (int)$itemid ) );
			if ($dbresult) {
				$row = $dbresult->FetchRow();
				//0 position is the prefix displayed in the list results.
				$result[0] = $this->GetFriendlyName();
				//1 position is the title
				$result[1] = $row['title'];
				//2 position is the URL to the title.
				$mode_article = $this->GetPreference('mode_article') ? $this->GetPreference('mode_article') : 'Article';
				$page_article = $row['returnid'] ? (int)$row['returnid'] : (int)$this->GetPreference('returnid');
				if ($page_article && (int)$page_article<1) $page_article = $this->adb->GetOne('SELECT content_id FROM '.cms_db_prefix().'content WHERE content_alias = ?', array($page_article));
				if (!$page_article || (int)$page_article<1) $page_article = $row['returnid'];
				$category = (int)$this->adb->GetOne('SELECT cat_id FROM '.cms_db_prefix().'module_articles_category_articles WHERE article_id = ? LIMIT 1', array($itemid));
				$result[2] = $this->CreateLink($id, 'default', $page_article, '', $category ? array('article'=>$itemid,'category'=>$category,'mode'=>$mode_article) : array('article'=>$itemid,'mode'=>$mode_article), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_article).'/'.$page_article.'/'.$mode_article.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
			}
		}
		if ($attr == 'category') {
			$now = $this->adb->DbTimeStamp(time());
			$zerotime = $this->adb->DbTimeStamp(1);
			$q = "SELECT title,seo_url,returnid FROM ".cms_db_prefix()."module_articles_category WHERE active=1 AND entry_id = ?";
			$dbresult = $this->adb->Execute( $q, array( (int)$itemid ) );
			if ($dbresult) {
				$row = $dbresult->FetchRow();
				//0 position is the prefix displayed in the list results.
				$result[0] = $this->GetFriendlyName();
				//1 position is the title
				$result[1] = $row['title'];
				//2 position is the URL to the title.
				$mode_articles = $this->GetPreference('mode_articles') ? $this->GetPreference('mode_articles') : 'Articles';
				$page_articles = $row['returnid'] ? (int)$row['returnid'] : (int)$this->GetPreference('returnid');
				if ($page_articles && (int)$page_articles<1) $page_articles = $this->adb->GetOne('SELECT content_id FROM '.cms_db_prefix().'content WHERE content_alias = ?', array($page_articles));
				if (!$page_articles || (int)$page_articles<1) $page_articles = $row['returnid'];
				#$result[2] = $this->CreateLink($id, 'default', $page_article, '', $category ? array('article'=>$itemid,'category'=>$category,'mode'=>$mode_article) : array('article'=>$itemid,'mode'=>$mode_article), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_article).'/'.$page_article.'/'.$mode_article.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
				$result[2] = $this->CreateLink($id, 'default', $page_articles, '', array('category'=>$itemid,'mode'=>$mode_articles), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_articles).'/'.$page_articles.'/'.$mode_articles.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
			}
		}
		return $result;
	}

	/**
	* Gets the search result
	* @param integer $returnid Return ID
	* @param integer $articleid Article ID
	* @param string $attr attributes
	* @param string $params additional parameter
	* @return string
	*/
	function SearchResultWithParams($returnid, $itemid, $attr = '', $params = '') {
		$result = array();
		if ($attr == 'article') {
			$now = $this->adb->DbTimeStamp(time());
			$zerotime = $this->adb->DbTimeStamp(1);
			$q = "SELECT title,seo_url,returnid FROM ".cms_db_prefix()."module_articles_articles WHERE active=1 AND entry_id = ?";
			$dbresult = $this->adb->Execute( $q, array( (int)$itemid ) );
			if ($dbresult) {
				$row = $dbresult->FetchRow();
				//0 position is the prefix displayed in the list results.
				$result[0] = $this->GetFriendlyName();
				//1 position is the title
				$result[1] = $row['title'];
				//2 position is the URL to the title.
				$mode_article = $this->GetPreference('mode_article') ? $this->GetPreference('mode_article') : 'Article';
				$page_article = $row['returnid'] ? (int)$row['returnid'] : (int)$this->GetPreference('returnid');
				if ($page_article && (int)$page_article<1) $page_article = $this->adb->GetOne('SELECT content_id FROM '.cms_db_prefix().'content WHERE content_alias = ?', array($page_article));
				if (!$page_article || (int)$page_article<1) $page_article = $row['returnid'];
				$category = (int)$this->adb->GetOne('SELECT cat_id FROM '.cms_db_prefix().'module_articles_category_articles WHERE article_id = ? LIMIT 1', array($itemid));
				$result[2] = $this->CreateLink($id, 'default', $page_article, '', $category ? array('article'=>$itemid,'category'=>$category,'mode'=>$mode_article) : array('article'=>$itemid,'mode'=>$mode_article), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_article).'/'.$page_article.'/'.$mode_article.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
			}
		}
		if ($attr == 'category') {
			$now = $this->adb->DbTimeStamp(time());
			$zerotime = $this->adb->DbTimeStamp(1);
			$q = "SELECT title,seo_url,returnid FROM ".cms_db_prefix()."module_articles_category WHERE active=1 AND entry_id = ?";
			$dbresult = $this->adb->Execute( $q, array( (int)$itemid ) );
			if ($dbresult) {
				$row = $dbresult->FetchRow();
				//0 position is the prefix displayed in the list results.
				$result[0] = $this->GetFriendlyName();
				//1 position is the title
				$result[1] = $row['title'];
				//2 position is the URL to the title.
				$mode_articles = $this->GetPreference('mode_articles') ? $this->GetPreference('mode_articles') : 'Articles';
				$page_articles = $row['returnid'] ? (int)$row['returnid'] : (int)$this->GetPreference('returnid');
				if ($page_articles && (int)$page_articles<1) $page_articles = $this->adb->GetOne('SELECT content_id FROM '.cms_db_prefix().'content WHERE content_alias = ?', array($page_articles));
				if (!$page_articles || (int)$page_articles<1) $page_articles = $row['returnid'];
				#$result[2] = $this->CreateLink($id, 'default', $page_article, '', $category ? array('article'=>$itemid,'category'=>$category,'mode'=>$mode_article) : array('article'=>$itemid,'mode'=>$mode_article), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_article).'/'.$page_article.'/'.$mode_article.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
				$result[2] = $this->CreateLink($id, 'default', $page_articles, '', array('category'=>$itemid,'mode'=>$mode_articles), '', true, true, '', false, $row['seo_url'] ? $row['seo_url'] : $this->PageID2Url($page_articles).'/'.$page_articles.'/'.$mode_articles.'/'.$itemid.'/'.$this->UrlSeoDecode($row['title']));
			}
		}
		return $result;
	}

	/**
	* Reindex the search module index, here for this module
	* @param object $module The module object
	*/
	function SearchReindex(&$module) {
		// Reindex articles
		$query = 'SELECT * FROM '.cms_db_prefix().'module_articles_articles';
		$result = $this->adb->Execute($query);
		while ($result && !$result->EOF) {
			if ($result->fields['active']) {
				$module->AddWords($this->GetName(), 
				$result->fields['entry_id'], 'article', 
				$result->fields['title'] . ' ' . $result->fields['short_desc'] . ' ' . $result->fields['long_desc'],
				($result->fields['end_date'] != NULL ?  $this->adb->UnixTimeStamp($result->fields['end_date']) : NULL));
			}
			$result->MoveNext();
		}
		// Reindex categories
		$query = 'SELECT * FROM '.cms_db_prefix().'module_articles_category';
		$result = $this->adb->Execute($query);
		while ($result && !$result->EOF) {
			if ($result->fields['active']) {
				$module->AddWords($this->GetName(), 
				$result->fields['entry_id'], 'category', 
				$result->fields['title'] . ' ' . $result->fields['short_desc'] . ' ' . $result->fields['long_desc']);
			}
			$result->MoveNext();
		}
	}

	/**
	 * 
	 * Get the installed jQuery File from ./lib/jquery
	 * @return string - filename
	 */
	public final function getjQuery() {
		$folders = scandir($this->tbConfig['root_path']."/lib/jquery/js");
		$subject = "";
		foreach ($folders as $folder) {
			$subject.=$folder."\n";
		}
		
		$matches = array();
		$pattern = "!jquery-[0-9\.]*\.min\.js!is";
		preg_match($pattern,$subject,$matches);
		
		return $matches[0];
	}

	/**
	 * Insert JavaScript to the backend HTML Header
	 * @access public
	 * @return Header JS and CSS
	 */
	public final function GetHeaderHTML(){

		$script = "";
		$script .= '<style type="text/css">
<!--
.tDnD_whileDrag {
    background-color: #eee;
}

tr.alt td {
    background-color: #ecf6fc;
}

tr.no_alt td {
    background-color: none;
}

tr.myDragClass td {
    color: yellow;
    background-color: black;
}

td.dragHandle {
    
}

td.showDragHandle {
	background-image: url(../modules/Articles/images/updown2.gif);
	background-repeat: no-repeat;
	background-position: center center;
	cursor: move;
}
-->
</style>'."\n";
		$script .= '<script type="text/javascript" src="../modules/Articles/js/jquery.tablednd.min.js"></script>'."\n";
		$script .= '<script type="text/javascript">
			$(document).ready(function() {	
                            $("#m1_articleview tr:nth-child(even)").addClass(\'row1\').removeClass(\'row2\');
                            $("#m1_articleview tr:nth-child(odd)").addClass(\'row2\').removeClass(\'row1\');
                            $("#m1_articleview").tableDnD({
                                onDrop: function(table, row) {
                                //alert($.tableDnD.serialize());
                                var cat = $("#filter_cat").val();
//                                $("#AjaxResult").load("'.html_entity_decode($this->create_url( 'm1_', 'admin_saveorder', '', array (), false, false)).'&m1_category="+cat+"&"+$.tableDnD.serialize());
                                $.ajax({
                                    type: "POST",
                                    url: "'.html_entity_decode($this->create_url( 'm1_', 'admin_saveorder', '', array (), false, false)).'&m1_category="+cat+"&"+$.tableDnD.serialize()
                                }).done(function( msg ) {
                                   // $("#AjaxResult").html(msg);
                                });
                                $("#m1_articleview tr:nth-child(even)").addClass(\'row1\').removeClass(\'row2\');
                                $("#m1_articleview tr:nth-child(odd)").addClass(\'row2\').removeClass(\'row1\');
                                $("#AjaxResult").show().delay(3000).hide(2000);
			        },
			        dragHandle: "dragHandle"
			    });

                            $("#m1_articleview tr.editable").hover(function() {
                                $(this.cells[0]).addClass(\'showDragHandle\');
                            }, function() {
                                $(this.cells[0]).removeClass(\'showDragHandle\');
                            });
			});
			
			
			</script>'."\n";
			    
		return $script;
	}

	/**
	* Get a page alias for a given page id
	* @param integer $pageid Page ID
	* @return string
	*/
	public final function GetLinkAlias($pageid) {
		$alias = $this->adb->GetOne('SELECT content_alias FROM '.cms_db_prefix().'content WHERE active=1 AND type!="errorpage" AND type!="separator" AND content_id = ?', array($pageid));
		return $alias ? $alias : false;
	}

	/**
	* Replace Umlaute
	* @param string $text A text replaced Umlauten.
	* @return string
	*/
	public final function UrlSeoDecode($text) {
		$text = str_replace ('�','ue',$text);
		$text = str_replace ('�','oe',$text);
		$text = str_replace ('�','ae',$text);
		$text = str_replace ('�','Ue',$text);
		$text = str_replace ('�','Oe',$text);
		$text = str_replace ('�','Ae',$text);
		$text = str_replace ('�','ss',$text);
		$text = str_replace ('&','-',$text);
		$text = str_replace ('_','-',$text);
		$text = str_replace (' ','-',$text);
		$text = str_replace ('/','-',$text);
		$text = preg_replace('/[^0-9a-zA-Z-]/','',$text);
		$text = str_replace ('---','-',$text);
		$text = str_replace ('--','-',$text);
		return $text;
	}

	/**
	* Get an URL of a page ID
	* @param int $pageid The Page ID
	* @return string
	*/
	public final function PageID2Url($pageid) {
		// Check Page ID
		$pageid = (int)$pageid; if (!$pageid) return '';
		// Get page alias and url
		$page = $this->adb->GetRow('SELECT content_alias,page_url,hierarchy_path FROM '.cms_db_prefix().'content WHERE active=1 AND type!="errorpage" AND type!="separator" AND content_id = ?', array($pageid));
		if (!$page) return '';
		// Return page url, if there is one
		if ($page['page_url']) {
			$url = $page['page_url'];
			while (substr($url,-1) == '/') { $url = substr($url,0,-1); }
			return $url;
		}
		// Set page url ending
		$ending = $GLOBALS['config']['page_extension']!='/' ? $GLOBALS['config']['page_extension'] : '';
		// Return page alias, if hierarchy is not used
		if (!$GLOBALS['config']['use_hierarchy']) return $page['content_alias'].$ending;
		// Return hierarchy path, if hierarchy is used
		return $page['hierarchy_path'].$ending;
	}
	
	/**
	* Format a price
	* @param float $price The unformated price
	* @return string
	*/
	public final function FormatPrice($price) {
		return number_format((float)str_replace(',','.',$price), 2, ',', '.').' '.$this->GetPreference('currency');
	}

	/**
	* Build a Gallery Chooser for selection
	* This is a convenience function similar to the CreateInputXXX functions of Class CMSModule
	* @param int $id The id given to the module on execution
	* @param string $name the html name of the input field
	* @param string $value The predefined value of the chooser, if any
	* @return string 
	*/
	public final function CreateGalleryChooser($id, $name, $value) {
		$modulename = $this->GetPreference('use_gallery','IPTCGallery'); // IPTCGAllery is default
		if (!$this->GetModuleInstance($modulename)) { return; }
		switch ($modulename) {
		case 'Gallery': $galleries = Gallery_utils::GetGalleries(); break;
		case 'IPTCGallery': $galleries = IPTCGallery_utils::GetGalleries(); break;
		default: return;
		}
		//trigger_error('function CreateGalleryChooser(): Galleries are '.print_r($galleries,1));
		$items = array();
		foreach ($galleries as $data) {
			$depth = substr_count($data['filepath'].$data['filename'],'/');
			$prefix = str_repeat("+-",$depth);
			if (!$data['title']) {$data['title']=$data['filename'];}
			$items[$prefix.$data['title']]=$data['galleryid'];
		}
		return $this->CreateInputDropdown($id,$name,$items,0,$value);
	}
	
	public final function smarty_function_galleryLink($params, &$smarty) {
		$galleryid = $params['galleryid'];
		$target = $params['target'] ? $params['target'] : $this->GetPreference('detailpage_use');
		if ((string)(int)$target != $target) { // target is not a id -> lookup id via HierarchyManager 
			      $manager = cmsms()->GetHierarchyManager();
			      $node = $manager->sureGetNodeByAlias($target);
			      if ($node) { $content = $node->GetContent();
			      	      $target = $content->Id();
			      } else {
			      	      trigger_error("missing page for '$target'");
			      }
		}
		$modulename = $this->GetPreference('use_gallery','IPTCGallery'); // IPTCGAllery is default
		$db = cmsms()->GetDB();
		if (!$galMod = $this->GetModuleInstance($modulename)) { return; }
		$prefix = $galMod->GetPreference('urlprefix',strtolower($modulename));
		$dbname = strtolower($modulename);
		$sql = "select fileid, filepath, filename from ".cms_db_prefix()."module_$dbname where galleryid=? and filename LIKE '%/'";
		$result = $db->Execute($sql, array($galleryid));
		if ($result) {
			$row=$result->FetchRow();
			$gpath = ltrim($row['filepath'] . $row['filename'], '/');
			$url = $prefix . "/$gpath" . $target;
			if ($params['assign']) {				 
				$smarty->assign($params['assign'],$url);
			} else {
				return $url;
			}
		}
		return '';
	}
} // End of class


// EOF