<?php
// Copyright 1999-2017. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\Utils;

/**
 * Collection of methods useful to work with files.
 *
 * Always use functions from this class instead of built-in ones and Plesk SDK functions.
 * Functions from this class respect security considerations and allow correct integration with backend.
 */
class FileUtils
{
    public static function createDirectory($path)
    {
        // Plesk Migrator frontend is running under "psaadm" user and "psaadm" group.
        // New directory will have the following permissions:
        // rwxrwx--- psaadm psaadm
        // So, nobody except for "psaadm" and superuser could work with the directory.
        mkdir($path, 0770);
    }

    public static function putFileContents($filepath, $contents)
    {
        // Plesk Migrator frontend is running under "psaadm" user and "psaadm" group.
        // New file will have the following permissions:
        // rw-rw---- psaadm psaadm
        // So, nobody except for "psaadm" and superuser could work with the file.
        $oldUmask = umask(0007);
        try {
            file_put_contents($filepath, $contents);
        } finally {
            umask($oldUmask);
        }
    }

    public static function fileExists($filepath)
    {
        return file_exists($filepath);
    }

    public static function fileGetContents($filename)
    {
        return file_get_contents($filename);
    }

    public static function removeDirectory($directory)
    {
        $fileManager = new \pm_ServerFileManager();
        $fileManager->removeDirectory($directory);
    }
}
