Move file or directory to another folder

@throws \Exception
170396
private function movePath() {
		$source = $this->getSource();
		$destinationPath = $source->getPath();
		$sourcePath = $source->getPath($this->request->from);

		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $destinationPath);
		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $sourcePath);

		if ($sourcePath) {
			if ($destinationPath) {
				if (is_file($sourcePath) or is_dir($sourcePath)) {
					rename($sourcePath, $destinationPath . basename($sourcePath));
				} else {
					throw new \Exception('Not file', Consts::ERROR_CODE_NOT_EXISTS);
				}
			} else {
				throw new \Exception('Need destination path', Consts::ERROR_CODE_BAD_REQUEST);
			}
		} else {
			throw new \Exception('Need source path', Consts::ERROR_CODE_BAD_REQUEST);
		}
	}
398723
public function move()
    {
        // do any actions if files exists

        foreach ($this->files as $n => $file) {

            $filename = $file->getName();

            if (isset($this->rules['hash']) === true) {
                if (empty($this->rules['hash']) === true) {
                    $this->rules['hash'] = 'md5';
                }

                if (!is_string($this->rules['hash']) === true) {
                    $filename = call_user_func($this->rules['hash']) . '.' . $file->getExtension();
                } else {
                    $filename = $this->rules['hash']($filename) . '.' . $file->getExtension();
                }
            }

            if (isset($this->rules['sanitize']) === true) {
                $filename = Format::toLatin($filename, '', true);
            }

            if (isset($this->rules['directory'])) {
                $tmp = rtrim($this->rules['directory'], '/') . DIRECTORY_SEPARATOR . $filename;
            } else {
                $tmp = rtrim($this->rules['dynamic'], '/') . DIRECTORY_SEPARATOR . $filename;

            }

            // move file to target directory
            $isUploaded = $file->moveTo($tmp);

            if ($isUploaded === true) {
                $this->info[] = [
                    'path'      =>  $tmp,
                    'directory' => dirname($tmp),
                    'filename'  => $filename,
                    'size'      => $file->getSize(),
                    'extension' => $file->getExtension(),
                ];
            }
        }

        return $this->getInfo();
    }
179536
public final function remove()
    {
        if ($this->exists())
        {
            if (unlink($this->getPath()))
                return true;
            throw new \Exception($this->getName() . ': Deleting failed');
        }
    }
910061
public function moveToDirectory(string $newDirectoryPath): self
    {
        $newDirectoryPath = normalize_path($newDirectoryPath);

        if (is_dir($newDirectoryPath)) {
            if (is_writeable($newDirectoryPath)) {
                $newFolderPath = $newDirectoryPath.DIRECTORY_SEPARATOR.$this->getName();

                return $this->move($newFolderPath);
            }
            throw new FolderException('Cannot move the folder, because the directory ('.$newDirectoryPath.') is not writable',
                FolderException::NOT_WRITEABLE);
        }
        throw new FolderException('Cannot move the folder, because the directory (('.$newDirectoryPath.')) does not exist',
            FolderException::DONT_EXIST);
    }
1050920
def move(srcpath, dstpath, overwrite=True):
    """"""
    # TODO: (JRR@201612230924) Consider adding smarter checks to prevent files ending up with directory names; e.g. if dstpath directory does not exist.
    if not op.exists(srcpath):
        return False
    if srcpath == dstpath:
        return True
    if op.isfile(srcpath) and op.isdir(dstpath):
        verfunc = op.isfile
        verpath = op.join(dstpath, op.basename(srcpath))
    elif op.isfile(srcpath):
        verfunc = op.isfile
        verpath = dstpath
        makedirs(dstpath)
    elif op.isdir(srcpath) and op.isdir(dstpath):
        verfunc = op.isdir
        verpath = op.join(dstpath, op.basename(srcpath))
    elif op.isdir(srcpath):
        verfunc = op.isdir
        verpath = dstpath
    else:
        return False
    if op.isfile(verpath):
        if not overwrite:
            return False
        else:
            # On Windows, filename case is ignored so the following check will
            # prevent unintentionally deleting the srcpath before moving.
            if "nt" == os.name and srcpath.lower() == dstpath.lower():
                pass
            elif not delete(verpath):
                return False
    try:
        shutil.move(srcpath, dstpath)
    except:
        return False
    return verfunc(verpath)
979664
public final function moveTo($targetPath)
    {    
        $path = str_replace(["/", "\\"], DIRECTORY_SEPARATOR, $targetPath);
        $lastDirPos = strripos($path, DIRECTORY_SEPARATOR);
        $dir  = $lastDirPos ? substr($path, 0, $lastDirPos + 1) : null;
        if (!$dir || !is_dir($dir)) {
            throw new InvalidArgumentException("Can't move to: " . $path);
        }
        try {
            if (false === @file_put_contents(
                    $path,
                    (string) $this->getStream())) {
                throw new RuntimeException("Can't move to: " . $path);
            }
        } catch (RuntimeException $e) {
            throw $e;
        }
        $this->body->detach();
        $this->body = null;
        @unlink($this->tmpName);
    }
366591
def move(fname, folder, options):
    
    if os.path.isfile(fname):
        shutil.move(fname, folder)
    else:
        if options.silent is False:
            print('{0} missing'.format(fname))
257254
public function saveTemporary()
    {
        $this->applyFilters();

        if (!$this->hasTranslations() || !$this->isValid()) {
            throw new Exception('unable to save empty or invalid translations');
        }

        $path = $this->getTemporaryTranslationPath();

        Filesystem::mkdir(dirname($path));

        return file_put_contents($path, $this->__toString());
    }
