<?php
global $_,$conf;
switch($_['action']){
	/** COMMON **/
	case 'wiki_logo_download':
		$logoDir = File::dir().'wiki'.SLASH.'logo';
		$logo = $logoDir.SLASH.'logo.png';
		if(!file_exists($logoDir)) mkdir($logoDir,0755,true);
		if(!file_exists($logo)) copy(__DIR__.SLASH.'img'.SLASH.'logo.png', $logo);

		header('Content-Type: image/png');
		echo file_get_contents($logo);
	break;

	case 'wiki_logo_delete':
		Action::write(function(&$response){
		    global $myUser,$_;
		    if(!$myUser->can('wiki', 'configure')) throw new Exception("Permissions insuffisantes",403);

		    foreach (glob(File::dir().'wiki'.SLASH."logo".SLASH."logo.*") as $filename)
		        unlink($filename);
		});
	break;

	/** HOME **/
	case 'wiki_page_home':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);

			ob_start();
			require_once(__DIR__.SLASH.'page.home.php');
			$response['content'] = ob_get_clean();
		});
	break;

	case 'wiki_page_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);

			ob_start();
			require_once(__DIR__.SLASH.'page.search.php');
			$response['content'] = ob_get_clean();
		});
	break;

	case 'wiki_page_download':
		require_once(__DIR__.SLASH.'WikiPage.class.php');
		$workspace = WikiPage::workspace();
		$page = WikiPage::getById($_['page']);
		File::downloadFile($workspace.SLASH.wiki_os_encode($page->path),null,null,true);
	break;

	/** CATEGORY **/
	//Récuperation d'une liste de page
	case 'wiki_category_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');
			
			$workspace = WikiPage::workspace();
			if(!file_exists($workspace)) mkdir($workspace,0755,true);
			
			
			foreach(WikiCategory::loadAll() as $category){
				$response['rows'][] = $category;
			}
		});
	break;

	case 'wiki_category_edit':
		require_once(__DIR__.SLASH.'modal.category.php');
	break;

	case 'wiki_category_open':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');

			$category = WikiCategory::load(array('slug'=>$_['category']));
			$pages = $category->pages();
			$recents = WikiPage::loadAll(array('category'=>$category->id),array('updated DESC'),array('10'), array('*'), 1);
			ob_start();
			require_once(__DIR__.SLASH.'page.category.php');
			$response['content'] = ob_get_clean();
			
			$response['categorySlug'] = $category->slug;
			$response['pages'] = $pages;
		});
	break;

	case 'wiki_category_download':
		try{
		require_once(__DIR__.SLASH.'WikiCategory.class.php');
		require_once(__DIR__.SLASH.'WikiPage.class.php');
		$workspace = WikiPage::workspace();
		$category = WikiCategory::getById($_['category']);
		$path = $workspace.SLASH.wiki_os_encode($category->path);
		$zipName = tempnam(sys_get_temp_dir(), "zip123");
		if (!extension_loaded('zip')) throw new Exception("L'extension ZIP est manquante");
		$zip = new ZipArchive();
	    if (!$zip->open($zipName, ZIPARCHIVE::CREATE)) 
	        throw new Exception ("Impossible de créer l'archive (problèmes de permissions ?");
	    
	    foreach(glob($path.SLASH.'*.md') as $file){
	    	$zip->addFromString(basename($file), file_get_contents($file));
	    }
	    $zip->close();
	    $stream = file_get_contents($zipName);
	 
	    unlink($zipName);
	    File::downloadStream($stream,$category->slug.'.zip');
	    }catch(Exception $e){
	    	echo 'Erreur : '.$e->getMessage();
	    }
	break;

	//Ajout ou modification d'élément page
	case 'wiki_category_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');
			$workspace = WikiPage::workspace();

			$item = isset($_['id']) && is_numeric($_['id']) ? WikiCategory::getById($_['id']) : new WikiCategory();
			
			$item->icon = $_['icon'];
			$item->color = $_['color'];

			if($item->id==0){
				$item->label = $_['label'];
				$item->slug = slugify($item->label);
				$item->path = WikiPage::path_from_label($item->label);
				$dir = $workspace.SLASH.wiki_os_encode($item->path);
				if(!file_exists($dir)) mkdir($dir,0755,true);
			}else{
				if($item->label!=$_['label']){
					$oldDir = $workspace.SLASH.wiki_os_encode($item->path);

					$item->label = $_['label'] ;
					$item->slug = slugify($item->label);
					$item->path = WikiPage::path_from_label($item->label);

					$newDir = $workspace.SLASH.wiki_os_encode($item->path);
					if(file_exists($newDir)) throw new Exception("Ce nom de catégorie est déja pris");
					rename($oldDir, $newDir);
				}
			}

			$item->save();
			$response = $item->toArray();
		});
	break;

	//Suppression d'élement page
	case 'wiki_category_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');
			WikiPage::delete(array('category'=>$_['id']));
			WikiCategory::deleteById($_['id']);
			
		});
	break;

	/** PAGE **/
	//Ajout ou modification d'élément page
	case 'wiki_page_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');

			$page = WikiPage::provide();
			$page->content = html_entity_decode($_['content']);
			
			if($page->id == 0 && isset($_['category'])){
				$category = WikiCategory::getById($_['category']);
				$page->state = WikiPage::PUBLISHED;
				$page->category = $category->id;
				$page->label = 'Nouvelle page - '.date('d/m/y h:i:s');
				$page->path = $category->path.SLASH.WikiPage::path_from_label($page->label).'.md';
				$page->slug = slugify($page->label);
			} else {
				$category = WikiCategory::getById($page->category);
				
				if($page->label!=$_['label']){
					$oldPath = WikiPage::workspace().SLASH.wiki_os_encode($page->path);
					$page->label = $_['label'];
					$page->path = $category->path.SLASH.WikiPage::path_from_label($page->label).'.md';
					$page->slug = slugify($page->label);

					$newPath = WikiPage::workspace().SLASH.wiki_os_encode($page->path);
					if(file_exists($newPath)) throw new Exception("Ce nom de page pour cette catégorie est déja pris");
					unlink($oldPath);
				}
			}
			if(isset($page->content)) file_put_contents(WikiPage::workspace().SLASH.wiki_os_encode($page->path),$page->content);
			$page->save();
			
			ob_start();
			require_once(__DIR__.SLASH.'page.page.php');
			$response['content'] = ob_get_clean();
			$response['page'] = $page->toArray();
			$response['category'] = $category->toArray();
		});
	break;

	//Suppression d'élement page
	case 'wiki_page_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			$page = WikiPage::getById($_['id']);
			$category = WikiCategory::getById($page->category);
			$response['category']= $category->toArray();
			WikiPage::deleteById($page->id);
			$path = WikiPage::workspace().SLASH.wiki_os_encode($page->path);
			if(file_exists($path)) unlink($path);
		});
	break;

	case 'wiki_page_open':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');

			$page = WikiPage::load(array('slug'=>$_['page']));
			if(!$page){
				$page = new WikiPage();
				$page->label = $_['page'];
			}
			$category = WikiCategory::load(array('slug'=>$_['category']));

			ob_start();
			require_once(__DIR__.SLASH.'page.page.php');
			$response['content'] = ob_get_clean();
			$response['categorySlug'] = $category->slug;
			if($page->id!=0) $response['pageSlug'] = $page->slug;
		});
	break;
	
	//Sauvegarde des configurations de wiki
	case 'wiki_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('wiki','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('wiki') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value)
				if(in_array($key, $allowed)) $conf->put($key,$value);

			if(!empty($_FILES['logo']) && $_FILES['logo']['size']!=0 ){
			    $logo = File::upload('logo','wiki'.SLASH.'logo'.SLASH.'logo.{{ext}}', 1048576, array('jpg','png','jpeg'));
			    Image::resize($logo['absolute'], 38, 38, false);
			    Image::toPng($logo['absolute']);
			}
		});
	break;

	case 'wiki_file_upload':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('wiki','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'WikiPage.class.php');
			$uploads = WikiPage::uploads().SLASH;
			if(!file_exists($uploads)) mkdir($uploads,0755,true);
			$maxSize = $conf->get('wiki_max_size') * 1048576;
			$extensions = explode(',',str_replace(' ', '', $conf->get('wiki_ext'))); 
			$response['rows'] = array();

			if(!is_array($_FILES['file']['name'])){
				$_FILES['file']['name'] = array($_FILES['file']['name']);
				$_FILES['file']['size'] = array($_FILES['file']['size']);
				$_FILES['file']['tmp_name'] = array($_FILES['file']['tmp_name']);
			}
			for ($i=0; $i<count($_FILES['file']['name']); $i++) {

				$extension = getExt($_FILES['file']['name'][$i]);
				if($_FILES['file']['size'][$i] > $maxSize) throw new Exception("Taille du fichier ".$_FILES['file']['name'][$i]." trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)');
				if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$_FILES['file']['name'][$i]." non permise, autorisé :".implode(', ',$extensions));
				
				$filePath = $uploads.wiki_os_encode($_FILES['file']['name'][$i]);

				$u = 0;
				while(file_exists($filePath)){
					$u++;
					$filePath = $uploads.$u.'_'.wiki_os_encode($_FILES['file']['name'][$i]);
				}

				rename($_FILES['file']['tmp_name'][$i],$filePath);

				$row = array(
					'name'=>$_FILES['file']['name'][$i],
					'relative'=>str_replace($uploads,'',$filePath),
					'absolute'=>$filePath,
				);
				
				switch($extension){
				case 'jpg':
				case 'jpeg':
				case 'gif':
				case 'png':
					$row['tag'] = '!['.$row['name'].'](action.php?action=wiki_file_read&file='.base64_encode($row['relative']).')';
				break;
				default:
					$row['tag'] = '['.$row['name'].'](action.php?action=wiki_file_read&file='.base64_encode($row['relative']).')';
				break;
				}
				$response['rows'][] = $row;
				Log::put("Upload d'un élément : ".$filePath,'WIKI');
			}
		});
	break;

	case 'wiki_file_read':
		global $myUser,$_,$conf;
		if(!$myUser->can('wiki','read')) throw new Exception("Permissions insuffisantes",403);
		File::downloadFile('file/wiki/uploads/'.base64_decode($_['file']));
	break;

	case 'wiki_night_mode':
		Action::write(function(&$response){
			global $myUser,$_,$conf;

			$myUser->preference('wiki_night_mode', isset($_['nightmode']) && !empty($_['nightmode'])?true:false);
			$myUser->loadPreferences();
		});
	break;

}
?>