PluginProbe
Depicter — Popup & Slider Builder / 1.5.2
Depicter — Popup & Slider Builder v1.5.2
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.5.2, at app/src/Services/MediaLibraryService.php

316 lines 8.1 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 $mime_type = get_post_mime_type( $id );
121
122 // If media not found
123 if( false === $mime_type ){
124 throw new \Exception('Media does not exists.');
125 }
126 // If mime type was not detected try to retrieve original attachment url
127 if( empty( $mime_type ) && $attachment_url = wp_get_attachment_url( $id ) ){
128 return $attachment_url;
129 }
130
131 // If it was video mime type
132 if( 0 === strpos( $mime_type, 'video' ) ){
133 $attachment_url = wp_get_attachment_url( $id );
134 return $attachment_url;
135 }
136
137 // If it was image mime type
138 if ( $media = wp_get_attachment_image_src( $id, $mediaSize ) ) {
139 if ( is_array( $size ) ) {
140 if ( $media[1] < $size[0] * 2 ){
141 return $media[0];
142 }
143 $url = ImageEditor::resize( $media[0], $size[0], $size[1], $args );
144 return $url ? $url : $media[0];
145 }
146 return $media[0];
147 }
148
149 throw new \Exception('Media not found.');
150 }
151
152 /**
153 * Imports an asset to media library
154 *
155 * @param $assetID
156 *
157 * @param bool $forceToDownloadAgain
158 *
159 * @return false|int Attachment ID or false on failure
160 * @throws GuzzleException
161 */
162 public function importAsset( $assetID, $forceToDownloadAgain = false ) {
163
164 // Check if this asset id is imported before or not
165 // Useful while user publishes document during edit process multiple times
166 $attachmentId = $this->getAttachmentForImportedAsset( $assetID );
167 if( ! $forceToDownloadAgain && $attachmentId && is_attachment( $attachmentId ) ){
168 return $attachmentId;
169 }
170
171 $args = [
172 'forcePreview' => false,
173 'event' => 'download'
174 ];
175 $mediaHotlinkUrl = AssetsAPIService::getHotlink( $assetID, 'large', $args );
176
177 $assetFileName = Sanitize::fileName( $assetID );
178
179 $response = Depicter::remote()->get( $mediaHotlinkUrl, [
180 'on_stats' => function (TransferStats $stats) use (&$url) {
181 $url = $stats->getEffectiveUri();
182 }
183 ]);
184
185 $type = $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
186
187 if ( ! $type || $response->getStatusCode() == 404 ){
188 return false;
189 }
190
191 if ( $type == 'image/jpeg' ){
192 $filename = $assetFileName . '.jpg';
193 } elseif ( $type == 'image/png' ) {
194 $filename = $assetFileName . '.png';
195 } elseif ( $type == 'image/bmp' ) {
196 $filename = $assetFileName . '.bmp';
197 } elseif ( $type == 'image/svg+xml' ) {
198 $filename = basename( $url );
199 } else {
200 // $parts = parse_url( $url );
201 // parse_str( $parts['query'], $query);
202 // $filename = isset( $query['filename'] ) ? $query['filename'] : $assetFileName . '.mp4';
203 $filename = $assetFileName . '.mp4';
204 }
205
206 $fileSystem = Depicter::storage()->filesystem();
207
208 $file = Depicter::storage()->uploads()->getPath() . '/' . $filename;
209
210 if( $fileSystem->exists( $file ) ){
211 $fileUrl = Depicter::storage()->uploads()->getUrl() . '/' . $filename;
212 $attachmentId = attachment_url_to_postid( $fileUrl );
213 if ( $attachmentId ) {
214 $this->registerImportedAsset( $assetID, (int) $attachmentId );
215 }
216 return false;
217 }
218
219 $isFileDownloaded = $fileSystem->write(
220 $file,
221 $response->getBody()->getContents()
222 );
223
224 if ( ! $isFileDownloaded ) {
225 return false;
226 }
227
228 $fileType = wp_check_filetype( $filename, null );
229
230 $attachment = array(
231 'post_mime_type' => $fileType['type'],
232 'post_title' => $assetFileName,
233 'post_content' => '',
234 'post_status' => 'inherit'
235 );
236
237 $attachmentId = wp_insert_attachment( $attachment, $file );
238
239 if( is_wp_error( $attachmentId ) || ! $attachmentId ){
240 error_log( 'Error while inserting asset with ID of ' . $attachmentId, 0 );
241 return false;
242 }
243
244 wp_update_attachment_metadata( $attachmentId, wp_generate_attachment_metadata( $attachmentId, $file ) );
245
246 $this->registerImportedAsset( $assetID, (int) $attachmentId );
247
248 return $attachmentId;
249 }
250
251 /**
252 * Imports list of assets to media library
253 *
254 * @param $assetIDs
255 * @param $forceToDownloadAgain
256 *
257 * @throws GuzzleException
258 */
259 public function importAssets( $assetIDs, $forceToDownloadAgain = false )
260 {
261 foreach( $assetIDs as $ID ){
262 $this->importAsset( $ID, $forceToDownloadAgain );
263 }
264 }
265
266 /**
267 * Retrieves an attachment ID for an asset if it was imported and registered before.
268 *
269 * @param string $assetId
270 *
271 * @return string|bool False if attachment ID does not exists for asset ID
272 */
273 public function getAttachmentForImportedAsset( $assetId )
274 {
275 if( empty( $assetId ) ){
276 Error::trigger('Asset ID is not valid.');
277 return false;
278 }
279
280 $dictionary = $this->getImportedAssetsDictionary();
281 return isset( $dictionary[ $assetId ] ) ? $dictionary[ $assetId ] : false;
282 }
283
284
285 /**
286 * Registers the attachment ID and belonging asset ID in a dictionary.
287 *
288 * @param string $assetId
289 * @param int $attachmentId
290 *
291 * @return bool False on failure
292 */
293 private function registerImportedAsset( $assetId, $attachmentId )
294 {
295 if( empty( $assetId ) || empty( $attachmentId ) ){
296 Error::trigger('Asset ID or attachment ID is not valid.');
297 return false;
298 }
299
300 $dictionary = $this->getImportedAssetsDictionary();
301 $dictionary[ $assetId ] = $attachmentId;
302
303 return \Depicter::options()->set( 'imported_assets', $dictionary );
304 }
305
306 /**
307 * Retrieves list of all assets which were imported and registered before.
308 *
309 * @return array
310 */
311 private function getImportedAssetsDictionary(){
312 return \Depicter::options()->get('imported_assets', []);
313 }
314
315 }
316