File.php 31.3 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
totten's avatar
totten committed
4
 | CiviCRM version 5                                                  |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
6
 | Copyright CiviCRM LLC (c) 2004-2019                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
31
 * @copyright CiviCRM LLC (c) 2004-2019
totten's avatar
totten committed
32 33 34 35 36 37 38 39 40 41
 */

/**
 * class to provide simple static functions for file objects
 */
class CRM_Utils_File {

  /**
   * Given a file name, determine if the file contents make it an ascii file
   *
42 43
   * @param string $name
   *   Name of file.
totten's avatar
totten committed
44
   *
totten's avatar
totten committed
45
   * @return bool
46
   *   true if file is ascii
totten's avatar
totten committed
47
   */
48
  public static function isAscii($name) {
totten's avatar
totten committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    $fd = fopen($name, "r");
    if (!$fd) {
      return FALSE;
    }

    $ascii = TRUE;
    while (!feof($fd)) {
      $line = fgets($fd, 8192);
      if (!CRM_Utils_String::isAscii($line)) {
        $ascii = FALSE;
        break;
      }
    }

    fclose($fd);
    return $ascii;
  }

  /**
   * Given a file name, determine if the file contents make it an html file
   *
70 71
   * @param string $name
   *   Name of file.
totten's avatar
totten committed
72
   *
totten's avatar
totten committed
73
   * @return bool
74
   *   true if file is html
totten's avatar
totten committed
75
   */
76
  public static function isHtml($name) {
totten's avatar
totten committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    $fd = fopen($name, "r");
    if (!$fd) {
      return FALSE;
    }

    $html = FALSE;
    $lineCount = 0;
    while (!feof($fd) & $lineCount <= 5) {
      $lineCount++;
      $line = fgets($fd, 8192);
      if (!CRM_Utils_String::isHtml($line)) {
        $html = TRUE;
        break;
      }
    }

    fclose($fd);
    return $html;
  }

