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 =
'')
302 if (!isset($_FILES)) {
309 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']))) {
312 $oFile = isset($_FILES[
'NewFile']) ? $_FILES[
'NewFile'] : $_FILES[
'upload'];
318 $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand);
321 $sFileName = $oFile[
'name'];
326 $sOriginalFileName = $sFileName;
329 $sExtension = substr($sFileName, (strrpos($sFileName,
'.') + 1));
330 $sExtension = strtolower($sExtension);
333 $permissiontouploadmediaisok = 1;
334 if (!empty($user->socid)) {
335 $permissiontouploadmediaisok = 0;
340 if (!$permissiontouploadmediaisok) {
341 dol_syslog(
"connector.lib.php Try to upload a file with no permission");
342 $sErrorNumber =
'202';
345 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
348 $isImageValid = ($imgsupported >= 0);
349 if (!$isImageValid) {
350 $sErrorNumber =
'202';
355 if (!$sErrorNumber) {
356 if (IsAllowedExt($sExtension, $resourceType)) {
360 $sFilePath = $sServerDir.$sFileName;
362 if (is_file($sFilePath)) {
364 $sFileName = RemoveExtension($sOriginalFileName).
'('.$iCounter.
').'.$sExtension;
365 $sErrorNumber =
'201';
367 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
370 if (is_file($sFilePath)) {
371 if (isset($Config[
'ChmodOnUpload']) && !$Config[
'ChmodOnUpload']) {
375 $permissions =
'0777';
376 if (isset($Config[
'ChmodOnUpload']) && $Config[
'ChmodOnUpload']) {
377 $permissions = (string) $Config[
'ChmodOnUpload'];
379 $permissionsdec = octdec($permissions);
380 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
381 $oldumask = umask(0);
382 chmod($sFilePath, $permissionsdec);
390 if (file_exists($sFilePath)) {
392 if (isset($isImageValid) && $imgsupported === -1 && IsImageValid($sFilePath, $sExtension) ===
false) {
393 dol_syslog(
"connector.lib.php IsImageValid is ko");
395 $sErrorNumber =
'202';
397 $detectHtml = DetectHtml($sFilePath);
398 if ($detectHtml ===
true || $detectHtml == -1) {
400 dol_syslog(
"connector.lib.php DetectHtml is ko");
402 $sErrorNumber =
'202';
407 $sErrorNumber =
'202';
411 $sErrorNumber =
'203';
415 $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
416 $sFileUrl = CombinePaths($sFileUrl, $sFileName);
421 if ($CKEcallback ==
'') {
423 SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
429 ($sErrorNumber != 0 ?
'Error '.$sErrorNumber.
' upload failed.' :
'Upload Successful')
445function CombinePaths($sBasePath, $sFolder)
447 return RemoveFromEnd($sBasePath,
'/').
'/'.RemoveFromStart($sFolder,
'/');
457function GetResourceTypePath($resourceType, $sCommand)
461 if ($sCommand ==
"QuickUpload") {
462 return $Config[
'QuickUploadPath'][$resourceType];
464 return $Config[
'FileTypesPath'][$resourceType];
475function GetResourceTypeDirectory($resourceType, $sCommand)
478 if ($sCommand ==
"QuickUpload") {
479 if (strlen($Config[
'QuickUploadAbsolutePath'][$resourceType]) > 0) {
480 return $Config[
'QuickUploadAbsolutePath'][$resourceType];
484 return Server_MapPath($Config[
'QuickUploadPath'][$resourceType]);
486 if (strlen($Config[
'FileTypesAbsolutePath'][$resourceType]) > 0) {
487 return $Config[
'FileTypesAbsolutePath'][$resourceType];
491 return Server_MapPath($Config[
'FileTypesPath'][$resourceType]);
503function GetUrlFromPath($resourceType, $folderPath, $sCommand)
505 return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
514function RemoveExtension($fileName)
516 return substr($fileName, 0, strrpos($fileName,
'.'));
527function ServerMapFolder($resourceType, $folderPath, $sCommand)
530 $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
533 $sErrorMsg = CreateServerFolder($sResourceTypePath);
534 if ($sErrorMsg !=
'') {
535 SendError(1,
"Error creating folder \"$sResourceTypePath\" ($sErrorMsg)");
539 return CombinePaths($sResourceTypePath, $folderPath);
548function GetParentFolder($folderPath)
550 $sPattern =
"-[/\\\\][^/\\\\]+[/\\\\]?$-";
551 return preg_replace($sPattern,
'', $folderPath);
561function CreateServerFolder($folderPath, $lastFolder =
null)
566 $sParent = GetParentFolder($folderPath);
569 while (strpos($folderPath,
'//') !==
false) {
570 $folderPath = str_replace(
'//',
'/', $folderPath);
573 $permissiontouploadmediaisok = 1;
574 if (!empty($user->socid)) {
575 $permissiontouploadmediaisok = 0;
580 if (!$permissiontouploadmediaisok) {
581 return 'Bad permissions to create a folder in media directory';
585 if (!empty($sParent) && !file_exists($sParent)) {
587 if (!is_null($lastFolder) && $lastFolder === $sParent) {
588 return "Can't create $folderPath directory";
592 $sErrorMsg = CreateServerFolder($sParent, $folderPath);
593 if ($sErrorMsg !=
'') {
598 if (!file_exists($folderPath)) {
604 ini_set(
'track_errors',
'1');
606 if (isset($Config[
'ChmodOnFolderCreate']) && !$Config[
'ChmodOnFolderCreate']) {
609 $permissions =
'0777';
610 if (isset($Config[
'ChmodOnFolderCreate']) && $Config[
'ChmodOnFolderCreate']) {
611 $permissions = (string) $Config[
'ChmodOnFolderCreate'];
613 $permissionsdec = octdec($permissions);
614 $permissionsdec |= octdec(
'0111');
615 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
617 $oldumask = umask(0);
618 mkdir($folderPath, $permissionsdec);
622 $sErrorMsg = $php_errormsg;
625 ini_restore(
'track_errors');
626 ini_restore(
'error_reporting');
639function GetRootPath()
641 if (!isset($_SERVER)) {
644 $sRealPath = realpath(
'./');
646 $sRealPath = rtrim($sRealPath,
"\\/");
648 $sSelfPath = $_SERVER[
'PHP_SELF'];
649 $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath,
'/'));
651 $sSelfPath = str_replace(
'/', DIRECTORY_SEPARATOR, $sSelfPath);
653 $position = strpos($sRealPath, $sSelfPath);
657 if ($position ===
false || $position != strlen($sRealPath) - strlen($sSelfPath)) {
658 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".');
661 return substr($sRealPath, 0, $position);
669function Server_MapPath($path)
672 if (function_exists(
'apache_lookup_uri')) {
673 $info = apache_lookup_uri($path);
674 return $info->filename.$info->path_info;
679 return GetRootPath().$path;
689function IsAllowedExt($sExtension, $resourceType)
693 $arAllowed = $Config[
'AllowedExtensions'][$resourceType];
694 $arDenied = $Config[
'DeniedExtensions'][$resourceType];
696 if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
700 if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
713function IsAllowedType($resourceType)
716 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
729function IsAllowedCommand($sCommand)
733 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
745function GetCurrentFolder()
747 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'alphanohtml', 1) :
'/';
750 if (!preg_match(
'|/$|', $sCurrentFolder)) {
751 $sCurrentFolder .=
'/';
753 if (strpos($sCurrentFolder,
'/') !== 0) {
754 $sCurrentFolder =
'/'.$sCurrentFolder;
758 while (strpos($sCurrentFolder,
'//') !==
false) {
759 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
763 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
767 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
771 return $sCurrentFolder;
780function SanitizeFolderName($sNewFolderName)
782 $sNewFolderName = stripslashes($sNewFolderName);
785 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
787 return $sNewFolderName;
796function SanitizeFileName($sNewFileName)
800 $sNewFileName = stripslashes($sNewFileName);
803 if ($Config[
'ForceSingleExtension']) {
804 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
808 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
810 return $sNewFileName;
822function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
827<script
type=
"text/javascript">
828(
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;}}})();
831 if ($errorNumber && $errorNumber !=
'201') {
836 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
837 echo
'console.log('.$errorNumber.
');';
838 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
855function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
857 echo
'<script type="text/javascript">';
859 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
861 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
875function RemoveFromStart($sourceString, $charToRemove)
877 $sPattern =
'|^'.$charToRemove.
'+|';
878 return preg_replace($sPattern,
'', $sourceString);
888function RemoveFromEnd($sourceString, $charToRemove)
890 $sPattern =
'|'.$charToRemove.
'+$|';
891 return preg_replace($sPattern,
'', $sourceString);
900function FindBadUtf8($string)
902 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
903 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
906 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
907 if (isset($matches[2])) {
910 $string = substr($string, strlen($matches[0]));
922function ConvertToXmlAttribute($value)
924 if (defined(
'PHP_OS')) {
930 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
931 return (mb_convert_encoding(htmlspecialchars($value),
'UTF-8',
'ISO-8859-1'));
933 return (htmlspecialchars($value));
944function IsHtmlExtension($ext, $formExtensions)
946 if (!$formExtensions || !is_array($formExtensions)) {
949 $lcaseHtmlExtensions = array();
950 foreach ($formExtensions as $key => $val) {
951 $lcaseHtmlExtensions[$key] = strtolower($val);
953 return in_array($ext, $lcaseHtmlExtensions);
963function DetectHtml($filePath)
965 $fp = @fopen($filePath,
'rb');
968 if ($fp ===
false || !flock($fp, LOCK_SH)) {
972 $chunk = fread($fp, 1024);
976 $chunk = strtolower($chunk);
982 $chunk = trim($chunk);
984 if (preg_match(
"/<!DOCTYPE\W*X?HTML/sim", $chunk)) {
988 $tags = array(
'<body',
'<head',
'<html',
'<img',
'<pre',
'<script',
'<table',
'<title');
990 foreach ($tags as $tag) {
991 if (
false !== strpos($chunk, $tag)) {
997 if (preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) {
1004 if (preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1009 if (preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1024function IsImageValid($filePath, $extension)
1026 if (!@is_readable($filePath)) {
1030 $imageCheckExtensions = array(
1050 if (!in_array($extension, $imageCheckExtensions)) {
1054 if (@getimagesize($filePath) ===
false) {
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, $varfiles='addedfile', $upload_dir='')
Check validity of a file upload from an GUI page, and move it to its final destination.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type