<?php if(!defined('master_script')) die();

/**
 * Copyright (C) Nico Wenig
 * All rights reserved
 *
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @filesource
 */



/**
 * Load stylesheet
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-07-11
 */

	$system_data['backend']['header'] .= '
		<link rel="MoreCSS" href="' . $system_data['folder']['extensions'] . 'edit-page/MoreCSS.css">
		<link rel="stylesheet" type="text/css" media="all" href="' . $system_data['folder']['extensions'] . 'edit-page/index.css">
	';

/**
 * Get page data (if page is not in folder pages)
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-05-29
 */

	if(!isset($_GET['pagetype']) || $_GET['pagetype'] == '') $_GET['pagetype'] = 'standard';
	
	if($page_info->alias == '' || !is_dir($system_data['folder']['pages'] . $page_info->alias)) {
		if(isset($_GET['path']) && is_dir($_GET['path']) && $_GET['path'] != '') {
			$page_info_file = $_GET['path'] . '/' . $system_data['file']['page info file'];
		} else {
			$pages_trashcan = $system_data['folder']['settings'] . 'extensions/trashcan/pages/';
			$page_info_file = $pages_trashcan . $_GET['page'] . '/' . $system_data['file']['page info file'];
		}
		
		$page_info = is_file($page_info_file) ? simplexml_load_file($page_info_file) : simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><page></page>');
		
		connector('edit page get page data');
	}

/**
 * Get real pagetype
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-05-29
 */

	if(is_file($page_info->index) && $page_info->pagetype != '') $_GET['pagetype'] = $page_info->pagetype;
	
/**
 * Include page type index script
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-05-25
 */
	
	if(isset($_GET['pagetype'])) {
	   	switch($_GET['pagetype']) {
	   		case 'standard' : default : include('standard/index.php'); break;
	   		case 'news' : include('news/index.php'); break;
	   	}
	   	
	   	connector('edit page type messages script');
   	}

/**
 * Delete page
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2010-05-14
 */
 	
	if(isset($_POST['delete_page']) && $_SESSION['user'] == sha1($administrator_name)) {
		// Include page type script
    	switch($_GET['pagetype']) {
    		case 'standard' : include('standard/delete.php'); break;
    		case 'news' : include('news/delete.php'); break;
    	}
	
		$page_dir = $system_data['folder']['pages'] . $_GET['page'];
		
		if(is_dir($page_dir)) {
			$pages_trashcan = $system_data['folder']['settings'] . 'extensions/trashcan/pages/';
			if(!is_dir($pages_trashcan)) rmkdir($pages_trashcan);
			if(is_dir($pages_trashcan . $_GET['page'])) rec_rmdir($pages_trashcan . $_GET['page']);
			rename($page_dir, $pages_trashcan . $_GET['page']);
		}
    	
		// Delete page from latest pages database
		$database_latest_file = $system_data['folder']['database'] . 'latest/catalogue.xml';
		
		if(is_file($database_latest_file)) {
			$database_latest_xml = simplexml_load_file($database_latest_file);
    	
	    	if(count($database_latest_xml->page) > 0) {
	    		foreach($database_latest_xml->page as $page_entry) if(strval($page_entry->alias) == $_GET['page']) { $existing_entry = $page_entry->asXML(); break; }
	    		if(isset($existing_entry)) $database_latest_xml = simplexml_load_string(str_replace($existing_entry, '', $database_latest_xml->asXML()));
				$database_latest_xml->saveXML($database_latest_file);
	    	}
	    }    	

   		// Delete page from tags database
   		$database_tags_file = $system_data['folder']['database'] . 'tags/catalogue.xml';
   		
   		if(is_file($database_tags_file)) {
   			$database_tags_xml = simplexml_load_file($database_tags_file);
   			
   			// Delete link from tag
   			foreach($database_tags_xml->tag as $tag_entry)
				foreach($tag_entry->link as $link_entry) if(strval($link_entry) == trim($_GET['page'])) $database_tags_xml = simplexml_load_string(str_replace($link_entry->asXML(), '', $database_tags_xml->asXML()));
			
			// Delete complete tag if no more links
   			foreach($database_tags_xml->tag as $tag_entry)
   				if(count($tag_entry->link) == 0) $database_tags_xml = simplexml_load_string(str_replace($tag_entry->asXML(), '', $database_tags_xml->asXML()));

	   		$database_tags_xml->saveXML($database_tags_file);
   		}

    	connector('edit page type script delete');

		// Reload backend page
		header('location: index.php?backend=edit-page&page=' . $_GET['page'] . '&status=page-deleted');
	}
	
	if(isset($_POST['delete_folder']) && isset($_GET['path']) && is_dir($_GET['path']) && $_SESSION['user'] == sha1($administrator_name)) {
		rec_rmdir($_GET['path']);

		// Reload backend page
		header('location: index.php?backend=edit-page&page=' . $_GET['page'] . '&status=page-folder-deleted');
	}

