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

314 lines 8.0 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 if( ! $forceToDownloadAgain && $attachmentId = $this->getAttachmentForImportedAsset( $assetID ) ){
167 return $attachmentId;
168 }
169
170 $args = [
171 'forcePreview' => false,
172 'event' => 'download'
173 ];
174 $mediaHotlinkUrl = AssetsAPIService::getHotlink( $assetID, 'large', $args );
175
176 $assetFileName = Sanitize::fileName( $assetID );
177
178 $response = Depicter::remote()->get( $mediaHotlinkUrl, [
179 'on_stats' => function (TransferStats $stats) use (&$url) {
180 $url = $stats->getEffectiveUri();
181 }
182 ]);
183
184 $type = $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
185
186 if ( ! $type || $response->getStatusCode() == 404 ){
187 return false;
188 }
189
190 if ( $type == 'image/jpeg' ){
191 $filename = $assetFileName . '.jpg';
192 } elseif ( $type == 'image/png' ) {
193 $filename = $assetFileName . '.png';
194 } elseif ( $type == 'image/bmp' ) {
195 $filename = $assetFileName . '.bmp';
196 } elseif ( $type == 'image/svg+xml' ) {
197 $filename = basename( $url );
198 } else {
199 // $parts = parse_url( $url );
200 // parse_str( $parts['query'], $query);
201 // $filename = isset( $query['filename'] ) ? $query['filename'] : $assetFileName . '.mp4';
202 $filename = $assetFileName . '.mp4';
203 }
204
205 $fileSystem = Depicter::storage()->filesystem();
206
207 $file = Depicter::storage()->uploads()->getPath() . '/' . $filename;
208
209 if( $fileSystem->exists( $file ) ){
210 $fileUrl = Depicter::storage()->uploads()->getUrl() . '/' . $filename;
211 $attachmentId = attachment_url_to_postid( $fileUrl );
212 if ( $attachmentId ) {
213 $this->registerImportedAsset( $assetID, (int) $attachmentId );
214 }
215 return false;
216 }
217
218 $isFileDownloaded = $fileSystem->write(
219 $file,
220 $response->getBody()->getContents()
221 );
222
223 if ( ! $isFileDownloaded ) {
224 return false;
225 }
226
227 $fileType = wp_check_filetype( $filename, null );
228
229 $attachment = array(
230 'post_mime_type' => $fileType['type'],
231 'post_title' => $assetFileName,
232 'post_content' => '',
233 'post_status' => 'inherit'
234 );
235
236 $attachmentId = wp_insert_attachment( $attachment, $file );
237
238 if( is_wp_error( $attachmentId ) || ! $attachmentId ){
239 error_log( 'Error while inserting asset with ID of ' . $attachmentId, 0 );
240 return false;
241 }
242
243 wp_update_attachment_metadata( $attachmentId, wp_generate_attachment_metadata( $attachmentId, $file ) );
244
245 $this->registerImportedAsset( $assetID, (int) $attachmentId );
246
247 return $attachmentId;
248 }
249
250 /**
251 * Imports list of assets to media library
252 *
253 * @param $assetIDs
254 *
255 * @throws GuzzleException
256 */
257 public function importAssets( $assetIDs )
258 {
259 foreach( $assetIDs as $ID ){
260 $this->importAsset( $ID );
261 }
262 }
263
264 /**
265 * Retrieves an attachment ID for an asset if it was imported and registered before.
266 *
267 * @param string $assetId
268 *
269 * @return string|bool False if attachment ID does not exists for asset ID
270 */
271 public function getAttachmentForImportedAsset( $assetId )
272 {
273 if( empty( $assetId ) ){
274 Error::trigger('Asset ID is not valid.');
275 return false;
276 }
277
278 $dictionary = $this->getImportedAssetsDictionary();
279 return isset( $dictionary[ $assetId ] ) ? $dictionary[ $assetId ] : false;
280 }
281
282
283 /**
284 * Registers the attachment ID and belonging asset ID in a dictionary.
285 *
286 * @param string $assetId
287 * @param int $attachmentId
288 *
289 * @return bool False on failure
290 */
291 private function registerImportedAsset( $assetId, $attachmentId )
292 {
293 if( empty( $assetId ) || empty( $attachmentId ) ){
294 Error::trigger('Asset ID or attachment ID is not valid.');
295 return false;
296 }
297
298 $dictionary = $this->getImportedAssetsDictionary();
299 $dictionary[ $assetId ] = $attachmentId;
300
301 return \Depicter::options()->set( 'imported_assets', $dictionary );
302 }
303
304 /**
305 * Retrieves list of all assets which were imported and registered before.
306 *
307 * @return array
308 */
309 private function getImportedAssetsDictionary(){
310 return \Depicter::options()->get('imported_assets', []);
311 }
312
313 }
314