bp-core-attachments.php 47.3 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
<?php
/**
 * BuddyPress Attachments functions.
 *
 * @package BuddyPress
 * @subpackage Attachments
lechuck's avatar
lechuck committed
7
 * @since 2.3.0
ale's avatar
ale committed
8
9
 */

lechuck's avatar
lechuck committed
10
// Exit if accessed directly.
ale's avatar
ale committed
11
12
13
14
15
16
17
18
19
defined( 'ABSPATH' ) || exit;

/**
 * Check if the current WordPress version is using Plupload 2.1.1
 *
 * Plupload 2.1.1 was introduced in WordPress 3.9. Our bp-plupload.js
 * script requires it. So we need to make sure the current WordPress
 * match with our needs.
 *
lechuck's avatar
lechuck committed
20
 * @since 2.3.0
lucha's avatar
lucha committed
21
 * @since 3.0.0 We now require WP >= 4.5, so this is always true.
ale's avatar
ale committed
22
 *
lucha's avatar
lucha committed
23
 * @return bool Always true.
ale's avatar
ale committed
24
25
 */
function bp_attachments_is_wp_version_supported() {
lucha's avatar
lucha committed
26
	return true;
ale's avatar
ale committed
27
28
29
}

/**
lechuck's avatar
lechuck committed
30
 * Get the Attachments Uploads dir data.
ale's avatar
ale committed
31
 *
lechuck's avatar
lechuck committed
32
 * @since 2.4.0
ale's avatar
ale committed
33
 *
lechuck's avatar
lechuck committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 * @param string $data The data to get. Possible values are: 'dir', 'basedir' & 'baseurl'.
 *                     Leave empty to get all datas.
 * @return string|array The needed Upload dir data.
 */
function bp_attachments_uploads_dir_get( $data = '' ) {
	$attachments_dir = 'buddypress';
	$retval          = '';

	if ( 'dir' === $data ) {
		$retval = $attachments_dir;
	} else {
		$upload_data = bp_upload_dir();

		// Return empty string, if Uploads data are not available.
		if ( ! $upload_data ) {
			return $retval;
		}

		// Build the Upload data array for BuddyPress attachments.
		foreach ( $upload_data as $key => $value ) {
			if ( 'basedir' === $key || 'baseurl' === $key ) {
				$upload_data[ $key ] = trailingslashit( $value ) . $attachments_dir;
lucha's avatar
lucha committed
56
57
58
59
60

				// Fix for HTTPS.
				if ( 'baseurl' === $key && is_ssl() ) {
					$upload_data[ $key ] = str_replace( 'http://', 'https://', $upload_data[ $key ] );
				}
lechuck's avatar
lechuck committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
			} else {
				unset( $upload_data[ $key ] );
			}
		}

		// Add the dir to the array.
		$upload_data['dir'] = $attachments_dir;

		if ( empty( $data ) ) {
			$retval = $upload_data;
		} elseif ( isset( $upload_data[ $data ] ) ) {
			$retval = $upload_data[ $data ];
		}
	}

	/**
	 * Filter here to edit the Attachments upload dir data.
	 *
	 * @since 2.4.0
	 *
	 * @param string|array $retval The needed Upload dir data or the full array of data
	 * @param string       $data   The data requested
	 */
	return apply_filters( 'bp_attachments_uploads_dir_get', $retval, $data );
}

lucha's avatar
lucha committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
 * Gets the upload dir array for cover images.
 *
 * @since 3.0.0
 *
 * @return array See wp_upload_dir().
 */
function bp_attachments_cover_image_upload_dir( $args = array() ) {
	// Default values are for profiles.
	$object_id = bp_displayed_user_id();

	if ( empty( $object_id ) ) {
		$object_id = bp_loggedin_user_id();
	}

	$object_directory = 'members';

	// We're in a group, edit default values.
	if ( bp_is_group() || bp_is_group_create() ) {
		$object_id        = bp_get_current_group_id();
		$object_directory = 'groups';
	}

	$r = bp_parse_args( $args, array(
		'object_id' => $object_id,
		'object_directory' => $object_directory,
	), 'cover_image_upload_dir' );


	// Set the subdir.
	$subdir  = '/' . $r['object_directory'] . '/' . $r['object_id'] . '/cover-image';

	$upload_dir = bp_attachments_uploads_dir_get();

	/**
	 * Filters the cover image upload directory.
	 *
	 * @since 2.4.0
	 *
	 * @param array $value      Array containing the path, URL, and other helpful settings.
	 * @param array $upload_dir The original Uploads dir.
	 */
	return apply_filters( 'bp_attachments_cover_image_upload_dir', array(
		'path'    => $upload_dir['basedir'] . $subdir,
		'url'     => set_url_scheme( $upload_dir['baseurl'] ) . $subdir,
		'subdir'  => $subdir,
		'basedir' => $upload_dir['basedir'],
		'baseurl' => set_url_scheme( $upload_dir['baseurl'] ),
		'error'   => false,
	), $upload_dir );
}

lechuck's avatar
lechuck committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
 * Get the max upload file size for any attachment.
 *
 * @since 2.4.0
 *
 * @param string $type A string to inform about the type of attachment
 *                     we wish to get the max upload file size for.
 * @return int Max upload file size for any attachment.
 */
function bp_attachments_get_max_upload_file_size( $type = '' ) {
	$fileupload_maxk = bp_core_get_root_option( 'fileupload_maxk' );

	if ( '' === $fileupload_maxk ) {
		$fileupload_maxk = 5120000; // 5mb;
	} else {
		$fileupload_maxk = $fileupload_maxk * 1024;
	}

	/**
	 * Filter here to edit the max upload file size.
	 *
	 * @since 2.4.0
	 *
	 * @param int    $fileupload_maxk Max upload file size for any attachment.
	 * @param string $type            The attachment type (eg: 'avatar' or 'cover_image').
	 */
	return apply_filters( 'bp_attachments_get_max_upload_file_size', $fileupload_maxk, $type );
}

/**
 * Get allowed types for any attachment.
 *
 * @since 2.4.0
 *
 * @param string $type The extension types to get.
 *                     Default: 'avatar'.
 * @return array The list of allowed extensions for attachments.
 */
function bp_attachments_get_allowed_types( $type = 'avatar' ) {
	// Defaults to BuddyPress supported image extensions.
	$exts = array( 'jpeg', 'gif', 'png' );

	/**
	 * It's not a BuddyPress feature, get the allowed extensions
	 * matching the $type requested.
	 */
	if ( 'avatar' !== $type && 'cover_image' !== $type ) {
		// Reset the default exts.
		$exts = array();

		switch ( $type ) {
			case 'video' :
				$exts = wp_get_video_extensions();
			break;

			case 'audio' :
				$exts = wp_get_video_extensions();
			break;

			default:
				$allowed_mimes = get_allowed_mime_types();

				/**
				 * Search for allowed mimes matching the type.
				 *
				 * Eg: using 'application/vnd.oasis' as the $type
				 * parameter will get all OpenOffice extensions supported
				 * by WordPress and allowed for the current user.
				 */
				if ( '' !== $type ) {
					$allowed_mimes = preg_grep( '/' . addcslashes( $type, '/.+-' ) . '/', $allowed_mimes );
				}

				$allowed_types = array_keys( $allowed_mimes );

				// Loop to explode keys using '|'.
				foreach ( $allowed_types as $allowed_type ) {
					$t = explode( '|', $allowed_type );
					$exts = array_merge( $exts, (array) $t );
				}
			break;
		}
	}

	/**
	 * Filter here to edit the allowed extensions by attachment type.
	 *
	 * @since 2.4.0
	 *
	 * @param array  $exts List of allowed extensions.
	 * @param string $type The requested file type.
	 */
	return apply_filters( 'bp_attachments_get_allowed_types', $exts, $type );
}

