<?php

	/** COMMON **/
	Action::register('wiki_logo_download',function(&$response){
		global $myUser;
		if(!$myUser->connected()) throw new Exception("Permission denied");
		$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);

		File::downloadFile($logo);
		exit();
	});

	Action::register('wiki_logo_delete',function(&$response){
	
		    global $myUser,$_;
		    User::check_access('wiki','configure');

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

		    Log::put("Suppression du logo",'Wiki');
		
	});

	/** HOME **/
	Action::register('wiki_page_home',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','read');

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

	Action::register('wiki_page_search',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','read');
			Log::put("Recherche lancée avec les mots clés : ".$_['term'],'Wiki');

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

	Action::register('wiki_page_download',function(&$response){
		User::check_access('wiki','read');
		require_once(__DIR__.SLASH.'WikiPage.class.php');
		$workspace = WikiPage::workspace();
		$page = WikiPage::getById($_['page']);
	    Log::put("Téléchargement de la page ".$workspace.SLASH.$page->path,'Wiki');
	    
		File::downloadFile($workspace.SLASH.wiki_os_encode($page->path),null,null,true);
	});


	/** CATEGORY **/
	//Récuperation d'une liste de page
	Action::register('wiki_category_search',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','read');
			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(array(), array('sort','label')) as $category){
				$response['rows'][] = $category;
			}
		
	});

	Action::register('wiki_category_edit',function(&$response){
		User::check_access('wiki','read');
		require_once(__DIR__.SLASH.'modal.category.php');
	});

	Action::register('wiki_category_open',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','read');
			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;

	 		Log::put("Consultation de la catégorie ".$category->toText(),'Wiki');
		
	});

	Action::register('wiki_category_download',function(&$response){
		try{
		User::check_access('wiki','read');
		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);
	 	Log::put("Téléchargement de la catégorie ".$workspace.SLASH.$category->path,'Wiki');
	 	
	    unlink($zipName);
	    File::downloadStream($stream,$category->slug.'.zip');
	    }catch(Exception $e){
	    	echo 'Erreur : '.$e->getMessage();
	    }
	});

	//Ajout ou modification d'élément page
	Action::register('wiki_category_save',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','edit');
			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();
			Log::put("Création/Modification de catégorie :".$item->toText(),'Wiki');
		
	});

	//Suppression d'élement page
	Action::register('wiki_category_delete',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','delete');
			require_once(__DIR__.SLASH.'WikiCategory.class.php');
			require_once(__DIR__.SLASH.'WikiPage.class.php');
			$category = WikiCategory::getById($_['id']);
			WikiPage::delete(array('category'=>$_['id']));
			WikiCategory::deleteById($_['id']);
			Log::put("Suppression de catégorie :".$category->toText(),'Wiki');
		
	});

	/** PAGE **/


	Action::register('wiki_page_move',function(&$response){
	
		global $myUser,$_;
		User::check_access('wiki','edit');
		if(empty($_['category'])) throw new Exception("catégorie non spécifiée", 400);
		require_once(__DIR__.SLASH.'WikiPage.class.php');
		require_once(__DIR__.SLASH.'WikiCategory.class.php');

		$page = WikiPage::provide('page');
		$category = WikiCategory::getById($_['category']);

		$page->category = $category->id;

		$oldPath = $page->path;
		$page->path = $category->path.SLASH.WikiPage::path_from_label($page->label).'.md';


		$oldPath = WikiPage::workspace().SLASH.wiki_os_encode($oldPath);
		$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");
		if(!file_exists($oldPath)) throw new Exception("Impossible de retrouver l'ancien chemin de la page");
		rename($oldPath, $newPath);

		$page->save();

	
	});

	//tri des pages
	Action::register('wiki_page_sort',function(&$response){
	
		global $myUser,$_;
		User::check_access('wiki','edit');
		if(empty($_['sort'])) throw new Exception("tri non spécifiée", 400);
		require_once(__DIR__.SLASH.'WikiPage.class.php');

		foreach ($_['sort'] as $sort => $id) {
			$page = WikiPage::getById($id);
			$page->sort = $sort;
			$page->save();
		}

	
	});

	//tri des categories
	Action::register('wiki_category_sort',function(&$response){
	
		global $myUser,$_;
		User::check_access('wiki','edit');
		if(empty($_['sort'])) throw new Exception("tri non spécifiée", 400);
		require_once(__DIR__.SLASH.'WikiCategory.class.php');

		foreach ($_['sort'] as $sort => $id) {
			$page = WikiCategory::getById($id);
			$page->sort = $sort;
			$page->save();
		}

	
	});

	//Ajout ou modification d'élément page
	Action::register('wiki_page_save',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','edit');
			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->content = WikiPage::defaultContent();
				$page->slug = slugify($page->label);
			} else {
				$category = WikiCategory::getById($page->category);
				if(!isset($_['label']) || empty($_['label'])) throw new Exception("Le nom de la page ne peut être vide");
				
				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();

			Log::put("Création/Modification de page :".$page->toText(),'Wiki');
		
	});

	//Suppression d'élement page
	Action::register('wiki_page_delete',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','delete');
			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);

			Log::put("Suppression de page :".$page->toText(),'Wiki');
		
	});

	Action::register('wiki_page_open',function(&$response){
	
			global $myUser,$_;
			User::check_access('wiki','read');
			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;

			Log::put("Consultation de page :".$page->toText(),'Wiki');
		
	});
	
	//Sauvegarde des configurations de wiki
	Action::register('wiki_setting_save',function(&$response){
	
			global $myUser,$_,$conf;
			User::check_access('wiki','configure');
			foreach(Configuration::setting('wiki') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}

			if(!empty($_['fields']['wiki_default_content'])){
				$defaultFile = File::dir().'wiki'.SLASH.'default.md';
				file_put_contents($defaultFile, $_['fields']['wiki_default_content']);
				unset($_['fields']['wiki_default_content']);
			}


			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']);
			}



			Log::put("Enregistrement des réglages : ".implode(', ', $_['fields']),'Wiki');
		
	});

	Action::register('wiki_file_upload',function(&$response){
	
			global $myUser,$_,$conf;
			User::check_access('wiki','edit');
			if(!isset($_FILES['file']) || empty($_FILES)) return;
			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]);
				}


				
				
				$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']).')';
					rename($_FILES['file']['tmp_name'][$i],$filePath);
				break;
				case 'md':
					$row['tag'] = file_get_contents($_FILES['file']['tmp_name'][$i]);
				break;
				default:
					$row['tag'] = '['.$row['name'].'](action.php?action=wiki_file_read&file='.base64_encode($row['relative']).')';
					rename($_FILES['file']['tmp_name'][$i],$filePath);
				break;
				}
				$response['rows'][] = $row;
				Log::put("Upload d'un élément : ".$filePath,'Wiki');
			}
	});

	Action::register('wiki_file_read',function(&$response){
		global $myUser,$_,$conf;
		User::check_access('wiki','read');
		File::downloadFile('file/wiki/uploads/'.base64_decode($_['file']));
	});

	Action::register('wiki_night_mode',function(&$response){
	
			global $myUser,$_,$conf;
			if(!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
			$myUser->preference('wiki_night_mode', isset($_['nightmode']) && !empty($_['nightmode'])?true:false);
			$myUser->loadPreferences();
		
	});


?>