PluginProbe
Depicter — Popup & Slider Builder / 1.2.0
Depicter — Popup & Slider Builder v1.2.0
4.8.1 trunk 1.0.0 1.1.0 1.1.2 1.1.4 1.1.6 1.1.7 1.1.8 1.1.9 1.2.0 1.3.0 1.3.1 1.3.2 1.3.3 1.3.5 1.3.8 1.5.0 1.5.1 1.5.2 1.5.5 1.6.0 1.6.1 1.6.2 1.7.0 All 76 releases
depicter / app / src / Services / MediaLibraryService.php

MediaLibraryService.php in Depicter — Popup & Slider Builder 1.2.0, at app/src/Services/MediaLibraryService.php

308 lines 7.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Depicter\Services;
3
4
5 use Averta\Core\Utility\Arr;
6 use Averta\WordPress\Handler\Error;
7 use Averta\WordPress\Utility\Sanitize;
8 use Depicter;
9 use Depicter\GuzzleHttp\Exception\GuzzleException;
10 use Depicter\GuzzleHttp\TransferStats;
11 use Depicter\Media\Image\ImageEditor;
12 use SimpleXMLElement;
13
14 class MediaLibraryService
15 {
16 /**
17 * Query the database
18 *
19 * @param array $queryParams
20 *
21 * @return \WP_Query
22 */
23 public function query( $queryParams = [] ){
24 return new \WP_Query( $queryParams );
25 }
26
27
28 /**
29 * Generate output for attachments
30 *
31 * @param \WP_Query $attachments
32 *
33 * @param string $assetType
34 *
35 * @return array
36 */
37 public function getQueryOutput( $attachments, $assetType = '' ){
38 $result = [];
39
40 if ( $attachments->have_posts() ) {
41 $hits = [];
42
43 foreach ( $attachments->posts as $key => $attachment ) {
44 $attachmentMeta = wp_get_attachment_metadata( $attachment->ID );
45 $mimType = get_post_mime_type( $attachment->ID );
46 $hits[ $key ] = [
47 "id" => $attachment->ID . "",
48 "type" => $assetType,
49 "mimeType" => $mimType,
50 "sourceType" => "library",
51 "title" => $attachment->post_title,
52 "description" => $attachment->post_content,
53 ];
54
55 if ( $mimType == 'image/svg+xml' ) {
56 $fileContent = @file_get_contents(get_attached_file( $attachment->ID ));
57 if( empty( trim( $fileContent ) ) ){
58 continue;
59 }
60 $svg = new SimpleXMLElement( $fileContent );
61 $hits[ $key ] = Arr::merge( $hits[ $key ], [
62 'width' => (int) $svg['width'],
63 'height' => (int) $svg['height'],
64 ]);
65 } else if ( strpos( $mimType, 'audio' ) !== 0 ) {
66 $hits[ $key ] = Arr::merge( $hits[ $key ], [
67 'width' => $attachmentMeta['width'],
68 'height' => $attachmentMeta['height'],
69 "thumb" => wp_get_attachment_image_src( $attachment->ID, 'depicter-thumbnail' )[0]
70 ]);
71 }
72 }
73
74 $result = [
75 'page' => $attachments->query['paged'],
76 'perpage' => $attachments->query['posts_per_page'],
77 'totalPages' => $attachments->max_num_pages,
78 'total' => $attachments->found_posts,
79 'hasMore' => $attachments->query['paged'] < $attachments->max_num_pages,
80 'hits' => $hits
81 ];
82
83 }
84
85 return $result;
86 }
87
88
89 /**
90 * Get the direct link to media source
91 *
92 * @param $id
93 * @param $size
94 * @param $args
95 *
96 * @return false|string
97 * @throws \Exception
98 */
99 public function getSourceURL( $id, $size = 'full', $args = [] ) {
100
101 if( empty( $id ) ){
102 throw new \Exception('Media ID is required.');
103 }
104
105 $available_sizes = [
106 'screen' => 'full',
107 'full' => 'full',
108 'large' => 'full',
109 'medium' => 'medium_large',
110 'small' => 'medium',
111 'thumb' => 'thumbnail'
112 ];
113
114 if ( ! is_array( $size ) ) {
115 $mediaSize = ! in_array( $size, array_keys( $available_sizes ) ) ? 'full' : $available_sizes[ $size ];
116 } else {
117 $mediaSize = 'full';
118 }
119
120 // If media not found
121 if( false === $mime_type = get_post_mime_type( $id ) ){
122 throw new \Exception('Media does not exists.');
123 }
124
125 // If it was video mime type
126 if( 0 === strpos( $mime_type, 'video' ) ){
127 $attachment_url = wp_get_attachment_url( $id );
128 return $attachment_url;
129 }
130
131 // If it was image mime type
132 if ( $media = wp_get_attachment_image_src( $id, $mediaSize ) ) {
133 if ( is_array( $size ) ) {
134 if ( $media[1] < $size[0] * 2 ){
135 return $media[0];
136 }
137 $url = ImageEditor::resize( $media[0], $size[0], $size[1], $args );
138 return $url ? $url : $media[0];
139 }
140 return $media[0];
141 }
142
143 throw new \Exception('Media not found.');
144 }
145
146 /**
147 * Imports an asset to media library
148 *
149 * @param $assetID
150 *
151 * @param bool $forceToDownloadAgain
152 *
153 * @return false|int Attachment ID or false on failure
154 * @throws GuzzleException
155 */
156 public function importAsset( $assetID, $forceToDownloadAgain = false ) {
157
158 // Check if this asset id is imported before or not
159 // Useful while user publishes document during edit process multiple times
160 if( ! $forceToDownloadAgain && $attachmentId = $this->getAttachmentForImportedAsset( $assetID ) ){
161 return $attachmentId;
162 }
163
164 $args = [
165 'forcePreview' => false,
166 'event' => 'download'
167 ];
168 $mediaHotlinkUrl = AssetsAPIService::getHotlink( $assetID, 'large', $args );
169
170 $assetFileName = Sanitize::fileName( $assetID );
171
172 $response = Depicter::remote()->get( $mediaHotlinkUrl, [
173 'on_stats' => function (TransferStats $stats) use (&$url) {
174 $url = $stats->getEffectiveUri();
175 }
176 ]);
177
178 $type = $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
179
180 if ( ! $type || $response->getStatusCode() == 404 ){
181 return false;
182 }
183
184 if ( $type == 'image/jpeg' ){
185 $filename = $assetFileName . '.jpg';
186 } elseif ( $type == 'image/png' ) {
187 $filename = $assetFileName . '.png';
188 } elseif ( $type == 'image/bmp' ) {
189 $filename = $assetFileName . '.bmp';
190 } elseif ( $type == 'image/svg+xml' ) {
191 $filename = basename( $url );
192 } else {
193 // $parts = parse_url( $url );
194 // parse_str( $parts['query'], $query);
195 // $filename = isset( $query['filename'] ) ? $query['filename'] : $assetFileName . '.mp4';
196 $filename = $assetFileName . '.mp4';
197 }
198
199 $fileSystem = Depicter::storage()->filesystem();
200
201 $file = Depicter::storage()->uploads()->getPath() . '/' . $filename;
202
203 if( $fileSystem->exists( $file ) ){
204 $fileUrl = Depicter::storage()->uploads()->getUrl() . '/' . $filename;
205 $attachmentId = attachment_url_to_postid( $fileUrl );
206 if ( $attachmentId ) {
207 $this->registerImportedAsset( $assetID, (int) $attachmentId );
208 }
209 return false;
210 }
211
212 $isFileDownloaded = $fileSystem->write(
213 $file,
214 $response->getBody()->getContents()
215 );
216
217 if ( ! $isFileDownloaded ) {
218 return false;
219 }
220
221 $fileType = wp_check_filetype( $filename, null );
222
223 $attachment = array(
224 'post_mime_type' => $fileType['type'],
225 'post_title' => $assetFileName,
226 'post_content' => '',
227 'post_status' => 'inherit'
228 );
229
230 $attachmentId = wp_insert_attachment( $attachment, $file );
231
232 if( is_wp_error( $attachmentId ) || ! $attachmentId ){
233 error_log( 'Error while inserting asset with ID of ' . $attachmentId, 0 );
234 return false;
235 }
236
237 wp_update_attachment_metadata( $attachmentId, wp_generate_attachment_metadata( $attachmentId, $file ) );
238
239 $this->registerImportedAsset( $assetID, (int) $attachmentId );
240
241 return $attachmentId;
242 }
243
244 /**
245 * Imports list of assets to media library
246 *
247 * @param $assetIDs
248 *
249 * @throws GuzzleException
250 */
251 public function importAssets( $assetIDs )
252 {
253 foreach( $assetIDs as $ID ){
254 $this->importAsset( $ID );
255 }
256 }
257
258 /**
259 * Retrieves an attachment ID for an asset if it was imported and registered before.
260 *
261 * @param string $assetId
262 *
263 * @return string|bool False if attachment ID does not exists for asset ID
264 */
265 public function getAttachmentForImportedAsset( $assetId )
266 {
267 if( empty( $assetId ) ){
268 Error::trigger('Asset ID is not valid.');
269 return false;
270 }
271
272 $dictionary = $this->getImportedAssetsDictionary();
273 return isset( $dictionary[ $assetId ] ) ? $dictionary[ $assetId ] : false;
274 }
275
276
277 /**
278 * Registers the attachment ID and belonging asset ID in a dictionary.
279 *
280 * @param string $assetId
281 * @param int $attachmentId
282 *
283 * @return bool False on failure
284 */
285 private function registerImportedAsset( $assetId, $attachmentId )
286 {
287 if( empty( $assetId ) || empty( $attachmentId ) ){
288 Error::trigger('Asset ID or attachment ID is not valid.');
289 return false;
290 }
291
292 $dictionary = $this->getImportedAssetsDictionary();
293 $dictionary[ $assetId ] = $attachmentId;
294
295 return \Depicter::options()->set( 'imported_assets', $dictionary );
296 }
297
298 /**
299 * Retrieves list of all assets which were imported and registered before.
300 *
301 * @return array
302 */
303 private function getImportedAssetsDictionary(){
304 return \Depicter::options()->get('imported_assets', []);
305 }
306
307 }
308