/**
 * Get allowed attachment mime types.
 *
 * @since 2.4.0
 *
 * @param string $type          The extension types to get (Optional).
 * @param array  $allowed_types List of allowed extensions.
 * @return array List of allowed mime types.
 */
function bp_attachments_get_allowed_mimes( $type = '', $allowed_types = array() ) {
	if ( empty( $allowed_types ) ) {
		$allowed_types = bp_attachments_get_allowed_types( $type );
	}

	$validate_mimes = wp_match_mime_types( join( ',', $allowed_types ), wp_get_mime_types() );
	$allowed_mimes  = array_map( 'implode', $validate_mimes );

	/**
	 * Include jpg type if jpeg is set
	 */
	if ( isset( $allowed_mimes['jpeg'] ) && ! isset( $allowed_mimes['jpg'] ) ) {
		$allowed_mimes['jpg'] = $allowed_mimes['jpeg'];
	}

	return $allowed_mimes;
}

/**
 * Check the uploaded attachment type is allowed.
 *
 * @since 2.4.0
 *
 * @param string $file          Full path to the file.
 * @param string $filename      The name of the file (may differ from $file due to $file being
 *                              in a tmp directory).
 * @param array  $allowed_mimes The attachment allowed mimes (Required).
 * @return bool True if the attachment type is allowed. False otherwise
 */
function bp_attachments_check_filetype( $file, $filename, $allowed_mimes ) {
	$filetype = wp_check_filetype_and_ext( $file, $filename, $allowed_mimes );

	if ( ! empty( $filetype['ext'] ) && ! empty( $filetype['type'] ) ) {
		return true;
	}

	return false;
}

/**
 * Use the absolute path to an image to set an attachment type for a given item.
 *
 * @since 2.4.0
 *
 * @param string $type The attachment type to create (avatar or cover_image). Default: avatar.
 * @param array  $args {
 *     @type int    $item_id   The ID of the object (Required). Default: 0.
 *     @type string $object    The object type (eg: group, user, blog) (Required). Default: 'user'.
 *     @type string $component The component for the object (eg: groups, xprofile, blogs). Default: ''.
 *     @type string $image     The absolute path to the image (Required). Default: ''.
 *     @type int    $crop_w    Crop width. Default: 0.
 *     @type int    $crop_h    Crop height. Default: 0.
 *     @type int    $crop_x    The horizontal starting point of the crop. Default: 0.
 *     @type int    $crop_y    The vertical starting point of the crop. Default: 0.
 * }
 * @return bool True on success, false otherwise.
 */
function bp_attachments_create_item_type( $type = 'avatar', $args = array() ) {
	if ( empty( $type ) || ( $type !== 'avatar' && $type !== 'cover_image' ) ) {
		return false;
	}

	$r = bp_parse_args( $args, array(
		'item_id'   => 0,
		'object'    => 'user',
		'component' => '',
		'image'     => '',
		'crop_w'    => 0,
		'crop_h'    => 0,
		'crop_x'    => 0,
		'crop_y'    => 0
	), 'create_item_' . $type );

	if ( empty( $r['item_id'] ) || empty( $r['object'] ) || ! file_exists( $r['image'] ) || ! @getimagesize( $r['image'] ) ) {
		return false;
	}

	// Make sure the file path is safe.
lucha's avatar
lucha committed
321
	if ( 1 === validate_file( $r['image'] ) ) {
lechuck's avatar
lechuck committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
		return false;
	}

	// Set the component if not already done.
	if ( empty( $r['component'] ) ) {
		if ( 'user' === $r['object'] ) {
			$r['component'] = 'xprofile';
		} else {
			$r['component'] = $r['object'] . 's';
		}
	}

	// Get allowed mimes for the Attachment type and check the image one is.
	$allowed_mimes = bp_attachments_get_allowed_mimes( $type );
	$is_allowed    = wp_check_filetype( $r['image'], $allowed_mimes );

	// It's not an image.
	if ( ! $is_allowed['ext'] ) {
		return false;
	}

	// Init the Attachment data.
	$attachment_data = array();

	if ( 'avatar' === $type ) {
		// Set crop width for the avatar if not given.
		if ( empty( $r['crop_w'] ) ) {
			$r['crop_w'] = bp_core_avatar_full_width();
		}

		// Set crop height for the avatar if not given.
		if ( empty( $r['crop_h'] ) ) {
			$r['crop_h'] = bp_core_avatar_full_height();
		}

		if ( is_callable( $r['component'] . '_avatar_upload_dir' ) ) {
			$dir_args = array( $r['item_id'] );

			// In case  of xprofile, we need an extra argument.
			if ( 'xprofile' === $r['component'] ) {
				$dir_args = array( false, $r['item_id'] );
			}

			$attachment_data = call_user_func_array( $r['component'] . '_avatar_upload_dir', $dir_args );
		}
	} elseif ( 'cover_image' === $type ) {
lucha's avatar
lucha committed
368
		$attachment_data = bp_attachments_cover_image_upload_dir();
lechuck's avatar
lechuck committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

		// The BP Attachments Uploads Dir is not set, stop.
		if ( ! $attachment_data ) {
			return false;
		}

		// Default to members for xProfile.
		$object_subdir = 'members';

		if ( 'xprofile' !== $r['component'] ) {
			$object_subdir = sanitize_key( $r['component'] );
		}

		// Set Subdir.
		$attachment_data['subdir'] = $object_subdir . '/' . $r['item_id'] . '/cover-image';

		// Set Path.
		$attachment_data['path'] = trailingslashit( $attachment_data['basedir'] ) . $attachment_data['subdir'];
	}

	if ( ! isset( $attachment_data['path'] ) || ! isset( $attachment_data['subdir'] ) ) {
		return false;
	}

	// It's not a regular upload, we may need to create some folders.
	if ( ! is_dir( $attachment_data['path'] ) ) {
		if ( ! wp_mkdir_p( $attachment_data['path'] ) ) {
			return false;
		}
	}

	// Set the image name and path.
	$image_file_name = wp_unique_filename( $attachment_data['path'], basename( $r['image'] ) );
	$image_file_path = $attachment_data['path'] . '/' . $image_file_name;

	// Copy the image file into the avatar dir.
	if ( ! copy( $r['image'], $image_file_path ) ) {
		return false;
	}

	// Init the response.
	$created = false;

	// It's an avatar, we need to crop it.
	if ( 'avatar' === $type ) {
		$created = bp_core_avatar_handle_crop( array(
			'object'        => $r['object'],
			'avatar_dir'    => trim( dirname( $attachment_data['subdir'] ), '/' ),
			'item_id'       => (int) $r['item_id'],
			'original_file' => trailingslashit( $attachment_data['subdir'] ) . $image_file_name,
			'crop_w'        => $r['crop_w'],
			'crop_h'        => $r['crop_h'],
			'crop_x'        => $r['crop_x'],
			'crop_y'        => $r['crop_y']
		) );

	// It's a cover image we need to fit it to feature's dimensions.
	} elseif ( 'cover_image' === $type ) {
		$cover_image = bp_attachments_cover_image_generate_file( array(
			'file'            => $image_file_path,
			'component'       => $r['component'],
			'cover_image_dir' => $attachment_data['path']
		) );

		$created = ! empty( $cover_image['cover_file'] );
	}

	// Remove copied file if it fails.
	if ( ! $created ) {
		@unlink( $image_file_path );
	}

	// Return the response.
	return $created;
}

