Issues (48)

src/Tasks/PublishAllFiles.php (3 issues)

1
<?php
2
3
namespace Sunnysideup\MigrateData\Tasks;
4
5
use SilverStripe\AssetAdmin\Controller\AssetAdmin;
0 ignored issues
show
The type SilverStripe\AssetAdmin\Controller\AssetAdmin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use SilverStripe\Assets\File;
7
use SilverStripe\Assets\Folder;
8
use SilverStripe\Core\Injector\Injector;
9
use SilverStripe\ORM\DB;
10
use SilverStripe\ORM\Queries\SQLSelect;
11
use SilverStripe\Versioned\Versioned;
0 ignored issues
show
The type SilverStripe\Versioned\Versioned was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Sunnysideup\Flush\FlushNow;
13
use Sunnysideup\Flush\FlushNowImplementor;
14
15
class PublishAllFiles extends MigrateDataTaskBase
16
{
17
    /**
18
     * @var mixed
19
     */
20
    public $admin;
21
22
    protected $title = 'Publish All Files';
23
24
    protected $description = 'Get all files ready to go - useful in SS3 to SS4 conversion.';
25
26
    protected $updateLocation = false;
27
28
    protected $generateThumbnails = false;
29
30
    protected $oneFolderOnlyID = 0;
31
32
    protected $oneFileOnlyID = 0;
33
34
    protected $enabled = true;
35
36
    /**
37
     * @return PublishAllFiles
38
     */
39
    public function setUpdateLocation(bool $b)
40
    {
41
        $this->updateLocation = $b;
42
43
        return $this;
44
    }
45
46
    /**
47
     * @return PublishAllFiles
48
     */
49
    public function setGenerateThumbnails(bool $b)
50
    {
51
        $this->generateThumbnails = $b;
52
53
        return $this;
54
    }
55
56
    protected function performMigration()
57
    {
58
        $this->admin = Injector::inst()->get(AssetAdmin::class);
59
        $this->runForFolder(0);
60
        $this->compareCount();
61
    }
62
63
    protected function runForFolder($parentID)
64
    {
65
        if ($this->oneFolderOnlyID && $this->oneFolderOnlyID !== $parentID) {
66
            return;
67
        }
68
        if ($parentID) {
69
            $folder = Folder::get_by_id($parentID);
70
            FlushNowImplementor::do_flush('<h3>Processing Folder: ' . $folder->getFilename() . '</h3>');
71
        } else {
72
            FlushNowImplementor::do_flush('<h3>Processing Root Folder</h3>');
73
        }
74
        $sqlQuery = new SQLSelect();
75
        $sqlQuery->setFrom('File');
76
        $sqlQuery->selectField('ID');
77
        $sqlQuery->addWhere(['ParentID' => $parentID]);
78
        $sqlQuery->setOrderBy('Name');
79
80
        // Execute and return a Query object
81
        $result = $sqlQuery->execute();
82
        foreach ($result as $row) {
83
            $file = File::get_by_id($row['ID']);
84
            if (null !== $file) {
85
                $name = $file->getFilename();
86
                if (!$name) {
87
                    $file->write();
88
                    $name = $file->getFilename();
89
                }
90
                if ($this->oneFileOnlyID && $this->oneFileOnlyID !== $file->ID) {
91
                    continue;
92
                }
93
                if ($name) {
94
                    if ($this->updateLocation) {
95
                        $this->updateLocationForOneFile($file, $name);
96
                        $file = File::get_by_id($row['ID']);
97
                    }
98
99
                    try {
100
                        if ($file->exists()) {
101
                            FlushNowImplementor::do_flush('... Publishing: ' . $name . ', ID = ' . $file->ID);
102
                            if ($this->generateThumbnails) {
103
                                $this->admin->generateThumbnails($file);
104
                            }
105
                            $file->forceChange();
106
                            $file->write();
107
                            $file->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
108
                            $test = DB::query('SELECT COUNT(ID) FROM File_Live WHERE ID = ' . $file->ID)->value();
109
                            if (0 === (int) $test) {
110
                                FlushNowImplementor::do_flush('... error finding: ' . $name, 'deleted');
111
                            }
112
                        } else {
113
                            FlushNowImplementor::do_flush('... Error in publishing V2 ...' . print_r($file->toMap(), 1), 'deleted');
0 ignored issues
show
Are you sure print_r($file->toMap(), 1) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
                            FlushNowImplementor::do_flush('... Error in publishing V2 ...' . /** @scrutinizer ignore-type */ print_r($file->toMap(), 1), 'deleted');
Loading history...
114
                        }
115
                    } catch (\Exception $exception) {
116
                        FlushNowImplementor::do_flush('... Error in publishing V1 ...' . print_r($file->toMap(), 1), 'deleted');
117
                    }
118
                } else {
119
                    FlushNowImplementor::do_flush('... Error in finding name for ' . print_r($file->toMap(), 1), 'deleted');
120
                }
121
122
                $file->destroy();
123
            }
124
125
            if ($file instanceof Folder) {
126
                $this->runForFolder($file->ID);
127
            }
128
        }
129
    }
130
131
    protected function updateLocationForOneFile($file, $name)
132
    {
133
        $originalDir = ASSETS_PATH . '/';
134
        if (file_exists($originalDir . $name) && !is_dir($originalDir . $name)) {
135
            if (!$file->getField('FileHash')) {
136
                $hash = sha1_file($originalDir . $name);
137
                $this->runUpdateQuery('UPDATE "File" SET "FileHash" = \'' . $hash . '\' WHERE "ID" = \'' . $file->ID . "' LIMIT 1;");
138
            } else {
139
                $hash = $file->FileHash;
140
            }
141
142
            $targetDir = str_replace(
143
                './',
144
                '',
145
                ASSETS_PATH . '/.protected/' . dirname($name)
146
                    . '/' . substr((string) $hash, 0, 10) . '/'
147
            );
148
149
            if (!file_exists($targetDir)) {
150
                mkdir($targetDir, 0755, true);
151
            }
152
153
            FlushNowImplementor::do_flush($originalDir . $name . ' > ' . $targetDir . basename($name), 'obsolete');
154
155
            rename(
156
                $originalDir . $name,
157
                $targetDir . basename($name)
158
            );
159
        }
160
    }
161
162
    /**
163
     * @param null|int $parentID
164
     */
165
    protected function compareCount($parentID = null)
166
    {
167
        $where = '';
168
        if (null === $parentID) {
169
        } else {
170
            $where = ' WHERE ParentID = ' . $parentID;
171
        }
172
        $count1 = DB::query('SELECT COUNT("ID") FROM "File" ' . $where)->value();
173
        $count2 = DB::query('SELECT COUNT("ID") FROM "File_Live" ' . $where)->value();
174
        if ($count1 === $count2) {
175
            FlushNowImplementor::do_flush('<h1>Draft and Live have the same amount of items ' . $where . '</h1>', 'created');
176
        } else {
177
            FlushNowImplementor::do_flush(
178
                '
179
                Draft and Live DO NOT have the same amount of items ' . $where . ', ' . $count1 . ' not equal ' . $count2 . '',
180
                'deleted'
181
            );
182
            if (null === $parentID) {
183
                $parentIDs = File::get()->column('ParentID');
184
                $parentIDs = array_unique($parentIDs);
185
                foreach ($parentIDs as $parentID) {
186
                    $this->compareCount($parentID);
187
                }
188
            }
189
        }
190
    }
191
}
192