/**
 * Save page
 *
 * @category   Extension (edit-page)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2010-06-17
 */

	if(isset($_POST['save_page'])) {
		// Clean standard data
		$_POST['published'] = isset($_POST['published']) ? 1 : 0;
		$_POST['searchable'] = isset($_POST['searchable']) ? 1 : 0;
		$_POST['timestamp'] = strtotime(clean_string($_POST['timestamp']));
		$_POST['alias'] = transcribe($_POST['alias'], true);
		$_POST['title'] = clean_string($_POST['title'], true);
		$_POST['template'] = isset($_POST['template']) ? $_POST['template'] : '';
		
		// Error handling
		if($_POST['alias'] == '') $_POST['alias'] = transcribe($_POST['title'], true);
		if($_POST['title'] == '') $message = txt('edit-page', 'Bitte geben Sie einen Namen für die Seite an.');
		if($_POST['timestamp'] == '' || strlen($_POST['timestamp']) < 10) $_POST['timestamp'] = time();
		
		if(is_dir($system_data['folder']['pages'] . $_POST['alias']) && $_POST['alias'] != $_GET['page']) $message = txt('edit-page', 'Der angegebene Alias ist bereits für eine andere Seite vergeben.');
		if(in_array($_POST['alias'], $system_data['backend']['not editable pages']) && $_POST['alias'] != $_GET['page']) $message = txt('edit-page', 'Der angegebene Alias ist für eine Systemseite reserviert und kann nicht verwendet werden.');

		// Parse standard data
		$cleaned_tags = explode(',', $_POST['tags']);
		$_POST['tags'] = '';
		foreach($cleaned_tags as $tag) if(trim($tag) != '') $_POST['tags'] .= ($_POST['tags'] == '' ? '' : ', ') . trim($tag);
		$cleaned_tags = explode(', ', $_POST['tags']);
		
		if($_GET['page'] == $system_data['file']['homepage'] || $_GET['page'] == $system_data['file']['404']) {
			$_GET['pagetype'] = 'standard';
			$_POST['category'] = 'Info pages';
			$database_category_id = $system_data['backend']['info pages id'];
		}
		
		// Create page info file content
		$page_info_xml = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><page></page>');

    	$page_info_xml->pagetype = xml_string($_GET['pagetype']);
    	$page_info_xml->published = xml_string($_POST['published']);
    	$page_info_xml->searchable = xml_string($_POST['searchable']);
    	$page_info_xml->timestamp = xml_string($_POST['timestamp']);
    	$page_info_xml->alias = xml_string($_POST['alias']);
    	$page_info_xml->title = xml_string($_POST['title']);
    	$page_info_xml->template = xml_string($_POST['template']);
    	$page_info_xml->author = $user_name;
    		
		// Save page
		if(!isset($message)) {
    		// Recycle page in trashcan
			if(isset($_GET['path']) && is_dir($_GET['path']) && $_GET['path'] != '') {
				if(is_dir($system_data['folder']['pages'] . $_POST['alias'])) rec_rmdir($system_data['folder']['pages'] . $_POST['alias']);
				rename($_GET['path'], $system_data['folder']['pages'] . $_POST['alias']);
			}

			// Include page type script
			switch($_GET['pagetype']) {
				case 'standard' : default : include('standard/save.php'); break;
				case 'news' : include('news/save.php'); break;
			}
			
			connector('edit page type script save');
	
			// Create or rename page dir
			if($_POST['alias'] != $_GET['page']) {
				if($_GET['page'] == '' || !is_dir($system_data['folder']['pages'] . $_GET['page'])) {
					if($_POST['alias'] != '') mkdir($system_data['folder']['pages'] . $_POST['alias']);
				} 
				
				if($_GET['page'] != '' && is_dir($system_data['folder']['pages'] . $_GET['page'])) {
					rename($system_data['folder']['pages'] . $_GET['page'], $system_data['folder']['pages'] . $_POST['alias']);
				}
			} else {
				if($_POST['alias'] != '' && !is_dir($system_data['folder']['pages'] . $_POST['alias'])) {
					mkdir($system_data['folder']['pages'] . $_POST['alias']);
				}
			}
			
			// Create page index file
			$page_index_file = $system_data['folder']['pages'] . $_POST['alias'] . '/' . $system_data['file']['index page'];
			
			if(!is_file($page_index_file)) {
				if(!isset($page_template_file) || !is_file($page_template_file))
					$page_template_file = $system_data['folder']['defaults'] . 'pages/standard-page.php';
				
				copy($page_template_file, $page_index_file);
			}
			
			// Create page info file
    		$page_info_xml->saveXML($system_data['folder']['pages'] . $_POST['alias'] . '/' . $system_data['file']['page info file']);
    		
    		// Save page in latest pages database
    		$database_latest_folder = $system_data['folder']['database'] . 'latest/';
    		rmkdir($database_latest_folder);
    		
    		$database_latest_file = $database_latest_folder . 'catalogue.xml';
    		$database_latest_xml = is_file($database_latest_file) ? simplexml_load_file($database_latest_file) : simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><pages></pages>');
			
			if(count($database_latest_xml->page) > 0) {
				// Delete old entry
				foreach($database_latest_xml->page as $page_entry) if(strval($page_entry->alias) == $_GET['page']) { $existing_entry = $page_entry->asXML(); break; }
				if(isset($existing_entry)) $database_latest_xml = simplexml_load_string(str_replace($existing_entry, '', $database_latest_xml->asXML()));
				
				// Create new entry
				$next_entry = 0;
				
				if(count($database_latest_xml->page) > 0 && intval($page_info_xml->timestamp) >= intval($database_latest_xml->page[0]->timestamp)) {
					for($i = 0; $i < count($database_latest_xml->page); $i++)
						if(intval($page_info_xml->timestamp) >= intval($database_latest_xml->page[$i]->timestamp)) $next_entry = $i + 1; else break;
				}
			}
			
			$database_latest_xml_new = '';
    		
    		for($i = 0; $i < count($database_latest_xml->page); $i++) {
    			if($page_info_xml->published == 1 && $next_entry == 0 && $i == 0) $database_latest_xml_new .= '<page></page>';
				
				if(isset($database_latest_xml->page[$i]) && $database_latest_xml->page[$i]->published == 1)
					$database_latest_xml_new .= $database_latest_xml->page[$i]->asXML();
				
				if($page_info_xml->published == 1 && $next_entry != 0 && $i + 1 == $next_entry) $database_latest_xml_new .= '<page></page>';
			}
    		
    		$database_latest_xml_new = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><pages>' . $database_latest_xml_new . '</pages>');
    		$database_latest_xml = $database_latest_xml_new;
    		
    		if(count($database_latest_xml->page) == 0) $paste_entry = 0;
    		if(isset($next_entry)) $paste_entry = $next_entry;
    		
    		if($page_info_xml->searchable == 1 && isset($paste_entry)) {
    			if(count($database_latest_xml->page) < $paste_entry) $paste_entry = count($database_latest_xml->page);
    	    	
    	    	$database_latest_xml->page[$paste_entry]->pagetype = $page_info_xml->pagetype;
    	    	$database_latest_xml->page[$paste_entry]->published = $page_info_xml->published;
    	    	$database_latest_xml->page[$paste_entry]->searchable = $page_info_xml->searchable;
    	    	$database_latest_xml->page[$paste_entry]->timestamp = $page_info_xml->timestamp;
    	    	$database_latest_xml->page[$paste_entry]->alias = $page_info_xml->alias;
    	    	$database_latest_xml->page[$paste_entry]->title = $page_info_xml->title;
    	    	$database_latest_xml->page[$paste_entry]->author = $page_info_xml->author;
    		}
    		
    		if(count($database_latest_xml->page) > $system_data['backend']['maximum latest pages']) {
    			$spare_pages = count($database_latest_xml->page) - $system_data['backend']['maximum latest pages'];
    			
    			$spare_pages_xml_string = '';
    			for($i = 0; $i < $spare_pages; $i++) $spare_pages_xml_string .= $database_latest_xml->page[$i]->asXML();
    			
    			if($spare_pages_xml_string != '')
    				$database_latest_xml = simplexml_load_string(str_replace($spare_pages_xml_string, '', $database_latest_xml->asXML()));
    		}
			
			$database_latest_xml->saveXML($database_latest_file);
			
    		// Save page in tags database
    		$database_tags_folder = $system_data['folder']['database'] . 'tags/';
    		rmkdir($database_tags_folder);
    		
    		$database_tags_file = $database_tags_folder . 'catalogue.xml';
    		$database_tags_xml = is_file($database_tags_file) ? simplexml_load_file($database_tags_file) : simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><tags></tags>');
    		
    		$found_tags = array();
    		$empty_tags = array();
    		$i = 0;

    		foreach($database_tags_xml->tag as $tag_entry) {
    			if(in_array($tag_entry->name, $cleaned_tags)) {
    				$found_tags[] = $tag_entry->name;

    				if(!empty($_GET['page']) && $_GET['page'] != $_POST['alias']) {
	    				$link_position = in_node($_GET['page'], 'link', $tag_entry);
    					if($link_position != -1) unset($tag_entry->link[$link_position]);
    				}

    				if(in_node($_POST['alias'], 'link', $tag_entry) == -1) $tag_entry->link[] = $_POST['alias'];
    			} else {
    				$link_position = in_node($_GET['page'], 'link', $tag_entry);
    				if($link_position != -1) unset($tag_entry->link[$link_position]);
    			}
    			
    			if($tag_entry->link[0] == '') $empty_tags[] = $i;
        		$i++;
    		}
    		
    		$new_tags = array_diff($cleaned_tags, $found_tags);
    		
    		foreach($new_tags as $tag_entry) if(trim($tag_entry) != '') {
    			$database_tags_xml->tag[$i]->name = trim($tag_entry);
    			$database_tags_xml->tag[$i]->link = $_POST['alias'];
    			$i++;
    		}
    		
    		if(count($empty_tags) > 0) rsort($empty_tags);
    		foreach($empty_tags as $tag_entry) unset($database_tags_xml->tag[$tag_entry]);
    		
    		$database_tags_xml->saveXML($database_tags_file);
    		
			// Reload backend page
			header('location: index.php?backend=edit-page&page=' . $_POST['alias'] . '&pagetype=' . $_GET['pagetype']);
		}
	}

?>