Prepare file reference information.

@inheritDocs
491724
public function get_file_reference($source) {
        global $USER;
        $reference = new stdClass;
        $reference->userid = $USER->id;
        $reference->username = fullname($USER);
        $reference->path = $source;

        // Determine whether we are downloading the file, or should use a file reference.
        $usefilereference = optional_param('usefilereference', false, PARAM_BOOL);
        if ($usefilereference) {
            if ($data = $this->dropbox->get_file_share_info($source)) {
                $reference = (object) array_merge((array) $data, (array) $reference);
            }
        }

        return serialize($reference);
    }
852459
protected function prepareProjectData()
  {
    $this->logVerbose('Get source and resource file names.');

    // Get file list form the project by fileset ID.
    $resources               = $this->getProject()->getReference($this->resourcesFilesetId);
    $this->resourceFileNames = $resources->getDirectoryScanner($this->getProject())->getIncludedFiles();

    // Get full path name of resource dir.
    $this->parentResourceDirFullPath = realpath($resources->getDir($this->getProject()).'/'.$this->parentResourceDir);

    // Get full path name of resource dir.
    $this->resourceDirFullPath = realpath($this->parentResourceDirFullPath.'/'.$this->resourceDir);
  }
762680
public function prepare($fileContent)
    {
        $replacings = [
            '{name}',
            '{namespace}',
            '{testNamespace}',
            '{table}',
            '{getters}',
            '{interfaceGetters}',
            '{fillable}',
            '{repository}',
            '{directory}',
            '{eloquentTest}',
            '{repositoryTest}',
            '{repositoryTestData}',
        ];

        $replacements = [
            $this->getProvidedName(),
            $this->getAppNamespace(),
            $this->getTestsNamespace(),
            $this->getTable(),
            $this->getSettersGetters($this->fields),
            $this->getSettersGetters($this->fields, true),
            $this->getFillable($this->fields),
            $this->getRepositoryPayloads($this->fields),
            $this->getDirectory(),
            $this->getEloquentTests($this->fields),
            $this->getRepositoryTests($this->fields),
            $this->getRepositoryDataTests($this->fields),
        ];

        return str_replace($replacings, $replacements, $fileContent);
    }
789608
private function prepareBuilder(): void
    {
        if (!file_exists($this->getReportCacheDir())) {
            @mkdir($this->getReportCacheDir(), 0777, true);
        }

        $this->builder
             ->setCacheDir($this->getReportCacheDir())
             ->initialise();

        return;
    }
121154
protected function prepareFilesEditor(array $data)
    {
        $prepared = array();

        foreach ($data as $folder => $files) {
            foreach ($files as $file) {

                $path = trim(str_replace($this->data_module['directory'], '', $file), '/');
                $depth = substr_count(str_replace('\\', '/', $path), '/'); // WIN compatibility

                $pathinfo = pathinfo($path);
                $directory = is_dir($file);
                $parent = $directory ? $path : $pathinfo['dirname'];

                $prepared[$folder][$parent][] = array(
                    'file' => $file,
                    'path' => $path,
                    'depth' => $depth,
                    'directory' => $directory,
                    'name' => $pathinfo['basename'],
                    'id' => gplcart_string_encode($path),
                    'indentation' => str_repeat('<span class="indentation"></span>', $depth)
                );
            }

            ksort($prepared[$folder]);
        }
        return $prepared;
    }
522307
protected function fileInfo()
    {
        $stackFrame = $this->trace();
        if (\preg_match('/eval\(/', $stackFrame['file'])) {
            \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);
            $file = $matches[1][0];
            $line = (int) $matches[2][0];
        } else {
            $file = $stackFrame['file'];
            $line = $stackFrame['line'];
        }

        return \compact('file', 'line');
    }
1221275
protected function prepareTarget($target)
    {
        $dirname = dirname($target);
        if (! $this->file->exists($dirname)) {
            $this->file->makeDirectory($dirname);
        }
    }
1022884
protected function prepare()
    {
        //Force passice mode if not specified
        $this->addOption('passive', true);

        //To make call on different files, we must retrieve the root and apply commands to the path
        $tmp = clone $this->getUrl();
        $tmp->path('');
        $this->addOption('url', $tmp->toString());
    }