  /**
colemanw's avatar
colemanw committed
98
   * Create a directory given a path name, creates parent directories
totten's avatar
totten committed
99 100
   * if needed
   *
101 102 103 104
   * @param string $path
   *   The path name.
   * @param bool $abort
   *   Should we abort or just return an invalid code.
105 106 107 108
   * @return bool|NULL
   *   NULL: Folder already exists or was not specified.
   *   TRUE: Creation succeeded.
   *   FALSE: Creation failed.
totten's avatar
totten committed
109
   */
110
  public static function createDir($path, $abort = TRUE) {
totten's avatar
totten committed
111
    if (is_dir($path) || empty($path)) {
112
      return NULL;
totten's avatar
totten committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    }

    CRM_Utils_File::createDir(dirname($path), $abort);
    if (@mkdir($path, 0777) == FALSE) {
      if ($abort) {
        $docLink = CRM_Utils_System::docURL2('Moving an Existing Installation to a New Server or Location', NULL, NULL, NULL, NULL, "wiki");
        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>";

        CRM_Utils_System::civiExit();
      }
      else {
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
colemanw's avatar
colemanw committed
131
   * Delete a directory given a path name, delete children directories
totten's avatar
totten committed
132 133
   * and files if needed
   *
134 135
   * @param string $target
   *   The path name.
Eileen McNaughton's avatar
Eileen McNaughton committed
136 137 138 139
   * @param bool $rmdir
   * @param bool $verbose
   *
   * @throws Exception
totten's avatar
totten committed
140
   */
141
  public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
142
    static $exceptions = ['.', '..'];
143
    if ($target == '' || $target == '/' || !$target) {
totten's avatar
totten committed
144 145 146
      throw new Exception("Overly broad deletion");
    }

147 148
    if ($dh = @opendir($target)) {
      while (FALSE !== ($sibling = readdir($dh))) {
totten's avatar
totten committed
149 150 151 152 153 154 155 156
        if (!in_array($sibling, $exceptions)) {
          $object = $target . DIRECTORY_SEPARATOR . $sibling;

          if (is_dir($object)) {
            CRM_Utils_File::cleanDir($object, $rmdir, $verbose);
          }
          elseif (is_file($object)) {
            if (!unlink($object)) {
157
              CRM_Core_Session::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
totten's avatar
totten committed
158
            }
totten's avatar
totten committed
159 160 161
          }
        }
      }
162
      closedir($dh);
totten's avatar
totten committed
163 164 165 166

      if ($rmdir) {
        if (rmdir($target)) {
          if ($verbose) {
167
            CRM_Core_Session::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
totten's avatar
totten committed
168 169
          }
          return TRUE;
totten's avatar
totten committed
170
        }
totten's avatar
totten committed
171
        else {
172
          CRM_Core_Session::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
totten's avatar
totten committed
173 174
        }
      }
totten's avatar
totten committed
175 176 177
    }
  }

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  /**
   * Concatenate several files.
   *
   * @param array $files
   *   List of file names.
   * @param string $delim
   *   An optional delimiter to put between files.
   * @return string
   */
  public static function concat($files, $delim = '') {
    $buf = '';
    $first = TRUE;
    foreach ($files as $file) {
      if (!$first) {
        $buf .= $delim;
      }
      $buf .= file_get_contents($file);
      $first = FALSE;
    }
    return $buf;
  }

200
  /**
totten's avatar
totten committed
201 202
   * @param string $source
   * @param string $destination
203
   */
totten's avatar
totten committed
204
  public static function copyDir($source, $destination) {
205
    if ($dh = opendir($source)) {
xurizaemon's avatar
xurizaemon committed
206
      @mkdir($destination);
207
      while (FALSE !== ($file = readdir($dh))) {
xurizaemon's avatar
xurizaemon committed
208 209 210 211 212 213 214
        if (($file != '.') && ($file != '..')) {
          if (is_dir($source . DIRECTORY_SEPARATOR . $file)) {
            CRM_Utils_File::copyDir($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
          }
          else {
            copy($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
          }
totten's avatar
totten committed
215 216
        }
      }
217
      closedir($dh);
totten's avatar
totten committed
218 219 220 221 222 223
    }
  }

  /**
   * Given a file name, recode it (in place!) to UTF-8
   *
224 225
   * @param string $name
   *   Name of file.
totten's avatar
totten committed
226
   *
totten's avatar
totten committed
227
   * @return bool
228
   *   whether the file was recoded properly
totten's avatar
totten committed
229
   */
230
  public static function toUtf8($name) {
totten's avatar
totten committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    static $config = NULL;
    static $legacyEncoding = NULL;
    if ($config == NULL) {
      $config = CRM_Core_Config::singleton();
      $legacyEncoding = $config->legacyEncoding;
    }

    if (!function_exists('iconv')) {

      return FALSE;

    }

    $contents = file_get_contents($name);
    if ($contents === FALSE) {
      return FALSE;
    }

    $contents = iconv($legacyEncoding, 'UTF-8', $contents);
    if ($contents === FALSE) {
      return FALSE;
    }

    $file = fopen($name, 'w');
    if ($file === FALSE) {
      return FALSE;
    }

    $written = fwrite($file, $contents);
    $closed = fclose($file);
    if ($written === FALSE or !$closed) {
      return FALSE;
    }

    return TRUE;
  }

  /**
colemanw's avatar
colemanw committed
269
   * Appends a slash to the end of a string if it doesn't already end with one
totten's avatar
totten committed
270
   *
colemanw's avatar
colemanw committed
271 272
   * @param string $path
   * @param string $slash
Eileen McNaughton's avatar
Eileen McNaughton committed
273
   *
totten's avatar
totten committed
274 275
   * @return string
   */
276
  public static function addTrailingSlash($path, $slash = NULL) {
colemanw's avatar
colemanw committed
277
    if (!$slash) {
eileenmcnaugton's avatar
eileenmcnaugton committed
278
      // FIXME: Defaulting to backslash on windows systems can produce
279
      // unexpected results, esp for URL strings which should always use forward-slashes.
colemanw's avatar
colemanw committed
280 281
      // I think this fn should default to forward-slash instead.
      $slash = DIRECTORY_SEPARATOR;
totten's avatar
totten committed
282
    }
283
    if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
colemanw's avatar
colemanw committed
284
      $path .= $slash;
totten's avatar
totten committed
285
    }
colemanw's avatar
colemanw committed
286
    return $path;
totten's avatar
totten committed
287 288
  }

289 290 291 292 293 294 295
  /**
   * Save a fake file somewhere
   *
   * @param string $dir
   *   The directory where the file should be saved.
   * @param string $contents
   *   Optional: the contents of the file.
296
   * @param string $fileName
297 298 299 300
   *
   * @return string
   *   The filename saved, or FALSE on failure.
   */
301
  public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
302
    $dir = self::addTrailingSlash($dir);
303 304 305
    if (!$fileName) {
      $fileName = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
    }
306
    $success = @file_put_contents($dir . $fileName, $contents);
307

308
    return ($success === FALSE) ? FALSE : $fileName;
309 310
  }

311
  /**
312 313 314
   * @param string|NULL $dsn
   *   Use NULL to load the default/active connection from CRM_Core_DAO.
   *   Otherwise, give a full DSN string.
colemanw's avatar
colemanw committed
315
   * @param string $fileName
316
   * @param string $prefix
317 318
   * @param bool $dieOnErrors
   */
319 320 321 322 323
  public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $dieOnErrors = TRUE) {
    if (FALSE === file_get_contents($fileName)) {
      // Our file cannot be found.
      // Using 'die' here breaks this on extension upgrade.
      throw new CRM_Exception('Could not find the SQL file.');
324 325
    }

326 327 328 329 330 331 332 333 334 335 336 337 338
    self::runSqlQuery($dsn, file_get_contents($fileName), $prefix, $dieOnErrors);
  }

  /**
   *
   * @param string|NULL $dsn
   * @param string $queryString
   * @param string $prefix
   * @param bool $dieOnErrors
   */
  public static function runSqlQuery($dsn, $queryString, $prefix = NULL, $dieOnErrors = TRUE) {
    $string = $prefix . $queryString;

339 340 341 342 343 344 345
    if ($dsn === NULL) {
      $db = CRM_Core_DAO::getConnection();
    }
    else {
      require_once 'DB.php';
      $db = DB::connect($dsn);
    }
totten's avatar
totten committed
346 347 348 349 350 351 352

    if (PEAR::isError($db)) {
      die("Cannot open $dsn: " . $db->getMessage());
    }
    if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
      $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
    }
cividesk's avatar
cividesk committed
353
    $db->query('SET NAMES utf8');
354
    $transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
Seamus Lee's avatar
Seamus Lee committed
355
    $db->query('SET @uniqueID = ' . "'$transactionId'");
totten's avatar
totten committed
356

357
    // get rid of comments starting with # and --
totten's avatar
totten committed
358

359
    $string = self::stripComments($string);
totten's avatar
totten committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

    $queries = preg_split('/;\s*$/m', $string);
    foreach ($queries as $query) {
      $query = trim($query);
      if (!empty($query)) {
        CRM_Core_Error::debug_query($query);
        $res = &$db->query($query);
        if (PEAR::isError($res)) {
          if ($dieOnErrors) {
            die("Cannot execute $query: " . $res->getMessage());
          }
          else {
            echo "Cannot execute $query: " . $res->getMessage() . "<p>";
          }
        }
      }
    }
  }
378

379 380 381 382 383 384 385
  /**
   *
   * Strips comment from a possibly multiline SQL string
   *
   * @param string $string
   *
   * @return string
386
   *   stripped string
387 388 389 390
   */
  public static function stripComments($string) {
    return preg_replace("/^(#|--).*\R*/m", "", $string);
  }
totten's avatar
totten committed
391

392 393 394 395 396
  /**
   * @param $ext
   *
   * @return bool
   */
397
  public static function isExtensionSafe($ext) {
totten's avatar
totten committed
398 399 400 401
    static $extensions = NULL;
    if (!$extensions) {
      $extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);

402
      // make extensions to lowercase
totten's avatar
totten committed
403 404 405 406
      $extensions = array_change_key_case($extensions, CASE_LOWER);
      // allow html/htm extension ONLY if the user is admin
      // and/or has access CiviMail
      if (!(CRM_Core_Permission::check('access CiviMail') ||
407 408 409 410 411 412
        CRM_Core_Permission::check('administer CiviCRM') ||
        (CRM_Mailing_Info::workflowEnabled() &&
          CRM_Core_Permission::check('create mailings')
        )
      )
      ) {
totten's avatar
totten committed
413 414 415 416
        unset($extensions['html']);
        unset($extensions['htm']);
      }
    }
417
    // support lower and uppercase file extensions
totten's avatar
totten committed
418 419 420 421
    return isset($extensions[strtolower($ext)]) ? TRUE : FALSE;
  }

  /**
422
   * Determine whether a given file is listed in the PHP include path.
totten's avatar
totten committed
423
   *
424 425
   * @param string $name
   *   Name of file.
totten's avatar
totten committed
426
   *
totten's avatar
totten committed
427
   * @return bool
428
   *   whether the file can be include()d or require()d
totten's avatar
totten committed
429
   */
