30function 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');
57function 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;
78function CreateXmlFooter()
90function 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);
123function SendErrorNode($number, $text)
126 echo
'<Error number="'.$number.
'" text="'.htmlspecialchars($text).
'" />';
128 echo
'<Error number="'.$number.
'" />';
142function GetFolders($resourceType, $currentFolder)
145 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFolders');
150 $oCurrentFolder = @opendir($sServerDir);
152 if ($oCurrentFolder !==
false) {
153 while ($sFile = readdir($oCurrentFolder)) {
154 if ($sFile !=
'.' && $sFile !=
'..' && is_dir($sServerDir.$sFile)) {
155 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
158 closedir($oCurrentFolder);
164 natcasesort($aFolders);
165 foreach ($aFolders as $sFolder) {
180function GetFoldersAndFiles($resourceType, $currentFolder)
183 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'GetFoldersAndFiles');
189 $oCurrentFolder = @opendir($sServerDir);
191 if ($oCurrentFolder !==
false) {
192 while ($sFile = readdir($oCurrentFolder)) {
193 if ($sFile !=
'.' && $sFile !=
'..') {
194 if (is_dir($sServerDir.$sFile)) {
195 $aFolders[] =
'<Folder name="'.ConvertToXmlAttribute($sFile).
'" />';
197 $iFileSize = @filesize($sServerDir.$sFile);
201 if ($iFileSize > 0) {
202 $iFileSize = round($iFileSize / 1024);
203 if ($iFileSize < 1) {
208 $aFiles[] =
'<File name="'.ConvertToXmlAttribute($sFile).
'" size="'.$iFileSize.
'" />';
212 closedir($oCurrentFolder);
216 natcasesort($aFolders);
219 foreach ($aFolders as $sFolder) {
226 natcasesort($aFiles);
229 foreach ($aFiles as $sFiles) {
243function CreateFolder($resourceType, $currentFolder)
251 if (isset($_GET[
'NewFolderName'])) {
252 $sNewFolderName = $_GET[
'NewFolderName'];
253 $sNewFolderName = SanitizeFolderName($sNewFolderName);
255 if (strpos($sNewFolderName,
'..') !==
false) {
256 $sErrorNumber =
'102';
259 $sServerDir = ServerMapFolder($resourceType, $currentFolder,
'CreateFolder');
261 if (is_writable($sServerDir)) {
262 $sServerDir .= $sNewFolderName;
264 $sErrorMsg = CreateServerFolder($sServerDir);
266 switch ($sErrorMsg) {
270 case 'Invalid argument':
271 case 'No such file or directory':
272 $sErrorNumber =
'102';
275 $sErrorNumber =
'110';
279 $sErrorNumber =
'103';
283 $sErrorNumber =
'102';
287 echo
'<Error number="'.$sErrorNumber.
'" />';
299function FileUpload($resourceType, $currentFolder, $sCommand, $CKEcallback =
'')
303 if (!isset($_FILES)) {
309 if (isset($_FILES[
'NewFile']) && !is_null($_FILES[
'NewFile'][
'tmp_name']) || (isset($_FILES[
'upload']) && !is_null($_FILES[
'upload'][
'tmp_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 ? true :
false);
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';
396 } elseif (isset($detectHtml) && $detectHtml === -1 && DetectHtml($sFilePath) ===
true) {
397 dol_syslog(
"connector.lib.php DetectHtml is ko");
399 $sErrorNumber =
'202';
403 $sErrorNumber =
'202';
407 $sErrorNumber =
'203';
411 $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
412 $sFileUrl = CombinePaths($sFileUrl, $sFileName);
417 if ($CKEcallback ==
'') {
419 SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
425 ($sErrorNumber != 0 ?
'Error '.$sErrorNumber.
' upload failed.' :
'Upload Successful')
441function CombinePaths($sBasePath, $sFolder)
443 return RemoveFromEnd($sBasePath,
'/').
'/'.RemoveFromStart($sFolder,
'/');
453function GetResourceTypePath($resourceType, $sCommand)
457 if ($sCommand ==
"QuickUpload") {
458 return $Config[
'QuickUploadPath'][$resourceType];
460 return $Config[
'FileTypesPath'][$resourceType];
471function GetResourceTypeDirectory($resourceType, $sCommand)
474 if ($sCommand ==
"QuickUpload") {
475 if (strlen($Config[
'QuickUploadAbsolutePath'][$resourceType]) > 0) {
476 return $Config[
'QuickUploadAbsolutePath'][$resourceType];
480 return Server_MapPath($Config[
'QuickUploadPath'][$resourceType]);
482 if (strlen($Config[
'FileTypesAbsolutePath'][$resourceType]) > 0) {
483 return $Config[
'FileTypesAbsolutePath'][$resourceType];
487 return Server_MapPath($Config[
'FileTypesPath'][$resourceType]);
499function GetUrlFromPath($resourceType, $folderPath, $sCommand)
501 return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
510function RemoveExtension($fileName)
512 return substr($fileName, 0, strrpos($fileName,
'.'));
523function ServerMapFolder($resourceType, $folderPath, $sCommand)
526 $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
529 $sErrorMsg = CreateServerFolder($sResourceTypePath);
530 if ($sErrorMsg !=
'') {
531 SendError(1,
"Error creating folder \"$sResourceTypePath\" ($sErrorMsg)");
535 return CombinePaths($sResourceTypePath, $folderPath);
544function GetParentFolder($folderPath)
546 $sPattern =
"-[/\\\\][^/\\\\]+[/\\\\]?$-";
547 return preg_replace($sPattern,
'', $folderPath);
557function CreateServerFolder($folderPath, $lastFolder =
null)
562 $sParent = GetParentFolder($folderPath);
565 while (strpos($folderPath,
'//') !==
false) {
566 $folderPath = str_replace(
'//',
'/', $folderPath);
569 $permissiontouploadmediaisok = 1;
570 if (!empty($user->socid)) {
571 $permissiontouploadmediaisok = 0;
576 if (!$permissiontouploadmediaisok) {
577 return 'Bad permissions to create a folder in media directory';
581 if (!empty($sParent) && !file_exists($sParent)) {
583 if (!is_null($lastFolder) && $lastFolder === $sParent) {
584 return "Can't create $folderPath directory";
587 $sErrorMsg = CreateServerFolder($sParent, $folderPath);
588 if ($sErrorMsg !=
'') {
593 if (!file_exists($folderPath)) {
599 ini_set(
'track_errors',
'1');
601 if (isset($Config[
'ChmodOnFolderCreate']) && !$Config[
'ChmodOnFolderCreate']) {
604 $permissions =
'0777';
605 if (isset($Config[
'ChmodOnFolderCreate']) && $Config[
'ChmodOnFolderCreate']) {
606 $permissions = (string) $Config[
'ChmodOnFolderCreate'];
608 $permissionsdec = octdec($permissions);
609 $permissionsdec |= octdec(
'0111');
610 dol_syslog(
"connector.lib.php permission = ".$permissions.
" ".$permissionsdec.
" ".decoct($permissionsdec));
612 $oldumask = umask(0);
613 mkdir($folderPath, $permissionsdec);
617 $sErrorMsg = $php_errormsg;
620 ini_restore(
'track_errors');
621 ini_restore(
'error_reporting');
634function GetRootPath()
636 if (!isset($_SERVER)) {
639 $sRealPath = realpath(
'./');
641 $sRealPath = rtrim($sRealPath,
"\\/");
643 $sSelfPath = $_SERVER[
'PHP_SELF'];
644 $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath,
'/'));
646 $sSelfPath = str_replace(
'/', DIRECTORY_SEPARATOR, $sSelfPath);
648 $position = strpos($sRealPath, $sSelfPath);
652 if ($position ===
false || $position <> strlen($sRealPath) - strlen($sSelfPath)) {
653 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".');
656 return substr($sRealPath, 0, $position);
664function Server_MapPath($path)
667 if (function_exists(
'apache_lookup_uri')) {
668 $info = apache_lookup_uri($path);
669 return $info->filename.$info->path_info;
674 return GetRootPath().$path;
684function IsAllowedExt($sExtension, $resourceType)
688 $arAllowed = $Config[
'AllowedExtensions'][$resourceType];
689 $arDenied = $Config[
'DeniedExtensions'][$resourceType];
691 if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
695 if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
708function IsAllowedType($resourceType)
711 if (!in_array($resourceType, $Config[
'ConfigAllowedTypes'])) {
724function IsAllowedCommand($sCommand)
728 if (!in_array($sCommand, $Config[
'ConfigAllowedCommands'])) {
740function GetCurrentFolder()
745 $sCurrentFolder = isset($_GET[
'CurrentFolder']) ?
GETPOST(
'CurrentFolder',
'', 1) :
'/';
748 if (!preg_match(
'|/$|', $sCurrentFolder)) {
749 $sCurrentFolder .=
'/';
751 if (strpos($sCurrentFolder,
'/') !== 0) {
752 $sCurrentFolder =
'/'.$sCurrentFolder;
756 while (strpos($sCurrentFolder,
'//') !==
false) {
757 $sCurrentFolder = str_replace(
'//',
'/', $sCurrentFolder);
761 if (strpos($sCurrentFolder,
'..') || strpos($sCurrentFolder,
"\\")) {
765 if (preg_match(
",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"<>\|]),", $sCurrentFolder)) {
769 return $sCurrentFolder;
778function SanitizeFolderName($sNewFolderName)
780 $sNewFolderName = stripslashes($sNewFolderName);
783 $sNewFolderName = preg_replace(
'/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFolderName);
785 return $sNewFolderName;
794function SanitizeFileName($sNewFileName)
798 $sNewFileName = stripslashes($sNewFileName);
801 if ($Config[
'ForceSingleExtension']) {
802 $sNewFileName = preg_replace(
'/\\.(?![^.]*$)/',
'_', $sNewFileName);
806 $sNewFileName = preg_replace(
'/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/',
'_', $sNewFileName);
808 return $sNewFileName;
820function SendUploadResults($errorNumber, $fileUrl =
'', $fileName =
'', $customMsg =
'')
825<script
type=
"text/javascript">
826(
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;}}})();
829 if ($errorNumber && $errorNumber != 201) {
834 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
835 echo
'console.log('.$errorNumber.
');';
836 echo
'window.parent.OnUploadCompleted('.$errorNumber.
', "'.strtr($fileUrl, $rpl).
'", "'.strtr($fileName, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
853function SendCKEditorResults($callback, $sFileUrl, $customMsg =
'')
855 echo
'<script type="text/javascript">';
857 $rpl = array(
'\\' =>
'\\\\',
'"' =>
'\\"');
859 echo
'window.parent.CKEDITOR.tools.callFunction("'.$callback.
'","'.strtr($sFileUrl, $rpl).
'", "'.strtr($customMsg, $rpl).
'");';
873function RemoveFromStart($sourceString, $charToRemove)
875 $sPattern =
'|^'.$charToRemove.
'+|';
876 return preg_replace($sPattern,
'', $sourceString);
886function RemoveFromEnd($sourceString, $charToRemove)
888 $sPattern =
'|'.$charToRemove.
'+$|';
889 return preg_replace($sPattern,
'', $sourceString);
898function FindBadUtf8($string)
900 $regex =
'([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
901 $regex .=
'|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}|(.{1}))';
904 while (preg_match(
'/'.$regex.
'/S', $string, $matches)) {
905 if (isset($matches[2])) {
908 $string = substr($string, strlen($matches[0]));
920function ConvertToXmlAttribute($value)
922 if (defined(
'PHP_OS')) {
928 if (strtoupper(substr($os, 0, 3)) ===
'WIN' || FindBadUtf8($value)) {
929 return (utf8_encode(htmlspecialchars($value)));
931 return (htmlspecialchars($value));
942function IsHtmlExtension($ext, $formExtensions)
944 if (!$formExtensions || !is_array($formExtensions)) {
947 $lcaseHtmlExtensions = array();
948 foreach ($formExtensions as $key => $val) {
949 $lcaseHtmlExtensions[$key] = strtolower($val);
951 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)) {
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='')
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