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)) {
308 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']))) {
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);
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';
396 $detectHtml = DetectHtml($sFilePath);
397 if ($detectHtml ===
true || $detectHtml == -1) {
399 dol_syslog(
"connector.lib.php DetectHtml is ko");
401 $sErrorNumber =
'202';
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 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 if (!isset($_SERVER)) {
643 $sRealPath = realpath(
'./');
645 $sRealPath = rtrim($sRealPath,
"\\/");
647 $sSelfPath = $_SERVER[
'PHP_SELF'];
648 $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath,
'/'));
650 $sSelfPath = str_replace(
'/', DIRECTORY_SEPARATOR, $sSelfPath);
652 $position = strpos($sRealPath, $sSelfPath);
656 if ($position ===
false || $position != strlen($sRealPath) - strlen($sSelfPath)) {
657 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".');
660 return substr($sRealPath, 0, $position);
668function Server_MapPath($path)
671 if (function_exists(
'apache_lookup_uri')) {
672 $info = apache_lookup_uri($path);
673 return $info->filename.$info->path_info;
678 return GetRootPath().$path;
688function IsAllowedExt($sExtension, $resourceType)
692 $arAllowed = $Config[
'AllowedExtensions'][$resourceType];
693 $arDenied = $Config[
'DeniedExtensions'][$resourceType];
695 if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
699 if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
712function IsAllowedType($resourceType)
715 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
728function IsAllowedCommand($sCommand)
732 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
744function GetCurrentFolder()
746 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'alphanohtml', 1) :
'/';
749 if (!preg_match(
'|/$|', $sCurrentFolder)) {
750 $sCurrentFolder .=
'/';
752 if (strpos($sCurrentFolder,
'/') !== 0) {
753 $sCurrentFolder =
'/'.$sCurrentFolder;
757 while (strpos($sCurrentFolder,
'//') !==
false) {
758 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
762 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
766 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
770 return $sCurrentFolder;
779function SanitizeFolderName($sNewFolderName)
781 $sNewFolderName = stripslashes($sNewFolderName);
784 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
786 return $sNewFolderName;
795function SanitizeFileName($sNewFileName)
799 $sNewFileName = stripslashes($sNewFileName);
802 if ($Config[
'ForceSingleExtension']) {
803 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
807 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
809 return $sNewFileName;
821function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
826<script
type=
"text/javascript">
827(
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;}}})();
830 if ($errorNumber && $errorNumber !=
'201') {
835 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
836 echo
'console.log('.$errorNumber.
');';
837 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
854function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
856 echo
'<script type="text/javascript">';
858 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
860 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
874function RemoveFromStart($sourceString, $charToRemove)
876 $sPattern =
'|^'.$charToRemove.
'+|';
877 return preg_replace($sPattern,
'', $sourceString);
887function RemoveFromEnd($sourceString, $charToRemove)
889 $sPattern =
'|'.$charToRemove.
'+$|';
890 return preg_replace($sPattern,
'', $sourceString);
899function FindBadUtf8($string)
901 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
902 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
905 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
906 if (isset($matches[2])) {
909 $string = substr($string, strlen($matches[0]));
921function ConvertToXmlAttribute($value)
923 if (defined(
'PHP_OS')) {
929 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
930 return (mb_convert_encoding(htmlspecialchars($value),
'UTF-8',
'ISO-8859-1'));
932 return (htmlspecialchars($value));
943function IsHtmlExtension($ext, $formExtensions)
945 if (!$formExtensions || !is_array($formExtensions)) {
948 $lcaseHtmlExtensions = array();
949 foreach ($formExtensions as $key => $val) {
950 $lcaseHtmlExtensions[$key] = strtolower($val);
952 return in_array($ext, $lcaseHtmlExtensions);
962function DetectHtml($filePath)
964 $fp = @fopen($filePath,
'rb');
967 if ($fp ===
false || !flock($fp, LOCK_SH)) {
971 $chunk = fread($fp, 1024);
975 $chunk = strtolower($chunk);
981 $chunk = trim($chunk);
983 if (preg_match(
"/<!DOCTYPE\W*X?HTML/sim", $chunk)) {
987 $tags = array(
'<body',
'<head',
'<html',
'<img',
'<pre',
'<script',
'<table',
'<title');
989 foreach ($tags as $tag) {
990 if (
false !== strpos($chunk, $tag)) {
996 if (preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) {
1003 if (preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1008 if (preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
1023function 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='')
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