32function SetXmlHeaders()
38 header(
'Expires: Mon, 26 Jul 1997 05:00:00 GMT');
40 header(
'Last-Modified: '.gmdate(
'D, d M Y H:i:s').
' GMT');
42 header(
'Cache-Control: no-store, no-cache, must-revalidate');
43 header(
'Cache-Control: post-check=0, pre-check=0',
false);
45 header(
'Pragma: no-cache');
48 header(
'Content-Type: text/xml; charset=utf-8');
59function CreateXmlHeader($command, $resourceType, $currentFolder)
64 echo
'<?xml version="1.0" encoding="utf-8" ?>';
67 echo
'<Connector command="'.$command.
'" resourceType="'.$resourceType.
'">';
70 echo
'<CurrentFolder path="'.ConvertToXmlAttribute($currentFolder).
'" url="'.ConvertToXmlAttribute(GetUrlFromPath($resourceType, $currentFolder, $command)).
'" />';
72 $GLOBALS[
'HeaderSent'] =
true;
80function CreateXmlFooter()
92function SendError($number, $text)
94 if ($_GET[
'Command'] ==
'FileUpload') {
95 SendUploadResults((
string) $number,
"",
"", $text);
98 if (isset($GLOBALS[
'HeaderSent']) && $GLOBALS[
'HeaderSent']) {
99 SendErrorNode($number, $text);
104 dol_syslog(
'Error: '.$number.
' '.$text, LOG_ERR);
107 echo
'<?xml version="1.0" encoding="utf-8" ?>';
111 SendErrorNode($number, $text);
125function SendErrorNode($number, $text)
128 echo
'<Error number="'.$number.
'" text="'.htmlspecialchars($text).
'" />';
130 echo
'<Error number="'.$number.
'" />';
144function GetFolders($resourceType, $currentFolder)
147 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFolders');
152 $oCurrentFolder = @opendir($sServerDir);
154 if ($oCurrentFolder !==
false) {
155 while ($sFile = readdir($oCurrentFolder)) {
156 if ($sFile !=
'.' && $sFile !=
'..' && is_dir($sServerDir.$sFile)) {
157 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
160 closedir($oCurrentFolder);
166 natcasesort($aFolders);
167 foreach ($aFolders as $sFolder) {
182function GetFoldersAndFiles($resourceType, $currentFolder)
185 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFoldersAndFiles');
191 $oCurrentFolder = @opendir($sServerDir);
193 if ($oCurrentFolder !==
false) {
194 while ($sFile = readdir($oCurrentFolder)) {
195 if ($sFile !=
'.' && $sFile !=
'..') {
196 if (is_dir($sServerDir.$sFile)) {
197 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
199 $iFileSize = @filesize($sServerDir.$sFile);
203 if ($iFileSize > 0) {
204 $iFileSize = round($iFileSize / 1024);
205 if ($iFileSize < 1) {
210 $aFiles[] =
'<File name="'.ConvertToXmlAttribute($sFile).
'" size="'.$iFileSize.
'" />';
214 closedir($oCurrentFolder);
218 natcasesort($aFolders);
221 foreach ($aFolders as $sFolder) {
228 natcasesort($aFiles);
231 foreach ($aFiles as $sFiles) {
245function CreateFolder($resourceType, $currentFolder)
250 if (isset($_GET[
'NewFolderName'])) {
251 $sNewFolderName =
GETPOST(
'NewFolderName');
252 $sNewFolderName = SanitizeFolderName($sNewFolderName);
254 if (strpos($sNewFolderName,
'..') !==
false) {
255 $sErrorNumber =
'102';
258 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'CreateFolder');
260 if (is_writable($sServerDir)) {
261 $sServerDir .= $sNewFolderName;
263 $sErrorMsg = CreateServerFolder($sServerDir);
265 switch ($sErrorMsg) {
269 case 'Invalid argument':
270 case 'No such file or directory':
271 $sErrorNumber =
'102';
274 $sErrorNumber =
'110';
278 $sErrorNumber =
'103';
282 $sErrorNumber =
'102';
286 echo
'<Error number="'.$sErrorNumber.
'" />';
298function FileUpload($resourceType, $currentFolder, $sCommand, $CKEcallback =
'')
306 if (isset($_FILES[
'NewFile']) && !is_null($_FILES[
'NewFile'][
'tmp_name']) && !is_null($_FILES[
'NewFile'][
'name']) || (isset($_FILES[
'upload']) && !is_null($_FILES[
'upload'][
'tmp_name']) && !is_null($_FILES[
'upload'][
'name']))) {
309 $oFile = isset($_FILES[
'NewFile']) ? $_FILES[
'NewFile'] : $_FILES[
'upload'];
315 $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand);
318 $sFileName = $oFile[
'name'];
323 dol_syslog(
"FileUpload sFileName=".$sFileName);
325 $sOriginalFileName = $sFileName;
328 $sExtension = substr($sFileName, (strrpos($sFileName,
'.') + 1));
329 $sExtension = strtolower($sExtension);
332 $permissiontouploadmediaisok = 1;
333 if (!empty($user->socid)) {
334 $permissiontouploadmediaisok = 0;
339 if (!$permissiontouploadmediaisok) {
340 dol_syslog(
"connector.lib.php Try to upload a file with no permission");
341 $sErrorNumber =
'204';
344 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
347 $isImageValid = ($imgsupported >= 0);
348 if (!$isImageValid) {
349 $sErrorNumber =
'202';
354 if (!$sErrorNumber) {
355 if (IsAllowedExt($sExtension, $resourceType)) {
359 $sFilePath = $sServerDir.$sFileName;
361 if (is_file($sFilePath)) {
363 $sFileName = RemoveExtension($sOriginalFileName).
'('.$iCounter.
').'.$sExtension;
364 $sErrorNumber =
'201';
366 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
369 if (is_file($sFilePath)) {
370 if (isset($Config[
'ChmodOnUpload']) && !$Config[
'ChmodOnUpload']) {
374 $permissions =
'0777';
375 if (isset($Config[
'ChmodOnUpload']) && $Config[
'ChmodOnUpload']) {
376 $permissions = (string) $Config[
'ChmodOnUpload'];
378 $permissionsdec = octdec($permissions);
379 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
380 $oldumask = umask(0);
381 chmod($sFilePath, $permissionsdec);
389 if (file_exists($sFilePath)) {
391 if ($imgsupported === -1 && IsImageValid($sFilePath, $sExtension) ===
false) {
392 dol_syslog(
"connector.lib.php IsImageValid is ko");
394 $sErrorNumber =
'202';
396 $detectHtml = DetectHtml($sFilePath);
397 if ($detectHtml ===
true || $detectHtml == -1) {
399 dol_syslog(
"connector.lib.php DetectHtml is ko detectHtml=".$detectHtml.
", we delete the file.");
401 $sErrorNumber =
'205';
406 $sErrorNumber =
'202';
410 $sErrorNumber =
'203';
414 $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
415 $sFileUrl = CombinePaths($sFileUrl, $sFileName);
420 if ($CKEcallback ==
'') {
422 SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
428 ($sErrorNumber != 0 ?
'Error '.$sErrorNumber.
' upload failed.' :
'Upload Successful')
444function CombinePaths($sBasePath, $sFolder)
446 return RemoveFromEnd($sBasePath,
'/').
'/'.RemoveFromStart($sFolder,
'/');
456function GetResourceTypePath($resourceType, $sCommand)
460 if ($sCommand ==
"QuickUpload") {
461 return $Config[
'QuickUploadPath'][$resourceType];
463 return $Config[
'FileTypesPath'][$resourceType];
474function GetResourceTypeDirectory($resourceType, $sCommand)
477 if ($sCommand ==
"QuickUpload") {
478 if (strlen($Config[
'QuickUploadAbsolutePath'][$resourceType]) > 0) {
479 return $Config[
'QuickUploadAbsolutePath'][$resourceType];
483 return Server_MapPath($Config[
'QuickUploadPath'][$resourceType]);
485 if (strlen($Config[
'FileTypesAbsolutePath'][$resourceType]) > 0) {
486 return $Config[
'FileTypesAbsolutePath'][$resourceType];
490 return Server_MapPath($Config[
'FileTypesPath'][$resourceType]);
502function GetUrlFromPath($resourceType, $folderPath, $sCommand)
504 return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
513function RemoveExtension($fileName)
515 return dol_substr($fileName, 0, strrpos($fileName,
'.'));
526function ServerMapFolder($resourceType, $folderPath, $sCommand)
529 $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
532 $sErrorMsg = CreateServerFolder($sResourceTypePath);
533 if ($sErrorMsg !=
'') {
534 SendError(1,
"Error creating folder \"$sResourceTypePath\" ($sErrorMsg)");
538 return CombinePaths($sResourceTypePath, $folderPath);
547function GetParentFolder($folderPath)
549 $sPattern =
"-[/\\\\][^/\\\\]+[/\\\\]?$-";
550 return preg_replace($sPattern,
'', $folderPath);
560function CreateServerFolder($folderPath, $lastFolder =
null)
565 $sParent = GetParentFolder($folderPath);
568 while (strpos($folderPath,
'//') !==
false) {
569 $folderPath = str_replace(
'//',
'/', $folderPath);
572 $permissiontouploadmediaisok = 1;
573 if (!empty($user->socid)) {
574 $permissiontouploadmediaisok = 0;
579 if (!$permissiontouploadmediaisok) {
580 return 'Bad permissions to create a folder in media directory';
584 if (!empty($sParent) && !file_exists($sParent)) {
586 if (!is_null($lastFolder) && $lastFolder === $sParent) {
587 return "Can't create $folderPath directory";
591 $sErrorMsg = CreateServerFolder($sParent, $folderPath);
592 if ($sErrorMsg !=
'') {
597 if (!file_exists($folderPath)) {
603 ini_set(
'track_errors',
'1');
605 if (isset($Config[
'ChmodOnFolderCreate']) && !$Config[
'ChmodOnFolderCreate']) {
608 $permissions =
'0777';
609 if (isset($Config[
'ChmodOnFolderCreate']) && $Config[
'ChmodOnFolderCreate']) {
610 $permissions = (string) $Config[
'ChmodOnFolderCreate'];
612 $permissionsdec = octdec($permissions);
613 $permissionsdec |= octdec(
'0111');
614 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
616 $oldumask = umask(0);
617 mkdir($folderPath, $permissionsdec);
621 $sErrorMsg = $php_errormsg;
624 ini_restore(
'track_errors');
625 ini_restore(
'error_reporting');
638function GetRootPath()
640 $sRealPath = realpath(
'./');
642 $sRealPath = rtrim($sRealPath,
"\\/");
644 $sSelfPath = $_SERVER[
'PHP_SELF'];
645 $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath,
'/'));
647 $sSelfPath = str_replace(
'/', DIRECTORY_SEPARATOR, $sSelfPath);
649 $position = strpos($sRealPath, $sSelfPath);
653 if ($position ===
false || $position != strlen($sRealPath) - strlen($sSelfPath)) {
654 SendError(1,
'Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/php/config.inc.php".');
657 return substr($sRealPath, 0, $position);
665function Server_MapPath($path)
668 if (function_exists(
'apache_lookup_uri')) {
669 $info = apache_lookup_uri($path);
670 return $info->filename.$info->path_info;
675 return GetRootPath().$path;
685function IsAllowedExt($sExtension, $resourceType)
689 $arAllowed = $Config[
'AllowedExtensions'][$resourceType];
690 $arDenied = $Config[
'DeniedExtensions'][$resourceType];
692 if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
696 if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
709function IsAllowedType($resourceType)
712 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
725function IsAllowedCommand($sCommand)
729 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
741function GetCurrentFolder()
743 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'alphanohtml', 1) :
'/';
746 if (!preg_match(
'|/$|', $sCurrentFolder)) {
747 $sCurrentFolder .=
'/';
749 if (strpos($sCurrentFolder,
'/') !== 0) {
750 $sCurrentFolder =
'/'.$sCurrentFolder;
754 while (strpos($sCurrentFolder,
'//') !==
false) {
755 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
759 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
763 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
767 return $sCurrentFolder;
776function SanitizeFolderName($sNewFolderName)
778 $sNewFolderName = stripslashes($sNewFolderName);
781 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
783 return $sNewFolderName;
792function SanitizeFileName($sNewFileName)
796 $sNewFileName = stripslashes($sNewFileName);
799 if ($Config[
'ForceSingleExtension']) {
800 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
804 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
806 return $sNewFileName;
818function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
823<script
type=
"text/javascript">
824(
function(){var d=document.domain;
while (
true){
try{var A=window.parent.document.domain;
break;}
catch(e) {};d=d.replace(/.*?(?:\.|$)/,
'');
if (d.length==0)
break;
try{document.domain=d;}
catch (e){
break;}}})();
827 if ($errorNumber && $errorNumber !=
'201') {
832 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
833 echo
'console.log('.$errorNumber.
');';
834 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
851function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
853 echo
'<script type="text/javascript">';
855 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
857 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
871function RemoveFromStart($sourceString, $charToRemove)
873 $sPattern =
'|^'.$charToRemove.
'+|';
874 return preg_replace($sPattern,
'', $sourceString);
884function RemoveFromEnd($sourceString, $charToRemove)
886 $sPattern =
'|'.$charToRemove.
'+$|';
887 return preg_replace($sPattern,
'', $sourceString);
896function FindBadUtf8($string)
898 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
899 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
902 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
903 if (isset($matches[2])) {
906 $string = substr($string, strlen($matches[0]));
918function ConvertToXmlAttribute($value)
920 if (defined(
'PHP_OS')) {
926 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
927 return (mb_convert_encoding(htmlspecialchars($value),
'UTF-8',
'ISO-8859-1'));
929 return (htmlspecialchars($value));
940function IsHtmlExtension($ext, $formExtensions)
942 if (!$formExtensions || !is_array($formExtensions)) {
945 $lcaseHtmlExtensions = array();
946 foreach ($formExtensions as $key => $val) {
947 $lcaseHtmlExtensions[$key] = strtolower($val);
949 return in_array($ext, $lcaseHtmlExtensions);
959function DetectHtml($filePath)
961 $fp = @fopen($filePath,
'rb');
967 $chunk = fread($fp, 1024);
970 $chunk = strtolower($chunk);
976 $chunk = trim($chunk);
978 if (preg_match(
"/<!DOCTYPE\W*X?HTML/sim", $chunk)) {
982 $tags = array(
'<body',
'<head',
'<html',
'<img',
'<pre',
'<script',
'<table',
'<title');
984 foreach ($tags as $tag) {
985 if (
false !== strpos($chunk, $tag)) {
991 if (preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) {
998 if (preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1003 if (preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1018function IsImageValid($filePath, $extension)
1020 if (!@is_readable($filePath)) {
1024 $imageCheckExtensions = array(
1044 if (!in_array($extension, $imageCheckExtensions)) {
1048 if (@getimagesize($filePath) ===
false) {
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
This class is used to manage file upload using ajax.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.