31function SetXmlHeaders()
37 header(
'Expires: Mon, 26 Jul 1997 05:00:00 GMT');
39 header(
'Last-Modified: '.gmdate(
'D, d M Y H:i:s').
' GMT');
41 header(
'Cache-Control: no-store, no-cache, must-revalidate');
42 header(
'Cache-Control: post-check=0, pre-check=0',
false);
44 header(
'Pragma: no-cache');
47 header(
'Content-Type: text/xml; charset=utf-8');
58function CreateXmlHeader($command, $resourceType, $currentFolder)
63 echo
'<?xml version="1.0" encoding="utf-8" ?>';
66 echo
'<Connector command="'.$command.
'" resourceType="'.$resourceType.
'">';
69 echo
'<CurrentFolder path="'.ConvertToXmlAttribute($currentFolder).
'" url="'.ConvertToXmlAttribute(GetUrlFromPath($resourceType, $currentFolder, $command)).
'" />';
71 $GLOBALS[
'HeaderSent'] =
true;
79function CreateXmlFooter()
91function SendError($number, $text)
93 if ($_GET[
'Command'] ==
'FileUpload') {
94 SendUploadResults($number,
"",
"", $text);
97 if (isset($GLOBALS[
'HeaderSent']) && $GLOBALS[
'HeaderSent']) {
98 SendErrorNode($number, $text);
103 dol_syslog(
'Error: '.$number.
' '.$text, LOG_ERR);
106 echo
'<?xml version="1.0" encoding="utf-8" ?>';
110 SendErrorNode($number, $text);
124function SendErrorNode($number, $text)
127 echo
'<Error number="'.$number.
'" text="'.htmlspecialchars($text).
'" />';
129 echo
'<Error number="'.$number.
'" />';
143function GetFolders($resourceType, $currentFolder)
146 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFolders');
151 $oCurrentFolder = @opendir($sServerDir);
153 if ($oCurrentFolder !==
false) {
154 while ($sFile = readdir($oCurrentFolder)) {
155 if ($sFile !=
'.' && $sFile !=
'..' && is_dir($sServerDir.$sFile)) {
156 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
159 closedir($oCurrentFolder);
165 natcasesort($aFolders);
166 foreach ($aFolders as $sFolder) {
181function GetFoldersAndFiles($resourceType, $currentFolder)
184 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFoldersAndFiles');
190 $oCurrentFolder = @opendir($sServerDir);
192 if ($oCurrentFolder !==
false) {
193 while ($sFile = readdir($oCurrentFolder)) {
194 if ($sFile !=
'.' && $sFile !=
'..') {
195 if (is_dir($sServerDir.$sFile)) {
196 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
198 $iFileSize = @filesize($sServerDir.$sFile);
202 if ($iFileSize > 0) {
203 $iFileSize = round($iFileSize / 1024);
204 if ($iFileSize < 1) {
209 $aFiles[] =
'<File name="'.ConvertToXmlAttribute($sFile).
'" size="'.$iFileSize.
'" />';
213 closedir($oCurrentFolder);
217 natcasesort($aFolders);
220 foreach ($aFolders as $sFolder) {
227 natcasesort($aFiles);
230 foreach ($aFiles as $sFiles) {
244function CreateFolder($resourceType, $currentFolder)
249 if (isset($_GET[
'NewFolderName'])) {
250 $sNewFolderName =
GETPOST(
'NewFolderName');
251 $sNewFolderName = SanitizeFolderName($sNewFolderName);
253 if (strpos($sNewFolderName,
'..') !==
false) {
254 $sErrorNumber =
'102';
257 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'CreateFolder');
259 if (is_writable($sServerDir)) {
260 $sServerDir .= $sNewFolderName;
262 $sErrorMsg = CreateServerFolder($sServerDir);
264 switch ($sErrorMsg) {
268 case 'Invalid argument':
269 case 'No such file or directory':
270 $sErrorNumber =
'102';
273 $sErrorNumber =
'110';
277 $sErrorNumber =
'103';
281 $sErrorNumber =
'102';
285 echo
'<Error number="'.$sErrorNumber.
'" />';
297function FileUpload($resourceType, $currentFolder, $sCommand, $CKEcallback =
'')
301 if (!isset($_FILES)) {
307 if (isset($_FILES[
'NewFile']) && !is_null($_FILES[
'NewFile'][
'tmp_name']) || (isset($_FILES[
'upload']) && !is_null($_FILES[
'upload'][
'tmp_name']))) {
310 $oFile = isset($_FILES[
'NewFile']) ? $_FILES[
'NewFile'] : $_FILES[
'upload'];
316 $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand);
319 $sFileName = $oFile[
'name'];
324 $sOriginalFileName = $sFileName;
327 $sExtension = substr($sFileName, (strrpos($sFileName,
'.') + 1));
328 $sExtension = strtolower($sExtension);
331 $permissiontouploadmediaisok = 1;
332 if (!empty($user->socid)) {
333 $permissiontouploadmediaisok = 0;
338 if (!$permissiontouploadmediaisok) {
339 dol_syslog(
"connector.lib.php Try to upload a file with no permission");
340 $sErrorNumber =
'202';
343 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
346 $isImageValid = ($imgsupported >= 0 ? true :
false);
347 if (!$isImageValid) {
348 $sErrorNumber =
'202';
353 if (!$sErrorNumber) {
354 if (IsAllowedExt($sExtension, $resourceType)) {
358 $sFilePath = $sServerDir.$sFileName;
360 if (is_file($sFilePath)) {
362 $sFileName = RemoveExtension($sOriginalFileName).
'('.$iCounter.
').'.$sExtension;
363 $sErrorNumber =
'201';
365 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
368 if (is_file($sFilePath)) {
369 if (isset($Config[
'ChmodOnUpload']) && !$Config[
'ChmodOnUpload']) {
373 $permissions =
'0777';
374 if (isset($Config[
'ChmodOnUpload']) && $Config[
'ChmodOnUpload']) {
375 $permissions = (string) $Config[
'ChmodOnUpload'];
377 $permissionsdec = octdec($permissions);
378 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
379 $oldumask = umask(0);
380 chmod($sFilePath, $permissionsdec);
388 if (file_exists($sFilePath)) {
390 if (isset($isImageValid) && $imgsupported === -1 && IsImageValid($sFilePath, $sExtension) ===
false) {
391 dol_syslog(
"connector.lib.php IsImageValid is ko");
393 $sErrorNumber =
'202';
394 } elseif (isset($detectHtml) && $detectHtml === -1 && DetectHtml($sFilePath) ===
true) {
395 dol_syslog(
"connector.lib.php DetectHtml is ko");
397 $sErrorNumber =
'202';
401 $sErrorNumber =
'202';
405 $sErrorNumber =
'203';
409 $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
410 $sFileUrl = CombinePaths($sFileUrl, $sFileName);
415 if ($CKEcallback ==
'') {
417 SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
423 ($sErrorNumber != 0 ?
'Error '.$sErrorNumber.
' upload failed.' :
'Upload Successful')
439function CombinePaths($sBasePath, $sFolder)
441 return RemoveFromEnd($sBasePath,
'/').
'/'.RemoveFromStart($sFolder,
'/');
451function GetResourceTypePath($resourceType, $sCommand)
455 if ($sCommand ==
"QuickUpload") {
456 return $Config[
'QuickUploadPath'][$resourceType];
458 return $Config[
'FileTypesPath'][$resourceType];
469function GetResourceTypeDirectory($resourceType, $sCommand)
472 if ($sCommand ==
"QuickUpload") {
473 if (strlen($Config[
'QuickUploadAbsolutePath'][$resourceType]) > 0) {
474 return $Config[
'QuickUploadAbsolutePath'][$resourceType];
478 return Server_MapPath($Config[
'QuickUploadPath'][$resourceType]);
480 if (strlen($Config[
'FileTypesAbsolutePath'][$resourceType]) > 0) {
481 return $Config[
'FileTypesAbsolutePath'][$resourceType];
485 return Server_MapPath($Config[
'FileTypesPath'][$resourceType]);
497function GetUrlFromPath($resourceType, $folderPath, $sCommand)
499 return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
508function RemoveExtension($fileName)
510 return substr($fileName, 0, strrpos($fileName,
'.'));
521function ServerMapFolder($resourceType, $folderPath, $sCommand)
524 $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
527 $sErrorMsg = CreateServerFolder($sResourceTypePath);
528 if ($sErrorMsg !=
'') {
529 SendError(1,
"Error creating folder \"$sResourceTypePath\" ($sErrorMsg)");
533 return CombinePaths($sResourceTypePath, $folderPath);
542function GetParentFolder($folderPath)
544 $sPattern =
"-[/\\\\][^/\\\\]+[/\\\\]?$-";
545 return preg_replace($sPattern,
'', $folderPath);
555function CreateServerFolder($folderPath, $lastFolder =
null)
560 $sParent = GetParentFolder($folderPath);
563 while (strpos($folderPath,
'//') !==
false) {
564 $folderPath = str_replace(
'//',
'/', $folderPath);
567 $permissiontouploadmediaisok = 1;
568 if (!empty($user->socid)) {
569 $permissiontouploadmediaisok = 0;
574 if (!$permissiontouploadmediaisok) {
575 return 'Bad permissions to create a folder in media directory';
579 if (!empty($sParent) && !file_exists($sParent)) {
581 if (!is_null($lastFolder) && $lastFolder === $sParent) {
582 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');
633function 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);
663function 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;
683function 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)) {
707function IsAllowedType($resourceType)
710 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
723function IsAllowedCommand($sCommand)
727 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
739function GetCurrentFolder()
741 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'alphanohtml', 1) :
'/';
744 if (!preg_match(
'|/$|', $sCurrentFolder)) {
745 $sCurrentFolder .=
'/';
747 if (strpos($sCurrentFolder,
'/') !== 0) {
748 $sCurrentFolder =
'/'.$sCurrentFolder;
752 while (strpos($sCurrentFolder,
'//') !==
false) {
753 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
757 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
761 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
765 return $sCurrentFolder;
774function SanitizeFolderName($sNewFolderName)
776 $sNewFolderName = stripslashes($sNewFolderName);
779 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
781 return $sNewFolderName;
790function SanitizeFileName($sNewFileName)
794 $sNewFileName = stripslashes($sNewFileName);
797 if ($Config[
'ForceSingleExtension']) {
798 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
802 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
804 return $sNewFileName;
816function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
821<script
type=
"text/javascript">
822(
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;}}})();
825 if ($errorNumber && $errorNumber != 201) {
830 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
831 echo
'console.log('.$errorNumber.
');';
832 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
849function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
851 echo
'<script type="text/javascript">';
853 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
855 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
869function RemoveFromStart($sourceString, $charToRemove)
871 $sPattern =
'|^'.$charToRemove.
'+|';
872 return preg_replace($sPattern,
'', $sourceString);
882function RemoveFromEnd($sourceString, $charToRemove)
884 $sPattern =
'|'.$charToRemove.
'+$|';
885 return preg_replace($sPattern,
'', $sourceString);
894function FindBadUtf8($string)
896 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
897 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
900 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
901 if (isset($matches[2])) {
904 $string = substr($string, strlen($matches[0]));
916function ConvertToXmlAttribute($value)
918 if (defined(
'PHP_OS')) {
924 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
925 return (mb_convert_encoding(htmlspecialchars($value),
'UTF-8',
'ISO-8859-1'));
927 return (htmlspecialchars($value));
938function IsHtmlExtension($ext, $formExtensions)
940 if (!$formExtensions || !is_array($formExtensions)) {
943 $lcaseHtmlExtensions = array();
944 foreach ($formExtensions as $key => $val) {
945 $lcaseHtmlExtensions[$key] = strtolower($val);
947 return in_array($ext, $lcaseHtmlExtensions);
957function DetectHtml($filePath)
959 $fp = @fopen($filePath,
'rb');
962 if ($fp ===
false || !flock($fp, LOCK_SH)) {
966 $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) {
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