430
  public static function isIncludable($name) {
totten's avatar
totten committed
431 432 433 434 435 436 437 438 439 440 441
    $x = @fopen($name, 'r', TRUE);
    if ($x) {
      fclose($x);
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
eileenmcnaugton's avatar
eileenmcnaugton committed
442 443 444 445 446
   * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
   *
   * @param $name
   *
   * @return mixed
totten's avatar
totten committed
447
   */
448
  public static function cleanFileName($name) {
totten's avatar
totten committed
449 450 451 452 453
    // replace the last 33 character before the '.' with null
    $name = preg_replace('/(_[\w]{32})\./', '.', $name);
    return $name;
  }

454
  /**
eileen's avatar
eileen committed
455 456
   * Make a valid file name.
   *
colemanw's avatar
colemanw committed
457
   * @param string $name
458 459 460
   *
   * @return string
   */
461
  public static function makeFileName($name) {
462 463
    $uniqID = md5(uniqid(rand(), TRUE));
    $info = pathinfo($name);
totten's avatar
totten committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477
    $basename = substr($info['basename'],
      0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
    );
    if (!self::isExtensionSafe(CRM_Utils_Array::value('extension', $info))) {
      // munge extension so it cannot have an embbeded dot in it
      // The maximum length of a filename for most filesystems is 255 chars.
      // We'll truncate at 240 to give some room for the extension.
      return CRM_Utils_String::munge("{$basename}_" . CRM_Utils_Array::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
    }
    else {
      return CRM_Utils_String::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array::value('extension', $info);
    }
  }

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
  /**
   * Copies a file
   *
   * @param $filePath
   * @return mixed
   */
  public static function duplicate($filePath) {
    $oldName = pathinfo($filePath, PATHINFO_FILENAME);
    $uniqID = md5(uniqid(rand(), TRUE));
    $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
    $newPath = str_replace($oldName, $newName, $filePath);
    copy($filePath, $newPath);
    return $newPath;
  }

493
  /**
eileen's avatar
eileen committed
494 495 496 497
   * Get files for the extension.
   *
   * @param string $path
   * @param string $ext
498 499 500
   *
   * @return array
   */
501
  public static function getFilesByExtension($path, $ext) {
502
    $path = self::addTrailingSlash($path);
503
    $files = [];
xurizaemon's avatar
xurizaemon committed
504 505 506 507 508
    if ($dh = opendir($path)) {
      while (FALSE !== ($elem = readdir($dh))) {
        if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
          $files[] .= $path . $elem;
        }
totten's avatar
totten committed
509
      }
xurizaemon's avatar
xurizaemon committed
510
      closedir($dh);
totten's avatar
totten committed
511 512 513 514 515 516 517
    }
    return $files;
  }

  /**
   * Restrict access to a given directory (by planting there a restrictive .htaccess file)
   *
518 519
   * @param string $dir
   *   The directory to be secured.
Eileen McNaughton's avatar
Eileen McNaughton committed
520
   * @param bool $overwrite
totten's avatar
totten committed
521
   */
522
  public static function restrictAccess($dir, $overwrite = FALSE) {
totten's avatar
totten committed
523 524 525
    // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
    // of site, causing site to stop functioning.
    // FIXME: we should do more checks here -
526
    if (!empty($dir) && is_dir($dir)) {
totten's avatar
totten committed
527 528 529 530 531 532 533 534
      $htaccess = <<<HTACCESS
<Files "*">
  Order allow,deny
  Deny from all
</Files>

HTACCESS;
      $file = $dir . '.htaccess';
535 536 537 538
      if ($overwrite || !file_exists($file)) {
        if (file_put_contents($file, $htaccess) === FALSE) {
          CRM_Core_Error::movedSiteError($file);
        }
totten's avatar
totten committed
539 540 541 542
      }
    }
  }

543 544 545 546 547
  /**
   * Restrict remote users from browsing the given directory.
   *
   * @param $publicDir
   */
548
  public static function restrictBrowsing($publicDir) {
549 550 551 552
    if (!is_dir($publicDir) || !is_writable($publicDir)) {
      return;
    }

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    // base dir
    $nobrowse = realpath($publicDir) . '/index.html';
    if (!file_exists($nobrowse)) {
      @file_put_contents($nobrowse, '');
    }

    // child dirs
    $dir = new RecursiveDirectoryIterator($publicDir);
    foreach ($dir as $name => $object) {
      if (is_dir($name) && $name != '..') {
        $nobrowse = realpath($name) . '/index.html';
        if (!file_exists($nobrowse)) {
          @file_put_contents($nobrowse, '');
        }
      }
    }
  }

totten's avatar
totten committed
571 572 573 574
  /**
   * Create the base file path from which all our internal directories are
   * offset. This is derived from the template compile directory set
   */
575
  public static function baseFilePath() {
totten's avatar
totten committed
576 577
    static $_path = NULL;
    if (!$_path) {
578 579 580
      // Note: Don't rely on $config; that creates a dependency loop.
      if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
        throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
totten's avatar
totten committed
581
      }
582
      $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
totten's avatar
totten committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

      $path = dirname($templateCompileDir);

      //this fix is to avoid creation of upload dirs inside templates_c directory
      $checkPath = explode(DIRECTORY_SEPARATOR, $path);

      $cnt = count($checkPath) - 1;
      if ($checkPath[$cnt] == 'templates_c') {
        unset($checkPath[$cnt]);
        $path = implode(DIRECTORY_SEPARATOR, $checkPath);
      }

      $_path = CRM_Utils_File::addTrailingSlash($path);
    }
    return $_path;
  }

600 601 602
  /**
   * Determine if a path is absolute.
   *
eileenmcnaugton's avatar
eileenmcnaugton committed
603 604
   * @param string $path
   *
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
   * @return bool
   *   TRUE if absolute. FALSE if relative.
   */
  public static function isAbsolute($path) {
    if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
      return TRUE;
    }
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
      if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
        return TRUE;
      }
    }
    return FALSE;
  }