/**
 * Get the url or the path for a type of attachment.
 *
 * @since 2.4.0
 *
 * @param string $data whether to get the url or the path.
 * @param array  $args {
 *     @type string $object_dir  The object dir (eg: members/groups). Defaults to members.
 *     @type int    $item_id     The object id (eg: a user or a group id). Defaults to current user.
 *     @type string $type        The type of the attachment which is also the subdir where files are saved.
 *                               Defaults to 'cover-image'
 *     @type string $file        The name of the file.
 * }
 * @return string|bool The url or the path to the attachment, false otherwise
 */
function bp_attachments_get_attachment( $data = 'url', $args = array() ) {
	// Default value.
	$attachment_data = false;

	$r = bp_parse_args( $args, array(
		'object_dir' => 'members',
		'item_id'    => bp_loggedin_user_id(),
		'type'       => 'cover-image',
		'file'       => '',
	), 'attachments_get_attachment_src' );

	/**
	 * Filters whether or not to handle fetching a BuddyPress image attachment.
	 *
	 * If you want to override this function, make sure you return false.
	 *
	 * @since 2.5.1
	 *
	 * @param null|string $value If null is returned, proceed with default behaviour. Otherwise, value returned verbatim.
	 * @param array $r {
	 *     @type string $object_dir The object dir (eg: members/groups). Defaults to members.
	 *     @type int    $item_id    The object id (eg: a user or a group id). Defaults to current user.
	 *     @type string $type       The type of the attachment which is also the subdir where files are saved.
	 *                              Defaults to 'cover-image'
	 *     @type string $file       The name of the file.
	 * }
	 */
	$pre_filter = apply_filters( 'bp_attachments_pre_get_attachment', null, $r );
	if ( $pre_filter !== null ) {
		return $pre_filter;
	}

	// Get BuddyPress Attachments Uploads Dir datas.
	$bp_attachments_uploads_dir = bp_attachments_uploads_dir_get();

	// The BP Attachments Uploads Dir is not set, stop.
	if ( ! $bp_attachments_uploads_dir ) {
		return $attachment_data;
	}

	$type_subdir = $r['object_dir'] . '/' . $r['item_id'] . '/' . $r['type'];
	$type_dir    = trailingslashit( $bp_attachments_uploads_dir['basedir'] ) . $type_subdir;

lucha's avatar
lucha committed
503
	if ( 1 === validate_file( $type_dir ) || ! is_dir( $type_dir ) ) {
lechuck's avatar
lechuck committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
		return $attachment_data;
	}

	if ( ! empty( $r['file'] ) ) {
		if ( ! file_exists( trailingslashit( $type_dir ) . $r['file'] ) ) {
			return $attachment_data;
		}

		if ( 'url' === $data ) {
			$attachment_data = trailingslashit( $bp_attachments_uploads_dir['baseurl'] ) . $type_subdir . '/' . $r['file'];
		} else {
			$attachment_data = trailingslashit( $type_dir ) . $r['file'];
		}

	} else {
		$file = false;

		// Open the directory and get the first file.
		if ( $att_dir = opendir( $type_dir ) ) {

			while ( false !== ( $attachment_file = readdir( $att_dir ) ) ) {
				// Look for the first file having the type in its name.
				if ( false !== strpos( $attachment_file, $r['type'] ) && empty( $file ) ) {
					$file = $attachment_file;
					break;
				}
			}
		}

		if ( empty( $file ) ) {
			return $attachment_data;
		}

		if ( 'url' === $data ) {
			$attachment_data = trailingslashit( $bp_attachments_uploads_dir['baseurl'] ) . $type_subdir . '/' . $file;
		} else {
			$attachment_data = trailingslashit( $type_dir ) . $file;
		}
	}

	return $attachment_data;
}

/**
 * Delete an attachment for the given arguments
 *
 * @since 2.4.0
 *
 * @see bp_attachments_get_attachment() For more information on accepted arguments.
 *
 * @param array $args Array of arguments for the attachment deletion.
 * @return bool True if the attachment was deleted, false otherwise.
 */
function bp_attachments_delete_file( $args = array() ) {
	$attachment_path = bp_attachments_get_attachment( 'path', $args );

	/**
	 * Filters whether or not to handle deleting an existing BuddyPress attachment.
	 *
	 * If you want to override this function, make sure you return false.
	 *
	 * @since 2.5.1
	 *
	 * @param bool $value Whether or not to delete the BuddyPress attachment.
lucha's avatar
lucha committed
568
`	 * @param array $args Array of arguments for the attachment deletion.
lechuck's avatar
lechuck committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
	 */
	if ( ! apply_filters( 'bp_attachments_pre_delete_file', true, $args ) ) {
		return true;
	}

	if ( empty( $attachment_path ) ) {
		return false;
	}

	@unlink( $attachment_path );
	return true;
}

/**
 * Get the BuddyPress Plupload settings.
 *
 * @since 2.3.0
 *
 * @return array List of BuddyPress Plupload settings.
ale's avatar
ale committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
 */
function bp_attachments_get_plupload_default_settings() {

	$max_upload_size = wp_max_upload_size();

	if ( ! $max_upload_size ) {
		$max_upload_size = 0;
	}

	$defaults = array(
		'runtimes'            => 'html5,flash,silverlight,html4',
		'file_data_name'      => 'file',
		'multipart_params'    => array(
			'action'          => 'bp_upload_attachment',
			'_wpnonce'        => wp_create_nonce( 'bp-uploader' ),
		),
		'url'                 => admin_url( 'admin-ajax.php', 'relative' ),
		'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
		'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
		'filters' => array(
			'max_file_size'   => $max_upload_size . 'b',
		),
		'multipart'           => true,
		'urlstream_upload'    => true,
	);

	// WordPress is not allowing multi selection for iOs 7 device.. See #29602.
	if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
		strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {

		$defaults['multi_selection'] = false;
	}

	$settings = array(
		'defaults' => $defaults,
		'browser'  => array(
			'mobile'    => wp_is_mobile(),
			'supported' => _device_can_upload(),
		),
		'limitExceeded' => is_multisite() && ! is_upload_space_available(),
	);

	/**
	 * Filter the BuddyPress Plupload default settings.
	 *
	 * @since 2.3.0
	 *
lechuck's avatar
lechuck committed
635
	 * @param array $settings Default Plupload parameters array.
ale's avatar
ale committed
636
637
638
639
640
	 */
	return apply_filters( 'bp_attachments_get_plupload_default_settings', $settings );
}

/**
lechuck's avatar
lechuck committed
641
 * Builds localization strings for the BuddyPress Uploader scripts.
ale's avatar
ale committed
642
 *
lechuck's avatar
lechuck committed
643
 * @since 2.3.0
ale's avatar
ale committed
644
 *
lechuck's avatar
lechuck committed
645
 * @return array Plupload default localization strings.
ale's avatar
ale committed
646
647
 */
