<?php
global $_,$conf;
switch($_['action']){

	case 'document_load_template':
		
		global $myUser,$_;
		require_once(__DIR__.SLASH.'template.document.php');
		
	break;

	case 'document_widget_load':
		global $myUser;
		require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		
		$root = $widget->data('widget-document-root');
		$root = !empty($root) ? ': <strong>'.$root.')</strong>':'';

		$widget->title = 'Mes documents'.$root;
		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
	break;

	case 'document_widget_configure_save':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

			User::check_access('document','configure');

			$widget = DashboardWidget::getById($_['id']);
			
			$widget->data('widget-document-tree',$_['widget-document-tree']);
			$widget->data('widget-document-detail',$_['widget-document-detail']);
			$widget->data('widget-document-search',$_['widget-document-search']);

			$root = str_replace(array('./','../'),'',$_['widget-document-root']);
			$widget->data('widget-document-root',$root);
			
			$widget->save();
		});
	break;

	case 'document_widget_configure':
		global $myUser;
		require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.configure.php');
		$content = ob_get_clean();
		echo $content ;
	break;


	

	case 'document_embedded':
		Action::write(function(&$response){
			Plugin::addCss("/css/main.css"); 
			Plugin::addJs("/js/main.js"); 

			ob_start();
			global $myUser,$_;
			$embedded = true;
			//l'ui de la ged prend en entrée / quel que soit l'os
			if(isset($_['data']['root'])) $_['data']['root'] = str_replace('\\', '/', $_['data']['root']);
			require_once(__DIR__.SLASH.'page.list.php');
			$response['html'] = ob_get_clean();
		});
	break;


	case 'document_folder_create':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');
			$path = str_replace('/',SLASH,$_['path']);
			$path =  Element::root().$path;
			if(!document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['folder']), ENT_QUOTES))) throw new Exception("Caractères interdits : \\/:*?\"<>|");

			if(strlen($_['folder']) > 80) throw new Exception("Taille maximale autorisée de 80 caractères.");
			Element::addFolder($path);
			if($conf->get('document_enable_logs'))  Log::put("Création d'un dossier : ".$path,'document');

		});
	break;

	

	/** ELEMENT **/	


	//Récuperation d'une liste de element
	case 'document_element_search':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','read');
			require_once(__DIR__.SLASH.'Element.class.php');
			
			
			//recherche par libellé
			if(!empty($_['keyword'])){
				$query = 'SELECT * FROM {{table}} WHERE 1';
				$data = $elements = array();
				
				$query .= ' AND label LIKE ?';
				$data[] = '%'.$_['keyword'].'%';				

				$folder = isset($_['folder']) && !empty($_['folder']) ? $_['folder'] : '.';
				if(isset($_['folder']) && !empty($_['folder']))
					$query .= ' AND `path` LIKE "'.$_['folder'].'%'.'"';

				
				//Tri des colonnes
				if(isset($_['sort'])) sort_secure_query($_['sort'],array('label','creator','size'),$query,$data);

				$response['qry'] = $query;
				foreach (Element::staticQuery($query,$data,true) as $element) {
					// Check pour ne pas faire ressortir le dossier lui même
					if ($element->path == $folder) continue;
					$elemPath =str_replace(SLASH.'.'.SLASH,SLASH,Element::root().$element->path) ;
					$line = Element::fromPath($elemPath);
					$line->path = rtrim($line->path, SLASH);

					$osPath = Element::root().str_replace('/',SLASH,$line->path);
					if(!file_exists($osPath)){
						Element::deleteById($line->id);
						continue;
					}

					$row = $line->toArray();
					
					$row['updatedRelative'] = relative_time($line->updated);
					$row['sizeReadable'] = $row['type'] == 'directory' ? $line->childNumber.' élements' :  readable_size($line->size);
					$row['updatedReadable'] = day_name(date('N',$line->updated)).' '. date('d ',$line->updated).month_name(date('m',$line->updated)).date(' Y à H:i',$line->updated);
					$row['thumbnail'] = $line->thumbnail();
					$row['icon'] = $line->icon();
					$row['childNumber'] = $line->childNumber;
					

					$elements[] = $row;
				}

				$response['rows'] = $elements;
			//recherche par arborescence
			}else{
				if(isset($_['folder']) && !empty($_['folder'])){
				$folder = str_replace('/',SLASH,$_['folder']);
				}else {
					$folder = '.';
					if(isset($_['root'])) $folder = str_replace('/',SLASH,$_['root']);
				}

				$response['rows'] = array();
				$scanned = Element::root().$folder.SLASH.'*';
				//L'ui ne traite que les / quel que soit l'os
				foreach (Element::browse($scanned) as $line) {
					$line->path = str_replace('\\', '/', $line->path);
					$row = $line->toArray();

					$row['updatedRelative'] = relative_time($line->updated);
					$row['sizeReadable'] = $row['type'] == 'directory' ? $line->childNumber.' élements' :  readable_size($line->size);
					$row['updatedReadable'] = day_name(date('N',$line->updated)).' '. date('d ',$line->updated).month_name(date('m',$line->updated)).date(' Y à H:i',$line->updated);
					$row['thumbnail'] = $line->thumbnail();
					$row['icon'] = $line->icon();

					$row['childNumber'] = $line->childNumber;
			
					$response['rows'][] = $row;
				}

				//tri du résultat si demandé
				if(isset($_['sort'])){
					$direction = $_['sort']['sort'] == 'asc' ? 1:-1 ;
					//le in_array permet de s'assurer qu'une colonne triable est spécifiée
					$attribute = in_array($_['sort']['column'],array('label','size','creator','updated'))? $_['sort']['column']: 'label';
					usort($response['rows'],function($a,$b) use($attribute,$direction){
							if($a[$attribute] > $b[$attribute]) return 1*$direction;
							if($a[$attribute] < $b[$attribute]) return -1*$direction;
							if($a[$attribute] == $b[$attribute]) return 0;
					});
				}

				if($conf->get('document_enable_logs_verbose')) Log::put('Ouverture du dossier '.str_replace(array('/','\\',SLASH.'.'.SLASH.'*'),array(SLASH,SLASH,''),$scanned).' ','document');

				

			}


			
		});
	break;

	case 'document_element_preview':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('document','read');
			require_once(__DIR__.SLASH.'Element.class.php');
			
			//l'ui ne renvois que les /, on les convertis par le separateur de l'os
			$_['path'] = str_replace('/', SLASH, $_['path']);

			$path = str_replace(SLASH.'.'.SLASH,SLASH,Element::root().$_['path']);
			
			$osPath = File::convert_decoding($path);
			if(!file_exists($osPath)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
			$element = Element::fromPath($path);

			//L'ui ne traite que les / quel que soit l'os
			$element->path = str_replace('\\', '/', $element->path);

			$row = $element->toArray();
			$row['updatedRelative'] = relative_time($element->updated);
			$row['sizeReadable'] = readable_size($element->size);
			$row['updatedReadable'] = day_name(date('N',$element->updated)).' '. date('d ',$element->updated).month_name(date('m',$element->updated)).date(' Y à H:i',$element->updated);
			$row['thumbnail'] = $element->thumbnail();
			$row['icon'] = $element->icon();
			$row['childNumber'] = $element->childNumber;


			$response['row'] = $row;
		});
	break;

	case 'document_properties_show':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('document','read');
			require_once(__DIR__.SLASH.'Element.class.php');

			$element = Element::provide();
			$element->path = str_replace('\\', '/', $element->path);
			$row = $element->toArray();
			$row['createdLabel'] = date('d/m/Y H:i',$element->updated);
			$row['updatedLabel'] = date('d/m/Y H:i',$element->updated);
			$bundle = base64_encode(json_encode(array(
				'root' => $element->path,
				'folder' => '',
			)));
			$row['rootUrl'] = ROOT_URL.'/index.php?module=document&data='.$bundle;
			$response['row'] = $row;
		});
	break;

	case 'document_element_execute':
		global $myUser,$_,$conf;
		User::check_access('document','read');
		require_once(__DIR__.SLASH.'Element.class.php');
		
		$isopath =  Element::root().base64_decode(rawurldecode($_['path']));
		$utf8Path = utf8_encode($isopath);
		$osPath = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? $isopath : $utf8Path;
		
		$stream = Element::download($utf8Path);
		$name = mt_basename($utf8Path);
		
		$mime = 'application/octet-stream';
		if(is_dir($osPath)){
			$mime = 'application/zip';
			$name .= '.zip';
		}
		if($conf->get('document_enable_logs_verbose')) Log::put('Téléchargement de '.$utf8Path,'document');
		File::downloadStream($stream, $name, $mime);
	break;


	case 'document_element_move':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');

			//l'ui ne renvois que les /, on les convertis par le separateur de l'os
			$_['from'] = str_replace('/', SLASH, $_['from']);
			$_['to'] = str_replace('/', SLASH, $_['to']);

			$from =  Element::root().$_['from'];
			$osFrom =  File::convert_decoding($from);
			if(!file_exists($osFrom)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
			//if($_['to']=='.') $_['to'] = '';
			
			$to = Element::root().$_['to'];
			$osTo = File::convert_decoding($to);
			if(!is_dir($osTo)) return;

			if(!document_check_element_name(basename(htmlspecialchars_decode(html_entity_decode($to), ENT_QUOTES)))) throw new Exception("Caractères interdits : \\/:*?\"<>|");
			$to .= SLASH.basename($from);

			$element = Element::move($from,$to);
			$response['element'] = $element;
			if($conf->get('document_enable_logs')) Log::put('Déplacement de '.$from.' dans '.$to,'document');
		});
	break;

	case 'document_element_rename':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');

			//les exception vides reset le champ de l'ui sans afficher d'erreur
			if(!isset($_['label']) || empty($_['label'])) throw new Exception("Le nom ne dois pas être vide");

			if(strlen($_['label']) > 80) throw new Exception("Taille maximale autorisée de 80 caractères.");
			
			//l'ui ne renvois que les /, on les convertis par le separateur de l'os
			$_['path'] = str_replace('/', SLASH, $_['path']);
			$from =  Element::root().$_['path'];
			$fromOs =  File::convert_decoding($from);
			if(!file_exists($fromOs)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');


			if(is_dir($fromOs) && substr($_['label'], -1,1)=='.') throw new Exception("Les dossiers ne peuvent pas terminer par un .");
			

			$to =  dirname($from).SLASH.$_['label'];

			if(file_exists($to)) throw new Exception('Action impossible, un élément existe déjà avec ce nom.');
				

		
			if(!document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['label']), ENT_QUOTES))) throw new Exception("Caractères interdits : \\/:*?\"<>|");
			$element = Element::move($from,$to);
			
			if(!$element) throw new Exception("Erreur lors de la récuperation de l'élement renommé", 500);
			
			$element->path = str_replace('\\', '/', $element->path);
			$response['element'] = $element;
			if($conf->get('document_enable_logs') ) Log::put('Renommage de l\'élément : '.$from.' en '.$to,'document');
		});
	break;

	case 'document_element_delete':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','delete');
			require_once(__DIR__.SLASH.'Element.class.php');

			
			
			//l'ui ne renvois que les /, on les convertis par le separateur de l'os
			$path =  Element::root().str_replace('/', SLASH,$_['path']);
			$osPath =  File::convert_decoding($path);
			if(!file_exists($osPath)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
			Element::remove($path);

			$extension = getExt($path);
			if( in_array($extension, array('jpg','jpeg','png','gif','bmp'))) {

				$thumbname = str_replace(array('\\'),array('/'),$_['path']);
				$thumbpath = Element::root().'.thumbnails'.SLASH.base64_encode($thumbname).'.'.$extension;
				if(file_exists($thumbpath)) unlink($thumbpath);
			}

			if($conf->get('document_enable_logs')) Log::put("Suppression d'un élément : ".$path,'document');
		});
	break;

	//edition d'un fichier (chargement)
	case 'document_element_edit':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');

			if(!isset($_['path'])) throw new Exception("Veuillez spécifier le chemin du fichier");
			$path = str_replace(array('..'),'',$_['path']);


			$path = Element::root().$path;
			$osPath = File::convert_decoding($path);

			if(!file_exists($osPath)) throw new Exception("Impossible de trouver le fichier, peut être a t-il été supprimé entree temps, veuillez recharger la page.");
			
			
			$response['path'] = $path;
			$response['label'] = mt_basename($path);
			$response['content'] = Element::download($path);

		});
	break;

	//edition d'un fichier (sauvegarde)
	case 'document_element_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');

			if(!isset($_['label'])) throw new Exception("Veuillez spécifier le nom du fichier");
			$label = str_replace(array('..','/','\\'),'',$_['label']);


			$path = Element::root().$_['path'].SLASH;
			$osPath = File::convert_decoding($path);

			$content = html_entity_decode($_['content']);

			$maxSize = $conf->get('document_allowed_size');
			$extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
			$extension = getExt($_['label']);
			if(strlen($content) > $maxSize) throw new Exception("Taille du fichier ".$_['label']." trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)');
			if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$_['label']." non permise, autorisé :".implode(', ',$extensions));
			$filePath =  $path.$_['label'];
			Element::addFile($filePath,$content);

		});
	break;

	//upload d'un fichier
	case 'document_element_upload':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'Element.class.php');

			$response['sort'] = $_['sort'];

			if(empty($_FILES)) throw new Exception("Aucun document à importer");
			


			$path = Element::root().$_['path'].SLASH;
			$osPath = File::convert_decoding($path);

			if(!file_exists($osPath)) throw new Exception("Dossier ".$osPath." introuvable");
			
			$maxSize = $conf->get('document_allowed_size');
			$extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
			


			

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


			if($_['method'] == 'paste') $_FILES['file']['name'][0] = 'presse papier '.date('d-m-Y H-i-s').'.'.$extension;

			$filePath =  $path.$_FILES['file']['name'][0];

			if(!file_exists($_FILES['file']['tmp_name'][0]))  throw new Exception("Fichier temporaire n°".$_['sort']." inexistant, verifiez la clause upload_max_size de PHP.");
			
			
			
			Element::addFile($filePath,file_get_contents($_FILES['file']['tmp_name'][0]));
			
			if($conf->get('document_enable_logs')) Log::put("Upload d'un élément : ".$filePath,'document');
		

			
		});
	break;

	//Sauvegarde des configurations de document
	case 'document_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			User::check_access('document','configure');

			foreach(Configuration::setting('document') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value)
				if(in_array($key, $allowed)) $conf->put($key,$value);
		});
	break;



	/** ELEMENTRIGHT **/
	//Récuperation d'une liste de elementright
	case 'document_right_search':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('document','read');
			require_once(__DIR__.SLASH.'ElementRight.class.php');
			
			$rights = ElementRight::loadAll(array('element'=>$_['id']));
			foreach($rights as $right){
				if($right->entity =='rank'){
					$rank = Rank::getById($right->uid);
					if(!$rank) continue;
					$right->uid = $rank->label.' <small class="text-muted">(rang)</small>';
				}
				$row = $right->toArray();
				if($row['read'] == 0) unset($row['read']);
				if($row['edit'] == 0) unset($row['edit']);
				if($row['recursive'] == 0) unset($row['recursive']);
				$response['rows'][] = $row;
			}
			
		});
	break;

	//Ajout ou modification d'élément elementright
	case 'document_right_save':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('document','edit');
			require_once(__DIR__.SLASH.'ElementRight.class.php');
			require_once(__DIR__.SLASH.'Element.class.php');

			if(!isset($_['uid']) || empty($_['uid'])) throw new Exception("UID de partage non spécifié");

			$element = Element::provide('element');
			if(!$element) throw new Exception("Cet élément n'existe pas",404);
			if($element->creator != $myUser->login && !$myUser->can('document','configure') && !$myUser->superadmin) throw new Exception("Vous n'êtes pas propriétaire de cet élement",403);

			$item = ElementRight::provide();
			$item->element = $element->id;
			$item->recursive =  isset($_['recursive']) ? $_['recursive'] : 0 ;
			$item->edit = isset($_['edit']) ? $_['edit'] : 0 ;
			$item->read = isset($_['read']) ? $_['read'] : 0 ;
			$item->uid = $_['uid'];
			$item->entity = is_numeric($_['uid']) ? 'rank' : 'user';
			//supression des anciens droits sur le même couple element / utilisateur si existants
			ElementRight::delete(array('element'=>$item->element,'entity'=>$item->entity,'uid'=>$item->uid));

			$item->save();
		});
	break;
	
	//Suppression d'élement elementright
	case 'document_right_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('document','delete');
			require_once(__DIR__.SLASH.'ElementRight.class.php');
			require_once(__DIR__.SLASH.'Element.class.php');
			$right = ElementRight::provide('id',1);
			$element = $right->join('element');
			if(!$element) throw new Exception("Cet élément n'existe pas",404);
			if($element->creator != $myUser->login && !$myUser->can('document','configure') && !$myUser->superadmin) throw new Exception("Vous n'etes pas propriétaire de cet élement",403);

			ElementRight::deleteById($right->id);
		});
	break;

}
?>