419866
public function moveToTrash()
    {

        // run any internal event we have for page trashing
        $pe = new Event($this);
        Events::dispatch('on_page_move_to_trash', $pe);

        $trash = self::getByPath(Config::get('concrete.paths.trash'));
        $app = Facade::getFacadeApplication();
        $logger = $app->make('log/factory')->createLogger(Channels::CHANNEL_SITE_ORGANIZATION);
        $logger->notice(t('Page "%s" at path "%s" Moved to trash',
            $this->getCollectionName(),
            $this->getCollectionPath()
        ));

        $this->move($trash);
        $this->deactivate();

        // if this page has a custom canonical path we need to clear it
        $path = $this->getCollectionPathObject();
        if (!$path->isPagePathAutoGenerated()) {
            $path = $this->getAutoGeneratedPagePathObject();
            $this->setCanonicalPagePath($path->getPagePath(), true);
            $this->rescanCollectionPath();
        }
        $cID = ($this->getCollectionPointerOriginalID() > 0) ? $this->getCollectionPointerOriginalID() : $this->cID;
        $pages = [];
        $pages = $this->populateRecursivePages($pages, ['cID' => $cID], $this->getCollectionParentID(), 0, false);
        $db = Database::connection();
        foreach ($pages as $page) {
            $db->executeQuery('update Pages set cIsActive = 0 where cID = ?', [$page['cID']]);
        }
    }
601345
protected function moveSettings()
    {
        try {
            if (!$this->fs->exists($this->appRoot.'/sites/'.$this->directory.'/settings.php')) {
                $this->fs->copy(
                    $this->appRoot.'/sites/'.$this->uri.'/settings.php',
                    $this->appRoot.'/sites/'.$this->directory.'/settings.php'
                );
                $this->fs->remove($this->appRoot.'/sites/'.$this->uri.'/settings.php');
            }
        } catch (IOExceptionInterface $e) {
            $this->getIo()->error(
                sprintf(
                    $this->trans('commands.multisite.update.errors.copy-fail'),
                    $this->appRoot.'/sites/'.$this->explodeDirectory[0].'/settings.php',
                    $this->directory.'/settings.php'
                )
            );
            return 1;
        }
    }
387393
def move(self, fnames=None, directory=None):
        """"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        orig = fixpath(osp.dirname(fnames[0]))
        while True:
            self.redirect_stdio.emit(False)
            if directory is None:
                folder = getexistingdirectory(self, _("Select directory"),
                                              orig)
            else:
                folder = directory
            self.redirect_stdio.emit(True)
            if folder:
                folder = fixpath(folder)
                if folder != orig:
                    break
            else:
                return
        for fname in fnames:
            basename = osp.basename(fname)
            try:
                misc.move_file(fname, osp.join(folder, basename))
            except EnvironmentError as error:
                QMessageBox.critical(self, _("Error"),
                                     _("<b>Unable to move <i>%s</i></b>"
                                       "<br><br>Error message:<br>%s"
                                       ) % (basename, to_text_string(error)))
1372964
protected function saveArchive() {
        if (!$this->archive->close() || !$this->archive->open($this->tempFile)) {
            throw new \Exception("Saving archive failed.");
        }
    }
805304
public function output() {
        $parts = explode('/', $this->output_path);
        // get rid of the filename
        array_pop($parts);

        $path = implode('/', $parts);
        if ($path && !file_exists($path)) {
            if (!mkdir($path, 0777, true)) {
                throw new \Exception("could not make directory $path");
            }
        }

        if (!file_put_contents($this->output_path, $this->render())) {
            throw new \Exception("could not write $filename");
        }
    }
1234379
public function actionFolderRemove() {
		$source = $this->getSource();

		$file_path = false;

		$path = $source->getPath();

		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);

		$target = $this->request->name;

		if (realpath($path . $target) && strpos(realpath($path . $target), $source->getRoot()) !== false) {
			$file_path = realpath($path . $target);
		}

		if ($file_path && file_exists($file_path)) {
			if (is_dir($file_path)) {
				$thumb = $file_path . Consts::DS . $source->thumbFolderName . Consts::DS;
				if (is_dir($thumb)) {
					Helper::deleteDir($thumb);
				}
				Helper::deleteDir($file_path);
			} else {
				throw new \Exception('It is not a directory!', Consts::ERROR_CODE_IS_NOT_WRITEBLE);
			}
		} else {
			throw new \Exception('Directory not exists', Consts::ERROR_CODE_NOT_EXISTS);
		}
	}
520790
public function rmdirR($dir)
    {
        $finder = $this->finder->create();
        $files = $finder->notRecursive()->find($dir);
        foreach ($files as $file) {
            if (! $file->isExists()) continue;

            if ($file->isDir()) {
                $this->rmdirR("{$file}/*");
                if ($file->isWritable()) {
                    rmdir($file);
                } else {
                    throw new Exception("Can not delete this directory. -> {$file}");
                }
            } else {
                if ($file->isWritable()) {
                    unlink($file);
                } else {
                    throw new Exception("Can not delete this file. -> {$file}");
                }
            }
        }
    }
786070
static void move(File src, File dest) throws IOException {
        try {
            Files.move(src.toPath(), dest.toPath());
        } catch (IOException x) {
            throw x;
        } catch (Exception x) {
            throw new IOException(x);
        }
    }
1006363
public function moveToTrash($name)
    {
        if (file_exists(route()->com.$name)) {
            (new Files())->moveDir(route()->com, route()->storage_data.'com', $name);
        }
    }