function bp_attachments_get_plupload_l10n() {
lechuck's avatar
lechuck committed
648
	// Localization strings.
ale's avatar
ale committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
	return apply_filters( 'bp_attachments_get_plupload_l10n', array(
			'queue_limit_exceeded'      => __( 'You have attempted to queue too many files.', 'buddypress' ),
			'file_exceeds_size_limit'   => __( '%s exceeds the maximum upload size for this site.', 'buddypress' ),
			'zero_byte_file'            => __( 'This file is empty. Please try another.', 'buddypress' ),
			'invalid_filetype'          => __( 'This file type is not allowed. Please try another.', 'buddypress' ),
			'not_an_image'              => __( 'This file is not an image. Please try another.', 'buddypress' ),
			'image_memory_exceeded'     => __( 'Memory exceeded. Please try another smaller file.', 'buddypress' ),
			'image_dimensions_exceeded' => __( 'This is larger than the maximum size. Please try another.', 'buddypress' ),
			'default_error'             => __( 'An error occurred. Please try again later.', 'buddypress' ),
			'missing_upload_url'        => __( 'There was a configuration error. Please contact the server administrator.', 'buddypress' ),
			'upload_limit_exceeded'     => __( 'You may only upload 1 file.', 'buddypress' ),
			'http_error'                => __( 'HTTP error.', 'buddypress' ),
			'upload_failed'             => __( 'Upload failed.', 'buddypress' ),
			'big_upload_failed'         => __( 'Please try uploading this file with the %1$sbrowser uploader%2$s.', 'buddypress' ),
			'big_upload_queued'         => __( '%s exceeds the maximum upload size for the multi-file uploader when used in your browser.', 'buddypress' ),
			'io_error'                  => __( 'IO error.', 'buddypress' ),
			'security_error'            => __( 'Security error.', 'buddypress' ),
			'file_cancelled'            => __( 'File canceled.', 'buddypress' ),
			'upload_stopped'            => __( 'Upload stopped.', 'buddypress' ),
			'dismiss'                   => __( 'Dismiss', 'buddypress' ),
			'crunching'                 => __( 'Crunching&hellip;', 'buddypress' ),
			'unique_file_warning'       => __( 'Make sure to upload a unique file', 'buddypress' ),
			'error_uploading'           => __( '&#8220;%s&#8221; has failed to upload.', 'buddypress' ),
			'has_avatar_warning'        => __( 'If you&#39;d like to delete the existing profile photo but not upload a new one, please use the delete tab.', 'buddypress' )
	) );
}

/**
lechuck's avatar
lechuck committed
677
 * Enqueues the script needed for the Uploader UI.
ale's avatar
ale committed
678
 *
lechuck's avatar
lechuck committed
679
 * @since 2.3.0
ale's avatar
ale committed
680
 *
lechuck's avatar
lechuck committed
681
682
 * @see BP_Attachment::script_data() && BP_Attachment_Avatar::script_data() for examples showing how
 * to set specific script data.
ale's avatar
ale committed
683
 *
lechuck's avatar
lechuck committed
684
685
 * @param string $class Name of the class extending BP_Attachment (eg: BP_Attachment_Avatar).
 * @return null|WP_Error
ale's avatar
ale committed
686
687
688
689
690
691
692
693
694
695
696
 */
function bp_attachments_enqueue_scripts( $class = '' ) {
	// Enqueue me just once per page, please.
	if ( did_action( 'bp_attachments_enqueue_scripts' ) ) {
		return;
	}

	if ( ! $class || ! class_exists( $class ) ) {
		return new WP_Error( 'missing_parameter' );
	}

lechuck's avatar
lechuck committed
697
	// Get an instance of the class and get the script data.
ale's avatar
ale committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
	$attachment = new $class;
	$script_data  = $attachment->script_data();

	$args = bp_parse_args( $script_data, array(
		'action'            => '',
		'file_data_name'    => '',
		'max_file_size'     => 0,
		'browse_button'     => 'bp-browse-button',
		'container'         => 'bp-upload-ui',
		'drop_element'      => 'drag-drop-area',
		'bp_params'         => array(),
		'extra_css'         => array(),
		'extra_js'          => array(),
		'feedback_messages' => array(),
	), 'attachments_enqueue_scripts' );

	if ( empty( $args['action'] ) || empty( $args['file_data_name'] ) ) {
		return new WP_Error( 'missing_parameter' );
	}

lechuck's avatar
lechuck committed
718
	// Get the BuddyPress uploader strings.
ale's avatar
ale committed
719
720
	$strings = bp_attachments_get_plupload_l10n();

lechuck's avatar
lechuck committed
721
	// Get the BuddyPress uploader settings.
ale's avatar
ale committed
722
723
	$settings = bp_attachments_get_plupload_default_settings();

lechuck's avatar
lechuck committed
724
	// Set feedback messages.
ale's avatar
ale committed
725
726
727
728
	if ( ! empty( $args['feedback_messages'] ) ) {
		$strings['feedback_messages'] = $args['feedback_messages'];
	}

lechuck's avatar
lechuck committed
729
	// Use a temporary var to ease manipulation.
ale's avatar
ale committed
730
731
	$defaults = $settings['defaults'];

lechuck's avatar
lechuck committed
732
	// Set the upload action.
ale's avatar
ale committed
733
734
	$defaults['multipart_params']['action'] = $args['action'];

lechuck's avatar
lechuck committed
735
	// Set BuddyPress upload parameters if provided.
ale's avatar
ale committed
736
737
738
739
	if ( ! empty( $args['bp_params'] ) ) {
		$defaults['multipart_params']['bp_params'] = $args['bp_params'];
	}

lechuck's avatar
lechuck committed
740
	// Merge other arguments.
ale's avatar
ale committed
741
742
743
744
745
746
747
748
749
750
751
752
753
	$ui_args = array_intersect_key( $args, array(
		'file_data_name' => true,
		'browse_button'  => true,
		'container'      => true,
		'drop_element'   => true,
	) );

	$defaults = array_merge( $defaults, $ui_args );

	if ( ! empty( $args['max_file_size'] ) ) {
		$defaults['filters']['max_file_size'] = $args['max_file_size'] . 'b';
	}

lechuck's avatar
lechuck committed
754
	// Specific to BuddyPress Avatars.
ale's avatar
ale committed
755
756
	if ( 'bp_avatar_upload' === $defaults['multipart_params']['action'] ) {

lechuck's avatar
lechuck committed
757
		// Include the cropping informations for avatars.
ale's avatar
ale committed
758
759
760
761
762
763
764
765
		$settings['crop'] = array(
			'full_h'  => bp_core_avatar_full_height(),
			'full_w'  => bp_core_avatar_full_width(),
		);

		// Avatar only need 1 file and 1 only!
		$defaults['multi_selection'] = false;

lechuck's avatar
lechuck committed
766
		// Does the object already has an avatar set.
ale's avatar
ale committed
767
768
		$has_avatar = $defaults['multipart_params']['bp_params']['has_avatar'];

lechuck's avatar
lechuck committed
769
		// What is the object the avatar belongs to.
ale's avatar
ale committed
770
771
		$object = $defaults['multipart_params']['bp_params']['object'];

lechuck's avatar
lechuck committed
772
		// Init the Avatar nav.
ale's avatar
ale committed
773
774
775
		$avatar_nav = array(
			'upload' => array( 'id' => 'upload', 'caption' => __( 'Upload', 'buddypress' ), 'order' => 0  ),

lechuck's avatar
lechuck committed
776
			// The delete view will only show if the object has an avatar.
ale's avatar
ale committed
777
778
779
			'delete' => array( 'id' => 'delete', 'caption' => __( 'Delete', 'buddypress' ), 'order' => 100, 'hide' => (int) ! $has_avatar ),
		);

lechuck's avatar
lechuck committed
780
		// Create the Camera Nav if the WebCam capture feature is enabled.
ale's avatar
ale committed
781
782
783
		if ( bp_avatar_use_webcam() && 'user' === $object ) {
			$avatar_nav['camera'] = array( 'id' => 'camera', 'caption' => __( 'Take Photo', 'buddypress' ), 'order' => 10 );

lechuck's avatar
lechuck committed
784
			// Set warning messages.
ale's avatar
ale committed
785
786
787
788
789
790
791
792
793
794
795
796
797
			$strings['camera_warnings'] = array(
				'requesting'  => __( 'Please allow us to access to your camera.', 'buddypress'),
				'loading'     => __( 'Please wait as we access your camera.', 'buddypress' ),
				'loaded'      => __( 'Camera loaded. Click on the "Capture" button to take your photo.', 'buddypress' ),
				'noaccess'    => __( 'It looks like you do not have a webcam or we were unable to get permission to use your webcam. Please upload a photo instead.', 'buddypress' ),
				'errormsg'    => __( 'Your browser is not supported. Please upload a photo instead.', 'buddypress' ),
				'videoerror'  => __( 'Video error. Please upload a photo instead.', 'buddypress' ),
				'ready'       => __( 'Your profile photo is ready. Click on the "Save" button to use this photo.', 'buddypress' ),
				'nocapture'   => __( 'No photo was captured. Click on the "Capture" button to take your photo.', 'buddypress' ),
			);
		}

		/**
lechuck's avatar
lechuck committed
798
		 * Use this filter to add a navigation to a custom tool to set the object's avatar.
ale's avatar
ale committed
799
		 *
lechuck's avatar
lechuck committed
800
		 * @since 2.3.0
ale's avatar
ale committed
801
		 *
lechuck's avatar
lechuck committed
802
803
804
805
806
807
808
809
810
		 * @param array  $avatar_nav {
		 *     An associative array of available nav items where each item is an array organized this way:
		 *     $avatar_nav[ $nav_item_id ].
		 *     @type string $nav_item_id The nav item id in lower case without special characters or space.
		 *     @type string $caption     The name of the item nav that will be displayed in the nav.
		 *     @type int    $order       An integer to specify the priority of the item nav, choose one.
		 *                               between 1 and 99 to be after the uploader nav item and before the delete nav item.
		 *     @type int    $hide        If set to 1 the item nav will be hidden
		 *                               (only used for the delete nav item).
ale's avatar
ale committed
811
		 * }
lechuck's avatar
lechuck committed
812
		 * @param string $object The object the avatar belongs to (eg: user or group).
ale's avatar
ale committed
813
814
		 */
		$settings['nav'] = bp_sort_by_key( apply_filters( 'bp_attachments_avatar_nav', $avatar_nav, $object ), 'order', 'num' );
lechuck's avatar
lechuck committed
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844

	// Specific to BuddyPress cover images.
	} elseif ( 'bp_cover_image_upload' === $defaults['multipart_params']['action'] ) {

		// Cover images only need 1 file and 1 only!
		$defaults['multi_selection'] = false;

		// Default cover component is xprofile.
		$cover_component = 'xprofile';

		// Get the object we're editing the cover image of.
		$object = $defaults['multipart_params']['bp_params']['object'];

		// Set the cover component according to the object.
		if ( 'group' === $object ) {
			$cover_component = 'groups';
		} elseif ( 'user' !== $object ) {
			$cover_component = apply_filters( 'bp_attachments_cover_image_ui_component', $cover_component );
		}
		// Get cover image advised dimensions.
		$cover_dimensions = bp_attachments_get_cover_image_dimensions( $cover_component );

		// Set warning messages.
		$strings['cover_image_warnings'] = apply_filters( 'bp_attachments_cover_image_ui_warnings', array(
			'dimensions'  => sprintf(
					__( 'For better results, make sure to upload an image that is larger than %1$spx wide, and %2$spx tall.', 'buddypress' ),
					(int) $cover_dimensions['width'],
					(int) $cover_dimensions['height']
				),
		) );
ale's avatar
ale committed
845
846
	}

lechuck's avatar
lechuck committed
847
	// Set Plupload settings.
ale's avatar
ale committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	$settings['defaults'] = $defaults;

	/**
	 * Enqueue some extra styles if required
	 *
	 * Extra styles need to be registered.
	 */
	if ( ! empty( $args['extra_css'] ) ) {
		foreach ( (array) $args['extra_css'] as $css ) {
			if ( empty( $css ) ) {
				continue;
			}

			wp_enqueue_style( $css );
		}
	}

	wp_enqueue_script ( 'bp-plupload' );
	wp_localize_script( 'bp-plupload', 'BP_Uploader', array( 'strings' => $strings, 'settings' => $settings ) );

	/**
	 * Enqueue some extra scripts if required
	 *
	 * Extra scripts need to be registered.
	 */
	if ( ! empty( $args['extra_js'] ) ) {
		foreach ( (array) $args['extra_js'] as $js ) {
			if ( empty( $js ) ) {
				continue;
			}

			wp_enqueue_script( $js );
		}
	}

	/**
	 * Fires at the conclusion of bp_attachments_enqueue_scripts()
	 * to avoid the scripts to be loaded more than once.
	 *
lechuck's avatar
lechuck committed
887
	 * @since 2.3.0
ale's avatar
ale committed
888
889
890
891
892
	 */
	do_action( 'bp_attachments_enqueue_scripts' );
}

