<?php
/*======================================================================================
Module: Articles
======================================================================================*/

// Check authorisation
$errors = array();
if (!isset($gCms)) exit;
if ( !$this->CheckPermission('Articles: modify articles') ) {
	$errors[] = $this->Lang('needpermission', array($this->Lang('modarticles')));
} else {

	// Get POST data
	$tabto = preg_replace('/[^0-9a-zA-Z_]/','',$params['tabto']);
	$article = (int)$params['article'];

	// Delete the article
	if ($article) {
		// check article for existence
		$query = 'SELECT 0 FROM '.cms_db_prefix().'module_articles_articles WHERE entry_id=?';
		$result = $db->Execute($query, array($article));
		if(!$result->FetchRow()) $errors[] = $this->Lang('nosuchid', array($article));
		// delete article
		if (!$errors) {
			// delete image, if one exists
			$filename = $db->GetOne('SELECT image_url FROM '.cms_db_prefix().'module_articles_articles WHERE entry_id = ?', array($article));
			if ($filename) {
				// get image path
				$deldir = cms_join_path($config['image_uploads_path'],'Articles','articles',$article);
				$delfile = cms_join_path($deldir,$filename);
				// delete image
				if (is_file($delfile)) unlink($delfile);
				// delete article directory
				if (is_dir($deldir)) rmdir($deldir);
			}
			// Delete filename from article entry
			$db->Execute('UPDATE '.cms_db_prefix().'module_articles_articles SET image_url = "" WHERE entry_id = ?', array($article));
			// delete from category-article table
			$sql = 'DELETE FROM '.cms_db_prefix().'module_articles_category_articles WHERE article_id=?';
			$res = $db->Execute($sql,array($article));
			if(!$res) $errors[] = 'SQL ERROR: ' . $db->ErrorMsg() . '(with ' . $db->sql . ')';
			// delete from article table
			$sql = 'DELETE FROM '.cms_db_prefix().'module_articles_articles WHERE entry_id=?';
			$res = $db->Execute($sql,array($article));
			if(!$res) $errors[] = 'SQL ERROR: ' . $db->ErrorMsg() . '(with ' . $db->sql . ')';
		}
	}

	// Redirect
	if (!$errors) $this->Redirect($id, 'defaultadmin', $returnid, array('tabto'=>$tabto, 'message' => $this->Lang('postdelete')));

}

// EOF