30 function SetXmlHeaders()
36 header(
'Expires: Mon, 26 Jul 1997 05:00:00 GMT');
38 header(
'Last-Modified: '.gmdate(
'D, d M Y H:i:s').
' GMT');
40 header(
'Cache-Control: no-store, no-cache, must-revalidate');
41 header(
'Cache-Control: post-check=0, pre-check=0',
false);
43 header(
'Pragma: no-cache');
46 header(
'Content-Type: text/xml; charset=utf-8');
57 function CreateXmlHeader($command, $resourceType, $currentFolder)
62 echo
'<?xml version="1.0" encoding="utf-8" ?>';
65 echo
'<Connector command="'.$command.
'" resourceType="'.$resourceType.
'">';
68 echo
'<CurrentFolder path="'.ConvertToXmlAttribute($currentFolder).
'" url="'.ConvertToXmlAttribute(GetUrlFromPath($resourceType, $currentFolder, $command)).
'" />';
70 $GLOBALS[
'HeaderSent'] =
true;
78 function CreateXmlFooter()
90 function SendError($number, $text)
92 if ($_GET[
'Command'] ==
'FileUpload') {
93 SendUploadResults($number,
"",
"", $text);
96 if (isset($GLOBALS[
'HeaderSent']) && $GLOBALS[
'HeaderSent']) {
97 SendErrorNode($number, $text);
102 dol_syslog(
'Error: '.$number.
' '.$text, LOG_ERR);
105 echo
'<?xml version="1.0" encoding="utf-8" ?>';
109 SendErrorNode($number, $text);
123 function SendErrorNode($number, $text)
126 echo
'<Error number="'.$number.
'" text="'.htmlspecialchars($text).
'" />';
128 echo
'<Error number="'.$number.
'" />';
141 function GetFolders($resourceType, $currentFolder)
144 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFolders');
149 $oCurrentFolder = @opendir($sServerDir);
151 if ($oCurrentFolder !==
false) {
152 while ($sFile = readdir($oCurrentFolder)) {
153 if ($sFile !=
'.' && $sFile !=
'..' && is_dir($sServerDir.$sFile)) {
154 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
157 closedir($oCurrentFolder);
163 natcasesort($aFolders);
164 foreach ($aFolders as $sFolder) {
179 function GetFoldersAndFiles($resourceType, $currentFolder)
182 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFoldersAndFiles');
188 $oCurrentFolder = @opendir($sServerDir);
190 if ($oCurrentFolder !==
false) {
191 while ($sFile = readdir($oCurrentFolder)) {
192 if ($sFile !=
'.' && $sFile !=
'..') {
193 if (is_dir($sServerDir.$sFile)) {
194 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
196 $iFileSize = @filesize($sServerDir.$sFile);
200 if ($iFileSize > 0) {
201 $iFileSize = round($iFileSize / 1024);
202 if ($iFileSize < 1) {
207 $aFiles[] =
'<File name="'.ConvertToXmlAttribute($sFile).
'" size="'.$iFileSize.
'" />';
211 closedir($oCurrentFolder);
215 natcasesort($aFolders);
218 foreach ($aFolders as $sFolder) {
225 natcasesort($aFiles);
228 foreach ($aFiles as $sFiles) {
242 function CreateFolder($resourceType, $currentFolder)
250 if (isset($_GET[
'NewFolderName'])) {
251 $sNewFolderName = $_GET[
'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.
'" />';
298 function FileUpload($resourceType, $currentFolder, $sCommand, $CKEcallback =
'')
302 if (!isset($_FILES)) {
308 if (isset($_FILES[
'NewFile']) && !is_null($_FILES[
'NewFile'][
'tmp_name']) || (isset($_FILES[
'upload']) && !is_null($_FILES[
'upload'][
'tmp_name']))) {
311 $oFile = isset($_FILES[
'NewFile']) ? $_FILES[
'NewFile'] : $_FILES[
'upload'];
317 $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand);
320 $sFileName = $oFile[
'name'];
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 =
'202';
344 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
347 $isImageValid = ($imgsupported >= 0 ? true :
false);
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 (isset($isImageValid) && $imgsupported === -1 && IsImageValid($sFilePath, $sExtension) ===
false) {
392 dol_syslog(
"connector.lib.php IsImageValid is ko");
394 $sErrorNumber =
'202';
395 } elseif (isset($detectHtml) && $detectHtml === -1 && DetectHtml($sFilePath) ===
true) {
396 dol_syslog(
"connector.lib.php DetectHtml is ko");
398 $sErrorNumber =
'202';
402 $sErrorNumber =
'202';
406 $sErrorNumber =
'203';
410 $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
411 $sFileUrl = CombinePaths($sFileUrl, $sFileName);
416 if ($CKEcallback ==
'') {
418 SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
424 ($sErrorNumber != 0 ?
'Error '.$sErrorNumber.
' upload failed.' :
'Upload Successful')
440 function CombinePaths($sBasePath, $sFolder)
442 return RemoveFromEnd($sBasePath,
'/').
'/'.RemoveFromStart($sFolder,
'/');
452 function GetResourceTypePath($resourceType, $sCommand)
456 if ($sCommand ==
"QuickUpload") {
457 return $Config[
'QuickUploadPath'][$resourceType];
459 return $Config[
'FileTypesPath'][$resourceType];
470 function GetResourceTypeDirectory($resourceType, $sCommand)
473 if ($sCommand ==
"QuickUpload") {
474 if (strlen($Config[
'QuickUploadAbsolutePath'][$resourceType]) > 0) {
475 return $Config[
'QuickUploadAbsolutePath'][$resourceType];
479 return Server_MapPath($Config[
'QuickUploadPath'][$resourceType]);
481 if (strlen($Config[
'FileTypesAbsolutePath'][$resourceType]) > 0) {
482 return $Config[
'FileTypesAbsolutePath'][$resourceType];
486 return Server_MapPath($Config[
'FileTypesPath'][$resourceType]);
498 function GetUrlFromPath($resourceType, $folderPath, $sCommand)
500 return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
509 function RemoveExtension($fileName)
511 return substr($fileName, 0, strrpos($fileName,
'.'));
522 function ServerMapFolder($resourceType, $folderPath, $sCommand)
525 $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
528 $sErrorMsg = CreateServerFolder($sResourceTypePath);
529 if ($sErrorMsg !=
'') {
530 SendError(1,
"Error creating folder \"{$sResourceTypePath}\" ({$sErrorMsg})");
534 return CombinePaths($sResourceTypePath, $folderPath);
543 function GetParentFolder($folderPath)
545 $sPattern =
"-[/\\\\][^/\\\\]+[/\\\\]?$-";
546 return preg_replace($sPattern,
'', $folderPath);
556 function CreateServerFolder($folderPath, $lastFolder =
null)
561 $sParent = GetParentFolder($folderPath);
564 while (strpos($folderPath,
'//') !==
false) {
565 $folderPath = str_replace(
'//',
'/', $folderPath);
568 $permissiontouploadmediaisok = 1;
569 if (!empty($user->socid)) {
570 $permissiontouploadmediaisok = 0;
575 if (!$permissiontouploadmediaisok) {
576 return 'Bad permissions to create a folder in media directory';
580 if (!empty($sParent) && !file_exists($sParent)) {
582 if (!is_null($lastFolder) && $lastFolder === $sParent) {
583 return "Can't create $folderPath directory";
586 $sErrorMsg = CreateServerFolder($sParent, $folderPath);
587 if ($sErrorMsg !=
'') {
592 if (!file_exists($folderPath)) {
598 ini_set(
'track_errors',
'1');
600 if (isset($Config[
'ChmodOnFolderCreate']) && !$Config[
'ChmodOnFolderCreate']) {
603 $permissions =
'0777';
604 if (isset($Config[
'ChmodOnFolderCreate']) && $Config[
'ChmodOnFolderCreate']) {
605 $permissions = (string) $Config[
'ChmodOnFolderCreate'];
607 $permissionsdec = octdec($permissions);
608 $permissionsdec |= octdec(
'0111');
609 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
611 $oldumask = umask(0);
612 mkdir($folderPath, $permissionsdec);
616 $sErrorMsg = $php_errormsg;
619 ini_restore(
'track_errors');
620 ini_restore(
'error_reporting');
633 function GetRootPath()
635 if (!isset($_SERVER)) {
638 $sRealPath = realpath(
'./');
640 $sRealPath = rtrim($sRealPath,
"\\/");
642 $sSelfPath = $_SERVER[
'PHP_SELF'];
643 $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath,
'/'));
645 $sSelfPath = str_replace(
'/', DIRECTORY_SEPARATOR, $sSelfPath);
647 $position = strpos($sRealPath, $sSelfPath);
651 if ($position ===
false || $position <> strlen($sRealPath) - strlen($sSelfPath)) {
652 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".');
655 return substr($sRealPath, 0, $position);
663 function Server_MapPath($path)
666 if (function_exists(
'apache_lookup_uri')) {
667 $info = apache_lookup_uri($path);
668 return $info->filename.$info->path_info;
673 return GetRootPath().$path;
683 function IsAllowedExt($sExtension, $resourceType)
687 $arAllowed = $Config[
'AllowedExtensions'][$resourceType];
688 $arDenied = $Config[
'DeniedExtensions'][$resourceType];
690 if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
694 if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
707 function IsAllowedType($resourceType)
710 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
723 function IsAllowedCommand($sCommand)
727 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
739 function GetCurrentFolder()
744 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'', 1) :
'/';
747 if (!preg_match(
'|/$|', $sCurrentFolder)) {
748 $sCurrentFolder .=
'/';
750 if (strpos($sCurrentFolder,
'/') !== 0) {
751 $sCurrentFolder =
'/'.$sCurrentFolder;
755 while (strpos($sCurrentFolder,
'//') !==
false) {
756 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
760 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
764 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
768 return $sCurrentFolder;
777 function SanitizeFolderName($sNewFolderName)
779 $sNewFolderName = stripslashes($sNewFolderName);
782 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
784 return $sNewFolderName;
793 function SanitizeFileName($sNewFileName)
797 $sNewFileName = stripslashes($sNewFileName);
800 if ($Config[
'ForceSingleExtension']) {
801 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
805 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
807 return $sNewFileName;
819 function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
824 <script
type=
"text/javascript">
825 (
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;}}})();
828 if ($errorNumber && $errorNumber != 201) {
833 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
834 echo
'console.log('.$errorNumber.
');';
835 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
852 function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
854 echo
'<script type="text/javascript">';
856 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
858 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
872 function RemoveFromStart($sourceString, $charToRemove)
874 $sPattern =
'|^'.$charToRemove.
'+|';
875 return preg_replace($sPattern,
'', $sourceString);
885 function RemoveFromEnd($sourceString, $charToRemove)
887 $sPattern =
'|'.$charToRemove.
'+$|';
888 return preg_replace($sPattern,
'', $sourceString);
897 function FindBadUtf8($string)
899 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
900 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
903 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
904 if (isset($matches[2])) {
907 $string = substr($string, strlen($matches[0]));
919 function ConvertToXmlAttribute($value)
921 if (defined(
'PHP_OS')) {
927 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
928 return (utf8_encode(htmlspecialchars($value)));
930 return (htmlspecialchars($value));
941 function IsHtmlExtension($ext, $formExtensions)
943 if (!$formExtensions || !is_array($formExtensions)) {
946 $lcaseHtmlExtensions = array();
947 foreach ($formExtensions as $key => $val) {
948 $lcaseHtmlExtensions[$key] = strtolower($val);
950 return in_array($ext, $lcaseHtmlExtensions);
961 function DetectHtml($filePath)
963 $fp = @fopen($filePath,
'rb');
966 if ($fp ===
false || !flock($fp, LOCK_SH)) {
970 $chunk = fread($fp, 1024);
974 $chunk = strtolower($chunk);
980 $chunk = trim($chunk);
982 if (preg_match(
"/<!DOCTYPE\W*X?HTML/sim", $chunk)) {
986 $tags = array(
'<body',
'<head',
'<html',
'<img',
'<pre',
'<script',
'<table',
'<title');
988 foreach ($tags as $tag) {
989 if (
false !== strpos($chunk, $tag)) {
995 if (preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) {
1002 if (preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1007 if (preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1023 function IsImageValid($filePath, $extension)
1025 if (!@is_readable($filePath)) {
1029 $imageCheckExtensions = array(
1049 if (!in_array($extension, $imageCheckExtensions)) {
1053 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='')
Make control on an uploaded file from an GUI page and move it to 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