<?php
global $_,$conf;

	//Récuperation d'une liste de element
	Action::register('document_element_search',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);





				foreach (Element::staticQuery($query,$data,true) as $element){
					// Check des partages sur l'élément
					if(!Element::hasRight($element,'read')) continue;

					// 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['link'] = $line->link;
					$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['link'] = $line->link;
					$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']['sortable'],array('label','size','creator','updated'))? $_['sort']['sortable']: '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');
			}
		});

	Action::register('document_element_tree_search',function(&$response){
		global $_,$myUser;
		if(!$myUser->can('document','read')) return;
		require_once(__DIR__.SLASH.'Element.class.php');
		if(isset($_['folder']) && !empty($_['folder'])){
			$folder = str_replace('/',SLASH,$_['folder']);
		}else{
			$folder = '.';
			if(isset($_['root'])) $folder = str_replace('/',SLASH,$_['root']);
		}

		if(strlen($folder)>=2 && substr($folder, 0,2)=='./') $folder = substr($folder,2);

		//Récuperation de tous les dossiers pour l'arborescence
		$response['tree'] = array();
		$parentFolder = dirname($folder);
		$parentFolder = $parentFolder == '.' ? '' : $parentFolder;

		$level = count(explode('/',$folder));
		$parentLevel = $level-1 < 0 ? 0 : $level-1;

		$parts = explode('/',$folder);
		$path = '';
		$level = 0;
		$query = 'SELECT * FROM {{table}} WHERE type = ? ';
		$data = array('directory');

		$query .=' AND ( ';
		$query .= ' (`path` LIKE ? AND LENGTH(`path`) - LENGTH(REPLACE(`path`, \'/\', \'\')) = ?) ';
		$data[] = '%';
		$data[] = 0;

		foreach($parts as $part){
			$level++;
			$path.= ($level==1?'':'/').$part;
			$query .=' OR ';
			$query .= ' (`path` LIKE ? AND LENGTH(`path`) - LENGTH(REPLACE(`path`, \'/\', \'\')) = ?) ';
			$data[] = $path.'/%';
			$data[] = $level;
		}

		$query .=' ) ORDER BY `path`';

		$elements = Element::staticQuery($query,$data,true);
		foreach($elements as $directory){
			$osPath = Element::root().str_replace('/',SLASH,$directory->path);
			//limitation a la root si existante
			if(!empty($_['root']) && strpos($directory->path,$_['root']) === false) continue;
			if(!file_exists($osPath)){
				Element::deleteById($directory->id);
				continue;
			}

			$response['tree'][] =$directory->path;
		}

	});

	Action::register('document_load_template',function(&$response){
		global $myUser,$_;
		User::check_access('document','read');
		require_once(__DIR__.SLASH.'template.document.php');
		exit();
	});

	Action::register('document_widget_load',function(&$response){
		global $myUser;
		User::check_access('document','read');
		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);
		exit();
	});

	Action::register('document_widget_configure_save',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();

	});


	Action::register('document_widget_configure',function(&$response){
		global $myUser;
		require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
		User::check_access('document_widget_configure','read');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.configure.php');
		$content = ob_get_clean();
		echo $content ;
		exit();
	});

	Action::register('document_embedded',function(&$response){
			User::check_access('document','read');
			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();

	});

	Action::register('document_folder_create',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;
			$char = document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['folder']), ENT_QUOTES));
			if(!empty($char)) throw new Exception("Caractères interdits : ".$char);

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


	Action::register('document_element_preview',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;
	});

	Action::register('document_properties_show',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();

			$filePath = Element::root().$element->path;
			$row['updatedLabel'] = date('d/m/Y H:i',filemtime($filePath));

			$bundle = base64_encode(json_encode(array(
				'root' => $element->path,
				'folder' => '',
			)));
			$row['rootUrl'] = ROOT_URL.'/index.php?module=document&data='.$bundle;
			$response['row'] = $row;
	});

	Action::register('document_element_execute',function(&$response){
		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 = get_OS() === '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);
		exit();
	});

	Action::register('document_element_move',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.');
			/*
				nb: cette ligne permet d'eviter d'ajouter un ./ devant le path de la bdd pour ce fichier lorsqu'il est déplacé
				si le ./ est présent, la méthode browse (qui retourne le cehmin sans le ./) ne match pas avec la ligne en bdd et créé
				une nouvelle ligne, ce qui rend le proprietaire du fichier anonymous
			*/
			if($_['to']=='.') $_['to'] = '';

			$to = Element::root().$_['to'];
			$osTo = File::convert_decoding($to);
			if(!is_dir($osTo)) return;
			$char = document_check_element_name(basename(htmlspecialchars_decode(html_entity_decode($to), ENT_QUOTES)));
			if(!empty($char)) throw new Exception("Caractères interdits : ".$char);
			$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');
	});

	Action::register('document_element_rename',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 doit 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 se 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.');
			$char = document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['label']), ENT_QUOTES));
			if(!empty($char)) throw new Exception("Caractères interdits : ".$char);

			$element = Element::move($from,$to);

			if(!$element) throw new Exception("Erreur lors de la récupération de l'élément 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');
	});

	Action::register('document_element_delete',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');
	});

	//edition d'un fichier (chargement)
	Action::register('document_element_edit',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é entre temps, veuillez recharger la page.");

			$response['path'] = $path;
			$response['label'] = mt_basename($path);
			$response['content'] = Element::download($path);
			if(in_array(getExt($path), array('html','htm'))) $response['wysiwyg'] = true;
	});

	//edition d'un fichier (sauvegarde)
	Action::register('document_element_save',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');
			if($maxSize=='') $maxSize = 28060000;
			$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);
	});

	//upload d'un fichier
	Action::register('document_element_upload',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(isset($_['method']) && $_['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');

	});

	//Sauvegarde des configurations de document
	Action::register('document_setting_save',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);

	});

	/** ELEMENTRIGHT **/
	//Récuperation d'une liste de elementright
	Action::register('document_right_search',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;
			}


	});

	//Ajout ou modification d'élément elementright
	Action::register('document_right_save',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();

	});

	//Suppression d'élement elementright
	Action::register('document_right_delete',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);

	});


?>
