3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * class to provide simple static functions for file objects
37 class CRM_Utils_File
{
40 * Given a file name, determine if the file contents make it an ascii file
46 * true if file is ascii
48 public static function isAscii($name) {
49 $fd = fopen($name, "r");
56 $line = fgets($fd, 8192);
57 if (!CRM_Utils_String
::isAscii($line)) {
68 * Given a file name, determine if the file contents make it an html file
74 * true if file is html
76 public static function isHtml($name) {
77 $fd = fopen($name, "r");
84 while (!feof($fd) & $lineCount <= 5) {
86 $line = fgets($fd, 8192);
87 if (!CRM_Utils_String
::isHtml($line)) {
98 * Create a directory given a path name, creates parent directories
101 * @param string $path
104 * Should we abort or just return an invalid code.
106 * NULL: Folder already exists or was not specified.
107 * TRUE: Creation succeeded.
108 * FALSE: Creation failed.
110 public static function createDir($path, $abort = TRUE) {
111 if (is_dir($path) ||
empty($path)) {
115 CRM_Utils_File
::createDir(dirname($path), $abort);
116 if (@mkdir
($path, 0777) == FALSE) {
118 $docLink = CRM_Utils_System
::docURL2('Moving an Existing Installation to a New Server or Location', NULL, NULL, NULL, NULL, "wiki");
119 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>";
121 CRM_Utils_System
::civiExit();
131 * Delete a directory given a path name, delete children directories
132 * and files if needed
134 * @param string $target
137 * @param bool $verbose
141 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
142 static $exceptions = ['.', '..'];
143 if ($target == '' ||
$target == '/' ||
!$target) {
144 throw new Exception("Overly broad deletion");
147 if ($dh = @opendir
($target)) {
148 while (FALSE !== ($sibling = readdir($dh))) {
149 if (!in_array($sibling, $exceptions)) {
150 $object = $target . DIRECTORY_SEPARATOR
. $sibling;
152 if (is_dir($object)) {
153 CRM_Utils_File
::cleanDir($object, $rmdir, $verbose);
155 elseif (is_file($object)) {
156 if (!unlink($object)) {
157 CRM_Core_Session
::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
165 if (rmdir($target)) {
167 CRM_Core_Session
::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
172 CRM_Core_Session
::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
179 * Concatenate several files.
181 * @param array $files
182 * List of file names.
183 * @param string $delim
184 * An optional delimiter to put between files.
187 public static function concat($files, $delim = '') {
190 foreach ($files as $file) {
194 $buf .= file_get_contents($file);
201 * @param string $source
202 * @param string $destination
204 public static function copyDir($source, $destination) {
205 if ($dh = opendir($source)) {
206 @mkdir
($destination);
207 while (FALSE !== ($file = readdir($dh))) {
208 if (($file != '.') && ($file != '..')) {
209 if (is_dir($source . DIRECTORY_SEPARATOR
. $file)) {
210 CRM_Utils_File
::copyDir($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
213 copy($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
222 * Given a file name, recode it (in place!) to UTF-8
224 * @param string $name
228 * whether the file was recoded properly
230 public static function toUtf8($name) {
231 static $config = NULL;
232 static $legacyEncoding = NULL;
233 if ($config == NULL) {
234 $config = CRM_Core_Config
::singleton();
235 $legacyEncoding = $config->legacyEncoding
;
238 if (!function_exists('iconv')) {
244 $contents = file_get_contents($name);
245 if ($contents === FALSE) {
249 $contents = iconv($legacyEncoding, 'UTF-8', $contents);
250 if ($contents === FALSE) {
254 $file = fopen($name, 'w');
255 if ($file === FALSE) {
259 $written = fwrite($file, $contents);
260 $closed = fclose($file);
261 if ($written === FALSE or !$closed) {
269 * Appends a slash to the end of a string if it doesn't already end with one
271 * @param string $path
272 * @param string $slash
276 public static function addTrailingSlash($path, $slash = NULL) {
278 // FIXME: Defaulting to backslash on windows systems can produce
279 // unexpected results, esp for URL strings which should always use forward-slashes.
280 // I think this fn should default to forward-slash instead.
281 $slash = DIRECTORY_SEPARATOR
;
283 if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
290 * Save a fake file somewhere
293 * The directory where the file should be saved.
294 * @param string $contents
295 * Optional: the contents of the file.
296 * @param string $fileName
299 * The filename saved, or FALSE on failure.
301 public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
302 $dir = self
::addTrailingSlash($dir);
304 $fileName = 'delete-this-' . CRM_Utils_String
::createRandom(10, CRM_Utils_String
::ALPHANUMERIC
);
306 $success = @file_put_contents
($dir . $fileName, $contents);
308 return ($success === FALSE) ?
FALSE : $fileName;
312 * @param string|NULL $dsn
313 * Use NULL to load the default/active connection from CRM_Core_DAO.
314 * Otherwise, give a full DSN string.
315 * @param string $fileName
316 * @param string $prefix
317 * @param bool $dieOnErrors
319 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $dieOnErrors = TRUE) {
320 if (FALSE === file_get_contents($fileName)) {
321 // Our file cannot be found.
322 // Using 'die' here breaks this on extension upgrade.
323 throw new CRM_Exception('Could not find the SQL file.');
326 self
::runSqlQuery($dsn, file_get_contents($fileName), $prefix, $dieOnErrors);
331 * @param string|NULL $dsn
332 * @param string $queryString
333 * @param string $prefix
334 * @param bool $dieOnErrors
336 public static function runSqlQuery($dsn, $queryString, $prefix = NULL, $dieOnErrors = TRUE) {
337 $string = $prefix . $queryString;
340 $db = CRM_Core_DAO
::getConnection();
343 require_once 'DB.php';
344 $db = DB
::connect($dsn);
347 if (PEAR
::isError($db)) {
348 die("Cannot open $dsn: " . $db->getMessage());
350 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
351 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
353 $db->query('SET NAMES utf8');
354 $transactionId = CRM_Utils_Type
::escape(CRM_Utils_Request
::id(), 'String');
355 $db->query('SET @uniqueID = ' . "'$transactionId'");
357 // get rid of comments starting with # and --
359 $string = self
::stripComments($string);
361 $queries = preg_split('/;\s*$/m', $string);
362 foreach ($queries as $query) {
363 $query = trim($query);
364 if (!empty($query)) {
365 CRM_Core_Error
::debug_query($query);
366 $res = &$db->query($query);
367 if (PEAR
::isError($res)) {
369 die("Cannot execute $query: " . $res->getMessage());
372 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
381 * Strips comment from a possibly multiline SQL string
383 * @param string $string
388 public static function stripComments($string) {
389 return preg_replace("/^(#|--).*\R*/m", "", $string);
397 public static function isExtensionSafe($ext) {
398 static $extensions = NULL;
400 $extensions = CRM_Core_OptionGroup
::values('safe_file_extension', TRUE);
402 // make extensions to lowercase
403 $extensions = array_change_key_case($extensions, CASE_LOWER
);
404 // allow html/htm extension ONLY if the user is admin
405 // and/or has access CiviMail
406 if (!(CRM_Core_Permission
::check('access CiviMail') ||
407 CRM_Core_Permission
::check('administer CiviCRM') ||
408 (CRM_Mailing_Info
::workflowEnabled() &&
409 CRM_Core_Permission
::check('create mailings')
413 unset($extensions['html']);
414 unset($extensions['htm']);
417 // support lower and uppercase file extensions
418 return isset($extensions[strtolower($ext)]) ?
TRUE : FALSE;
422 * Determine whether a given file is listed in the PHP include path.
424 * @param string $name
428 * whether the file can be include()d or require()d
430 public static function isIncludable($name) {
431 $x = @fopen
($name, 'r', TRUE);
442 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
448 public static function cleanFileName($name) {
449 // replace the last 33 character before the '.' with null
450 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
455 * Make a valid file name.
457 * @param string $name
461 public static function makeFileName($name) {
462 $uniqID = md5(uniqid(rand(), TRUE));
463 $info = pathinfo($name);
464 $basename = substr($info['basename'],
465 0, -(strlen(CRM_Utils_Array
::value('extension', $info)) +
(CRM_Utils_Array
::value('extension', $info) == '' ?
0 : 1))
467 if (!self
::isExtensionSafe(CRM_Utils_Array
::value('extension', $info))) {
468 // munge extension so it cannot have an embbeded dot in it
469 // The maximum length of a filename for most filesystems is 255 chars.
470 // We'll truncate at 240 to give some room for the extension.
471 return CRM_Utils_String
::munge("{$basename}_" . CRM_Utils_Array
::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
474 return CRM_Utils_String
::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array
::value('extension', $info);
484 public static function duplicate($filePath) {
485 $oldName = pathinfo($filePath, PATHINFO_FILENAME
);
486 $uniqID = md5(uniqid(rand(), TRUE));
487 $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
488 $newPath = str_replace($oldName, $newName, $filePath);
489 copy($filePath, $newPath);
494 * Get files for the extension.
496 * @param string $path
501 public static function getFilesByExtension($path, $ext) {
502 $path = self
::addTrailingSlash($path);
504 if ($dh = opendir($path)) {
505 while (FALSE !== ($elem = readdir($dh))) {
506 if (substr($elem, -(strlen($ext) +
1)) == '.' . $ext) {
507 $files[] .= $path . $elem;
516 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
519 * The directory to be secured.
520 * @param bool $overwrite
522 public static function restrictAccess($dir, $overwrite = FALSE) {
523 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
524 // of site, causing site to stop functioning.
525 // FIXME: we should do more checks here -
526 if (!empty($dir) && is_dir($dir)) {
527 $htaccess = <<<HTACCESS
530 <IfModule !authz_core_module>
536 <IfModule authz_core_module>
542 $file = $dir . '.htaccess';
543 if ($overwrite ||
!file_exists($file)) {
544 if (file_put_contents($file, $htaccess) === FALSE) {
545 CRM_Core_Error
::movedSiteError($file);
552 * Restrict remote users from browsing the given directory.
556 public static function restrictBrowsing($publicDir) {
557 if (!is_dir($publicDir) ||
!is_writable($publicDir)) {
562 $nobrowse = realpath($publicDir) . '/index.html';
563 if (!file_exists($nobrowse)) {
564 @file_put_contents
($nobrowse, '');
568 $dir = new RecursiveDirectoryIterator($publicDir);
569 foreach ($dir as $name => $object) {
570 if (is_dir($name) && $name != '..') {
571 $nobrowse = realpath($name) . '/index.html';
572 if (!file_exists($nobrowse)) {
573 @file_put_contents
($nobrowse, '');
580 * (Deprecated) Create the file-path from which all other internal paths are
581 * computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
583 * This approach is problematic - e.g. it prevents one from authentically
584 * splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation
585 * is preserved for backwards compatibility (and should only be called by
586 * CMS-adapters and by Civi\Core\Paths).
588 * Do not use it for new path construction logic. Instead, use Civi::paths().
591 * @see \Civi::paths()
592 * @see \Civi\Core\Paths
594 public static function baseFilePath() {
595 static $_path = NULL;
597 // Note: Don't rely on $config; that creates a dependency loop.
598 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
599 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
601 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR
;
603 $path = dirname($templateCompileDir);
605 //this fix is to avoid creation of upload dirs inside templates_c directory
606 $checkPath = explode(DIRECTORY_SEPARATOR
, $path);
608 $cnt = count($checkPath) - 1;
609 if ($checkPath[$cnt] == 'templates_c') {
610 unset($checkPath[$cnt]);
611 $path = implode(DIRECTORY_SEPARATOR
, $checkPath);
614 $_path = CRM_Utils_File
::addTrailingSlash($path);
620 * Determine if a path is absolute.
622 * @param string $path
625 * TRUE if absolute. FALSE if relative.
627 public static function isAbsolute($path) {
628 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR
) {
631 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
632 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
644 * Computation of a relative path requires some base.
645 * This implementation is problematic because it relies on an
646 * implicit base which was constructed problematically.
648 public static function relativeDirectory($directory) {
649 // Do nothing on windows
650 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
654 // check if directory is relative, if so return immediately
655 if (!self
::isAbsolute($directory)) {
659 // make everything relative from the baseFilePath
660 $basePath = self
::baseFilePath();
661 // check if basePath is a substr of $directory, if so
662 // return rest of string
663 if (substr($directory, 0, strlen($basePath)) == $basePath) {
664 return substr($directory, strlen($basePath));
667 // return the original value
673 * @param string $basePath
674 * The base path when evaluating relative paths. Should include trailing slash.
678 public static function absoluteDirectory($directory, $basePath) {
679 // check if directory is already absolute, if so return immediately
680 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
681 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
685 // check if directory is already absolute, if so return immediately
686 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR
) {
690 if ($basePath === NULL) {
691 // Previous versions interpreted `NULL` to mean "default to `self::baseFilePath()`".
692 // However, no code in the known `universe` relies on this interpretation, and
693 // the `baseFilePath()` function is problematic/deprecated.
694 throw new \
RuntimeException("absoluteDirectory() requires specifying a basePath");
697 // ensure that $basePath has a trailing slash
698 $basePath = self
::addTrailingSlash($basePath);
699 return $basePath . $directory;
703 * Make a file path relative to some base dir.
710 public static function relativize($directory, $basePath) {
711 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
712 $directory = strtr($directory, '\\', '/');
713 $basePath = strtr($basePath, '\\', '/');
715 if (substr($directory, 0, strlen($basePath)) == $basePath) {
716 return substr($directory, strlen($basePath));
724 * Create a path to a temporary file which can endure for multiple requests.
726 * @todo Automatic file cleanup using, eg, TTL policy
728 * @param string $prefix
730 * @return string, path to an openable/writable file
733 public static function tempnam($prefix = 'tmp-') {
734 // $config = CRM_Core_Config::singleton();
735 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
736 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
737 $fileName = tempnam(sys_get_temp_dir(), $prefix);
742 * Create a path to a temporary directory which can endure for multiple requests.
744 * @todo Automatic file cleanup using, eg, TTL policy
746 * @param string $prefix
748 * @return string, path to an openable/writable directory; ends with '/'
751 public static function tempdir($prefix = 'tmp-') {
752 $fileName = self
::tempnam($prefix);
754 mkdir($fileName, 0700);
755 return $fileName . '/';
759 * Search directory tree for files which match a glob pattern.
761 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
765 * @param string $pattern
766 * glob pattern, eg "*.txt".
767 * @param bool $relative
768 * TRUE if paths should be made relative to $dir
769 * @return array(string)
771 public static function findFiles($dir, $pattern, $relative = FALSE) {
775 $dir = rtrim($dir, '/');
778 while (!empty($todos)) {
779 $subdir = array_shift($todos);
780 $matches = glob("$subdir/$pattern");
781 if (is_array($matches)) {
782 foreach ($matches as $match) {
783 if (!is_dir($match)) {
784 $result[] = $relative ? CRM_Utils_File
::relativize($match, "$dir/") : $match;
788 if ($dh = opendir($subdir)) {
789 while (FALSE !== ($entry = readdir($dh))) {
790 $path = $subdir . DIRECTORY_SEPARATOR
. $entry;
791 if ($entry{0} == '.') {
794 elseif (is_dir($path)) {
805 * Determine if $child is a sub-directory of $parent
807 * @param string $parent
808 * @param string $child
809 * @param bool $checkRealPath
813 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
814 if ($checkRealPath) {
815 $parent = realpath($parent);
816 $child = realpath($child);
818 $parentParts = explode('/', rtrim($parent, '/'));
819 $childParts = explode('/', rtrim($child, '/'));
820 while (($parentPart = array_shift($parentParts)) !== NULL) {
821 $childPart = array_shift($childParts);
822 if ($parentPart != $childPart) {
826 if (empty($childParts)) {
836 * Move $fromDir to $toDir, replacing/deleting any
837 * pre-existing content.
839 * @param string $fromDir
840 * The directory which should be moved.
841 * @param string $toDir
842 * The new location of the directory.
843 * @param bool $verbose
848 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
849 if (is_dir($toDir)) {
850 if (!self
::cleanDir($toDir, TRUE, $verbose)) {
855 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
857 CRM_Utils_File
::copyDir($fromDir, $toDir);
858 if (!CRM_Utils_File
::cleanDir($fromDir, TRUE, FALSE)) {
859 CRM_Core_Session
::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
868 * @param array $param
869 * @param string $fileName
870 * @param array $extraParams
872 public static function formatFile(&$param, $fileName, $extraParams = []) {
873 if (empty($param[$fileName])) {
878 'uri' => $param[$fileName]['name'],
879 'type' => $param[$fileName]['type'],
880 'location' => $param[$fileName]['name'],
881 'upload_date' => date('YmdHis'),
884 $param[$fileName] = $fileParams;
888 * Return formatted file URL, like for image file return image url with image icon
890 * @param string $path
892 * @param string $fileType
894 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
896 * @return string $url
898 public static function getFileURL($path, $fileType, $url = NULL) {
899 if (empty($path) ||
empty($fileType)) {
902 elseif (empty($url)) {
903 $fileName = basename($path);
904 $url = CRM_Utils_System
::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
913 list($imageWidth, $imageHeight) = getimagesize($path);
914 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
915 $url = "<a href=\"$url\" class='crm-image-popup'>
916 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
921 $url = sprintf('<a href="%s">%s</a>', $url, self
::cleanFileName(basename($path)));
929 * Return formatted image icon
931 * @param string $imageURL
932 * Contact's image url
934 * @return string $url
936 public static function getImageURL($imageURL) {
937 // retrieve image name from $imageURL
938 $imageURL = CRM_Utils_String
::unstupifyUrl($imageURL);
939 parse_str(parse_url($imageURL, PHP_URL_QUERY
), $query);
942 if (!empty($query['photo'])) {
943 $path = CRM_Core_Config
::singleton()->customFileUploadDir
. $query['photo'];
946 $path = $url = $imageURL;
948 $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION
));
949 //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
950 // there are some extensions that would need translating.:
951 $translateMimeTypes = [
956 $mimeType = 'image/' . CRM_Utils_Array
::value(
962 return self
::getFileURL($path, $mimeType, $url);
968 * @param string $sourceFile
969 * Filesystem path to existing image on server
970 * @param int $targetWidth
971 * New width desired, in pixels
972 * @param int $targetHeight
973 * New height desired, in pixels
974 * @param string $suffix = ""
975 * If supplied, the image will be renamed to include this suffix. For
976 * example if the original file name is "foo.png" and $suffix = "_bar",
977 * then the final file name will be "foo_bar.png".
978 * @param bool $preserveAspect = TRUE
979 * When TRUE $width and $height will be used as a bounding box, outside of
980 * which the resized image will not extend.
981 * When FALSE, the image will be resized exactly to $width and $height, even
982 * if it means stretching it.
986 * @throws \CRM_Core_Exception
987 * Under the following conditions
988 * - When GD is not available.
989 * - When the source file is not an image.
991 public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
993 // Check if GD is installed
994 $gdSupport = CRM_Utils_System
::getModuleSetting('gd', 'GD Support');
996 throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
999 $sourceMime = mime_content_type($sourceFile);
1000 if ($sourceMime == 'image/gif') {
1001 $sourceData = imagecreatefromgif($sourceFile);
1003 elseif ($sourceMime == 'image/png') {
1004 $sourceData = imagecreatefrompng($sourceFile);
1006 elseif ($sourceMime == 'image/jpeg') {
1007 $sourceData = imagecreatefromjpeg($sourceFile);
1010 throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
1013 // get image about original image
1014 $sourceInfo = getimagesize($sourceFile);
1015 $sourceWidth = $sourceInfo[0];
1016 $sourceHeight = $sourceInfo[1];
1018 // Adjust target width/height if preserving aspect ratio
1019 if ($preserveAspect) {
1020 $sourceAspect = $sourceWidth / $sourceHeight;
1021 $targetAspect = $targetWidth / $targetHeight;
1022 if ($sourceAspect > $targetAspect) {
1023 $targetHeight = $targetWidth / $sourceAspect;
1025 if ($sourceAspect < $targetAspect) {
1026 $targetWidth = $targetHeight * $sourceAspect;
1030 // figure out the new filename
1031 $pathParts = pathinfo($sourceFile);
1032 $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
1033 . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];
1035 $targetData = imagecreatetruecolor($targetWidth, $targetHeight);
1038 imagecopyresized($targetData, $sourceData,
1040 $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
1042 // save the resized image
1043 $fp = fopen($targetFile, 'w+');
1045 imagejpeg($targetData);
1046 $image_buffer = ob_get_contents();
1048 imagedestroy($targetData);
1049 fwrite($fp, $image_buffer);
1053 // return the URL to link to
1054 $config = CRM_Core_Config
::singleton();
1055 return $config->imageUploadURL
. basename($targetFile);
1059 * Get file icon class for specific MIME Type
1061 * @param string $mimeType
1064 public static function getIconFromMimeType($mimeType) {
1065 if (!isset(Civi
::$statics[__CLASS__
]['mimeIcons'])) {
1066 Civi
::$statics[__CLASS__
]['mimeIcons'] = json_decode(file_get_contents(__DIR__
. '/File/mimeIcons.json'), TRUE);
1068 $iconClasses = Civi
::$statics[__CLASS__
]['mimeIcons'];
1069 foreach ($iconClasses as $text => $icon) {
1070 if (strpos($mimeType, $text) === 0) {
1074 return $iconClasses['*'];
1078 * Is the filename a safe and valid filename passed in from URL
1080 * @param string $fileName
1083 public static function isValidFileName($fileName = NULL) {
1085 $check = $fileName !== basename($fileName) ?
FALSE : TRUE;
1087 if (substr($fileName, 0, 1) == '/' ||
substr($fileName, 0, 1) == '.' ||
substr($fileName, 0, 1) == DIRECTORY_SEPARATOR
) {
1097 * Get the extensions that this MimeTpe is for
1098 * @param string $mimeType the mime-type we want extensions for
1101 public static function getAcceptableExtensionsForMimeType($mimeType = NULL) {
1102 $mapping = \MimeType\Mapping
::$types;
1104 foreach ($mapping as $extension => $type) {
1105 if ($mimeType == $type) {
1106 $extensions[] = $extension;
1113 * Get the extension of a file based on its path
1114 * @param string $path path of the file to query
1117 public static function getExtensionFromPath($path) {
1118 return pathinfo($path, PATHINFO_EXTENSION
);