1268564
public function dirPrepare()
    {
        $paths = $this->getPaths();
        $filesystem = $this->getFilesystem();
        $this->info('Preparing artifact directories');
        $filesystem->mkdir([
            $paths['coverage'],
            $paths['reports']
        ]);
        $this->info('Artifact directories prepared');
    }
797639
private function prepare(string $filename, array $options = []): ?string
    {
        if (!empty($options)) {
            $this->validateOptions($options);
        }

        $result = null;

        if ($this->hasEventListeners('beforePrepare')) {
            $eventDetails = new \BearFramework\App\Assets\BeforePrepareEventDetails($filename, $options);
            $this->dispatchEvent('beforePrepare', $eventDetails);
            $filename = $eventDetails->filename;
            $options = $eventDetails->options;
        }

        if (strlen($filename) > 0 && is_file($filename)) {
            if (!isset($options['width']) && !isset($options['height'])) {
                $result = $filename;
            } else {
                $extension = pathinfo($filename, PATHINFO_EXTENSION);
                if ($extension === '') {
                    $extension = 'tmp';
                }
                if (isset($options['outputType'])) {
                    $extension = $options['outputType'];
                }
                $tempFilename = $this->app->data->getFilename('.temp/assets/' . md5(md5($filename) . md5(json_encode($options))) . '.' . $extension);
                if (!is_file($tempFilename)) {
                    $this->resize($filename, $tempFilename, [
                        'width' => (isset($options['width']) ? $options['width'] : null),
                        'height' => (isset($options['height']) ? $options['height'] : null)
                    ]);
                }
                $result = $tempFilename;
            }
        }
        if ($this->hasEventListeners('prepare')) {
            $eventDetails = new \BearFramework\App\Assets\PrepareEventDetails($filename, $options, $result);
            $this->dispatchEvent('prepare', $eventDetails);
            $result = $eventDetails->returnValue;
        }
        return $result;
    }
1331581
private function prepareAutoloaderFile()
    {
        $plain_name      = pathinfo($this->getPlainPath(), PATHINFO_BASENAME);
        $obfuscated_name = pathinfo($this->getObfuscatedPath(), PATHINFO_BASENAME);

        $autoloader = $this->getPlainPath() . DIRECTORY_SEPARATOR . 'autoloader.php';
        $contents = file_get_contents($autoloader);
        $contents = str_replace($obfuscated_name, $plain_name, $contents);
        return (file_put_contents($autoloader, $contents) !== false);
    }
205514
public function prepare()
    {

        $options = $this->options->prepareOptions;

        if( $options & Options::BACKUP or true ) {

            $root = $this->options->pathRoot;
            $pathsToBackup = $this->options->getPathsToBackup();

            // make a fully qualified path relative to $root
            $anchorToRoot = function( $path ) use ($root) {
                return escapeshellarg( "." . substr( $path, strlen($root) ) );
            };

            $pathsToBackup = array_map( $anchorToRoot, $pathsToBackup );
            $pathsToBackup = implode( ' ', $pathsToBackup );

            $backupDir = $this->options->getPath('backup');
            $filename = "{$backupDir}/" . self::fileSystemFriendly(
                date( DateTime::POSTGRES_TIMESTAMP_WITHOUT_TIME_ZONE_NO_MICROSECONDS )
            ) . '.tar.gz';

            $command = sprintf(
                'cd %s; tar cszf %s --exclude=%s -C %s %s; cd -',
                escapeshellarg( $root ),
                escapeshellarg( $filename ),
                $anchorToRoot( $backupDir ),
                escapeshellarg( $root ),
                $pathsToBackup
            );

            exec( $command );

        }

        // trash _all_ previously generated entitys
        /* BROKEN - Too agressive. Doesn't consider $options['match']
        $rebuild = in_array( $option, array( self::REBUILD_AND_BACKUP, self::REBUILD_NO_BACKUP ) );
        if( $rebuild ) {
            foreach( new \DirectoryIterator( $this->paths['entity'] ) as $item ) {
                if( $item->isFile() ) {
                    // unlink( $item->getPathname() );
                }
            }
        }
         */

    }