620 621 622 623 624
  /**
   * @param $directory
   *
   * @return string
   */
625
  public static function relativeDirectory($directory) {
totten's avatar
totten committed
626 627 628 629 630 631
    // Do nothing on windows
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
      return $directory;
    }

    // check if directory is relative, if so return immediately
632
    if (!self::isAbsolute($directory)) {
totten's avatar
totten committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
      return $directory;
    }

    // make everything relative from the baseFilePath
    $basePath = self::baseFilePath();
    // check if basePath is a substr of $directory, if so
    // return rest of string
    if (substr($directory, 0, strlen($basePath)) == $basePath) {
      return substr($directory, strlen($basePath));
    }

    // return the original value
    return $directory;
  }

648 649
  /**
   * @param $directory
650 651
   * @param string|NULL $basePath
   *   The base path when evaluating relative paths. Should include trailing slash.
652 653 654
   *
   * @return string
   */
655
  public static function absoluteDirectory($directory, $basePath = NULL) {
656 657 658
    // check if directory is already absolute, if so return immediately
    // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
totten's avatar
totten committed
659 660 661 662 663 664 665 666 667
      return $directory;
    }

    // check if directory is already absolute, if so return immediately
    if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
      return $directory;
    }

    // make everything absolute from the baseFilePath
