3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * class to provide simple static functions for file objects
21 class CRM_Utils_File
{
24 * Given a file name, determine if the file contents make it an ascii file
30 * true if file is ascii
32 public static function isAscii($name) {
33 $fd = fopen($name, "r");
40 $line = fgets($fd, 8192);
41 if (!CRM_Utils_String
::isAscii($line)) {
52 * Given a file name, determine if the file contents make it an html file
58 * true if file is html
60 public static function isHtml($name) {
61 $fd = fopen($name, "r");
68 while (!feof($fd) & $lineCount <= 5) {
70 $line = fgets($fd, 8192);
71 if (!CRM_Utils_String
::isHtml($line)) {
82 * Create a directory given a path name, creates parent directories
88 * Should we abort or just return an invalid code.
90 * NULL: Folder already exists or was not specified.
91 * TRUE: Creation succeeded.
92 * FALSE: Creation failed.
94 public static function createDir($path, $abort = TRUE) {
95 if (is_dir($path) ||
empty($path)) {
99 CRM_Utils_File
::createDir(dirname($path), $abort);
100 if (@mkdir
($path, 0777) == FALSE) {
102 $docLink = CRM_Utils_System
::docURL2('Moving an Existing Installation to a New Server or Location', NULL, NULL, NULL, NULL, "wiki");
103 echo "Error: Could not create directory: $path.<p>If you have moved an existing CiviCRM installation from one location or server to another there are several steps you will need to follow. They are detailed on this CiviCRM wiki page - {$docLink}. A fix for the specific problem that caused this error message to be displayed is to set the value of the config_backend column in the civicrm_domain table to NULL. However we strongly recommend that you review and follow all the steps in that document.</p>";
105 CRM_Utils_System
::civiExit();
115 * Delete a directory given a path name, delete children directories
116 * and files if needed
118 * @param string $target
121 * @param bool $verbose
125 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
126 static $exceptions = ['.', '..'];
127 if ($target == '' ||
$target == '/' ||
!$target) {
128 throw new Exception("Overly broad deletion");
131 if ($dh = @opendir
($target)) {
132 while (FALSE !== ($sibling = readdir($dh))) {
133 if (!in_array($sibling, $exceptions)) {
134 $object = $target . DIRECTORY_SEPARATOR
. $sibling;
136 if (is_dir($object)) {
137 CRM_Utils_File
::cleanDir($object, $rmdir, $verbose);
139 elseif (is_file($object)) {
140 if (!unlink($object)) {
141 CRM_Core_Session
::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
149 if (rmdir($target)) {
151 CRM_Core_Session
::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
156 CRM_Core_Session
::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
163 * Concatenate several files.
165 * @param array $files
166 * List of file names.
167 * @param string $delim
168 * An optional delimiter to put between files.
171 public static function concat($files, $delim = '') {
174 foreach ($files as $file) {
178 $buf .= file_get_contents($file);
185 * @param string $source
186 * @param string $destination
188 public static function copyDir($source, $destination) {
189 if ($dh = opendir($source)) {
190 @mkdir
($destination);
191 while (FALSE !== ($file = readdir($dh))) {
192 if (($file != '.') && ($file != '..')) {
193 if (is_dir($source . DIRECTORY_SEPARATOR
. $file)) {
194 CRM_Utils_File
::copyDir($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
197 copy($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
206 * Given a file name, recode it (in place!) to UTF-8
208 * @param string $name
212 * whether the file was recoded properly
214 public static function toUtf8($name) {
215 static $config = NULL;
216 static $legacyEncoding = NULL;
217 if ($config == NULL) {
218 $config = CRM_Core_Config
::singleton();
219 $legacyEncoding = $config->legacyEncoding
;
222 if (!function_exists('iconv')) {
228 $contents = file_get_contents($name);
229 if ($contents === FALSE) {
233 $contents = iconv($legacyEncoding, 'UTF-8', $contents);
234 if ($contents === FALSE) {
238 $file = fopen($name, 'w');
239 if ($file === FALSE) {
243 $written = fwrite($file, $contents);
244 $closed = fclose($file);
245 if ($written === FALSE or !$closed) {
253 * Appends a slash to the end of a string if it doesn't already end with one
255 * @param string $path
256 * @param string $slash
260 public static function addTrailingSlash($path, $slash = NULL) {
262 // FIXME: Defaulting to backslash on windows systems can produce
263 // unexpected results, esp for URL strings which should always use forward-slashes.
264 // I think this fn should default to forward-slash instead.
265 $slash = DIRECTORY_SEPARATOR
;
267 if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
274 * Save a fake file somewhere
277 * The directory where the file should be saved.
278 * @param string $contents
279 * Optional: the contents of the file.
280 * @param string $fileName
283 * The filename saved, or FALSE on failure.
285 public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
286 $dir = self
::addTrailingSlash($dir);
288 $fileName = 'delete-this-' . CRM_Utils_String
::createRandom(10, CRM_Utils_String
::ALPHANUMERIC
);
290 $success = @file_put_contents
($dir . $fileName, $contents);
292 return ($success === FALSE) ?
FALSE : $fileName;
296 * @param string|NULL $dsn
297 * Use NULL to load the default/active connection from CRM_Core_DAO.
298 * Otherwise, give a full DSN string.
299 * @param string $fileName
300 * @param string $prefix
301 * @param bool $dieOnErrors
303 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $dieOnErrors = TRUE) {
304 if (FALSE === file_get_contents($fileName)) {
305 // Our file cannot be found.
306 // Using 'die' here breaks this on extension upgrade.
307 throw new CRM_Core_Exception('Could not find the SQL file.');
310 self
::runSqlQuery($dsn, file_get_contents($fileName), $prefix, $dieOnErrors);
315 * @param string|NULL $dsn
316 * @param string $queryString
317 * @param string $prefix
318 * @param bool $dieOnErrors
320 public static function runSqlQuery($dsn, $queryString, $prefix = NULL, $dieOnErrors = TRUE) {
321 $string = $prefix . $queryString;
324 $db = CRM_Core_DAO
::getConnection();
327 require_once 'DB.php';
328 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
330 $db = DB
::connect($dsn);
332 catch (Exception
$e) {
333 die("Cannot open $dsn: " . $e->getMessage());
337 $db->query('SET NAMES utf8mb4');
338 $transactionId = CRM_Utils_Type
::escape(CRM_Utils_Request
::id(), 'String');
339 $db->query('SET @uniqueID = ' . "'$transactionId'");
341 // get rid of comments starting with # and --
343 $string = self
::stripComments($string);
345 $queries = preg_split('/;\s*$/m', $string);
346 foreach ($queries as $query) {
347 $query = trim($query);
348 if (!empty($query)) {
349 CRM_Core_Error
::debug_query($query);
351 $res = &$db->query($query);
353 catch (Exception
$e) {
355 die("Cannot execute $query: " . $e->getMessage());
358 echo "Cannot execute $query: " . $e->getMessage() . "<p>";
367 * Strips comment from a possibly multiline SQL string
369 * @param string $string
374 public static function stripComments($string) {
375 return preg_replace("/^(#|--).*\R*/m", "", $string);
383 public static function isExtensionSafe($ext) {
384 static $extensions = NULL;
386 $extensions = CRM_Core_OptionGroup
::values('safe_file_extension', TRUE);
388 // make extensions to lowercase
389 $extensions = array_change_key_case($extensions, CASE_LOWER
);
390 // allow html/htm extension ONLY if the user is admin
391 // and/or has access CiviMail
392 if (!(CRM_Core_Permission
::check('access CiviMail') ||
393 CRM_Core_Permission
::check('administer CiviCRM') ||
394 (CRM_Mailing_Info
::workflowEnabled() &&
395 CRM_Core_Permission
::check('create mailings')
399 unset($extensions['html']);
400 unset($extensions['htm']);
403 // support lower and uppercase file extensions
404 return (bool) isset($extensions[strtolower($ext)]);
408 * Determine whether a given file is listed in the PHP include path.
410 * @param string $name
414 * whether the file can be include()d or require()d
416 public static function isIncludable($name) {
417 $x = @fopen
($name, 'r', TRUE);
428 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
434 public static function cleanFileName($name) {
435 // replace the last 33 character before the '.' with null
436 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
441 * Make a valid file name.
443 * @param string $name
447 public static function makeFileName($name) {
448 $uniqID = md5(uniqid(rand(), TRUE));
449 $info = pathinfo($name);
450 $basename = substr($info['basename'],
451 0, -(strlen(CRM_Utils_Array
::value('extension', $info)) +
(CRM_Utils_Array
::value('extension', $info) == '' ?
0 : 1))
453 if (!self
::isExtensionSafe(CRM_Utils_Array
::value('extension', $info))) {
454 // munge extension so it cannot have an embbeded dot in it
455 // The maximum length of a filename for most filesystems is 255 chars.
456 // We'll truncate at 240 to give some room for the extension.
457 return CRM_Utils_String
::munge("{$basename}_" . CRM_Utils_Array
::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
460 return CRM_Utils_String
::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array
::value('extension', $info);
470 public static function duplicate($filePath) {
471 $oldName = pathinfo($filePath, PATHINFO_FILENAME
);
472 $uniqID = md5(uniqid(rand(), TRUE));
473 $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
474 $newPath = str_replace($oldName, $newName, $filePath);
475 copy($filePath, $newPath);
480 * Get files for the extension.
482 * @param string $path
487 public static function getFilesByExtension($path, $ext) {
488 $path = self
::addTrailingSlash($path);
490 if ($dh = opendir($path)) {
491 while (FALSE !== ($elem = readdir($dh))) {
492 if (substr($elem, -(strlen($ext) +
1)) == '.' . $ext) {
493 $files[] .= $path . $elem;
502 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
505 * The directory to be secured.
506 * @param bool $overwrite
508 public static function restrictAccess($dir, $overwrite = FALSE) {
509 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
510 // of site, causing site to stop functioning.
511 // FIXME: we should do more checks here -
512 if (!empty($dir) && is_dir($dir)) {
513 $htaccess = <<<HTACCESS
516 <IfModule !authz_core_module>
522 <IfModule authz_core_module>
528 $file = $dir . '.htaccess';
529 if ($overwrite ||
!file_exists($file)) {
530 if (file_put_contents($file, $htaccess) === FALSE) {
531 CRM_Core_Error
::movedSiteError($file);
538 * Restrict remote users from browsing the given directory.
542 public static function restrictBrowsing($publicDir) {
543 if (!is_dir($publicDir) ||
!is_writable($publicDir)) {
548 $nobrowse = realpath($publicDir) . '/index.html';
549 if (!file_exists($nobrowse)) {
550 @file_put_contents
($nobrowse, '');
554 $dir = new RecursiveDirectoryIterator($publicDir);
555 foreach ($dir as $name => $object) {
556 if (is_dir($name) && $name != '..') {
557 $nobrowse = realpath($name) . '/index.html';
558 if (!file_exists($nobrowse)) {
559 @file_put_contents
($nobrowse, '');
566 * (Deprecated) Create the file-path from which all other internal paths are
567 * computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
569 * This approach is problematic - e.g. it prevents one from authentically
570 * splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation
571 * is preserved for backwards compatibility (and should only be called by
572 * CMS-adapters and by Civi\Core\Paths).
574 * Do not use it for new path construction logic. Instead, use Civi::paths().
577 * @see \Civi::paths()
578 * @see \Civi\Core\Paths
580 public static function baseFilePath() {
581 static $_path = NULL;
583 // Note: Don't rely on $config; that creates a dependency loop.
584 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
585 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
587 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR
;
589 $path = dirname($templateCompileDir);
591 //this fix is to avoid creation of upload dirs inside templates_c directory
592 $checkPath = explode(DIRECTORY_SEPARATOR
, $path);
594 $cnt = count($checkPath) - 1;
595 if ($checkPath[$cnt] == 'templates_c') {
596 unset($checkPath[$cnt]);
597 $path = implode(DIRECTORY_SEPARATOR
, $checkPath);
600 $_path = CRM_Utils_File
::addTrailingSlash($path);
606 * Determine if a path is absolute.
608 * @param string $path
611 * TRUE if absolute. FALSE if relative.
613 public static function isAbsolute($path) {
614 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR
) {
617 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
618 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
630 * Computation of a relative path requires some base.
631 * This implementation is problematic because it relies on an
632 * implicit base which was constructed problematically.
634 public static function relativeDirectory($directory) {
635 // Do nothing on windows
636 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
640 // check if directory is relative, if so return immediately
641 if (!self
::isAbsolute($directory)) {
645 // make everything relative from the baseFilePath
646 $basePath = self
::baseFilePath();
647 // check if basePath is a substr of $directory, if so
648 // return rest of string
649 if (substr($directory, 0, strlen($basePath)) == $basePath) {
650 return substr($directory, strlen($basePath));
653 // return the original value
659 * @param string $basePath
660 * The base path when evaluating relative paths. Should include trailing slash.
664 public static function absoluteDirectory($directory, $basePath) {
665 // check if directory is already absolute, if so return immediately
666 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
667 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
671 // check if directory is already absolute, if so return immediately
672 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR
) {
676 if ($basePath === NULL) {
677 // Previous versions interpreted `NULL` to mean "default to `self::baseFilePath()`".
678 // However, no code in the known `universe` relies on this interpretation, and
679 // the `baseFilePath()` function is problematic/deprecated.
680 throw new \
RuntimeException("absoluteDirectory() requires specifying a basePath");
683 // ensure that $basePath has a trailing slash
684 $basePath = self
::addTrailingSlash($basePath);
685 return $basePath . $directory;
689 * Make a file path relative to some base dir.
696 public static function relativize($directory, $basePath) {
697 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
698 $directory = strtr($directory, '\\', '/');
699 $basePath = strtr($basePath, '\\', '/');
701 if (substr($directory, 0, strlen($basePath)) == $basePath) {
702 return substr($directory, strlen($basePath));
710 * Create a path to a temporary file which can endure for multiple requests.
712 * @todo Automatic file cleanup using, eg, TTL policy
714 * @param string $prefix
716 * @return string, path to an openable/writable file
719 public static function tempnam($prefix = 'tmp-') {
720 // $config = CRM_Core_Config::singleton();
721 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
722 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
723 $fileName = tempnam(sys_get_temp_dir(), $prefix);
728 * Create a path to a temporary directory which can endure for multiple requests.
730 * @todo Automatic file cleanup using, eg, TTL policy
732 * @param string $prefix
734 * @return string, path to an openable/writable directory; ends with '/'
737 public static function tempdir($prefix = 'tmp-') {
738 $fileName = self
::tempnam($prefix);
740 mkdir($fileName, 0700);
741 return $fileName . '/';
745 * Search directory tree for files which match a glob pattern.
747 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
751 * @param string $pattern
752 * glob pattern, eg "*.txt".
753 * @param bool $relative
754 * TRUE if paths should be made relative to $dir
755 * @return array(string)
757 public static function findFiles($dir, $pattern, $relative = FALSE) {
758 if (!is_dir($dir) ||
!is_readable($dir)) {
761 // Which dirs should we exclude from our searches?
762 // If not defined, we default to excluding any dirname that begins
763 // with a . which is the old behaviour and therefore excludes .git/
764 $excludeDirsPattern = defined('CIVICRM_EXCLUDE_DIRS_PATTERN')
765 ?
constant('CIVICRM_EXCLUDE_DIRS_PATTERN')
766 : '@' . preg_quote(DIRECTORY_SEPARATOR
) . '\.@';
768 $dir = rtrim($dir, '/');
771 while (!empty($todos)) {
772 $subdir = array_shift($todos);
773 $matches = glob("$subdir/$pattern");
774 if (is_array($matches)) {
775 foreach ($matches as $match) {
776 if (!is_dir($match)) {
777 $result[] = $relative ? CRM_Utils_File
::relativize($match, "$dir/") : $match;
781 // Find subdirs to recurse into.
782 if ($dh = opendir($subdir)) {
783 while (FALSE !== ($entry = readdir($dh))) {
784 $path = $subdir . DIRECTORY_SEPARATOR
. $entry;
785 // Exclude . (self) and .. (parent) to avoid infinite loop.
786 // Exclude configured exclude dirs.
787 // Exclude dirs we can't read.
788 // Exclude anything that's not a dir.
792 && (empty($excludeDirsPattern) ||
!preg_match($excludeDirsPattern, $path))
794 && is_readable($path)
806 * Determine if $child is a sub-directory of $parent
808 * @param string $parent
809 * @param string $child
810 * @param bool $checkRealPath
814 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
815 if ($checkRealPath) {
816 $parent = realpath($parent);
817 $child = realpath($child);
819 $parentParts = explode('/', rtrim($parent, '/'));
820 $childParts = explode('/', rtrim($child, '/'));
821 while (($parentPart = array_shift($parentParts)) !== NULL) {
822 $childPart = array_shift($childParts);
823 if ($parentPart != $childPart) {
827 if (empty($childParts)) {
837 * Move $fromDir to $toDir, replacing/deleting any
838 * pre-existing content.
840 * @param string $fromDir
841 * The directory which should be moved.
842 * @param string $toDir
843 * The new location of the directory.
844 * @param bool $verbose
849 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
850 if (is_dir($toDir)) {
851 if (!self
::cleanDir($toDir, TRUE, $verbose)) {
856 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
858 CRM_Utils_File
::copyDir($fromDir, $toDir);
859 if (!CRM_Utils_File
::cleanDir($fromDir, TRUE, FALSE)) {
860 CRM_Core_Session
::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
869 * @param array $param
870 * @param string $fileName
871 * @param array $extraParams
873 public static function formatFile(&$param, $fileName, $extraParams = []) {
874 if (empty($param[$fileName])) {
879 'uri' => $param[$fileName]['name'],
880 'type' => $param[$fileName]['type'],
881 'location' => $param[$fileName]['name'],
882 'upload_date' => date('YmdHis'),
885 $param[$fileName] = $fileParams;
889 * Return formatted file URL, like for image file return image url with image icon
891 * @param string $path
893 * @param string $fileType
895 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
897 * @return string $url
899 public static function getFileURL($path, $fileType, $url = NULL) {
900 if (empty($path) ||
empty($fileType)) {
903 elseif (empty($url)) {
904 $fileName = basename($path);
905 $url = CRM_Utils_System
::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
914 list($imageWidth, $imageHeight) = getimagesize($path);
915 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
916 $url = "<a href=\"$url\" class='crm-image-popup'>
917 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
922 $url = sprintf('<a href="%s">%s</a>', $url, self
::cleanFileName(basename($path)));
930 * Return formatted image icon
932 * @param string $imageURL
933 * Contact's image url
935 * @return string $url
937 public static function getImageURL($imageURL) {
938 // retrieve image name from $imageURL
939 $imageURL = CRM_Utils_String
::unstupifyUrl($imageURL);
940 parse_str(parse_url($imageURL, PHP_URL_QUERY
), $query);
943 if (!empty($query['photo'])) {
944 $path = CRM_Core_Config
::singleton()->customFileUploadDir
. $query['photo'];
947 $path = $url = $imageURL;
949 $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION
));
950 //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
951 // there are some extensions that would need translating.:
952 $translateMimeTypes = [
957 $mimeType = 'image/' . CRM_Utils_Array
::value(
963 return self
::getFileURL($path, $mimeType, $url);
969 * @param string $sourceFile
970 * Filesystem path to existing image on server
971 * @param int $targetWidth
972 * New width desired, in pixels
973 * @param int $targetHeight
974 * New height desired, in pixels
975 * @param string $suffix = ""
976 * If supplied, the image will be renamed to include this suffix. For
977 * example if the original file name is "foo.png" and $suffix = "_bar",
978 * then the final file name will be "foo_bar.png".
979 * @param bool $preserveAspect = TRUE
980 * When TRUE $width and $height will be used as a bounding box, outside of
981 * which the resized image will not extend.
982 * When FALSE, the image will be resized exactly to $width and $height, even
983 * if it means stretching it.
987 * @throws \CRM_Core_Exception
988 * Under the following conditions
989 * - When GD is not available.
990 * - When the source file is not an image.
992 public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
994 // Check if GD is installed
995 $gdSupport = CRM_Utils_System
::getModuleSetting('gd', 'GD Support');
997 throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
1000 $sourceMime = mime_content_type($sourceFile);
1001 if ($sourceMime == 'image/gif') {
1002 $sourceData = imagecreatefromgif($sourceFile);
1004 elseif ($sourceMime == 'image/png') {
1005 $sourceData = imagecreatefrompng($sourceFile);
1007 elseif ($sourceMime == 'image/jpeg') {
1008 $sourceData = imagecreatefromjpeg($sourceFile);
1011 throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
1014 // get image about original image
1015 $sourceInfo = getimagesize($sourceFile);
1016 $sourceWidth = $sourceInfo[0];
1017 $sourceHeight = $sourceInfo[1];
1019 // Adjust target width/height if preserving aspect ratio
1020 if ($preserveAspect) {
1021 $sourceAspect = $sourceWidth / $sourceHeight;
1022 $targetAspect = $targetWidth / $targetHeight;
1023 if ($sourceAspect > $targetAspect) {
1024 $targetHeight = $targetWidth / $sourceAspect;
1026 if ($sourceAspect < $targetAspect) {
1027 $targetWidth = $targetHeight * $sourceAspect;
1031 // figure out the new filename
1032 $pathParts = pathinfo($sourceFile);
1033 $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
1034 . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];
1036 $targetData = imagecreatetruecolor($targetWidth, $targetHeight);
1039 imagecopyresized($targetData, $sourceData,
1041 $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
1043 // save the resized image
1044 $fp = fopen($targetFile, 'w+');
1046 imagejpeg($targetData);
1047 $image_buffer = ob_get_contents();
1049 imagedestroy($targetData);
1050 fwrite($fp, $image_buffer);
1054 // return the URL to link to
1055 $config = CRM_Core_Config
::singleton();
1056 return $config->imageUploadURL
. basename($targetFile);
1060 * Get file icon class for specific MIME Type
1062 * @param string $mimeType
1065 public static function getIconFromMimeType($mimeType) {
1066 if (!isset(Civi
::$statics[__CLASS__
]['mimeIcons'])) {
1067 Civi
::$statics[__CLASS__
]['mimeIcons'] = json_decode(file_get_contents(__DIR__
. '/File/mimeIcons.json'), TRUE);
1069 $iconClasses = Civi
::$statics[__CLASS__
]['mimeIcons'];
1070 foreach ($iconClasses as $text => $icon) {
1071 if (strpos($mimeType, $text) === 0) {
1075 return $iconClasses['*'];
1079 * Is the filename a safe and valid filename passed in from URL
1081 * @param string $fileName
1084 public static function isValidFileName($fileName = NULL) {
1086 $check = ($fileName === basename($fileName));
1088 if (substr($fileName, 0, 1) == '/' ||
substr($fileName, 0, 1) == '.' ||
substr($fileName, 0, 1) == DIRECTORY_SEPARATOR
) {
1098 * Get the extensions that this MimeTpe is for
1099 * @param string $mimeType the mime-type we want extensions for
1102 public static function getAcceptableExtensionsForMimeType($mimeType = []) {
1103 $mimeRepostory = new \MimeTyper\Repository\
ExtendedRepository();
1104 return $mimeRepostory->findExtensions($mimeType);
1108 * Get the extension of a file based on its path
1109 * @param string $path path of the file to query
1112 public static function getExtensionFromPath($path) {
1113 return pathinfo($path, PATHINFO_EXTENSION
);