/**
lechuck's avatar
lechuck committed
893
 * Check the current user's capability to edit an avatar for a given object.
ale's avatar
ale committed
894
 *
lechuck's avatar
lechuck committed
895
 * @since 2.3.0
ale's avatar
ale committed
896
 *
lechuck's avatar
lechuck committed
897
898
899
 * @param string $capability The capability to check.
 * @param array  $args       An array containing the item_id and the object to check.
 * @return bool
ale's avatar
ale committed
900
901
902
903
 */
function bp_attachments_current_user_can( $capability, $args = array() ) {
	$can = false;

lechuck's avatar
lechuck committed
904
	if ( 'edit_avatar' === $capability || 'edit_cover_image' === $capability ) {
ale's avatar
ale committed
905
906
907
908
		/**
		 * Needed avatar arguments are set.
		 */
		if ( isset( $args['item_id'] ) && isset( $args['object'] ) ) {
lechuck's avatar
lechuck committed
909
			// Group profile photo.
ale's avatar
ale committed
910
911
912
913
914
915
			if ( bp_is_active( 'groups' ) && 'group' === $args['object'] ) {
				if ( bp_is_group_create() ) {
					$can = (bool) groups_is_user_creator( bp_loggedin_user_id(), $args['item_id'] ) || bp_current_user_can( 'bp_moderate' );
				} else {
					$can = (bool) groups_is_user_admin( bp_loggedin_user_id(), $args['item_id'] ) || bp_current_user_can( 'bp_moderate' );
				}
lechuck's avatar
lechuck committed
916
			// User profile photo.
ale's avatar
ale committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
			} elseif ( bp_is_active( 'xprofile' ) && 'user' === $args['object'] ) {
				$can = bp_loggedin_user_id() === (int) $args['item_id'] || bp_current_user_can( 'bp_moderate' );
			}
		/**
		 * No avatar arguments, fallback to bp_user_can_create_groups()
		 * or bp_is_item_admin()
		 */
		} else {
			if ( bp_is_group_create() ) {
				$can = bp_user_can_create_groups();
			} else {
				$can = bp_is_item_admin();
			}
		}
	}

	return apply_filters( 'bp_attachments_current_user_can', $can, $capability, $args );
}

/**
 * Send a JSON response back to an Ajax upload request.
 *
lechuck's avatar
lechuck committed
939
 * @since 2.3.0
ale's avatar
ale committed
940
 *
lechuck's avatar
lechuck committed
941
942
943
 * @param bool  $success  True for a success, false otherwise.
 * @param bool  $is_html4 True if the Plupload runtime used is html4, false otherwise.
 * @param mixed $data     Data to encode as JSON, then print and die.
ale's avatar
ale committed
944
945
946
947
948
949
950
951
 */