668
    $basePath = ($basePath === NULL) ? self::baseFilePath() : $basePath;
totten's avatar
totten committed
669

Michael McAndrew's avatar
Michael McAndrew committed
670
    // ensure that $basePath has a trailing slash
671
    $basePath = self::addTrailingSlash($basePath);
totten's avatar
totten committed
672 673 674 675
    return $basePath . $directory;
  }

  /**
676
   * Make a file path relative to some base dir.
totten's avatar
totten committed
677
   *
Eileen McNaughton's avatar
Eileen McNaughton committed
678 679 680
   * @param $directory
   * @param $basePath
   *
totten's avatar
totten committed
681 682
   * @return string
   */
683
  public static function relativize($directory, $basePath) {
684 685 686 687
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
      $directory = strtr($directory, '\\', '/');
      $basePath = strtr($basePath, '\\', '/');
    }
totten's avatar
totten committed
688 689
    if (substr($directory, 0, strlen($basePath)) == $basePath) {
      return substr($directory, strlen($basePath));
690 691
    }
    else {
totten's avatar
totten committed
692 693 694 695 696
      return $directory;
    }
  }

  /**
697
   * Create a path to a temporary file which can endure for multiple requests.
totten's avatar
totten committed
698
   *
699
   * @todo Automatic file cleanup using, eg, TTL policy
totten's avatar
totten committed
700
   *
colemanw's avatar
colemanw committed
701
   * @param string $prefix
totten's avatar
totten committed
702 703 704 705
   *
   * @return string, path to an openable/writable file
   * @see tempnam
   */