1115155
private function ensureFileIndexes()
    {
        $indexKey = ['filename' => 1, 'uploadDate' => 1];
        foreach ($this->listIndexes() as $index) {
            if ($index['key'] === $indexKey) {
                return;
            }
        }

        $this->createIndex($indexKey);
    }
1002321
public function get_reference_details($reference, $filestatus = 0) {
        if (empty($reference)) {
            return get_string('unknownsource', 'repository');
        }
        $source = json_decode($reference);
        if (empty($source->usesystem)) {
            return '';
        }
        $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);

        if ($systemauth === false) {
            return '';
        }
        $systemservice = new repository_onedrive\rest($systemauth);
        $info = $this->get_file_summary($systemservice, $source->id);

        $owner = '';
        if (!empty($info->createdByUser->displayName)) {
            $owner = $info->createdByUser->displayName;
        }
        if ($owner) {
            return get_string('owner', 'repository_onedrive', $owner);
        } else {
            return $info->name;
        }
    }
1334348
def prepare(self):
        """"""
        p = PreparedRequest()
        p.prepare(
            method=self.method,
            url=self.url,
            headers=self.headers,
            files=self.files,
            data=self.data,
            params=self.params,
            auth=self.auth,
            cookies=self.cookies,
            hooks=self.hooks,
        )
        return p
1174455
public function prepareUpdateData($document)
    {
        $class = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        $updateData = array();
        foreach ($changeset as $fieldName => $change) {
            $mapping = $class->fieldMappings[$fieldName];

            // skip non embedded document identifiers
            if ( ! $class->isEmbeddedDocument && ! empty($mapping['id'])) {
                continue;
            }

            list($old, $new) = $change;

            // @Inc
            if ($mapping['type'] === 'increment') {
                if ($new === null) {
                    if ($mapping['nullable'] === true) {
                        $updateData['$set'][$mapping['name']] = null;
                    } else {
                        $updateData['$unset'][$mapping['name']] = true;
                    }
                } elseif ($new >= $old) {
                    $updateData['$inc'][$mapping['name']] = $new - $old;
                } else {
                    $updateData['$inc'][$mapping['name']] = ($old - $new) * -1;
                }

            // @Field, @String, @Date, etc.
            } elseif ( ! isset($mapping['association'])) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : Type::getType($mapping['type'])->convertToDatabaseValue($new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @EmbedOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
                // If we have a new embedded document then lets set the whole thing
                if ($new && $this->uow->isScheduledForInsert($new)) {
                    $updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);

                // If we don't have a new value then lets unset the embedded document
                } elseif ( ! $new) {
                    $updateData['$unset'][$mapping['name']] = true;

                // Update existing embedded document
                } else {
                    $update = $this->prepareUpdateData($new);
                    foreach ($update as $cmd => $values) {
                        foreach ($values as $key => $value) {
                            $updateData[$cmd][$mapping['name'] . '.' . $key] = $value;
                        }
                    }
                }

            // @EmbedMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_MANY) {
                if (null !== $new) {
                    foreach ($new as $key => $embeddedDoc) {
                        if ( ! $this->uow->isScheduledForInsert($embeddedDoc)) {
                            $update = $this->prepareUpdateData($embeddedDoc);
                            foreach ($update as $cmd => $values) {
                                foreach ($values as $name => $value) {
                                    $updateData[$cmd][$mapping['name'] . '.' . $key . '.' . $name] = $value;
                                }
                            }
                        }
                    }
                }

            // @ReferenceOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : $this->prepareReferencedDocumentValue($mapping, $new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @ReferenceMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_MANY) {
                // Do nothing right now
            }
        }
        return $updateData;
    }
625534
protected function prepareUploadedFiles($files)
    {
        $fileKeys = ['error', 'name', 'size', 'tmp_name', 'type'];
        $reformatFiles = new ReformatUploadedFiles($files);

        $output = [];
        foreach ($reformatFiles as $key => $value) {
            $keys = array_keys($value);
            sort($keys);

            if ($fileKeys == $keys && is_array($value['tmp_name'])) {
                $output[$key] = $this->prepareUploadedFiles($reformatFiles[$key]);
                continue;
            }

            $output[$key] = new UploadedFile(
                $value['tmp_name'],
                $value['error'],
                $value['name'],
                $value['type'],
                $value['size']
            );
        }

        return $output;
    }