function bp_attachments_json_response( $success, $is_html4 = false, $data = null ) {
	$response = array( 'success' => $success );

	if ( isset( $data ) ) {
		$response['data'] = $data;
	}

lechuck's avatar
lechuck committed
952
	// Send regular json response.
ale's avatar
ale committed
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
	if ( ! $is_html4 ) {
		wp_send_json( $response );

	/**
	 * Send specific json response
	 * the html4 Plupload handler requires a text/html content-type for older IE.
	 * See https://core.trac.wordpress.org/ticket/31037
	 */
	} else {
		echo wp_json_encode( $response );

		wp_die();
	}
}

/**
 * Get an Attachment template part.
 *
lechuck's avatar
lechuck committed
971
 * @since 2.3.0
ale's avatar
ale committed
972
 *
lechuck's avatar
lechuck committed
973
974
 * @param string $slug Template part slug. eg 'uploader' for 'uploader.php'.
 * @return bool
ale's avatar
ale committed
975
976
 */
function bp_attachments_get_template_part( $slug ) {
lucha's avatar
lucha committed
977
	$switched = false;
ale's avatar
ale committed
978

lucha's avatar
lucha committed
979
980
981
982
983
984
985
986
987
	/*
	 * Use bp-legacy attachment template part for older bp-default themes or if in
	 * admin area.
	 */
	if ( ! bp_use_theme_compat_with_current_theme() || ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) ) {
		$current = bp_get_theme_compat_id();
		if ( 'legacy' !== $current ) {
			$switched = true;
			bp_setup_theme_compat( 'legacy' );
ale's avatar
ale committed
988
		}
lucha's avatar
lucha committed
989
	}
ale's avatar
ale committed
990

lucha's avatar
lucha committed
991
992
	// Load the template part.
	bp_get_template_part( 'assets/_attachments/' . $slug );
ale's avatar
ale committed
993

lucha's avatar
lucha committed
994
995
	if ( $switched ) {
		bp_setup_theme_compat( $current );
ale's avatar
ale committed
996
997
	}
}
lechuck's avatar
lechuck committed
998
999
1000
1001
1002
1003
1004
1005
1006

/** Cover Image ***************************************************************/

/**
 * Get the cover image settings
 *
 * @since 2.4.0
 *
 * @param string $component The component to get the settings for ("xprofile" for user or "groups").
lucha's avatar
lucha committed
1007
 * @return false|array The cover image settings in array, false on failure.
lechuck's avatar
lechuck committed
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
 */
function bp_attachments_get_cover_image_settings( $component = 'xprofile' ) {
	// Default parameters.
	$args = array();

	// First look in BP Theme Compat.
	$cover_image = bp_get_theme_compat_feature( 'cover_image' );

	if ( ! empty( $cover_image ) ) {
		$args = (array) $cover_image;
	}

	/**
	 * Then let people override/set the feature using this dynamic filter
	 *
	 * Eg: for the user's profile cover image use:
	 * add_filter( 'bp_before_xprofile_cover_image_settings_parse_args', 'your_filter', 10, 1 );
	 *
lucha's avatar
lucha committed
1026
	 * @since 2.4.0
lechuck's avatar
lechuck committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
	 *
	 * @param array $settings The cover image settings
	 */
	$settings = bp_parse_args( $args, array(
		'components'    => array(),
		'width'         => 1300,
		'height'        => 225,
		'callback'      => '',
		'theme_handle'  => '',
		'default_cover' => '',
	), $component . '_cover_image_settings' );

	if ( empty( $settings['components'] ) || empty( $settings['callback'] ) || empty( $settings['theme_handle'] ) ) {
		return false;
	}

	// Current component is not supported.
	if ( ! in_array( $component, $settings['components'] ) ) {
		return false;
	}

	// Finally return the settings.
	return $settings;
}

/**
lucha's avatar
lucha committed
1053
 * Get cover image Width and Height.
lechuck's avatar
lechuck committed
1054
1055
1056
1057
 *
 * @since 2.4.0
 *
 * @param string $component The BuddyPress component concerned ("xprofile" for user or "groups").
lucha's avatar
lucha committed
1058
 * @return array|bool An associative array containing the advised width and height for the cover image. False if settings are empty.
lechuck's avatar
lechuck committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
 */
function bp_attachments_get_cover_image_dimensions( $component = 'xprofile' ) {
	// Let's prevent notices when setting the warning strings.
	$default = array( 'width' => 0, 'height' => 0 );

	$settings = bp_attachments_get_cover_image_settings( $component );

	if ( empty( $settings ) ) {
		return false;
	}

	// Get width and height.
	$wh = array_intersect_key( $settings, $default );

	/**
	 * Filter here to edit the cover image dimensions if needed.
	 *
	 * @since 2.4.0
	 *
	 * @param array  $wh       An associative array containing the width and height values.
	 * @param array  $settings An associative array containing all the feature settings.
	 * @param string $compnent The requested component.
	 */
	return apply_filters( 'bp_attachments_get_cover_image_dimensions', $wh, $settings, $component );
}

/**
 * Are we on a page to edit a cover image?
 *
 * @since 2.4.0
 *
 * @return bool True if on a page to edit a cover image, false otherwise.
 */
function bp_attachments_cover_image_is_edit() {
	$retval = false;

	$current_component = bp_current_component();
lucha's avatar
lucha committed
1096
	if ( bp_is_active( 'xprofile' ) && bp_is_current_component( 'xprofile' ) ) {
lechuck's avatar
lechuck committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
		$current_component = 'xprofile';
	}

	if ( ! bp_is_active( $current_component, 'cover_image' ) ) {
		return $retval;
	}

	if ( bp_is_user_change_cover_image() ) {
		$retval = ! bp_disable_cover_image_uploads();
	}

	if ( ( bp_is_group_admin_page() && 'group-cover-image' == bp_get_group_current_admin_tab() )
		|| ( bp_is_group_create() && bp_is_group_creation_step( 'group-cover-image' ) ) ) {
		$retval = ! bp_disable_group_cover_image_uploads();
	}

	return apply_filters( 'bp_attachments_cover_image_is_edit', $retval, $current_component );
}

/**
 * Does the user has a cover image?
 *
 * @since 2.4.0
 *
 * @param int $user_id User ID to retrieve cover image for.
 * @return bool True if the user has a cover image, false otherwise.
 */
function bp_attachments_get_user_has_cover_image( $user_id = 0 ) {
	if ( empty( $user_id ) ) {
		$user_id = bp_displayed_user_id();
	}

	$cover_src = bp_attachments_get_attachment( 'url', array(
		'item_id'   => $user_id,
	) );

	return (bool) apply_filters( 'bp_attachments_get_user_has_cover_image', $cover_src, $user_id );
}

/**
 * Does the group has a cover image?
 *
 * @since 2.4.0
 *
 * @param int $group_id Group ID to check cover image existence for.
 * @return bool True if the group has a cover image, false otherwise.
 */
function bp_attachments_get_group_has_cover_image( $group_id = 0 ) {
	if ( empty( $group_id ) ) {
		$group_id = bp_get_current_group_id();
	}

	$cover_src = bp_attachments_get_attachment( 'url', array(
		'object_dir' => 'groups',
		'item_id'    => $group_id,
	) );

	return (bool) apply_filters( 'bp_attachments_get_user_has_cover_image', $cover_src, $group_id );
}