706
  public static function tempnam($prefix = 'tmp-') {
707 708 709
    // $config = CRM_Core_Config::singleton();
    // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
    // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
totten's avatar
totten committed
710 711 712 713 714
    $fileName = tempnam(sys_get_temp_dir(), $prefix);
    return $fileName;
  }

  /**
715
   * Create a path to a temporary directory which can endure for multiple requests.
totten's avatar
totten committed
716
   *
717
   * @todo Automatic file cleanup using, eg, TTL policy
totten's avatar
totten committed
718
   *
colemanw's avatar
colemanw committed
719
   * @param string $prefix
totten's avatar
totten committed
720 721 722 723
   *
   * @return string, path to an openable/writable directory; ends with '/'
   * @see tempnam
   */
724
  public static function tempdir($prefix = 'tmp-') {
totten's avatar
totten committed
725 726 727 728 729 730 731
    $fileName = self::tempnam($prefix);
    unlink($fileName);
    mkdir($fileName, 0700);
    return $fileName . '/';
  }

  /**
732 733 734
   * Search directory tree for files which match a glob pattern.
   *
   * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
totten's avatar
totten committed
735
   *
colemanw's avatar
colemanw committed
736 737 738 739
   * @param string $dir
   *   base dir.
   * @param string $pattern
   *   glob pattern, eg "*.txt".
740 741
   * @param bool $relative
   *   TRUE if paths should be made relative to $dir
totten's avatar
totten committed
742 743
   * @return array(string)
   */
744
  public static function findFiles($dir, $pattern, $relative = FALSE) {
745
    if (!is_dir($dir)) {
746
      return [];
747
    }
748
    $dir = rtrim($dir, '/');
749 750
    $todos = [$dir];
    $result = [];
totten's avatar
totten committed
751 752
    while (!empty($todos)) {
      $subdir = array_shift($todos);
753 754 755
      $matches = glob("$subdir/$pattern");
      if (is_array($matches)) {
        foreach ($matches as $match) {
756
          if (!is_dir($match)) {
757
            $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
758
          }
totten's avatar
totten committed
759 760
        }
      }
xurizaemon's avatar
xurizaemon committed
761
      if ($dh = opendir($subdir)) {
totten's avatar
totten committed
762 763
        while (FALSE !== ($entry = readdir($dh))) {
          $path = $subdir . DIRECTORY_SEPARATOR . $entry;
764 765
          if ($entry{0} == '.') {
            // ignore
766 767
          }
          elseif (is_dir($path)) {
totten's avatar
totten committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781
            $todos[] = $path;
          }
        }
        closedir($dh);
      }
    }
    return $result;
  }

  /**
   * Determine if $child is a sub-directory of $parent
   *
   * @param string $parent
   * @param string $child
Eileen McNaughton's avatar
Eileen McNaughton committed
782 783
   * @param bool $checkRealPath
   *
totten's avatar
totten committed
784 785
   * @return bool
   */
786
  public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
totten's avatar
totten committed
787 788 789 790 791 792 793 794 795 796 797 798 799
    if ($checkRealPath) {
      $parent = realpath($parent);
      $child = realpath($child);
    }
    $parentParts = explode('/', rtrim($parent, '/'));
    $childParts = explode('/', rtrim($child, '/'));
    while (($parentPart = array_shift($parentParts)) !== NULL) {
      $childPart = array_shift($childParts);
      if ($parentPart != $childPart) {
        return FALSE;
      }
    }
    if (empty($childParts)) {
800 801
      // same directory
      return FALSE;
802 803
    }
    else {
totten's avatar
totten committed
804 805 806 807 808 809 810 811
      return TRUE;
    }
  }

  /**
   * Move $fromDir to $toDir, replacing/deleting any
   * pre-existing content.
   *
812 813 814 815
   * @param string $fromDir
   *   The directory which should be moved.
   * @param string $toDir
   *   The new location of the directory.
Eileen McNaughton's avatar
Eileen McNaughton committed
816 817
   * @param bool $verbose
   *
818 819
   * @return bool
   *   TRUE on success
totten's avatar
totten committed
820
   */
