2 * Copyright (C) 2005-2013 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
20 #include "network/Network.h"
21 #include "threads/SystemClock.h"
23 #if defined(TARGET_DARWIN)
24 #include <sys/param.h>
25 #include <mach-o/dyld.h>
28 #if defined(TARGET_FREEBSD)
29 #include <sys/param.h>
30 #include <sys/sysctl.h>
34 #include <sys/types.h>
39 #if defined(TARGET_ANDROID)
40 #include "android/bionic_supplement/bionic_supplement.h"
44 #include "Application.h"
46 #include "addons/Addon.h"
47 #include "filesystem/PVRDirectory.h"
48 #include "filesystem/Directory.h"
49 #include "filesystem/StackDirectory.h"
50 #include "filesystem/MultiPathDirectory.h"
51 #include "filesystem/SpecialProtocol.h"
52 #include "filesystem/RSSDirectory.h"
53 #ifdef HAS_FILESYSTEM_RAR
54 #include "filesystem/RarManager.h"
56 #include "filesystem/MythDirectory.h"
58 #include "filesystem/UPnPDirectory.h"
60 #include "profiles/ProfilesManager.h"
61 #include "utils/RegExp.h"
62 #include "guilib/GraphicContext.h"
63 #include "guilib/TextureManager.h"
64 #include "utils/fstrcmp.h"
65 #include "storage/MediaManager.h"
67 #include "utils/CharsetConverter.h"
69 #include "WIN32Util.h"
71 #if defined(TARGET_DARWIN)
72 #include "osx/DarwinUtils.h"
74 #include "GUIUserMessages.h"
75 #include "filesystem/File.h"
76 #include "settings/MediaSettings.h"
77 #include "settings/Settings.h"
78 #include "utils/StringUtils.h"
79 #include "settings/AdvancedSettings.h"
80 #ifdef HAS_IRSERVERSUITE
81 #include "input/windows/IRServerSuite.h"
83 #include "guilib/LocalizeStrings.h"
84 #include "utils/md5.h"
85 #include "utils/TimeUtils.h"
86 #include "utils/URIUtils.h"
87 #include "utils/log.h"
88 #include "utils/Environment.h"
90 #include "cores/dvdplayer/DVDSubtitles/DVDSubtitleTagSami.h"
91 #include "cores/dvdplayer/DVDSubtitles/DVDSubtitleStream.h"
93 #include "utils/LangCodeExpander.h"
95 #include <sys/capability.h>
98 #include "cores/dvdplayer/DVDDemuxers/DVDDemux.h"
103 #define clamp(x) (x) > 255.f ? 255 : ((x) < 0 ? 0 : (BYTE)(x+0.5f)) // Valid ranges: brightness[-1 -> 1 (0 is default)] contrast[0 -> 2 (1 is default)] gamma[0.5 -> 3.5 (1 is default)] default[ramp is linear]
104 static const int64_t SECS_BETWEEN_EPOCHS = 11644473600LL;
105 static const int64_t SECS_TO_100NS = 10000000;
107 using namespace XFILE;
108 using namespace PLAYLIST;
111 static D3DGAMMARAMP oldramp, flashramp;
112 #elif defined(HAS_SDL_2D)
113 static uint16_t oldrampRed[256];
114 static uint16_t oldrampGreen[256];
115 static uint16_t oldrampBlue[256];
116 static uint16_t flashrampRed[256];
117 static uint16_t flashrampGreen[256];
118 static uint16_t flashrampBlue[256];
121 #if !defined(TARGET_WINDOWS)
122 unsigned int CUtil::s_randomSeed = time(NULL);
132 CStdString CUtil::GetTitleFromPath(const CStdString& strFileNameAndPath, bool bIsFolder /* = false */)
134 // use above to get the filename
135 CStdString path(strFileNameAndPath);
136 URIUtils::RemoveSlashAtEnd(path);
137 CStdString strFilename = URIUtils::GetFileName(path);
139 CURL url(strFileNameAndPath);
140 CStdString strHostname = url.GetHostName();
144 if (url.GetProtocol() == "upnp")
145 strFilename = CUPnPDirectory::GetFriendlyName(strFileNameAndPath.c_str());
148 if (url.GetProtocol() == "rss")
152 if(dir.GetDirectory(strFileNameAndPath, items) && !items.m_strTitle.empty())
153 return items.m_strTitle;
157 else if (url.GetProtocol() == "shout")
159 const int genre = strFileNameAndPath.find_first_of('=');
161 strFilename = g_localizeStrings.Get(260);
163 strFilename = g_localizeStrings.Get(260) + " - " + strFileNameAndPath.substr(genre+1).c_str();
166 // Windows SMB Network (SMB)
167 else if (url.GetProtocol() == "smb" && strFilename.empty())
169 if (url.GetHostName().empty())
171 strFilename = g_localizeStrings.Get(20171);
175 strFilename = url.GetHostName();
178 // iTunes music share (DAAP)
179 else if (url.GetProtocol() == "daap" && strFilename.empty())
180 strFilename = g_localizeStrings.Get(20174);
183 else if (url.GetProtocol() == "hdhomerun" && strFilename.empty())
184 strFilename = "HDHomerun Devices";
187 else if (url.GetProtocol() == "sling")
188 strFilename = "Slingbox";
191 else if (url.GetProtocol() == "rtv")
192 strFilename = "ReplayTV Devices";
194 // HTS Tvheadend client
195 else if (url.GetProtocol() == "htsp")
196 strFilename = g_localizeStrings.Get(20256);
198 // VDR Streamdev client
199 else if (url.GetProtocol() == "vtp")
200 strFilename = g_localizeStrings.Get(20257);
203 else if (url.GetProtocol() == "myth")
204 strFilename = g_localizeStrings.Get(20258);
207 else if (url.GetProtocol() == "sap" && strFilename.empty())
208 strFilename = "SAP Streams";
211 else if (url.GetProtocol() == "sources")
212 strFilename = g_localizeStrings.Get(744);
215 else if (StringUtils::StartsWithNoCase(path, "special://musicplaylists"))
216 strFilename = g_localizeStrings.Get(136);
219 else if (StringUtils::StartsWithNoCase(path, "special://videoplaylists"))
220 strFilename = g_localizeStrings.Get(136);
222 else if (URIUtils::ProtocolHasParentInHostname(url.GetProtocol()) && strFilename.empty())
223 strFilename = URIUtils::GetFileName(url.GetHostName());
225 // now remove the extension if needed
226 if (!CSettings::Get().GetBool("filelists.showextensions") && !bIsFolder)
228 URIUtils::RemoveExtension(strFilename);
232 // URLDecode since the original path may be an URL
233 CURL::Decode(strFilename);
237 void CUtil::CleanString(const CStdString& strFileName, CStdString& strTitle, CStdString& strTitleAndYear, CStdString& strYear, bool bRemoveExtension /* = false */, bool bCleanChars /* = true */)
239 strTitleAndYear = strFileName;
241 if (strFileName.Equals(".."))
244 const CStdStringArray ®exps = g_advancedSettings.m_videoCleanStringRegExps;
246 CRegExp reTags(true, true);
247 CRegExp reYear(false, true);
249 if (!reYear.RegComp(g_advancedSettings.m_videoCleanDateTimeRegExp))
251 CLog::Log(LOGERROR, "%s: Invalid datetime clean RegExp:'%s'", __FUNCTION__, g_advancedSettings.m_videoCleanDateTimeRegExp.c_str());
255 if (reYear.RegFind(strTitleAndYear.c_str()) >= 0)
257 strTitleAndYear = reYear.GetMatch(1);
258 strYear = reYear.GetMatch(2);
262 URIUtils::RemoveExtension(strTitleAndYear);
264 for (unsigned int i = 0; i < regexps.size(); i++)
266 if (!reTags.RegComp(regexps[i].c_str()))
267 { // invalid regexp - complain in logs
268 CLog::Log(LOGERROR, "%s: Invalid string clean RegExp:'%s'", __FUNCTION__, regexps[i].c_str());
272 if ((j=reTags.RegFind(strTitleAndYear.c_str())) > 0)
273 strTitleAndYear = strTitleAndYear.substr(0, j);
276 // final cleanup - special characters used instead of spaces:
277 // all '_' tokens should be replaced by spaces
278 // if the file contains no spaces, all '.' tokens should be replaced by
279 // spaces - one possibility of a mistake here could be something like:
280 // "Dr..StrangeLove" - hopefully no one would have anything like this.
283 bool initialDots = true;
284 bool alreadyContainsSpace = (strTitleAndYear.find(' ') != std::string::npos);
286 for (size_t i = 0; i < strTitleAndYear.size(); i++)
288 char c = strTitleAndYear[i];
293 if ((c == '_') || ((!alreadyContainsSpace) && !initialDots && (c == '.')))
295 strTitleAndYear[i] = ' ';
300 StringUtils::Trim(strTitleAndYear);
301 strTitle = strTitleAndYear;
304 if (!strYear.empty())
305 strTitleAndYear = strTitle + " (" + strYear + ")";
307 // restore extension if needed
308 if (!bRemoveExtension)
309 strTitleAndYear += URIUtils::GetExtension(strFileName);
312 void CUtil::GetQualifiedFilename(const CStdString &strBasePath, CStdString &strFilename)
314 // Check if the filename is a fully qualified URL such as protocol://path/to/file
315 CURL plItemUrl(strFilename);
316 if (!plItemUrl.GetProtocol().empty())
319 // If the filename starts "x:", "\\" or "/" it's already fully qualified so return
320 if (strFilename.size() > 1)
322 if ( (strFilename[1] == ':') || (strFilename[0] == '/') )
324 if ( strFilename[1] == ':' || (strFilename[0] == '\\' && strFilename[1] == '\\'))
328 // add to base path and then clean
329 strFilename = URIUtils::AddFileToFolder(strBasePath, strFilename);
331 // get rid of any /./ or \.\ that happen to be there
332 StringUtils::Replace(strFilename, "\\.\\", "\\");
333 StringUtils::Replace(strFilename, "/./", "/");
335 // now find any "\\..\\" and remove them via GetParentPath
337 while ((pos = strFilename.find("/../")) != std::string::npos)
339 CStdString basePath = strFilename.substr(0, pos + 1);
340 strFilename.erase(0, pos + 4);
341 basePath = URIUtils::GetParentPath(basePath);
342 strFilename = URIUtils::AddFileToFolder(basePath, strFilename);
344 while ((pos = strFilename.find("\\..\\")) != std::string::npos)
346 CStdString basePath = strFilename.substr(0, pos + 1);
347 strFilename.erase(0, pos + 4);
348 basePath = URIUtils::GetParentPath(basePath);
349 strFilename = URIUtils::AddFileToFolder(basePath, strFilename);
354 bool CUtil::TestGetQualifiedFilename()
356 CStdString file = "../foo"; GetQualifiedFilename("smb://", file);
357 if (file != "foo") return false;
358 file = "C:\\foo\\bar"; GetQualifiedFilename("smb://", file);
359 if (file != "C:\\foo\\bar") return false;
360 file = "../foo/./bar"; GetQualifiedFilename("smb://my/path", file);
361 if (file != "smb://my/foo/bar") return false;
362 file = "smb://foo/bar/"; GetQualifiedFilename("upnp://", file);
363 if (file != "smb://foo/bar/") return false;
367 bool CUtil::TestMakeLegalPath()
370 #ifdef TARGET_WINDOWS
371 path = "C:\\foo\\bar"; path = MakeLegalPath(path);
372 if (path != "C:\\foo\\bar") return false;
373 path = "C:\\foo:\\bar\\"; path = MakeLegalPath(path);
374 if (path != "C:\\foo_\\bar\\") return false;
376 path = "/foo/bar/"; path = MakeLegalPath(path);
377 if (path != "/foo/bar/") return false;
378 path = "/foo?/bar"; path = MakeLegalPath(path);
379 if (path != "/foo_/bar") return false;
381 path = "smb://foo/bar"; path = MakeLegalPath(path);
382 if (path != "smb://foo/bar") return false;
383 path = "smb://foo/bar?/"; path = MakeLegalPath(path);
384 if (path != "smb://foo/bar_/") return false;
389 void CUtil::RunShortcut(const char* szShortcutPath)
393 void CUtil::GetHomePath(CStdString& strPath, const CStdString& strTarget)
395 strPath = CEnvironment::getenv(strTarget);
397 #ifdef TARGET_WINDOWS
398 if (strPath.find("..") != std::string::npos)
400 //expand potential relative path to full path
401 CStdStringW strPathW;
402 g_charsetConverter.utf8ToW(strPath, strPathW, false);
403 CWIN32Util::AddExtraLongPathPrefix(strPathW);
404 const unsigned int bufSize = GetFullPathNameW(strPathW, 0, NULL, NULL);
407 wchar_t * buf = new wchar_t[bufSize];
408 if (GetFullPathNameW(strPathW, bufSize, buf, NULL) <= bufSize-1)
410 std::wstring expandedPathW(buf);
411 CWIN32Util::RemoveExtraLongPathPrefix(expandedPathW);
412 g_charsetConverter.wToUTF8(expandedPathW, strPath);
422 CStdString strHomePath = ResolveExecutablePath();
423 #if defined(TARGET_DARWIN)
425 char given_path[2*MAXPATHLEN];
426 uint32_t path_size =2*MAXPATHLEN;
428 result = GetDarwinExecutablePath(given_path, &path_size);
431 // Move backwards to last /.
432 for (int n=strlen(given_path)-1; given_path[n] != '/'; n--)
433 given_path[n] = '\0';
435 #if defined(TARGET_DARWIN_IOS)
436 strcat(given_path, "/XBMCData/XBMCHome/");
438 // Assume local path inside application bundle.
439 strcat(given_path, "../Resources/XBMC/");
442 // Convert to real path.
443 char real_path[2*MAXPATHLEN];
444 if (realpath(given_path, real_path) != NULL)
451 size_t last_sep = strHomePath.find_last_of(PATH_SEPARATOR_CHAR);
452 if (last_sep != string::npos)
453 strPath = strHomePath.substr(0, last_sep);
455 strPath = strHomePath;
458 #if defined(TARGET_POSIX) && !defined(TARGET_DARWIN)
459 /* Change strPath accordingly when target is XBMC_HOME and when INSTALL_PATH
460 * and BIN_INSTALL_PATH differ
462 CStdString installPath = INSTALL_PATH;
463 CStdString binInstallPath = BIN_INSTALL_PATH;
464 if (!strTarget.compare("XBMC_HOME") && installPath.compare(binInstallPath))
466 int pos = strPath.length() - binInstallPath.length();
467 CStdString tmp = strPath;
469 if (!tmp.compare(binInstallPath))
471 strPath.erase(pos, strPath.length());
472 strPath.append(installPath);
478 bool CUtil::IsPVR(const CStdString& strFile)
480 return StringUtils::StartsWithNoCase(strFile, "pvr:");
483 bool CUtil::IsHTSP(const CStdString& strFile)
485 return StringUtils::StartsWithNoCase(strFile, "htsp:");
488 bool CUtil::IsLiveTV(const CStdString& strFile)
490 if (StringUtils::StartsWithNoCase(strFile, "pvr://channels"))
493 if(URIUtils::IsTuxBox(strFile)
494 || URIUtils::IsVTP(strFile)
495 || URIUtils::IsHDHomeRun(strFile)
496 || URIUtils::IsHTSP(strFile)
497 || StringUtils::StartsWithNoCase(strFile, "sap:"))
500 if (URIUtils::IsMythTV(strFile) && CMythDirectory::IsLiveTV(strFile))
506 bool CUtil::IsTVRecording(const CStdString& strFile)
508 return StringUtils::StartsWithNoCase(strFile, "pvr://recording");
511 bool CUtil::IsPicture(const CStdString& strFile)
513 return URIUtils::HasExtension(strFile,
514 g_advancedSettings.m_pictureExtensions + "|.tbn|.dds");
517 bool CUtil::ExcludeFileOrFolder(const CStdString& strFileOrFolder, const CStdStringArray& regexps)
519 if (strFileOrFolder.empty())
522 CRegExp regExExcludes(true, true); // case insensitive regex
524 for (unsigned int i = 0; i < regexps.size(); i++)
526 if (!regExExcludes.RegComp(regexps[i].c_str()))
527 { // invalid regexp - complain in logs
528 CLog::Log(LOGERROR, "%s: Invalid exclude RegExp:'%s'", __FUNCTION__, regexps[i].c_str());
531 if (regExExcludes.RegFind(strFileOrFolder) > -1)
533 CLog::Log(LOGDEBUG, "%s: File '%s' excluded. (Matches exclude rule RegExp:'%s')", __FUNCTION__, strFileOrFolder.c_str(), regexps[i].c_str());
540 void CUtil::GetFileAndProtocol(const CStdString& strURL, CStdString& strDir)
543 if (!URIUtils::IsRemote(strURL)) return ;
544 if (URIUtils::IsDVD(strURL)) return ;
547 strDir = StringUtils::Format("%s://%s", url.GetProtocol().c_str(), url.GetFileName().c_str());
550 int CUtil::GetDVDIfoTitle(const CStdString& strFile)
552 CStdString strFilename = URIUtils::GetFileName(strFile);
553 if (strFilename.Equals("video_ts.ifo")) return 0;
555 return atoi(strFilename.substr(4, 2).c_str());
558 CStdString CUtil::GetFileMD5(const CStdString& strPath)
562 if (file.Open(strPath))
570 read = file.Read(temp,1024);
572 md5.append(temp,read);
574 md5.getDigest(result);
581 bool CUtil::GetDirectoryName(const CStdString& strFileName, CStdString& strDescription)
583 CStdString strFName = URIUtils::GetFileName(strFileName);
584 strDescription = URIUtils::GetDirectory(strFileName);
585 URIUtils::RemoveSlashAtEnd(strDescription);
587 size_t iPos = strDescription.find_last_of("/\\");
588 if (iPos != std::string::npos)
589 strDescription = strDescription.substr(iPos + 1);
590 else if (strDescription.size() <= 0)
591 strDescription = strFName;
595 void CUtil::GetDVDDriveIcon( const CStdString& strPath, CStdString& strIcon )
597 if ( !g_mediaManager.IsDiscInDrive() )
599 strIcon = "DefaultDVDEmpty.png";
603 if ( URIUtils::IsDVD(strPath) )
606 CCdInfo* pInfo = g_mediaManager.GetCdInfo();
608 if ( pInfo != NULL && pInfo->IsUDFX( 1 ) )
610 strIcon = "DefaultXboxDVD.png";
614 strIcon = "DefaultDVDRom.png";
618 if ( URIUtils::IsISO9660(strPath) )
621 CCdInfo* pInfo = g_mediaManager.GetCdInfo();
622 if ( pInfo != NULL && pInfo->IsVideoCd( 1 ) )
624 strIcon = "DefaultVCD.png";
628 strIcon = "DefaultDVDRom.png";
632 if ( URIUtils::IsCDDA(strPath) )
634 strIcon = "DefaultCDDA.png";
639 void CUtil::RemoveTempFiles()
641 CStdString searchPath = CProfilesManager::Get().GetDatabaseFolder();
643 if (!XFILE::CDirectory::GetDirectory(searchPath, items, ".tmp", DIR_FLAG_NO_FILE_DIRS))
646 for (int i = 0; i < items.Size(); ++i)
648 if (items[i]->m_bIsFolder)
650 XFILE::CFile::Delete(items[i]->GetPath());
654 void CUtil::ClearSubtitles()
658 CDirectory::GetDirectory("special://temp/",items);
659 for( int i=0;i<items.Size();++i)
661 if (!items[i]->m_bIsFolder)
663 if (items[i]->GetPath().find("subtitle") != std::string::npos ||
664 items[i]->GetPath().find("vobsub_queue") != std::string::npos)
666 CLog::Log(LOGDEBUG, "%s - Deleting temporary subtitle %s", __FUNCTION__, items[i]->GetPath().c_str());
667 CFile::Delete(items[i]->GetPath());
673 void CUtil::ClearTempFonts()
675 CStdString searchPath = "special://temp/fonts/";
677 if (!CFile::Exists(searchPath))
681 CDirectory::GetDirectory(searchPath, items, "", DIR_FLAG_NO_FILE_DIRS | DIR_FLAG_BYPASS_CACHE);
683 for (int i=0; i<items.Size(); ++i)
685 if (items[i]->m_bIsFolder)
687 CFile::Delete(items[i]->GetPath());
691 static const char * sub_exts[] = { ".utf", ".utf8", ".utf-8", ".sub", ".srt", ".smi", ".rt", ".txt", ".ssa", ".aqt", ".jss", ".ass", ".idx", NULL};
693 int64_t CUtil::ToInt64(uint32_t high, uint32_t low)
702 CStdString CUtil::GetNextFilename(const CStdString &fn_template, int max)
704 if (fn_template.find("%03d") == std::string::npos)
707 CStdString searchPath = URIUtils::GetDirectory(fn_template);
708 CStdString mask = URIUtils::GetExtension(fn_template);
709 CStdString name = StringUtils::Format(fn_template.c_str(), 0);
712 if (!CDirectory::GetDirectory(searchPath, items, mask, DIR_FLAG_NO_FILE_DIRS))
715 items.SetFastLookup(true);
716 for (int i = 0; i <= max; i++)
718 CStdString name = StringUtils::Format(fn_template.c_str(), i);
719 if (!items.Get(name))
725 CStdString CUtil::GetNextPathname(const CStdString &path_template, int max)
727 if (path_template.find("%04d") == std::string::npos)
730 for (int i = 0; i <= max; i++)
732 CStdString name = StringUtils::Format(path_template.c_str(), i);
733 if (!CFile::Exists(name))
739 void CUtil::StatToStatI64(struct _stati64 *result, struct stat *stat)
741 result->st_dev = stat->st_dev;
742 result->st_ino = stat->st_ino;
743 result->st_mode = stat->st_mode;
744 result->st_nlink = stat->st_nlink;
745 result->st_uid = stat->st_uid;
746 result->st_gid = stat->st_gid;
747 result->st_rdev = stat->st_rdev;
748 result->st_size = (int64_t)stat->st_size;
751 result->st_atime = (long)(stat->st_atime & 0xFFFFFFFF);
752 result->st_mtime = (long)(stat->st_mtime & 0xFFFFFFFF);
753 result->st_ctime = (long)(stat->st_ctime & 0xFFFFFFFF);
755 result->_st_atime = (long)(stat->st_atime & 0xFFFFFFFF);
756 result->_st_mtime = (long)(stat->st_mtime & 0xFFFFFFFF);
757 result->_st_ctime = (long)(stat->st_ctime & 0xFFFFFFFF);
761 void CUtil::Stat64ToStatI64(struct _stati64 *result, struct __stat64 *stat)
763 result->st_dev = stat->st_dev;
764 result->st_ino = stat->st_ino;
765 result->st_mode = stat->st_mode;
766 result->st_nlink = stat->st_nlink;
767 result->st_uid = stat->st_uid;
768 result->st_gid = stat->st_gid;
769 result->st_rdev = stat->st_rdev;
770 result->st_size = stat->st_size;
772 result->st_atime = (long)(stat->st_atime & 0xFFFFFFFF);
773 result->st_mtime = (long)(stat->st_mtime & 0xFFFFFFFF);
774 result->st_ctime = (long)(stat->st_ctime & 0xFFFFFFFF);
776 result->_st_atime = (long)(stat->st_atime & 0xFFFFFFFF);
777 result->_st_mtime = (long)(stat->st_mtime & 0xFFFFFFFF);
778 result->_st_ctime = (long)(stat->st_ctime & 0xFFFFFFFF);
782 void CUtil::StatI64ToStat64(struct __stat64 *result, struct _stati64 *stat)
784 result->st_dev = stat->st_dev;
785 result->st_ino = stat->st_ino;
786 result->st_mode = stat->st_mode;
787 result->st_nlink = stat->st_nlink;
788 result->st_uid = stat->st_uid;
789 result->st_gid = stat->st_gid;
790 result->st_rdev = stat->st_rdev;
791 result->st_size = stat->st_size;
793 result->st_atime = stat->st_atime;
794 result->st_mtime = stat->st_mtime;
795 result->st_ctime = stat->st_ctime;
797 result->st_atime = stat->_st_atime;
798 result->st_mtime = stat->_st_mtime;
799 result->st_ctime = stat->_st_ctime;
803 void CUtil::Stat64ToStat(struct stat *result, struct __stat64 *stat)
805 result->st_dev = stat->st_dev;
806 result->st_ino = stat->st_ino;
807 result->st_mode = stat->st_mode;
808 result->st_nlink = stat->st_nlink;
809 result->st_uid = stat->st_uid;
810 result->st_gid = stat->st_gid;
811 result->st_rdev = stat->st_rdev;
813 if (stat->st_size <= LONG_MAX)
814 result->st_size = (_off_t)stat->st_size;
816 if (sizeof(stat->st_size) <= sizeof(result->st_size) )
817 result->st_size = stat->st_size;
822 CLog::Log(LOGWARNING, "WARNING: File is larger than 32bit stat can handle, file size will be reported as 0 bytes");
824 result->st_atime = (time_t)(stat->st_atime & 0xFFFFFFFF);
825 result->st_mtime = (time_t)(stat->st_mtime & 0xFFFFFFFF);
826 result->st_ctime = (time_t)(stat->st_ctime & 0xFFFFFFFF);
829 #ifdef TARGET_WINDOWS
830 void CUtil::Stat64ToStat64i32(struct _stat64i32 *result, struct __stat64 *stat)
832 result->st_dev = stat->st_dev;
833 result->st_ino = stat->st_ino;
834 result->st_mode = stat->st_mode;
835 result->st_nlink = stat->st_nlink;
836 result->st_uid = stat->st_uid;
837 result->st_gid = stat->st_gid;
838 result->st_rdev = stat->st_rdev;
840 if (stat->st_size <= LONG_MAX)
841 result->st_size = (_off_t)stat->st_size;
843 if (sizeof(stat->st_size) <= sizeof(result->st_size) )
844 result->st_size = stat->st_size;
849 CLog::Log(LOGWARNING, "WARNING: File is larger than 32bit stat can handle, file size will be reported as 0 bytes");
852 result->st_atime = stat->st_atime;
853 result->st_mtime = stat->st_mtime;
854 result->st_ctime = stat->st_ctime;
856 result->st_atime = stat->_st_atime;
857 result->st_mtime = stat->_st_mtime;
858 result->st_ctime = stat->_st_ctime;
863 bool CUtil::CreateDirectoryEx(const CStdString& strPath)
865 // Function to create all directories at once instead
866 // of calling CreateDirectory for every subdir.
867 // Creates the directory and subdirectories if needed.
869 // return true if directory already exist
870 if (CDirectory::Exists(strPath)) return true;
872 // we currently only allow HD and smb, nfs and afp paths
873 if (!URIUtils::IsHD(strPath) && !URIUtils::IsSmb(strPath) && !URIUtils::IsNfs(strPath) && !URIUtils::IsAfp(strPath))
875 CLog::Log(LOGERROR,"%s called with an unsupported path: %s", __FUNCTION__, strPath.c_str());
879 CStdStringArray dirs = URIUtils::SplitPath(strPath);
880 CStdString dir(dirs.front());
881 URIUtils::AddSlashAtEnd(dir);
882 for (CStdStringArray::iterator it = dirs.begin() + 1; it != dirs.end(); it ++)
884 dir = URIUtils::AddFileToFolder(dir, *it);
885 CDirectory::Create(dir);
888 // was the final destination directory successfully created ?
889 if (!CDirectory::Exists(strPath)) return false;
893 CStdString CUtil::MakeLegalFileName(const CStdString &strFile, int LegalType)
895 CStdString result = strFile;
897 StringUtils::Replace(result, '/', '_');
898 StringUtils::Replace(result, '\\', '_');
899 StringUtils::Replace(result, '?', '_');
901 if (LegalType == LEGAL_WIN32_COMPAT)
903 // just filter out some illegal characters on windows
904 StringUtils::Replace(result, ':', '_');
905 StringUtils::Replace(result, '*', '_');
906 StringUtils::Replace(result, '?', '_');
907 StringUtils::Replace(result, '\"', '_');
908 StringUtils::Replace(result, '<', '_');
909 StringUtils::Replace(result, '>', '_');
910 StringUtils::Replace(result, '|', '_');
911 StringUtils::TrimRight(result, ". ");
916 // legalize entire path
917 CStdString CUtil::MakeLegalPath(const CStdString &strPathAndFile, int LegalType)
919 if (URIUtils::IsStack(strPathAndFile))
920 return MakeLegalPath(CStackDirectory::GetFirstStackedFile(strPathAndFile));
921 if (URIUtils::IsMultiPath(strPathAndFile))
922 return MakeLegalPath(CMultiPathDirectory::GetFirstPath(strPathAndFile));
923 if (!URIUtils::IsHD(strPathAndFile) && !URIUtils::IsSmb(strPathAndFile) && !URIUtils::IsNfs(strPathAndFile) && !URIUtils::IsAfp(strPathAndFile))
924 return strPathAndFile; // we don't support writing anywhere except HD, SMB, NFS and AFP - no need to legalize path
926 bool trailingSlash = URIUtils::HasSlashAtEnd(strPathAndFile);
927 CStdStringArray dirs = URIUtils::SplitPath(strPathAndFile);
928 // we just add first token to path and don't legalize it - possible values:
929 // "X:" (local win32), "" (local unix - empty string before '/') or
930 // "protocol://domain"
931 CStdString dir(dirs.front());
932 URIUtils::AddSlashAtEnd(dir);
933 for (CStdStringArray::iterator it = dirs.begin() + 1; it != dirs.end(); it ++)
934 dir = URIUtils::AddFileToFolder(dir, MakeLegalFileName(*it, LegalType));
935 if (trailingSlash) URIUtils::AddSlashAtEnd(dir);
939 CStdString CUtil::ValidatePath(const CStdString &path, bool bFixDoubleSlashes /* = false */)
941 CStdString result = path;
943 // Don't do any stuff on URLs containing %-characters or protocols that embed
944 // filenames. NOTE: Don't use IsInZip or IsInRar here since it will infinitely
945 // recurse and crash XBMC
946 if (URIUtils::IsURL(path) &&
947 (path.find('%') != std::string::npos ||
948 StringUtils::StartsWithNoCase(path, "apk:") ||
949 StringUtils::StartsWithNoCase(path, "zip:") ||
950 StringUtils::StartsWithNoCase(path, "rar:") ||
951 StringUtils::StartsWithNoCase(path, "stack:") ||
952 StringUtils::StartsWithNoCase(path, "bluray:") ||
953 StringUtils::StartsWithNoCase(path, "multipath:") ))
956 // check the path for incorrect slashes
957 #ifdef TARGET_WINDOWS
958 if (URIUtils::IsDOSPath(path))
960 StringUtils::Replace(result, '/', '\\');
961 /* The double slash correction should only be used when *absolutely*
962 necessary! This applies to certain DLLs or use from Python DLLs/scripts
963 that incorrectly generate double (back) slashes.
965 if (bFixDoubleSlashes && !result.empty())
967 // Fixup for double back slashes (but ignore the \\ of unc-paths)
968 for (size_t x = 1; x < result.size() - 1; x++)
970 if (result[x] == '\\' && result[x+1] == '\\')
975 else if (path.find("://") != std::string::npos || path.find(":\\\\") != std::string::npos)
978 StringUtils::Replace(result, '\\', '/');
979 /* The double slash correction should only be used when *absolutely*
980 necessary! This applies to certain DLLs or use from Python DLLs/scripts
981 that incorrectly generate double (back) slashes.
983 if (bFixDoubleSlashes && !result.empty())
985 // Fixup for double forward slashes(/) but don't touch the :// of URLs
986 for (size_t x = 2; x < result.size() - 1; x++)
988 if ( result[x] == '/' && result[x + 1] == '/' && !(result[x - 1] == ':' || (result[x - 1] == '/' && result[x - 2] == ':')) )
996 bool CUtil::IsUsingTTFSubtitles()
998 return URIUtils::HasExtension(CSettings::Get().GetString("subtitles.font"), ".ttf");
1002 bool CUtil::TestSplitExec()
1004 CStdString function;
1005 vector<CStdString> params;
1006 CUtil::SplitExecFunction("ActivateWindow(Video, \"C:\\test\\foo\")", function, params);
1007 if (function != "ActivateWindow" || params.size() != 2 || params[0] != "Video" || params[1] != "C:\\test\\foo")
1010 CUtil::SplitExecFunction("ActivateWindow(Video, \"C:\\test\\foo\\\")", function, params);
1011 if (function != "ActivateWindow" || params.size() != 2 || params[0] != "Video" || params[1] != "C:\\test\\foo\"")
1013 CUtil::SplitExecFunction("ActivateWindow(Video, \"C:\\\\test\\\\foo\\\\\")", function, params);
1014 if (function != "ActivateWindow" || params.size() != 2 || params[0] != "Video" || params[1] != "C:\\test\\foo\\")
1016 CUtil::SplitExecFunction("ActivateWindow(Video, \"C:\\\\\\\\test\\\\\\foo\\\\\")", function, params);
1017 if (function != "ActivateWindow" || params.size() != 2 || params[0] != "Video" || params[1] != "C:\\\\test\\\\foo\\")
1019 CUtil::SplitExecFunction("SetProperty(Foo,\"\")", function, params);
1020 if (function != "SetProperty" || params.size() != 2 || params[0] != "Foo" || params[1] != "")
1022 CUtil::SplitExecFunction("SetProperty(foo,ba(\"ba black )\",sheep))", function, params);
1023 if (function != "SetProperty" || params.size() != 2 || params[0] != "foo" || params[1] != "ba(\"ba black )\",sheep)")
1029 void CUtil::SplitExecFunction(const CStdString &execString, CStdString &function, vector<CStdString> ¶meters)
1031 CStdString paramString;
1033 size_t iPos = execString.find("(");
1034 size_t iPos2 = execString.rfind(")");
1035 if (iPos != std::string::npos && iPos2 != std::string::npos)
1037 paramString = execString.substr(iPos + 1, iPos2 - iPos - 1);
1038 function = execString.substr(0, iPos);
1041 function = execString;
1043 // remove any whitespace, and the standard prefix (if it exists)
1044 StringUtils::Trim(function);
1045 if( StringUtils::StartsWithNoCase(function, "xbmc.") )
1046 function.erase(0, 5);
1048 SplitParams(paramString, parameters);
1051 void CUtil::SplitParams(const CStdString ¶mString, std::vector<CStdString> ¶meters)
1053 bool inQuotes = false;
1054 bool lastEscaped = false; // only every second character can be escaped
1056 size_t whiteSpacePos = 0;
1057 CStdString parameter;
1059 for (size_t pos = 0; pos < paramString.size(); pos++)
1061 char ch = paramString[pos];
1062 bool escaped = (pos > 0 && paramString[pos - 1] == '\\' && !lastEscaped);
1063 lastEscaped = escaped;
1065 { // if we're in a quote, we accept everything until the closing quote
1066 if (ch == '"' && !escaped)
1067 { // finished a quote - no need to add the end quote to our string
1072 { // not in a quote, so check if we should be starting one
1073 if (ch == '"' && !escaped)
1074 { // start of quote - no need to add the quote to our string
1077 if (inFunction && ch == ')')
1078 { // end of a function
1082 { // start of function
1085 if (!inFunction && ch == ',')
1086 { // not in a function, so a comma signfies the end of this parameter
1088 parameter = parameter.substr(0, whiteSpacePos);
1089 // trim off start and end quotes
1090 if (parameter.length() > 1 && parameter[0] == '"' && parameter[parameter.length() - 1] == '"')
1091 parameter = parameter.substr(1, parameter.length() - 2);
1092 else if (parameter.length() > 3 && parameter[parameter.length() - 1] == '"')
1094 // check name="value" style param.
1095 size_t quotaPos = parameter.find('"');
1096 if (quotaPos > 1 && quotaPos < parameter.length() - 1 && parameter[quotaPos - 1] == '=')
1098 parameter.erase(parameter.length() - 1);
1099 parameter.erase(quotaPos);
1102 parameters.push_back(parameter);
1108 if ((ch == '"' || ch == '\\') && escaped)
1109 { // escaped quote or backslash
1110 parameter[parameter.size()-1] = ch;
1113 // whitespace handling - we skip any whitespace at the left or right of an unquoted parameter
1114 if (ch == ' ' && !inQuotes)
1116 if (parameter.empty()) // skip whitespace on left
1118 if (!whiteSpacePos) // make a note of where whitespace starts on the right
1119 whiteSpacePos = parameter.size();
1125 if (inFunction || inQuotes)
1126 CLog::Log(LOGWARNING, "%s(%s) - end of string while searching for ) or \"", __FUNCTION__, paramString.c_str());
1128 parameter.erase(whiteSpacePos);
1129 // trim off start and end quotes
1130 if (parameter.size() > 1 && parameter[0] == '"' && parameter[parameter.size() - 1] == '"')
1131 parameter = parameter.substr(1,parameter.size() - 2);
1132 else if (parameter.size() > 3 && parameter[parameter.size() - 1] == '"')
1134 // check name="value" style param.
1135 size_t quotaPos = parameter.find('"');
1136 if (quotaPos > 1 && quotaPos < parameter.length() - 1 && parameter[quotaPos - 1] == '=')
1138 parameter.erase(parameter.length() - 1);
1139 parameter.erase(quotaPos);
1142 if (!parameter.empty() || parameters.size())
1143 parameters.push_back(parameter);
1146 int CUtil::GetMatchingSource(const CStdString& strPath1, VECSOURCES& VECSOURCES, bool& bIsSourceName)
1148 if (strPath1.empty())
1151 // copy as we may change strPath
1152 CStdString strPath = strPath1;
1154 // Check for special protocols
1155 CURL checkURL(strPath);
1158 if (checkURL.GetProtocol() == "stack")
1159 strPath.erase(0, 8); // remove the stack protocol
1161 if (checkURL.GetProtocol() == "shout")
1162 strPath = checkURL.GetHostName();
1163 if (checkURL.GetProtocol() == "tuxbox")
1165 if (checkURL.GetProtocol() == "plugin")
1167 if (checkURL.GetProtocol() == "multipath")
1168 strPath = CMultiPathDirectory::GetFirstPath(strPath);
1170 bIsSourceName = false;
1173 // we first test the NAME of a source
1174 for (int i = 0; i < (int)VECSOURCES.size(); ++i)
1176 CMediaSource share = VECSOURCES.at(i);
1177 CStdString strName = share.strName;
1179 // special cases for dvds
1180 if (URIUtils::IsOnDVD(share.strPath))
1182 if (URIUtils::IsOnDVD(strPath))
1185 // not a path, so we need to modify the source name
1186 // since we add the drive status and disc name to the source
1187 // "Name (Drive Status/Disc Name)"
1188 size_t iPos = strName.rfind('(');
1189 if (iPos != std::string::npos && iPos > 1)
1190 strName = strName.substr(0, iPos - 1);
1192 if (strPath.Equals(strName))
1194 bIsSourceName = true;
1199 // now test the paths
1201 // remove user details, and ensure path only uses forward slashes
1202 // and ends with a trailing slash so as not to match a substring
1203 CURL urlDest(strPath);
1204 urlDest.SetOptions("");
1205 CStdString strDest = urlDest.GetWithoutUserDetails();
1206 ForceForwardSlashes(strDest);
1207 if (!URIUtils::HasSlashAtEnd(strDest))
1211 size_t iLenPath = strDest.size();
1212 for (int i = 0; i < (int)VECSOURCES.size(); ++i)
1214 CMediaSource share = VECSOURCES.at(i);
1216 // does it match a source name?
1217 if (share.strPath.substr(0,8) == "shout://")
1219 CURL url(share.strPath);
1220 if (strPath.Equals(url.GetHostName()))
1224 // doesnt match a name, so try the source path
1225 vector<CStdString> vecPaths;
1227 // add any concatenated paths if they exist
1228 if (share.vecPaths.size() > 0)
1229 vecPaths = share.vecPaths;
1231 // add the actual share path at the front of the vector
1232 vecPaths.insert(vecPaths.begin(), share.strPath);
1235 for (int j = 0; j < (int)vecPaths.size(); ++j)
1237 // remove user details, and ensure path only uses forward slashes
1238 // and ends with a trailing slash so as not to match a substring
1239 CURL urlShare(vecPaths[j]);
1240 urlShare.SetOptions("");
1241 CStdString strShare = urlShare.GetWithoutUserDetails();
1242 ForceForwardSlashes(strShare);
1243 if (!URIUtils::HasSlashAtEnd(strShare))
1245 size_t iLenShare = strShare.size();
1247 if ((iLenPath >= iLenShare) && StringUtils::StartsWithNoCase(strDest, strShare) && (iLenShare > iLength))
1249 // if exact match, return it immediately
1250 if (iLenPath == iLenShare)
1252 // if the path EXACTLY matches an item in a concatentated path
1253 // set source name to true to load the full virtualpath
1254 bIsSourceName = false;
1255 if (vecPaths.size() > 1)
1256 bIsSourceName = true;
1260 iLength = iLenShare;
1265 // return the index of the share with the longest match
1269 // rar:// and zip://
1270 // if archive wasn't mounted, look for a matching share for the archive instead
1271 if( StringUtils::StartsWithNoCase(strPath, "rar://") || StringUtils::StartsWithNoCase(strPath, "zip://") )
1273 // get the hostname portion of the url since it contains the archive file
1274 strPath = checkURL.GetHostName();
1276 bIsSourceName = false;
1278 return GetMatchingSource(strPath, VECSOURCES, bDummy);
1281 CLog::Log(LOGDEBUG,"CUtil::GetMatchingSource: no matching source found for [%s]", strPath1.c_str());
1286 CStdString CUtil::TranslateSpecialSource(const CStdString &strSpecial)
1288 if (!strSpecial.empty() && strSpecial[0] == '$')
1290 if (StringUtils::StartsWithNoCase(strSpecial, "$home"))
1291 return URIUtils::AddFileToFolder("special://home/", strSpecial.substr(5));
1292 else if (StringUtils::StartsWithNoCase(strSpecial, "$subtitles"))
1293 return URIUtils::AddFileToFolder("special://subtitles/", strSpecial.substr(10));
1294 else if (StringUtils::StartsWithNoCase(strSpecial, "$userdata"))
1295 return URIUtils::AddFileToFolder("special://userdata/", strSpecial.substr(9));
1296 else if (StringUtils::StartsWithNoCase(strSpecial, "$database"))
1297 return URIUtils::AddFileToFolder("special://database/", strSpecial.substr(9));
1298 else if (StringUtils::StartsWithNoCase(strSpecial, "$thumbnails"))
1299 return URIUtils::AddFileToFolder("special://thumbnails/", strSpecial.substr(11));
1300 else if (StringUtils::StartsWithNoCase(strSpecial, "$recordings"))
1301 return URIUtils::AddFileToFolder("special://recordings/", strSpecial.substr(11));
1302 else if (StringUtils::StartsWithNoCase(strSpecial, "$screenshots"))
1303 return URIUtils::AddFileToFolder("special://screenshots/", strSpecial.substr(12));
1304 else if (StringUtils::StartsWithNoCase(strSpecial, "$musicplaylists"))
1305 return URIUtils::AddFileToFolder("special://musicplaylists/", strSpecial.substr(15));
1306 else if (StringUtils::StartsWithNoCase(strSpecial, "$videoplaylists"))
1307 return URIUtils::AddFileToFolder("special://videoplaylists/", strSpecial.substr(15));
1308 else if (StringUtils::StartsWithNoCase(strSpecial, "$cdrips"))
1309 return URIUtils::AddFileToFolder("special://cdrips/", strSpecial.substr(7));
1310 // this one will be removed post 2.0
1311 else if (StringUtils::StartsWithNoCase(strSpecial, "$playlists"))
1312 return URIUtils::AddFileToFolder(CSettings::Get().GetString("system.playlistspath"), strSpecial.substr(10));
1317 CStdString CUtil::MusicPlaylistsLocation()
1319 vector<CStdString> vec;
1320 vec.push_back(URIUtils::AddFileToFolder(CSettings::Get().GetString("system.playlistspath"), "music"));
1321 vec.push_back(URIUtils::AddFileToFolder(CSettings::Get().GetString("system.playlistspath"), "mixed"));
1322 return XFILE::CMultiPathDirectory::ConstructMultiPath(vec);
1325 CStdString CUtil::VideoPlaylistsLocation()
1327 vector<CStdString> vec;
1328 vec.push_back(URIUtils::AddFileToFolder(CSettings::Get().GetString("system.playlistspath"), "video"));
1329 vec.push_back(URIUtils::AddFileToFolder(CSettings::Get().GetString("system.playlistspath"), "mixed"));
1330 return XFILE::CMultiPathDirectory::ConstructMultiPath(vec);
1333 void CUtil::DeleteMusicDatabaseDirectoryCache()
1335 CUtil::DeleteDirectoryCache("mdb-");
1336 CUtil::DeleteDirectoryCache("sp-"); // overkill as it will delete video smartplaylists, but as we can't differentiate based on URL...
1339 void CUtil::DeleteVideoDatabaseDirectoryCache()
1341 CUtil::DeleteDirectoryCache("vdb-");
1342 CUtil::DeleteDirectoryCache("sp-"); // overkill as it will delete music smartplaylists, but as we can't differentiate based on URL...
1345 void CUtil::DeleteDirectoryCache(const CStdString &prefix)
1347 CStdString searchPath = "special://temp/";
1348 CFileItemList items;
1349 if (!XFILE::CDirectory::GetDirectory(searchPath, items, ".fi", DIR_FLAG_NO_FILE_DIRS))
1352 for (int i = 0; i < items.Size(); ++i)
1354 if (items[i]->m_bIsFolder)
1356 CStdString fileName = URIUtils::GetFileName(items[i]->GetPath());
1357 if (StringUtils::StartsWith(fileName, prefix))
1358 XFILE::CFile::Delete(items[i]->GetPath());
1363 void CUtil::GetRecursiveListing(const CStdString& strPath, CFileItemList& items, const CStdString& strMask, bool bUseFileDirectories)
1365 CFileItemList myItems;
1366 int flags = DIR_FLAG_DEFAULTS;
1367 if (!bUseFileDirectories)
1368 flags |= DIR_FLAG_NO_FILE_DIRS;
1369 CDirectory::GetDirectory(strPath,myItems,strMask,flags);
1370 for (int i=0;i<myItems.Size();++i)
1372 if (myItems[i]->m_bIsFolder)
1373 CUtil::GetRecursiveListing(myItems[i]->GetPath(),items,strMask,bUseFileDirectories);
1375 items.Add(myItems[i]);
1379 void CUtil::GetRecursiveDirsListing(const CStdString& strPath, CFileItemList& item)
1381 CFileItemList myItems;
1382 CDirectory::GetDirectory(strPath,myItems,"",DIR_FLAG_NO_FILE_DIRS);
1383 for (int i=0;i<myItems.Size();++i)
1385 if (myItems[i]->m_bIsFolder && !myItems[i]->GetPath().Equals(".."))
1387 item.Add(myItems[i]);
1388 CUtil::GetRecursiveDirsListing(myItems[i]->GetPath(),item);
1393 void CUtil::ForceForwardSlashes(CStdString& strPath)
1395 size_t iPos = strPath.rfind('\\');
1396 while (iPos != string::npos)
1398 strPath.at(iPos) = '/';
1399 iPos = strPath.rfind('\\');
1403 double CUtil::AlbumRelevance(const CStdString& strAlbumTemp1, const CStdString& strAlbum1, const CStdString& strArtistTemp1, const CStdString& strArtist1)
1405 // case-insensitive fuzzy string comparison on the album and artist for relevance
1406 // weighting is identical, both album and artist are 50% of the total relevance
1407 // a missing artist means the maximum relevance can only be 0.50
1408 CStdString strAlbumTemp = strAlbumTemp1;
1409 StringUtils::ToLower(strAlbumTemp);
1410 CStdString strAlbum = strAlbum1;
1411 StringUtils::ToLower(strAlbum);
1412 double fAlbumPercentage = fstrcmp(strAlbumTemp, strAlbum, 0.0f);
1413 double fArtistPercentage = 0.0f;
1414 if (!strArtist1.empty())
1416 CStdString strArtistTemp = strArtistTemp1;
1417 StringUtils::ToLower(strArtistTemp);
1418 CStdString strArtist = strArtist1;
1419 StringUtils::ToLower(strArtist);
1420 fArtistPercentage = fstrcmp(strArtistTemp, strArtist, 0.0f);
1422 double fRelevance = fAlbumPercentage * 0.5f + fArtistPercentage * 0.5f;
1426 bool CUtil::MakeShortenPath(CStdString StrInput, CStdString& StrOutput, size_t iTextMaxLength)
1428 size_t iStrInputSize = StrInput.size();
1429 if(iStrInputSize <= 0 || iTextMaxLength >= iStrInputSize)
1433 size_t nGreaterDelim, nPos;
1435 nPos = StrInput.find_last_of( '\\' );
1436 if (nPos != std::string::npos)
1440 nPos = StrInput.find_last_of( '/' );
1441 if (nPos != std::string::npos)
1444 if ( cDelim == '\0' )
1447 if (nPos == StrInput.size() - 1)
1449 StrInput.erase(StrInput.size() - 1);
1450 nPos = StrInput.find_last_of(cDelim);
1452 while( iTextMaxLength < iStrInputSize )
1454 nPos = StrInput.find_last_of( cDelim, nPos );
1455 nGreaterDelim = nPos;
1456 if ( nPos != std::string::npos )
1457 nPos = StrInput.find_last_of( cDelim, nPos - 1 );
1458 if ( nPos == CStdString::npos ) break;
1459 if ( nGreaterDelim > nPos ) StrInput.replace( nPos + 1, nGreaterDelim - nPos - 1, ".." );
1460 iStrInputSize = StrInput.size();
1462 // replace any additional /../../ with just /../ if necessary
1463 CStdString replaceDots = StringUtils::Format("..%c..", cDelim);
1464 while (StrInput.size() > (unsigned int)iTextMaxLength)
1465 if (!StringUtils::Replace(StrInput, replaceDots, ".."))
1467 // finally, truncate our string to force inside our max text length,
1468 // replacing the last 2 characters with ".."
1471 // "smb://../Playboy Swimsuit Cal.."
1472 if (iTextMaxLength > 2 && StrInput.size() > (unsigned int)iTextMaxLength)
1474 StrInput.erase(iTextMaxLength - 2);
1477 StrOutput = StrInput;
1481 bool CUtil::SupportsWriteFileOperations(const CStdString& strPath)
1483 // currently only hd, smb, nfs, afp and dav support delete and rename
1484 if (URIUtils::IsHD(strPath))
1486 if (URIUtils::IsSmb(strPath))
1488 if (CUtil::IsTVRecording(strPath))
1489 return CPVRDirectory::SupportsWriteFileOperations(strPath);
1490 if (URIUtils::IsNfs(strPath))
1492 if (URIUtils::IsAfp(strPath))
1494 if (URIUtils::IsDAV(strPath))
1496 if (URIUtils::IsMythTV(strPath))
1499 * Can't use CFile::Exists() to check whether the myth:// path supports file operations because
1500 * it hits the directory cache on the way through, which has the Live Channels and Guide
1503 return CMythDirectory::SupportsWriteFileOperations(strPath);
1505 if (URIUtils::IsStack(strPath))
1506 return SupportsWriteFileOperations(CStackDirectory::GetFirstStackedFile(strPath));
1507 if (URIUtils::IsMultiPath(strPath))
1508 return CMultiPathDirectory::SupportsWriteFileOperations(strPath);
1513 bool CUtil::SupportsReadFileOperations(const CStdString& strPath)
1515 if (URIUtils::IsVideoDb(strPath))
1521 CStdString CUtil::GetDefaultFolderThumb(const CStdString &folderThumb)
1523 if (g_TextureManager.HasTexture(folderThumb))
1528 void CUtil::GetSkinThemes(vector<CStdString>& vecTheme)
1530 CStdString strPath = URIUtils::AddFileToFolder(g_graphicsContext.GetMediaDir(), "media");
1531 CFileItemList items;
1532 CDirectory::GetDirectory(strPath, items);
1533 // Search for Themes in the Current skin!
1534 for (int i = 0; i < items.Size(); ++i)
1536 CFileItemPtr pItem = items[i];
1537 if (!pItem->m_bIsFolder)
1539 CStdString strExtension = URIUtils::GetExtension(pItem->GetPath());
1540 if ((strExtension == ".xpr" && !StringUtils::EqualsNoCase(pItem->GetLabel(), "Textures.xpr")) ||
1541 (strExtension == ".xbt" && !StringUtils::EqualsNoCase(pItem->GetLabel(), "Textures.xbt")))
1543 CStdString strLabel = pItem->GetLabel();
1544 vecTheme.push_back(strLabel.substr(0, strLabel.size() - 4));
1548 sort(vecTheme.begin(), vecTheme.end(), sortstringbyname());
1551 void CUtil::InitRandomSeed()
1555 now = CurrentHostCounter();
1556 unsigned int seed = (unsigned int)now;
1557 // CLog::Log(LOGDEBUG, "%s - Initializing random seed with %u", __FUNCTION__, seed);
1562 bool CUtil::RunCommandLine(const CStdString& cmdLine, bool waitExit)
1564 CStdStringArray args;
1566 StringUtils::SplitString(cmdLine, ",", args);
1568 // Strip quotes and whitespace around the arguments, or exec will fail.
1569 // This allows the python invocation to be written more naturally with any amount of whitespace around the args.
1570 // But it's still limited, for example quotes inside the strings are not expanded, etc.
1571 // TODO: Maybe some python library routine can parse this more properly ?
1572 for (CStdStringArray::iterator it = args.begin(); it != args.end(); ++it)
1575 pos = it->find_first_not_of(" \t\n\"'");
1576 if (pos != std::string::npos)
1581 pos = it->find_last_not_of(" \t\n\"'"); // if it returns npos we'll end up with an empty string which is OK
1583 it->erase(++pos, it->size());
1587 return Command(args, waitExit);
1591 // FIXME, this should be merged with the function below.
1593 bool CUtil::Command(const CStdStringArray& arrArgs, bool waitExit)
1596 printf("Executing: ");
1597 for (size_t i=0; i<arrArgs.size(); i++)
1598 printf("%s ", arrArgs[i].c_str());
1602 pid_t child = fork();
1608 // fork again in order not to leave a zombie process
1612 else if (child != 0)
1618 if (arrArgs.size() > 0)
1620 char **args = (char **)alloca(sizeof(char *) * (arrArgs.size() + 3));
1621 memset(args, 0, (sizeof(char *) * (arrArgs.size() + 3)));
1622 for (size_t i=0; i<arrArgs.size(); i++)
1623 args[i] = (char *)arrArgs[i].c_str();
1624 execvp(args[0], args);
1629 waitpid(child, &n, 0);
1632 return (waitExit) ? (WEXITSTATUS(n) == 0) : true;
1635 bool CUtil::SudoCommand(const CStdString &strCommand)
1637 CLog::Log(LOGDEBUG, "Executing sudo command: <%s>", strCommand.c_str());
1638 pid_t child = fork();
1642 close(0); // close stdin to avoid sudo request password
1645 CStdStringArray arrArgs;
1646 StringUtils::SplitString(strCommand, " ", arrArgs);
1647 if (arrArgs.size() > 0)
1649 char **args = (char **)alloca(sizeof(char *) * (arrArgs.size() + 3));
1650 memset(args, 0, (sizeof(char *) * (arrArgs.size() + 3)));
1651 args[0] = (char *)"/usr/bin/sudo";
1652 args[1] = (char *)"-S";
1653 for (size_t i=0; i<arrArgs.size(); i++)
1655 args[i+2] = (char *)arrArgs[i].c_str();
1657 execvp("/usr/bin/sudo", args);
1661 waitpid(child, &n, 0);
1663 return WEXITSTATUS(n) == 0;
1667 int CUtil::LookupRomanDigit(char roman_digit)
1669 switch (roman_digit)
1697 int CUtil::TranslateRomanNumeral(const char* roman_numeral)
1702 if (roman_numeral && roman_numeral[0])
1709 while (*roman_numeral)
1711 int digit = CUtil::LookupRomanDigit(*roman_numeral);
1714 // General sanity checks
1716 // numeral not in LUT
1723 // N = 10^n may not precede (N+1) > 10^(N+1)
1724 if (test == 1 && digit > last * 10)
1727 // N = 5*10^n may not precede (N+1) >= N
1728 if (test == 5 && digit >= last)
1731 // End general sanity checks
1735 // smaller numerals may not repeat before a larger one
1744 else if (last == digit)
1753 decimal += 2 * last - temp_sum;
1755 decimal += temp_sum;
1762 // Post general sanity checks
1764 // numerals may not repeat more than thrice
1773 decimal += temp_sum;
1775 decimal += 2 * last - temp_sum;
1780 CStdString CUtil::ResolveExecutablePath()
1782 CStdString strExecutablePath;
1783 #ifdef TARGET_WINDOWS
1784 static const size_t bufSize = MAX_PATH * 2;
1785 wchar_t* buf = new wchar_t[bufSize];
1787 ::GetModuleFileNameW(0, buf, bufSize);
1789 g_charsetConverter.wToUTF8(buf,strExecutablePath);
1791 #elif defined(TARGET_DARWIN)
1792 char given_path[2*MAXPATHLEN];
1793 uint32_t path_size =2*MAXPATHLEN;
1795 GetDarwinExecutablePath(given_path, &path_size);
1796 strExecutablePath = given_path;
1797 #elif defined(TARGET_FREEBSD)
1804 mib[2] = KERN_PROC_PATHNAME;
1807 buflen = sizeof(buf) - 1;
1808 if(sysctl(mib, 4, buf, &buflen, NULL, 0) < 0)
1809 strExecutablePath = "";
1811 strExecutablePath = buf;
1813 /* Get our PID and build the name of the link in /proc */
1814 pid_t pid = getpid();
1815 char linkname[64]; /* /proc/<pid>/exe */
1816 snprintf(linkname, sizeof(linkname), "/proc/%i/exe", pid);
1818 /* Now read the symbolic link */
1819 char buf[PATH_MAX + 1];
1822 int ret = readlink(linkname, buf, sizeof(buf) - 1);
1826 strExecutablePath = buf;
1828 return strExecutablePath;
1831 CStdString CUtil::GetFrameworksPath(bool forPython)
1833 CStdString strFrameworksPath;
1834 #if defined(TARGET_DARWIN)
1835 char given_path[2*MAXPATHLEN];
1836 uint32_t path_size =2*MAXPATHLEN;
1838 GetDarwinFrameworkPath(forPython, given_path, &path_size);
1839 strFrameworksPath = given_path;
1841 return strFrameworksPath;
1844 void CUtil::ScanForExternalSubtitles(const CStdString& strMovie, std::vector<CStdString>& vecSubtitles )
1846 unsigned int startTimer = XbmcThreads::SystemClockMillis();
1848 // new array for commons sub dirs
1849 const char * common_sub_dirs[] = {"subs",
1863 vector<CStdString> vecExtensionsCached;
1865 CFileItem item(strMovie, false);
1866 if ( item.IsInternetStream()
1867 || item.IsHDHomeRun()
1868 || item.IsSlingbox()
1869 || item.IsPlayList()
1874 vector<CStdString> strLookInPaths;
1876 CStdString strMovieFileName;
1879 URIUtils::Split(strMovie, strPath, strMovieFileName);
1880 CStdString strMovieFileNameNoExt(URIUtils::ReplaceExtension(strMovieFileName, ""));
1881 strLookInPaths.push_back(strPath);
1883 if (!CMediaSettings::Get().GetAdditionalSubtitleDirectoryChecked() && !CSettings::Get().GetString("subtitles.custompath").empty()) // to avoid checking non-existent directories (network) every time..
1885 if (!g_application.getNetwork().IsAvailable() && !URIUtils::IsHD(CSettings::Get().GetString("subtitles.custompath")))
1887 CLog::Log(LOGINFO,"CUtil::CacheSubtitles: disabling alternate subtitle directory for this session, it's nonaccessible");
1888 CMediaSettings::Get().SetAdditionalSubtitleDirectoryChecked(-1); // disabled
1890 else if (!CDirectory::Exists(CSettings::Get().GetString("subtitles.custompath")))
1892 CLog::Log(LOGINFO,"CUtil::CacheSubtitles: disabling alternate subtitle directory for this session, it's nonexistant");
1893 CMediaSettings::Get().SetAdditionalSubtitleDirectoryChecked(-1); // disabled
1896 CMediaSettings::Get().SetAdditionalSubtitleDirectoryChecked(1);
1899 if (StringUtils::StartsWith(strMovie, "rar://")) // <--- if this is found in main path then ignore it!
1902 CStdString strArchive = url.GetHostName();
1903 URIUtils::Split(strArchive, strPath, strMovieFileName);
1904 strLookInPaths.push_back(strPath);
1907 int iSize = strLookInPaths.size();
1908 for (int i=0; i<iSize; ++i)
1910 CStdStringArray directories;
1911 int nTokens = StringUtils::SplitString( strLookInPaths[i], "/", directories );
1913 StringUtils::SplitString( strLookInPaths[i], "\\", directories );
1915 // if it's inside a cdX dir, add parent path
1916 if (directories.size() >= 2 && directories[directories.size()-2].size() == 3 && StringUtils::StartsWithNoCase(directories[directories.size()-2], "cd")) // SplitString returns empty token as last item, hence size-2
1918 CStdString strPath2;
1919 URIUtils::GetParentPath(strLookInPaths[i], strPath2);
1920 strLookInPaths.push_back(strPath2);
1924 // checking if any of the common subdirs exist ..
1925 iSize = strLookInPaths.size();
1926 for (int i=0;i<iSize;++i)
1928 for (int j=0; common_sub_dirs[j]; j++)
1930 CStdString strPath2 = URIUtils::AddFileToFolder(strLookInPaths[i],common_sub_dirs[j]);
1931 URIUtils::AddSlashAtEnd(strPath2);
1932 if (CDirectory::Exists(strPath2))
1933 strLookInPaths.push_back(strPath2);
1936 // .. done checking for common subdirs
1938 // check if there any cd-directories in the paths we have added so far
1939 iSize = strLookInPaths.size();
1940 for (int i=0;i<9;++i) // 9 cd's
1942 CStdString cdDir = StringUtils::Format("cd%i",i+1);
1943 for (int i=0;i<iSize;++i)
1945 CStdString strPath2 = URIUtils::AddFileToFolder(strLookInPaths[i],cdDir);
1946 URIUtils::AddSlashAtEnd(strPath2);
1947 bool pathAlreadyAdded = false;
1948 for (unsigned int i=0; i<strLookInPaths.size(); i++)
1950 // if movie file is inside cd-dir, this directory can exist in vector already
1951 if (strLookInPaths[i].Equals( strPath2 ) )
1952 pathAlreadyAdded = true;
1954 if (CDirectory::Exists(strPath2) && !pathAlreadyAdded)
1955 strLookInPaths.push_back(strPath2);
1958 // .. done checking for cd-dirs
1960 // this is last because we dont want to check any common subdirs or cd-dirs in the alternate <subtitles> dir.
1961 if (CMediaSettings::Get().GetAdditionalSubtitleDirectoryChecked() == 1)
1963 strPath = CSettings::Get().GetString("subtitles.custompath");
1964 URIUtils::AddSlashAtEnd(strPath);
1965 strLookInPaths.push_back(strPath);
1972 // 2 steps for movie directory and alternate subtitles directory
1973 CLog::Log(LOGDEBUG,"%s: Searching for subtitles...", __FUNCTION__);
1974 for (unsigned int step = 0; step < strLookInPaths.size(); step++)
1976 if (strLookInPaths[step].length() != 0)
1978 CFileItemList items;
1980 CDirectory::GetDirectory(strLookInPaths[step], items, g_advancedSettings.m_subtitlesExtensions, DIR_FLAG_NO_FILE_DIRS);
1982 for (int j = 0; j < items.Size(); j++)
1984 URIUtils::Split(items[j]->GetPath(), strPath, strItem);
1986 if (StringUtils::StartsWithNoCase(strItem, strMovieFileNameNoExt))
1988 // is this a rar or zip-file
1989 if (URIUtils::IsRAR(strItem) || URIUtils::IsZIP(strItem))
1991 // zip-file name equals strMovieFileNameNoExt, don't check in zip-file
1992 ScanArchiveForSubtitles( items[j]->GetPath(), "", vecSubtitles );
1994 else // not a rar/zip file
1996 for (int i = 0; sub_exts[i]; i++)
1998 //Cache subtitle with same name as movie
1999 if (URIUtils::HasExtension(strItem, sub_exts[i]))
2001 vecSubtitles.push_back( items[j]->GetPath() );
2002 CLog::Log(LOGINFO, "%s: found subtitle file %s\n", __FUNCTION__, items[j]->GetPath().c_str() );
2009 // is this a rar or zip-file
2010 if (URIUtils::IsRAR(strItem) || URIUtils::IsZIP(strItem))
2012 // check strMovieFileNameNoExt in zip-file
2013 ScanArchiveForSubtitles( items[j]->GetPath(), strMovieFileNameNoExt, vecSubtitles );
2020 iSize = vecSubtitles.size();
2021 for (int i = 0; i < iSize; i++)
2023 if (URIUtils::HasExtension(vecSubtitles[i], ".smi"))
2025 //Cache multi-language sami subtitle
2026 CDVDSubtitleStream* pStream = new CDVDSubtitleStream();
2027 if(pStream->Open(vecSubtitles[i]))
2029 CDVDSubtitleTagSami TagConv;
2030 TagConv.LoadHead(pStream);
2031 if (TagConv.m_Langclass.size() >= 2)
2033 for (unsigned int k = 0; k < TagConv.m_Langclass.size(); k++)
2035 strDest = StringUtils::Format("special://temp/subtitle.%s.%d.smi", TagConv.m_Langclass[k].Name.c_str(), i);
2036 if (CFile::Cache(vecSubtitles[i], strDest))
2038 CLog::Log(LOGINFO, " cached subtitle %s->%s\n", vecSubtitles[i].c_str(), strDest.c_str());
2039 vecSubtitles.push_back(strDest);
2047 CLog::Log(LOGDEBUG,"%s: END (total time: %i ms)", __FUNCTION__, (int)(XbmcThreads::SystemClockMillis() - startTimer));
2050 int CUtil::ScanArchiveForSubtitles( const CStdString& strArchivePath, const CStdString& strMovieFileNameNoExt, std::vector<CStdString>& vecSubtitles )
2052 int nSubtitlesAdded = 0;
2053 CFileItemList ItemList;
2055 // zip only gets the root dir
2056 if (URIUtils::HasExtension(strArchivePath, ".zip"))
2058 CStdString strZipPath;
2059 URIUtils::CreateArchivePath(strZipPath,"zip",strArchivePath,"");
2060 if (!CDirectory::GetDirectory(strZipPath,ItemList,"",DIR_FLAG_NO_FILE_DIRS))
2065 #ifdef HAS_FILESYSTEM_RAR
2066 // get _ALL_files in the rar, even those located in subdirectories because we set the bMask to false.
2067 // so now we dont have to find any subdirs anymore, all files in the rar is checked.
2068 if( !g_RarManager.GetFilesInRar(ItemList, strArchivePath, false, "") )
2074 for (int it= 0 ; it <ItemList.Size();++it)
2076 CStdString strPathInRar = ItemList[it]->GetPath();
2077 CStdString strExt = URIUtils::GetExtension(strPathInRar);
2079 CLog::Log(LOGDEBUG, "ScanArchiveForSubtitles:: Found file %s", strPathInRar.c_str());
2080 // always check any embedded rar archives
2081 // checking for embedded rars, I moved this outside the sub_ext[] loop. We only need to check this once for each file.
2082 if (URIUtils::IsRAR(strPathInRar) || URIUtils::IsZIP(strPathInRar))
2084 CStdString strRarInRar;
2085 if (strExt == ".rar")
2086 URIUtils::CreateArchivePath(strRarInRar, "rar", strArchivePath, strPathInRar);
2088 URIUtils::CreateArchivePath(strRarInRar, "zip", strArchivePath, strPathInRar);
2089 ScanArchiveForSubtitles(strRarInRar,strMovieFileNameNoExt,vecSubtitles);
2091 // done checking if this is a rar-in-rar
2093 // check that the found filename matches the movie filename
2094 int fnl = strMovieFileNameNoExt.size();
2095 if (fnl && !StringUtils::StartsWithNoCase(URIUtils::GetFileName(strPathInRar), strMovieFileNameNoExt))
2099 while (sub_exts[iPos])
2101 if (StringUtils::EqualsNoCase(strExt, sub_exts[iPos]))
2103 CStdString strSourceUrl;
2104 if (URIUtils::HasExtension(strArchivePath, ".rar"))
2105 URIUtils::CreateArchivePath(strSourceUrl, "rar", strArchivePath, strPathInRar);
2107 strSourceUrl = strPathInRar;
2109 CLog::Log(LOGINFO, "%s: found subtitle file %s\n", __FUNCTION__, strSourceUrl.c_str() );
2110 vecSubtitles.push_back( strSourceUrl );
2118 return nSubtitlesAdded;
2121 void CUtil::GetExternalStreamDetailsFromFilename(const CStdString& strVideo, const CStdString& strStream, ExternalStreamInfo& info)
2123 CStdString videoBaseName = URIUtils::GetFileName(strVideo);
2124 URIUtils::RemoveExtension(videoBaseName);
2126 CStdString toParse = URIUtils::GetFileName(strStream);
2127 URIUtils::RemoveExtension(toParse);
2129 // we check left part - if it's same as video base name - strip it
2130 if (StringUtils::StartsWithNoCase(toParse, videoBaseName))
2131 toParse = toParse.substr(videoBaseName.length());
2133 // trim any non-alphanumeric char in the begining
2134 std::string::iterator result = std::find_if(toParse.begin(), toParse.end(), ::isalnum);
2137 if (result != toParse.end()) // if we have anything to parse
2139 std::string inputString(result, toParse.end());
2140 std::string delimiters(" .-");
2141 std::vector<std::string> tokens;
2142 StringUtils::Tokenize(inputString, tokens, delimiters);
2144 for (std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); ++it)
2146 if (info.language.empty())
2148 CStdString langTmp(*it);
2149 CStdString langCode;
2150 // try to recognize language
2151 if (g_LangCodeExpander.ConvertToThreeCharCode(langCode, langTmp))
2153 info.language = langCode;
2157 if (info.flag == 0x1111)
2159 std::string flag_tmp(*it);
2160 StringUtils::ToLower(flag_tmp);
2161 if (!flag_tmp.compare("none"))
2163 info.flag = CDemuxStream::FLAG_NONE;
2166 else if (!flag_tmp.compare("default"))
2168 info.flag = CDemuxStream::FLAG_DEFAULT;
2171 else if (!flag_tmp.compare("forced"))
2173 info.flag = CDemuxStream::FLAG_FORCED;
2177 name += " " + (*it);
2181 name += g_localizeStrings.Get(21602); // External
2182 StringUtils::Trim(name);
2183 info.name = StringUtils::RemoveDuplicatedSpacesAndTabs(name);
2184 if (info.flag == 0x1111)
2185 info.flag = CDemuxStream::FLAG_NONE;
2187 CLog::Log(LOGDEBUG, "%s - Language = '%s' / Name = '%s' / Flag = '%u' from %s", __FUNCTION__, info.language.c_str(), info.name.c_str(), info.flag, strStream.c_str());
2190 /*! \brief in a vector of subtitles finds the corresponding .sub file for a given .idx file
2192 bool CUtil::FindVobSubPair( const std::vector<CStdString>& vecSubtitles, const CStdString& strIdxPath, CStdString& strSubPath )
2194 if (URIUtils::HasExtension(strIdxPath, ".idx"))
2196 CStdString strIdxFile;
2197 CStdString strIdxDirectory;
2198 URIUtils::Split(strIdxPath, strIdxDirectory, strIdxFile);
2199 for (unsigned int j=0; j < vecSubtitles.size(); j++)
2201 CStdString strSubFile;
2202 CStdString strSubDirectory;
2203 URIUtils::Split(vecSubtitles[j], strSubDirectory, strSubFile);
2204 if (URIUtils::IsInArchive(vecSubtitles[j]))
2205 CURL::Decode(strSubDirectory);
2206 if (URIUtils::HasExtension(strSubFile, ".sub") &&
2207 (URIUtils::ReplaceExtension(strIdxFile,"").Equals(URIUtils::ReplaceExtension(strSubFile,"")) ||
2208 (strSubDirectory.size() >= 11 &&
2209 StringUtils::EqualsNoCase(strSubDirectory.substr(6, strSubDirectory.length()-11), URIUtils::ReplaceExtension(strIdxPath,"")))))
2211 strSubPath = vecSubtitles[j];
2219 /*! \brief checks if in the vector of subtitles the given .sub file has a corresponding idx and hence is a vobsub file
2221 bool CUtil::IsVobSub( const std::vector<CStdString>& vecSubtitles, const CStdString& strSubPath )
2223 if (URIUtils::HasExtension(strSubPath, ".sub"))
2225 CStdString strSubFile;
2226 CStdString strSubDirectory;
2227 URIUtils::Split(strSubPath, strSubDirectory, strSubFile);
2228 if (URIUtils::IsInArchive(strSubPath))
2229 CURL::Decode(strSubDirectory);
2230 for (unsigned int j=0; j < vecSubtitles.size(); j++)
2232 CStdString strIdxFile;
2233 CStdString strIdxDirectory;
2234 URIUtils::Split(vecSubtitles[j], strIdxDirectory, strIdxFile);
2235 if (URIUtils::HasExtension(strIdxFile, ".idx") &&
2236 (URIUtils::ReplaceExtension(strIdxFile,"").Equals(URIUtils::ReplaceExtension(strSubFile,"")) ||
2237 (strSubDirectory.size() >= 11 &&
2238 StringUtils::EqualsNoCase(strSubDirectory.substr(6, strSubDirectory.length()-11), URIUtils::ReplaceExtension(vecSubtitles[j],"")))))
2245 bool CUtil::CanBindPrivileged()
2250 return true; //root user can always bind to privileged ports
2254 //check if CAP_NET_BIND_SERVICE is enabled, this allows non-root users to bind to privileged ports
2255 bool canbind = false;
2256 cap_t capabilities = cap_get_proc();
2259 cap_flag_value_t value;
2260 if (cap_get_flag(capabilities, CAP_NET_BIND_SERVICE, CAP_EFFECTIVE, &value) == 0)
2263 cap_free(capabilities);
2272 #endif //HAVE_LIBCAP
2274 #else //TARGET_POSIX
2278 #endif //TARGET_POSIX
2281 bool CUtil::ValidatePort(int port)
2283 // check that it's a valid port
2285 if (!CUtil::CanBindPrivileged() && (port < 1024 || port > 65535))
2289 if (port <= 0 || port > 65535)
2295 int CUtil::GetRandomNumber()
2297 #ifdef TARGET_WINDOWS
2298 unsigned int number;
2299 if (rand_s(&number) == 0)
2302 return rand_r(&s_randomSeed);