/**
 * Generate the cover image file.
 *
 * @since 2.4.0
 *
 * @param array                          $args {
 *     @type string $file            The absolute path to the image. Required.
 *     @type string $component       The component for the object (eg: groups, xprofile). Required.
 *     @type string $cover_image_dir The Cover image dir to write the image into. Required.
 * }
 * @param BP_Attachment_Cover_Image|null $cover_image_class The class to use to fit the cover image.
lucha's avatar
lucha committed
1168
 * @return false|array An array containing cover image data on success, false otherwise.
lechuck's avatar
lechuck committed
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
 */
function bp_attachments_cover_image_generate_file( $args = array(), $cover_image_class = null ) {
	// Bail if an argument is missing.
	if ( empty( $args['file'] ) || empty( $args['component'] ) || empty( $args['cover_image_dir'] ) ) {
		return false;
	}

	// Get advised dimensions for the cover image.
	$dimensions = bp_attachments_get_cover_image_dimensions( $args['component'] );

	// No dimensions or the file does not match with the cover image dir, stop!
	if ( false === $dimensions || $args['file'] !== $args['cover_image_dir'] . '/' . wp_basename( $args['file'] ) ) {
		return false;
	}

	if ( ! is_a( $cover_image_class, 'BP_Attachment_Cover_Image' ) ) {
		$cover_image_class = new BP_Attachment_Cover_Image();
	}

lucha's avatar
lucha committed
1188
1189
	$upload_dir = bp_attachments_cover_image_upload_dir();

lechuck's avatar
lechuck committed
1190
	// Make sure the file is inside the Cover Image Upload path.
lucha's avatar
lucha committed
1191
	if ( false === strpos( $args['file'], $upload_dir['basedir'] ) ) {
lechuck's avatar
lechuck committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
		return false;
	}

	// Resize the image so that it fit with the cover image dimensions.
	$cover_image  = $cover_image_class->fit( $args['file'], $dimensions );
	$is_too_small = false;

	// Image is too small in width and height.
	if ( empty( $cover_image ) ) {
		$cover_file = $cover_image_class->generate_filename( $args['file'] );
		@rename( $args['file'], $cover_file );

		// It's too small!
		$is_too_small = true;
	} elseif ( ! empty( $cover_image['path'] ) ) {
		$cover_file = $cover_image['path'];

		// Image is too small in width or height.
		if ( $cover_image['width'] < $dimensions['width'] || $cover_image['height'] < $dimensions['height'] ) {
			$is_too_small = true;
		}
	}

	// We were not able to generate the cover image file.
	if ( empty( $cover_file ) ) {
		return false;
	}

	// Do some clean up with old cover image, now a new one is set.
	$cover_basename = wp_basename( $cover_file );

	if ( $att_dir = opendir( $args['cover_image_dir'] ) ) {
		while ( false !== ( $attachment_file = readdir( $att_dir ) ) ) {
			// Skip directories and the new cover image.
			if ( 2 < strlen( $attachment_file ) && 0 !== strpos( $attachment_file, '.' ) && $cover_basename !== $attachment_file ) {
				@unlink( $args['cover_image_dir'] . '/' . $attachment_file );
			}
		}
	}

	// Finally return needed data.
	return array(
		'cover_file'     => $cover_file,
		'cover_basename' => $cover_basename,
		'is_too_small'   => $is_too_small
	);
}

/**
 * Ajax Upload and set a cover image
 *
 * @since 2.4.0
 *
lucha's avatar
lucha committed
1245
 * @return string|null A json object containing success data if the upload succeeded,
lechuck's avatar
lechuck committed
1246
1247
1248
 *                     error message otherwise.
 */
function bp_attachments_cover_image_ajax_upload() {
lucha's avatar
lucha committed
1249
	if ( ! bp_is_post_request() ) {
lechuck's avatar
lechuck committed
1250
1251
1252
1253
1254
		wp_die();
	}

	check_admin_referer( 'bp-uploader' );

lucha's avatar
lucha committed
1255
1256
	// Sending the json response will be different if the current Plupload runtime is html4.
	$is_html4 = ! empty( $_POST['html4' ] );
lechuck's avatar
lechuck committed
1257

lucha's avatar
lucha committed
1258
	if ( empty( $_POST['bp_params'] ) ) {
lechuck's avatar
lechuck committed
1259
1260
1261
		bp_attachments_json_response( false, $is_html4 );
	}

lucha's avatar
lucha committed
1262
1263
1264
1265
1266
1267
1268
1269
	$bp_params = bp_parse_args( $_POST['bp_params'], array(
		'object'  => 'user',
		'item_id' => bp_loggedin_user_id(),
	), 'attachments_cover_image_ajax_upload' );

	$bp_params['item_id'] = (int) $bp_params['item_id'];
	$bp_params['object']  = sanitize_text_field( $bp_params['object'] );

lechuck's avatar
lechuck committed
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
	// We need the object to set the uploads dir filter.
	if ( empty( $bp_params['object'] ) ) {
		bp_attachments_json_response( false, $is_html4 );
	}

	// Capability check.
	if ( ! bp_attachments_current_user_can( 'edit_cover_image', $bp_params ) ) {
		bp_attachments_json_response( false, $is_html4 );
	}

	$bp          = buddypress();
	$needs_reset = array();

	// Member's cover image.
	if ( 'user' === $bp_params['object'] ) {
		$object_data = array( 'dir' => 'members', 'component' => 'xprofile' );

		if ( ! bp_displayed_user_id() && ! empty( $bp_params['item_id'] ) ) {
			$needs_reset = array( 'key' => 'displayed_user', 'value' => $bp->displayed_user );
			$bp->displayed_user->id = $bp_params['item_id'];
		}

	// Group's cover image.
	} elseif ( 'group' === $bp_params['object'] ) {
		$object_data = array( 'dir' => 'groups', 'component' => 'groups' );

		if ( ! bp_get_current_group_id() && ! empty( $bp_params['item_id'] ) ) {
			$needs_reset = array( 'component' => 'groups', 'key' => 'current_group', 'value' => $bp->groups->current_group );
lucha's avatar
lucha committed
1298
			$bp->groups->current_group = groups_get_group( $bp_params['item_id'] );
lechuck's avatar
lechuck committed
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
		}

	// Other object's cover image.
	} else {
		$object_data = apply_filters( 'bp_attachments_cover_image_object_dir', array(), $bp_params['object'] );
	}

	// Stop here in case of a missing parameter for the object.
	if ( empty( $object_data['dir'] ) || empty( $object_data['component'] ) ) {
		bp_attachments_json_response( false, $is_html4 );
	}

	/**
	 * Filters whether or not to handle cover image uploading.
	 *
	 * If you want to override this function, make sure you return an array with the 'result' key set.
	 *
	 * @since 2.5.1
	 *
	 * @param array $value
	 * @param array $bp_params
	 * @param array $needs_reset Stores original value of certain globals we need to revert to later.
	 * @param array $object_data
	 */
	$pre_filter = apply_filters( 'bp_attachments_pre_cover_image_ajax_upload', array(), $bp_params, $needs_reset, $object_data );
	if ( isset( $pre_filter['result'] ) ) {
		bp_attachments_json_response( $pre_filter['result'], $is_html4, $pre_filter );
	}

	$cover_image_attachment = new BP_Attachment_Cover_Image();
	$uploaded = $cover_image_attachment->upload( $_FILES );

	// Reset objects.
	if ( ! empty( $needs_reset ) ) {
		if ( ! empty( $needs_reset['component'] ) ) {
			$bp->{$needs_reset['component']}->{$needs_reset['key']} = $needs_reset['value'];
		} else {
			$bp->{$needs_reset['key']} = $needs_reset['value'];
		}
	}

	if ( ! empty( $uploaded['error'] ) ) {
		// Upload error response.
		bp_attachments_json_response( false, $is_html4, array(
			'type'    => 'upload_error',
			'message' => sprintf( __( 'Upload Failed! Error was: %s', 'buddypress' ), $uploaded['error'] ),
		) );
	}

	$error_message = __( 'There was a problem uploading the cover image.', 'buddypress' );

lucha's avatar
lucha committed
1350
	$bp_attachments_uploads_dir = bp_attachments_cover_image_upload_dir();
lechuck's avatar
lechuck committed
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362

	// The BP Attachments Uploads Dir is not set, stop.
	if ( ! $bp_attachments_uploads_dir ) {
		bp_attachments_json_response( false, $is_html4, array(
			'type'    => 'upload_error',
			'message' => $error_message,
		) );
	}

	$cover_subdir = $object_data['dir'] . '/' . $bp_params['item_id'] . '/cover-image';
	$cover_dir    = trailingslashit( $bp_attachments_uploads_dir['basedir'] ) . $cover_subdir;

lucha's avatar
lucha committed
1363
	if ( 1 === validate_file( $cover_dir ) || ! is_dir( $cover_dir ) ) {
lechuck's avatar
lechuck committed
1364
1365
1366
1367
1368
1369
1370
		// Upload error response.
		bp_attachments_json_response( false, $is_html4, array(
			'type'    => 'upload_error',
			'message' => $error_message,
		) );
	}

lucha's avatar
lucha committed
1371
	/*
lechuck's avatar
lechuck committed
1372
1373
	 * Generate the cover image so that it fit to feature's dimensions
	 *
lucha's avatar
lucha committed
1374
	 * Unlike the avatar, uploading and generating the cover image is happening during
lechuck's avatar
lechuck committed
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
	 * the same Ajax request, as we already instantiated the BP_Attachment_Cover_Image
	 * class, let's use it.
	 */
	$cover = bp_attachments_cover_image_generate_file( array(
		'file'            => $uploaded['file'],
		'component'       => $object_data['component'],
		'cover_image_dir' => $cover_dir
	), $cover_image_attachment );

	if ( ! $cover ) {
		bp_attachments_json_response( false, $is_html4, array(
			'type'    => 'upload_error',
			'message' => $error_message,
		) );
	}

	$cover_url = trailingslashit( $bp_attachments_uploads_dir['baseurl'] ) . $cover_subdir . '/' . $cover['cover_basename'];

lucha's avatar
lucha committed
1393
	// 1 is success.
lechuck's avatar
lechuck committed
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
	$feedback_code = 1;

	// 0 is the size warning.
	if ( $cover['is_too_small'] ) {
		$feedback_code = 0;
	}

	// Set the name of the file.
	$name = $_FILES['file']['name'];
	$name_parts = pathinfo( $name );
	$name = trim( substr( $name, 0, - ( 1 + strlen( $name_parts['extension'] ) ) ) );

	/**
	 * Fires if the new cover image was successfully uploaded.
	 *
	 * The dynamic portion of the hook will be xprofile in case of a user's
	 * cover image, groups in case of a group's cover image. For instance:
	 * Use add_action( 'xprofile_cover_image_uploaded' ) to run your specific
	 * code once the user has set his cover image.
	 *
	 * @since 2.4.0
lucha's avatar
lucha committed
1415
	 * @since 3.0.0 Added $cover_url, $name, $feedback_code arguments.
lechuck's avatar
lechuck committed
1416
	 *
lucha's avatar
lucha committed
1417
1418
1419
1420
	 * @param int    $item_id       Inform about the item id the cover image was set for.
	 * @param string $name          Filename.
	 * @param string $cover_url     URL to the image.
	 * @param int    $feedback_code If value not 1, an error occured.
lechuck's avatar
lechuck committed
1421
	 */
lucha's avatar
lucha committed
1422
1423
1424
1425
1426
1427
1428
	do_action(
		$object_data['component'] . '_cover_image_uploaded',
		(int) $bp_params['item_id'],
		$name,
		$cover_url,
		$feedback_code
	);
lechuck's avatar
lechuck committed
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447

	// Finally return the cover image url to the UI.
	bp_attachments_json_response( true, $is_html4, array(
		'name'          => $name,
		'url'           => $cover_url,
		'feedback_code' => $feedback_code,
	) );
}
add_action( 'wp_ajax_bp_cover_image_upload', 'bp_attachments_cover_image_ajax_upload' );