821
  public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
totten's avatar
totten committed
822 823 824 825 826 827
    if (is_dir($toDir)) {
      if (!self::cleanDir($toDir, TRUE, $verbose)) {
        return FALSE;
      }
    }

828
    // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
totten's avatar
totten committed
829 830 831

    CRM_Utils_File::copyDir($fromDir, $toDir);
    if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
832
      CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
totten's avatar
totten committed
833 834 835 836
      return FALSE;
    }
    return TRUE;
  }
837

eileen's avatar
eileen committed
838 839 840 841 842 843 844
  /**
   * Format file.
   *
   * @param array $param
   * @param string $fileName
   * @param array $extraParams
   */
845
  public static function formatFile(&$param, $fileName, $extraParams = []) {
846 847 848 849
    if (empty($param[$fileName])) {
      return;
    }

850
    $fileParams = [
851 852 853 854
      'uri' => $param[$fileName]['name'],
      'type' => $param[$fileName]['type'],
      'location' => $param[$fileName]['name'],
      'upload_date' => date('YmdHis'),
855
    ] + $extraParams;
856 857 858 859

    $param[$fileName] = $fileParams;
  }

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
  /**
   * Return formatted file URL, like for image file return image url with image icon
   *
   * @param string $path
   *   Absoulte file path
   * @param string $fileType
   * @param string $url
   *   File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
   *
   * @return string $url
   */
  public static function getFileURL($path, $fileType, $url = NULL) {
    if (empty($path) || empty($fileType)) {
      return '';
    }
    elseif (empty($url)) {
      $fileName = basename($path);
      $url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
    }
    switch ($fileType) {
      case 'image/jpeg':
      case 'image/pjpeg':
      case 'image/gif':
      case 'image/x-png':
      case 'image/png':
885
      case 'image/jpg':
886 887 888 889 890 891 892 893
        list($imageWidth, $imageHeight) = getimagesize($path);
        list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
        $url = "<a href=\"$url\" class='crm-image-popup'>
          <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
          </a>";
        break;

      default:
894
        $url = sprintf('<a href="%s">%s</a>', $url, self::cleanFileName(basename($path)));
895 896 897 898 899 900
        break;
    }

    return $url;
  }

901 902 903 904 905 906 907 908 909 910 911 912 913
  /**
   * Return formatted image icon
   *
   * @param string $imageURL
   *   Contact's image url
   *
   * @return string $url
   */
  public static function getImageURL($imageURL) {
    // retrieve image name from $imageURL
    $imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
    parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);

914 915 916 917 918 919 920
    $url = NULL;
    if (!empty($query['photo'])) {
      $path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
    }
    else {
      $path = $url = $imageURL;
    }
921
    $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
922 923 924 925 926 927 928 929 930 931 932 933
    //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
    // there are some extensions that would need translating.:
    $translateMimeTypes = [
      'tif' => 'tiff',
      'jpg' => 'jpeg',
      'svg' => 'svg+xml',
    ];
    $mimeType = 'image/' . CRM_Utils_Array::value(
      $fileExtension,
      $translateMimeTypes,
      $fileExtension
    );
934

935
    return self::getFileURL($path, $mimeType, $url);
936 937
  }

938
  /**
939 940 941 942 943 944 945 946 947 948 949 950
   * Resize an image.
   *
   * @param string $sourceFile
   *   Filesystem path to existing image on server
   * @param int $targetWidth
   *   New width desired, in pixels
   * @param int $targetHeight
   *   New height desired, in pixels
   * @param string $suffix = ""
   *   If supplied, the image will be renamed to include this suffix. For
   *   example if the original file name is "foo.png" and $suffix = "_bar",
   *   then the final file name will be "foo_bar.png".
951 952 953 954 955
   * @param bool $preserveAspect = TRUE
   *   When TRUE $width and $height will be used as a bounding box, outside of
   *   which the resized image will not extend.
   *   When FALSE, the image will be resized exactly to $width and $height, even
   *   if it means stretching it.
956 957 958
   *
   * @return string
   *   Path to image
959 960 961 962
   * @throws \CRM_Core_Exception
   *   Under the following conditions
   *   - When GD is not available.
   *   - When the source file is not an image.
963
   */
964
  public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
965

