PluginProbe
WP-Stateless – Google Cloud Storage / 2.1.4
WP-Stateless – Google Cloud Storage v2.1.4
4.4.3 2.1.7 2.1.8 2.1.9 2.2.0 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.3.0 2.3.1 2.3.2 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.1.0 3.1.1 3.2.0 3.2.1 3.2.2 All 62 releases
wp-stateless / lib / classes / class-utility.php

class-utility.php in WP-Stateless – Google Cloud Storage 2.1.4, at lib/classes/class-utility.php

331 lines 11.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Helper Functions List
4 *
5 * Can be called via Singleton. Since Singleton uses magic method __call().
6 * Example:
7 *
8 * Add Media to GS storage:
9 * ud_get_stateless_media()->add_media( false, $post_id );
10 *
11 * @class Utility
12 */
13 namespace wpCloud\StatelessMedia {
14
15 if( !class_exists( 'wpCloud\StatelessMedia\Utility' ) ) {
16
17 class Utility {
18
19 /**
20 * ChromeLogger
21 *
22 * @author potanin@UD
23 * @param $data
24 */
25 static public function log( $data ) {
26
27 if( !class_exists( 'wpCloud\StatelessMedia\Logger' )) {
28 include_once( __DIR__ . '/class-logger.php' );
29 }
30
31 if( !class_exists( 'wpCloud\StatelessMedia\Logger' )) {
32 return;
33 }
34
35 if( defined( 'WP_STATELESS_CONSOLE_LOG' ) && WP_STATELESS_CONSOLE_LOG ) {
36 Logger::log( '[wp-stateless]', $data );
37 }
38
39 }
40
41 /**
42 * Override Cache Control
43 * @param $cacheControl
44 * @return mixed
45 */
46 public static function override_cache_control( $cacheControl ) {
47 return ud_get_stateless_media()->get( 'sm.cache_control' );
48 }
49
50 /**
51 * wp_normalize_path was added in 3.9.0
52 *
53 * @param $path
54 * @return mixed|string
55 *
56 */
57 public static function normalize_path( $path ) {
58
59 if( function_exists( 'wp_normalize_path' ) ) {
60 return wp_normalize_path( $path );
61 }
62
63 $path = str_replace( '\\', '/', $path );
64 $path = preg_replace( '|/+|','/', $path );
65 return $path;
66
67 }
68
69 /**
70 * Randomize file name
71 * @param $filename
72 * @return string
73 */
74 public static function randomize_filename( $filename ) {
75 $info = pathinfo($filename);
76 $ext = empty($info['extension']) ? '' : '' . $info['extension'];
77 $_parts = array();
78 if (strpos($info['filename'], '@')) {
79 $_cleanName = explode('@', $info['filename'])[0];
80 $_retna = explode('@', $info['filename'])[1];
81 $_parts[] = substr(md5(time()), 0, 8);
82 $_parts[] = '-';
83 $_parts[] = strtolower($_cleanName);
84 $_parts[] = '@' . strtolower($_retna);
85 } else {
86 $_parts[] = substr(md5(time()), 0, 8);
87 $_parts[] = '-';
88 $_parts[] = strtolower($info['filename']);
89 }
90 return join('', $_parts) . '.' . $ext;
91 }
92
93 /**
94 * Get Media Item Content Disposition
95 *
96 * @param null $attachment_id
97 * @param array $metadata
98 * @param array $data
99 * @return string
100 */
101 public static function getContentDisposition( $attachment_id = null, $metadata = array(), $data = array() ) {
102 // return 'Content-Disposition: attachment; filename=some-file.sql';
103
104 return apply_filters( 'sm:item:contentDisposition', null, array( 'attachment_id' => $attachment_id, 'mime_type' => get_post_mime_type( $attachment_id ), 'metadata' => $metadata, 'data' => $data ) );
105
106 }
107
108 /**
109 * @param null $attachment_id
110 * @param array $metadata
111 * @param array $data
112 * @return string
113 */
114 public static function getCacheControl( $attachment_id = null, $metadata = array(), $data = array() ) {
115
116 if( !$attachment_id ) {
117 return apply_filters( 'sm:item:cacheControl', 'private, no-cache, no-store', $attachment_id, array( 'attachment_id' => null, 'mime_type' => null, 'metadata' => $metadata, 'data' => $data ) );
118 }
119
120 $_mime_type = get_post_mime_type( $attachment_id );
121
122 // Treat images as public.
123 if( strpos( $_mime_type, 'image/' ) !== false ) {
124 return apply_filters( 'sm:item:cacheControl', 'public, max-age=36000, must-revalidate', array( 'attachment_id' => $attachment_id, 'mime_type' => null, 'metadata' => $metadata, 'data' => $data ) );
125 }
126
127 // Treat images as public.
128 if( strpos( $_mime_type, 'sql' ) !== false ) {
129 return apply_filters( 'sm:item:cacheControl', 'private, no-cache, no-store', array( 'attachment_id' => $attachment_id, 'mime_type' => null, 'metadata' => $metadata, 'data' => $data ) );
130 }
131
132 return apply_filters( 'sm:item:cacheControl', 'public, max-age=30, no-store, must-revalidate', array( 'attachment_id' => $attachment_id, 'mime_type' => null, 'metadata' => $metadata, 'data' => $data ) );
133
134 }
135
136 /**
137 * Add/Update Media to Bucket
138 * Fired for every action with image add or update
139 *
140 * @action wp_generate_attachment_metadata
141 * @author peshkov@UD
142 * @param $metadata
143 * @param $attachment_id
144 * @return bool|string
145 */
146 public static function add_media( $metadata, $attachment_id ) {
147 $upload_dir = wp_upload_dir();
148
149 /* Get metadata in case if method is called directly. */
150 if( current_filter() !== 'wp_generate_attachment_metadata' && current_filter() !== 'wp_update_attachment_metadata' ) {
151 $metadata = wp_get_attachment_metadata( $attachment_id );
152 }
153
154 $client = ud_get_stateless_media()->get_client();
155
156 if( !is_wp_error( $client ) ) {
157
158 $fullsizepath = wp_normalize_path( get_attached_file( $attachment_id ) );
159 // Make non-images uploadable.
160 if( empty( $metadata['file'] ) && $attachment_id ) {
161 $metadata = array( "file" => str_replace( trailingslashit( $upload_dir[ 'basedir' ] ), '', get_attached_file( $attachment_id ) ) );
162 }
163
164 $file = wp_normalize_path( $metadata[ 'file' ] );
165
166 $image_host = ud_get_stateless_media()->get_gs_host();
167 $bucketLink = apply_filters('wp_stateless_bucket_link', $image_host);
168
169 $_metadata = array(
170 "width" => isset( $metadata[ 'width' ] ) ? $metadata[ 'width' ] : null,
171 "height" => isset( $metadata[ 'height' ] ) ? $metadata[ 'height' ] : null,
172 'object-id' => $attachment_id,
173 'source-id' => md5( $attachment_id.ud_get_stateless_media()->get( 'sm.bucket' ) ),
174 'file-hash' => md5( $metadata[ 'file' ] )
175 );
176
177 /* Add default image */
178 $media = $client->add_media( $_mediaOptions = array_filter( array(
179 'name' => $file,
180 'absolutePath' => wp_normalize_path( get_attached_file( $attachment_id ) ),
181 'cacheControl' => $_cacheControl = self::getCacheControl( $attachment_id, $metadata, null ),
182 'contentDisposition' => $_contentDisposition = self::getContentDisposition( $attachment_id, $metadata, null ),
183 'mimeType' => get_post_mime_type( $attachment_id ),
184 'metadata' => $_metadata
185 ) ));
186
187 // Break if we have errors.
188 // @note Errors could be due to key being invalid or now having sufficient permissions in which case should notify user.
189 if( is_wp_error( $media ) ) {
190 return $metadata;
191 }
192
193 /* Add Google Storage metadata to our attachment */
194 $fileLink = $bucketLink . '/' . ( !empty($media['name']) ? $media['name'] : $file );
195
196 $cloud_meta = array(
197 'id' => $media[ 'id' ],
198 'name' => !empty($media['name']) ? $media['name'] : $file,
199 'fileLink' => $fileLink,
200 'storageClass' => $media[ 'storageClass' ],
201 'mediaLink' => $media[ 'mediaLink' ],
202 'selfLink' => $media[ 'selfLink' ],
203 'bucket' => ud_get_stateless_media()->get( 'sm.bucket' ),
204 'object' => $media,
205 'sizes' => array(),
206 );
207
208 if( isset( $_cacheControl ) && $_cacheControl ) {
209 //update_post_meta( $attachment_id, 'sm_cloud:cacheControl', $_cacheControl );
210 $cloud_meta[ 'cacheControl' ] = $_cacheControl;
211 }
212
213 if( isset( $_contentDisposition ) && $_contentDisposition ) {
214 //update_post_meta( $attachment_id, 'sm_cloud:contentDisposition', $_contentDisposition );
215 $cloud_meta[ 'contentDisposition' ] = $_contentDisposition;
216 }
217
218 if( empty( $metadata[ 'sizes' ] ) ) {
219 // @note This could happen if WordPress does not have any wp_get_image_editor(), e.g. Imagemagic not installed.
220 }
221
222 /* Now we go through all available image sizes and upload them to Google Storage */
223 if( !empty( $metadata[ 'sizes' ] ) && is_array( $metadata[ 'sizes' ] ) ) {
224
225 $path = wp_normalize_path( dirname( get_attached_file( $attachment_id ) ) );
226 $mediaPath = wp_normalize_path( trim( str_replace( basename( $metadata[ 'file' ] ), '', $metadata[ 'file' ] ), '\/\\' ) );
227
228 foreach( (array) $metadata[ 'sizes' ] as $image_size => $data ) {
229
230 $absolutePath = wp_normalize_path( $path . '/' . $data[ 'file' ] );
231
232 /* Add 'image size' image */
233 $media = $client->add_media( array(
234 'name' => $file_path = trim($mediaPath . '/' . $data[ 'file' ], '/'),
235 'absolutePath' => $absolutePath,
236 'cacheControl' => $_cacheControl,
237 'contentDisposition' => $_contentDisposition,
238 'mimeType' => $data[ 'mime-type' ],
239 'metadata' => array_merge( $_metadata, array(
240 'width' => $data['width'],
241 'height' => $data['height'],
242 'child-of' => $attachment_id,
243 'file-hash' => md5( $data[ 'file' ] )
244 ))
245 ));
246
247 /* Break if we have errors. */
248 if( !is_wp_error( $media ) ) {
249
250 $fileLink = $bucketLink . '/' . (!empty($media['name']) ? $media['name'] : $file_path);
251
252 // @note We don't add storageClass because it's same as parent...
253 $cloud_meta[ 'sizes' ][ $image_size ] = array(
254 'id' => $mediaPath . '/' . $media[ 'id' ],
255 'name' => !empty($media['name']) ? $media['name'] : $file_path,
256 'fileLink' => $fileLink,
257 'mediaLink' => $media[ 'mediaLink' ],
258 'selfLink' => $media[ 'selfLink' ]
259 );
260
261 // Stateless mode: we don't need the local version.
262 if(ud_get_stateless_media()->get( 'sm.mode' ) === 'stateless'){
263 unlink($absolutePath);
264 }
265 }
266
267
268 }
269
270 }
271
272 // Stateless mode: we don't need the local version.
273 if(ud_get_stateless_media()->get( 'sm.mode' ) === 'stateless'){
274 unlink($fullsizepath);
275 }
276
277 update_post_meta( $attachment_id, 'sm_cloud', $cloud_meta );
278
279 }
280
281 return $metadata;
282 }
283
284 /**
285 * Remove Media from Bucket by post ID
286 * Fired on calling function wp_delete_attachment()
287 *
288 * @todo: add error logging. peshkov@UD
289 * @see wp_delete_attachment()
290 * @action delete_attachment
291 * @author peshkov@UD
292 * @param $post_id
293 */
294 public static function remove_media( $post_id ) {
295 /* Get attahcment's metadata */
296 $metadata = wp_get_attachment_metadata( $post_id );
297
298 /* Be sure we have the same bucket in settings and have GS object's name before proceed. */
299 if(
300 isset( $metadata[ 'gs_name' ] ) &&
301 isset( $metadata[ 'gs_bucket' ] ) &&
302 $metadata[ 'gs_bucket' ] == ud_get_stateless_media()->get( 'sm.bucket' )
303 ) {
304
305 $client = ud_get_stateless_media()->get_client();
306 if( !is_wp_error( $client ) ) {
307
308 /* Remove default image */
309 $client->remove_media( $metadata[ 'gs_name' ] );
310
311 /* Now, go through all sizes and remove 'image sizes' images from Bucket too. */
312 if( !empty( $metadata[ 'sizes' ] ) && is_array( $metadata[ 'sizes' ] ) ) {
313 foreach( $metadata[ 'sizes' ] as $k => $v ) {
314 if( !empty( $v[ 'gs_name' ] ) ) {
315 $client->remove_media( $v[ 'gs_name' ] );
316 }
317 }
318 }
319
320 }
321
322 }
323
324 }
325
326 }
327
328 }
329
330 }
331