/**
 * Ajax delete a cover image for a given object and item id.
 *
 * @since 2.4.0
 *
 * @return string|null A json object containing success data if the cover image was deleted
 *                     error message otherwise.
 */
function bp_attachments_cover_image_ajax_delete() {
lucha's avatar
lucha committed
1448
	if ( ! bp_is_post_request() ) {
lechuck's avatar
lechuck committed
1449
1450
1451
		wp_send_json_error();
	}

lucha's avatar
lucha committed
1452
	if ( empty( $_POST['object'] ) || empty( $_POST['item_id'] ) ) {
lechuck's avatar
lechuck committed
1453
1454
1455
		wp_send_json_error();
	}

lucha's avatar
lucha committed
1456
1457
1458
1459
	$args = array(
		'object'  => sanitize_text_field( $_POST['object'] ),
		'item_id' => (int) $_POST['item_id'],
	);
lechuck's avatar
lechuck committed
1460

lucha's avatar
lucha committed
1461
1462
1463
	// Check permissions.
	check_admin_referer( 'bp_delete_cover_image', 'nonce' );
	if ( ! bp_attachments_current_user_can( 'edit_cover_image', $args ) ) {
lechuck's avatar
lechuck committed
1464
1465
1466
1467
		wp_send_json_error();
	}

	// Set object for the user's case.
lucha's avatar
lucha committed
1468
	if ( 'user' === $args['object'] ) {
lechuck's avatar
lechuck committed
1469
1470
1471
1472
1473
		$component = 'xprofile';
		$dir       = 'members';

	// Set it for any other cases.
	} else {
lucha's avatar
lucha committed
1474
		$component = $args['object'] . 's';
lechuck's avatar
lechuck committed
1475
1476
1477
1478
		$dir       = $component;
	}

	// Handle delete.
lucha's avatar
lucha committed
1479
	if ( bp_attachments_delete_file( array( 'item_id' => $args['item_id'], 'object_dir' => $dir, 'type' => 'cover-image' ) ) ) {
lucha's avatar
lucha committed
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
		/**
		 * Fires if the cover image was successfully deleted.
		 *
		 * The dynamic portion of the hook will be xprofile in case of a user's
		 * cover image, groups in case of a group's cover image. For instance:
		 * Use add_action( 'xprofile_cover_image_deleted' ) to run your specific
		 * code once the user has deleted his cover image.
		 *
		 * @since 2.8.0
		 *
		 * @param int $item_id Inform about the item id the cover image was deleted for.
		 */
lucha's avatar
lucha committed
1492
		do_action( "{$component}_cover_image_deleted", (int) $args['item_id'] );
lechuck's avatar
lechuck committed
1493
1494
1495

		$response = array(
			'reset_url'     => '',
lucha's avatar
lucha committed
1496
			'feedback_code' => 3,
lechuck's avatar
lechuck committed
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
		);

		// Get cover image settings in case there's a default header.
		$cover_params = bp_attachments_get_cover_image_settings( $component );

		// Check if there's a default cover.
		if ( ! empty( $cover_params['default_cover'] ) ) {
			$response['reset_url'] = $cover_params['default_cover'];
		}

		wp_send_json_success( $response );

	} else {
		wp_send_json_error( array(
			'feedback_code' => 2,
		) );
	}
}
add_action( 'wp_ajax_bp_cover_image_delete', 'bp_attachments_cover_image_ajax_delete' );