966 967 968 969 970 971 972 973 974 975 976 977
    // Check if GD is installed
    $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
    if (!$gdSupport) {
      throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
    }

    $sourceMime = mime_content_type($sourceFile);
    if ($sourceMime == 'image/gif') {
      $sourceData = imagecreatefromgif($sourceFile);
    }
    elseif ($sourceMime == 'image/png') {
      $sourceData = imagecreatefrompng($sourceFile);
978
    }
979 980
    elseif ($sourceMime == 'image/jpeg') {
      $sourceData = imagecreatefromjpeg($sourceFile);
981 982
    }
    else {
983
      throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
984 985
    }

986 987 988 989 990
    // get image about original image
    $sourceInfo = getimagesize($sourceFile);
    $sourceWidth = $sourceInfo[0];
    $sourceHeight = $sourceInfo[1];

991 992 993 994 995 996 997 998 999 1000 1001 1002
    // Adjust target width/height if preserving aspect ratio
    if ($preserveAspect) {
      $sourceAspect = $sourceWidth / $sourceHeight;
      $targetAspect = $targetWidth / $targetHeight;
      if ($sourceAspect > $targetAspect) {
        $targetHeight = $targetWidth / $sourceAspect;
      }
      if ($sourceAspect < $targetAspect) {
        $targetWidth = $targetHeight * $sourceAspect;
      }
    }

1003 1004 1005 1006 1007 1008 1009
    // figure out the new filename
    $pathParts = pathinfo($sourceFile);
    $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
      . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];

    $targetData = imagecreatetruecolor($targetWidth, $targetHeight);

1010
    // resize
1011 1012 1013
    imagecopyresized($targetData, $sourceData,
      0, 0, 0, 0,
      $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
1014 1015

    // save the resized image
1016
    $fp = fopen($targetFile, 'w+');
1017
    ob_start();
1018
    imagejpeg($targetData);
1019 1020
    $image_buffer = ob_get_contents();
    ob_end_clean();
1021
    imagedestroy($targetData);
1022 1023 1024 1025 1026 1027
    fwrite($fp, $image_buffer);
    rewind($fp);
    fclose($fp);

    // return the URL to link to
    $config = CRM_Core_Config::singleton();
1028
    return $config->imageUploadURL . basename($targetFile);
1029
  }
1030 1031 1032 1033 1034 1035 1036 1037

  /**
   * Get file icon class for specific MIME Type
   *
   * @param string $mimeType
   * @return string
   */
  public static function getIconFromMimeType($mimeType) {
1038 1039 1040 1041
    if (!isset(Civi::$statics[__CLASS__]['mimeIcons'])) {
      Civi::$statics[__CLASS__]['mimeIcons'] = json_decode(file_get_contents(__DIR__ . '/File/mimeIcons.json'), TRUE);
    }
    $iconClasses = Civi::$statics[__CLASS__]['mimeIcons'];
1042 1043 1044 1045 1046
    foreach ($iconClasses as $text => $icon) {
      if (strpos($mimeType, $text) === 0) {
        return $icon;
      }
    }
1047
    return $iconClasses['*'];
1048 1049
  }

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  /**
   * Is the filename a safe and valid filename passed in from URL
   *
   * @param string $fileName
   * @return bool
   */
  public static function isValidFileName($fileName = NULL) {
    if ($fileName) {
      $check = $fileName !== basename($fileName) ? FALSE : TRUE;
      if ($check) {
        if (substr($fileName, 0, 1) == '/' || substr($fileName, 0, 1) == '.' || substr($fileName, 0, 1) == DIRECTORY_SEPARATOR) {
          $check = FALSE;
        }
      }
      return $check;
    }
    return FALSE;
  }

1069
  /**
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
   * Get the extensions that this MimeTpe is for
   * @param string $mimeType the mime-type we want extensions for
   * @return array
   */
  public static function getAcceptableExtensionsForMimeType($mimeType = NULL) {
    $mapping = \MimeType\Mapping::$types;
    $extensions = [];
    foreach ($mapping as $extension => $type) {
      if ($mimeType == $type) {
        $extensions[] = $extension;
      }
    }
    return $extensions;
  }

  /**
   * Get the extension of a file based on its path
   * @param string $path path of the file to query
   * @return string
1089
   */
1090 1091
  public static function getExtensionFromPath($path) {
    return pathinfo($path, PATHINFO_EXTENSION);
1092 1093
  }

totten's avatar
totten committed
1094
}