folderRootId = (int) $root_id;
add_action('init', array($this, 'includes'));
add_action('admin_init', array($this, 'adminRedirects'));
add_action('admin_init', array($this, 'disableTranslateTaxonomyWPML'));
if (!get_option('wpmf_update_count', false)) {
add_action('admin_init', array($this, 'updateCountTerm'));
}
if (!get_option('_wpmf_import_size_notice_flag', false)) {
add_action('admin_notices', array($this, 'showNoticeImportSize'), 3);
}
if (is_plugin_active('nextgen-gallery/nggallery.php')) {
if (!get_option('wpmf_import_nextgen_gallery', false)) {
add_action('admin_notices', array($this, 'showNoticeImportGallery'), 3);
}
}
add_action('restrict_manage_posts', array($this, 'addImageCategoryFilter'));
add_action('pre_get_posts', array($this, 'preGetPosts1'));
add_action('admin_enqueue_scripts', array($this, 'adminPageTableScript'));
add_action('enqueue_block_editor_assets', array($this, 'addEditorAssets'));
add_action('wp_enqueue_media', array($this, 'mediaPageTableScript'));
add_action('pre_get_posts', array($this, 'preGetPosts'), 0, 1);
add_filter('add_attachment', array($this, 'afterUpload'), 0, 1);
add_filter('media_send_to_editor', array($this, 'addRemoteVideo'), 10, 3);
add_filter('upload_mimes', array($this, 'allowMimeTypes'));
add_filter('wp_check_filetype_and_ext', array($this, 'avifUploadCheck'), 10, 4);
add_filter('wp_check_filetype_and_ext', array($this, 'svgsUploadCheck'), 10, 4);
add_filter('wp_check_filetype_and_ext', array($this, 'svgsAllowSvgUpload'), 10, 4);
add_filter('wp_prepare_attachment_for_js', array($this, 'svgsResponseForSvg'), 10, 3);
add_filter('wp_prepare_attachment_for_js', array($this, 'prepareAttachmentForJs'), 10, 3);
add_action('admin_footer', array($this, 'editorFooter'));
$format_mediatitle = 1;
$settings = get_option('wpmf_settings');
if (isset($settings) && isset($settings['format_mediatitle'])) {
$format_mediatitle = $settings['format_mediatitle'];
}
if ((int) $format_mediatitle === 1) {
add_action('add_attachment', array($this, 'updateFileTitle'));
}
add_filter('attachment_fields_to_edit', array($this, 'attachmentFieldsToEdit'), 10, 2);
add_filter('attachment_fields_to_save', array($this, 'attachmentFieldsToSave'), 10, 2);
add_action('wpml_media_create_duplicate_attachment', array($this, 'mediaSetFilesToFolderWpml'), 10, 2);
add_action('wpml_added_media_file_translation', array($this, 'wpmlAddedMediaFileTranslation'), 10, 3);
add_action('wpml_after_copy_attached_file_postmeta', array($this, 'wpmlAfterCopyAttachedFilePostmeta'), 10, 2);
add_action('pll_translate_media', array($this, 'pllTranslateMedia'), 10, 3);
add_action('wp_ajax_wpmf', array($this, 'startProcess'));
add_action('wp_ajax_wpmf_upload_folder', array($this, 'uploadFolder'));
add_filter('wpmf_syncMediaExternal', array($this, 'syncMediaExternal'), 10, 2);
add_action('delete_attachment', array($this, 'deleteAttachment'), 10);
add_action('wpmf_create_folder', array($this, 'afterCreateFolder'), 10, 4);
if (version_compare($wp_version, '5.8', '>=')) {
add_filter('block_categories_all', array($this, 'addBlockCategories'), 10, 2);
} else {
add_filter('block_categories', array($this, 'addBlockCategories'), 10, 2);
}
add_filter('wp_generate_attachment_metadata', array($this, 'wpUpdateAttachmentIptc'), 10, 2);
add_filter('wp_handle_upload', array($this, 'handleUpload'), 10, 1);
add_filter('pre_delete_attachment', array($this, 'preDeleteAttachment'), 10, 3);
add_action('check_ajax_referer', array($this, 'disableSaveAjax'), 10, 2);
add_filter('wp_insert_post_empty_content', array($this, 'disableSave'), 999999, 2);
add_action('pre-upload-ui', array( $this, 'selectFolderUpload'));
add_filter('add_attachment', array($this, 'moveFileUploadToSelectFolder'), 0, 1);
add_filter('bulk_actions-upload', array($this, 'registerTagBulkAction'), 10, 1);
add_action('wp_enqueue_media', array($this, 'removeDatabaseWhenCloudDisconnected'));
add_action('pre_get_posts', array($this, 'addTagFilter'), 10, 1);
add_filter('attachment_fields_to_edit', array($this, 'changeTagSlugToName'), 10, 2);
add_filter('attachment_fields_to_edit', array($this, 'addTagHelps'), 10, 2);
add_action('pre_delete_attachment', array($this, 'deleteAttachmentCloud'), 11, 2);
}
/**
* Fires once the Ajax request has been validated or not.
*
* @param string $action The Ajax nonce action.
* @param false|integer $result False if the nonce is invalid, 1 if the nonce is valid and generated between
* 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
*
* @return void
*/
public function disableSaveAjax($action, $result)
{
if (strpos($action, 'update-post_') !== false) {
$pid = str_replace('update-post_', '', $action);
$attachment = get_post((int)$pid);
if (!is_wp_error($attachment) && !empty($attachment) && $attachment->post_type === 'attachment') {
$active_media = get_option('wpmf_active_media');
if (!empty($active_media)) {
$user_id = get_current_user_id();
$terms = get_the_terms((int)$pid, WPMF_TAXO);
$check = null;
foreach ($terms as $term) {
$is_access = WpmfHelper::getAccess($term->term_id, $user_id, 'update_media');
if (!$is_access) {
$check = 'not_permission';
break;
}
}
if ($check === 'not_permission') {
wp_die(esc_html__('You do not have permission to update this attachment', 'wpmf'));
}
}
}
}
}
/**
* Filters whether the post should be considered "empty".
*
* @param boolean $maybe_empty Whether the post should be considered "empty".
* @param array $postarr Array of post data.
*
* @return boolean
*/
public function disableSave($maybe_empty, $postarr)
{
$active_media = get_option('wpmf_active_media');
if (empty($active_media)) {
return $maybe_empty;
}
$user_id = get_current_user_id();
$terms = get_the_terms($postarr['ID'], WPMF_TAXO);
if (empty($terms)) {
return $maybe_empty;
}
$check = null;
foreach ($terms as $term) {
$is_access = WpmfHelper::getAccess($term->term_id, $user_id, 'update_media');
if (!$is_access) {
$check = 'not_permission';
break;
}
}
if ($check === 'not_permission') {
wp_die(esc_html__('You do not have permission to update this attachment', 'wpmf'));
}
return $maybe_empty;
}
/**
* Filters whether an attachment deletion should take place.
*
* @param boolean|null $delete Whether to go forward with deletion.
* @param WP_Post $post Post object.
* @param boolean $force_delete Whether to bypass the Trash.
*
* @return boolean|null
*/
public function preDeleteAttachment($delete, $post, $force_delete)
{
$active_media = get_option('wpmf_active_media');
if (empty($active_media)) {
return $delete;
}
$user_id = get_current_user_id();
$terms = get_the_terms($post->ID, WPMF_TAXO);
if (empty($terms)) {
return $delete;
}
$check = null;
foreach ($terms as $term) {
$is_access = WpmfHelper::getAccess($term->term_id, $user_id, 'remove_media');
if (!$is_access) {
$check = true;
break;
}
}
if (null !== $check) {
wp_die(esc_html__('You do not have permission to delete this attachment', 'wpmf'));
}
return $delete;
}
/**
* Handler upload
*
* @param array $data Attachment data
*
* @return mixed
*/
public function handleUpload($data)
{
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
if (isset($_REQUEST['wpmf_folder'])) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- No action, nonce is not required
$parent = $this->getFolderParent($_POST['wpmf_folder'], $_POST['wpmf_folder']);
$user_id = get_current_user_id();
$is_access = WpmfHelper::getAccess($parent, $user_id, 'add_media');
if (!$is_access) {
$data['error'] = esc_html__('You not have a permission to upload the file to this folder!', 'wpmf');
}
}
return $data;
}
/**
* Update attachment metadata
*
* @param array $data Meta data
* @param integer $post_id Attachment ID
*
* @return array
*/
public function wpUpdateAttachmentIptc($data, $post_id)
{
if (is_null($data)) {
$data = wp_get_attachment_metadata($post_id, true);
}
$import_iptc_meta = wpmfGetOption('import_iptc_meta');
if ((int)$import_iptc_meta === 1) {
$attachment = get_post($post_id);
if (strpos($attachment->post_mime_type, 'image') !== false) {
$iptc_fields = wpmfGetOption('iptc_fields');
$filepath = get_attached_file($post_id);
$title = '';
$caption = '';
if (!empty($data['image_meta']['title']) && !empty($iptc_fields['title'])) {
$title = $data['image_meta']['title'];
}
if (!empty($data['image_meta']['caption']) && !empty($iptc_fields['caption'])) {
$caption = $data['image_meta']['caption'];
}
global $wpdb;
// update post
$field = array();
if ($title !== '') {
$field['post_title'] = $title;
}
if ($caption !== '') {
$field['post_excerpt'] = $caption;
}
// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Ignore warning php if can't read data
$exif = @exif_read_data($filepath);
if (!empty($exif['ImageDescription']) && $exif['ImageDescription'] !== null && !empty($iptc_fields['description'])) {
$field['post_content'] = $exif['ImageDescription'];
$format[] = '%s';
}
if (!empty($field)) {
$wpdb->update(
$wpdb->posts,
$field,
array('ID' => $post_id)
);
}
WpmfHelper::saveIptcMetadata($import_iptc_meta, $post_id, $filepath, $iptc_fields, $title, $attachment->post_mime_type);
}
}
return $data;
}
/**
* Check cloud media
*
* @param array $response Array of prepared attachment data.
* @param integer|object $attachment Attachment ID or object.
* @param array $meta Array of attachment meta data.
*
* @return mixed $response
*/
public function prepareAttachmentForJs($response, $attachment, $meta)
{
$drive_meta = get_post_meta($attachment->ID, 'wpmf_drive_id', true);
if (!empty($drive_meta)) {
$response['cloud_media'] = 1;
} else {
$response['cloud_media'] = 0;
}
$remote_video = get_post_meta($attachment->ID, 'wpmf_remote_video_link', true);
if (!empty($remote_video)) {
$response['is_video'] = 1;
$response['video_url'] = $remote_video;
} else {
$response['is_video'] = 0;
$response['video_url'] = '';
}
return $response;
}
/**
* Add blocks category
*
* @param array $categories List of current blocks categories
* @param object $post Current post
*
* @return array New array include our category
*/
public function addBlockCategories($categories, $post)
{
$newcats = array(
array(
'slug' => 'wp-media-folder',
'title' => esc_html__('WP Media Folder', 'wpmf')
)
);
return array_merge($categories, $newcats);
}
/**
* Update count files in a folder
*
* @return void
*/
public function updateCountTerm()
{
global $wpdb;
$terms = get_categories(
array(
'hide_empty' => false,
'taxonomy' => WPMF_TAXO,
'fields' => 'ids'
)
);
foreach ((array) $terms as $term) {
$count = (int) $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM ' . $wpdb->term_relationships . ' t, ' . $wpdb->posts . ' p1 WHERE p1.ID = t.object_id AND ( post_status = %s OR post_status = %s) AND post_type = %s AND term_taxonomy_id = %d', array('publish','inherit','attachment',$term)));
$wpdb->update($wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => (int) $term));
}
update_option('wpmf_update_count', 1);
}
/**
* Delete attachment
*
* @param integer $pid Attachment ID
*
* @return void
*/
public function deleteAttachment($pid)
{
$file_path = get_attached_file($pid);
if (!file_exists($file_path)) {
return;
}
$origin_infos = pathinfo($file_path);
$origin_name = $origin_infos['filename'] . 'imageswatermark.' . $origin_infos['extension'];
$paths = array(
'origin' => str_replace(wp_basename($file_path), $origin_name, $file_path)
);
$metas = get_post_meta($pid, '_wp_attachment_metadata', true);
if (isset($metas['sizes'])) {
foreach ($metas['sizes'] as $size => $file) {
$infos = pathinfo($file['file']);
if (!empty($infos['extension'])) {
$filewater = $infos['filename'] . 'imageswatermark.' . $infos['extension'];
$paths[$size] = str_replace(wp_basename($file_path), $filewater, $file_path);
}
}
}
foreach ($paths as $path) {
if (!realpath($path)) {
continue;
}
if (file_exists($path) && is_writable($path)) {
unlink($path);
}
}
}
/**
* Disable translate taxonomy WPML
*
* @return void
*/
public function disableTranslateTaxonomyWPML()
{
if (defined('ICL_SITEPRESS_VERSION') && ICL_SITEPRESS_VERSION) {
global $iclTranslationManagement;
if (isset($iclTranslationManagement->settings['taxonomies_readonly_config']) && is_array($iclTranslationManagement->settings['taxonomies_readonly_config'])) {
$iclTranslationManagement->settings['taxonomies_readonly_config'][ 'wpmf-category' ] = 1;
$iclTranslationManagement->settings['taxonomies_readonly_config'][ 'wpmf-gallery-category' ] = 1;
}
}
}
/**
* Handle redirects to setup/welcome page after install and updates.
*
* For setup wizard, transient must be present, the user must have access rights, and we must ignore the network/bulk plugin updaters.
*
* @return void
*/
public function adminRedirects()
{
//global $sitepress;
//var_dump($sitepress->is_translated_taxonomy(WPMF_TAXO));
// Disable all admin notice for page belong to plugin
add_action('admin_print_scripts', function () {
global $wp_filter;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
if ((!empty($_GET['page']) && in_array($_GET['page'], array('wpmf-setup', 'option-folder')))) {
if (is_user_admin()) {
if (isset($wp_filter['user_admin_notices'])) {
unset($wp_filter['user_admin_notices']);
}
} elseif (isset($wp_filter['admin_notices'])) {
unset($wp_filter['admin_notices']);
}
if (isset($wp_filter['all_admin_notices'])) {
unset($wp_filter['all_admin_notices']);
}
}
});
// Setup wizard redirect
if (is_null(get_option('_wpmf_activation_redirect', null)) && is_null(get_option('wpmf_version', null))) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
if ((!empty($_GET['page']) && in_array($_GET['page'], array('wpmf-setup')))) {
return;
}
update_option('_wpmf_activation_redirect', 1);
wp_safe_redirect(admin_url('index.php?page=wpmf-setup'));
exit;
}
}
/**
* Includes WP Media Folder setup
*
* @return void
*/
public function includes()
{
// check user full access
$this->user_full_access = WpmfHelper::checkUserFullAccess();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
if (!empty($_GET['page'])) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
switch ($_GET['page']) {
case 'wpmf-setup':
require_once WP_MEDIA_FOLDER_PLUGIN_DIR . '/class/install-wizard/install-wizard.php';
break;
}
}
}
/**
* Sync media from media library to server
*
* @param integer $folderID Id folder on media library
* @param integer $attachment_id Id of file
*
* @return mixed
*/
public function syncMediaExternal($folderID = 0, $attachment_id = 0)
{
$lists = get_option('wpmf_list_sync_media');
$folder_ftp = '';
if (isset($lists[$folderID])) {
$folder_ftp = $lists[$folderID]['folder_ftp'];
}
$file_path = get_attached_file($attachment_id);
$filename = pathinfo($file_path);
if (file_exists($file_path) && file_exists($folder_ftp)) {
copy($file_path, $folder_ftp . '/' . $filename['basename']);
}
return $folderID;
}
/**
* Run ajax
*
* @return void
*/
public function startProcess()
{
if (empty($_REQUEST['wpmf_nonce'])
|| !wp_verify_nonce($_REQUEST['wpmf_nonce'], 'wpmf_nonce')) {
die();
}
if (isset($_REQUEST['task'])) {
switch ($_REQUEST['task']) {
case 'reload_folder_tree':
$this->reloadFolderTree();
break;
case 'import':
$this->importCategories();
break;
case 'add_folder':
$this->addFolder();
break;
case 'edit_folder':
$this->editFolder();
break;
case 'delete_folder':
$this->deleteFolder();
break;
case 'delete_multiple_folders':
$this->deleteMultipleFolders();
break;
case 'download_folder':
$this->downloadFolder();
break;
case 'move_file':
$this->moveFile();
break;
case 'move_folder':
$this->moveFolder();
break;
case 'get_terms':
$this->getTerms();
break;
case 'get_assign_tree':
$this->getAssignTree();
break;
case 'gallery_get_image':
$this->galleryGetImage();
break;
case 'set_object_term':
$this->setObjectTerm();
break;
case 'create_remote_video':
$this->createRemoteVideo();
break;
case 'get_user_media_tree':
$this->getUserMediaTree();
break;
case 'set_folder_color':
$this->setFolderColor();
break;
case 'delete_file':
$this->deleteFile();
break;
case 'reorderfile':
$this->reorderFile();
break;
case 'reorderfolder':
$this->reorderfolder();
break;
case 'import_order':
$this->importOrder();
break;
case 'update_link':
$this->updateLink();
break;
case 'getcountfiles':
$this->getCountFilesInFolder();
break;
case 'get_folder_permissions':
$this->getFolderPermissions();
break;
case 'save_folder_permissions':
$this->saveFolderPermissions();
break;
case 'auto_load_video_thumbnail':
$this->autoLoadVideoThumbnail();
break;
case 'check_local_to_cloud':
$this->checkLocalToCloud();
break;
case 'wpmf_download_file':
$this->wpmfDownloadFile();
break;
case 'get_tag_item':
$this->getTagItem();
break;
case 'save_tag_item':
$this->saveTagItem();
break;
}
}
}
/**
* Auto load video thumbnail
*
* @return void
*/
public function autoLoadVideoThumbnail()
{
if (empty($_POST['wpmf_nonce'])
|| !wp_verify_nonce($_POST['wpmf_nonce'], 'wpmf_nonce')) {
die();
}
$thumb_url = '';
$video_url = (isset($_POST['video_url'])) ? $_POST['video_url'] : '';
if (!preg_match(WpmfHelper::$vimeo_pattern, $video_url, $output_array)
&& !preg_match('/(youtube.com|youtu.be)\/(watch)?(\?v=)?(\S+)?/', $video_url, $match)
&& !preg_match('/\b(?:dailymotion)\.com\b/i', $video_url, $vresult)
&& !preg_match('/(videos.kaltura)\.com\b/i', $video_url, $vresult)) {
wp_send_json(array('status' => false));
} elseif (preg_match(WpmfHelper::$vimeo_pattern, $video_url, $output_array)) {
// for vimeo
$id = WpmfHelper::getVimeoVideoIdFromUrl($video_url);
$videos = wp_remote_get('https://player.vimeo.com/video/' . $id . '/config');
$body = json_decode($videos['body']);
if (!empty($body->video->thumbs->base)) {
$thumb_url = $body->video->thumbs->base;
} else {
$videos = wp_remote_get('https://vimeo.com/api/v2/video/' . $id . '.json');
$body = json_decode($videos['body']);
$body = $body[0];
$thumb_url = '';
if (isset($body->thumbnail_large)) {
$thumb_url = $body->thumbnail_large;
} elseif (isset($body->thumbnail_medium)) {
$thumb_url = $body->thumbnail_large;
} elseif (isset($body->thumbnail_small)) {
$thumb_url = $body->thumbnail_small;
}
}
} elseif (preg_match('/(youtube.com|youtu.be)\/(watch)?(\?v=)?(\S+)?/', $video_url, $match)) {
// for youtube
$parts = parse_url($video_url);
if ($parts['host'] === 'youtu.be') {
$id = trim($parts['path'], '/');
} else {
parse_str($parts['query'], $query);
$id = $query['v'];
}
$thumb_url = 'http://img.youtube.com/vi/' . $id . '/maxresdefault.jpg';
$gets = wp_remote_get($thumb_url);
if (!empty($gets) && $gets['response']['code'] !== 200) {
$thumb_url = 'http://img.youtube.com/vi/' . $id . '/sddefault.jpg';
$gets = wp_remote_get($thumb_url);
}
if (!empty($gets) && $gets['response']['code'] !== 200) {
$thumb_url = 'http://img.youtube.com/vi/' . $id . '/hqdefault.jpg';
$gets = wp_remote_get($thumb_url);
}
if (!empty($gets) && $gets['response']['code'] !== 200) {
$thumb_url = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
$gets = wp_remote_get($thumb_url);
}
if (!empty($gets) && $gets['response']['code'] !== 200) {
$thumb_url = 'http://img.youtube.com/vi/' . $id . '/default.jpg';
}
} elseif (preg_match('/\b(?:dailymotion)\.com\b/i', $video_url, $vresult)) {
// for dailymotion
$id = WpmfHelper::getDailymotionVideoIdFromUrl($video_url);
$gets = wp_remote_get('http://www.dailymotion.com/services/oembed?format=json&url=http://www.dailymotion.com/embed/video/' . $id);
$info = json_decode($gets['body'], true);
if (empty($info)) {
wp_send_json(array('status' => false));
}
if (!empty($info['thumbnail_url'])) {
$thumb_url = $info['thumbnail_url'];
}
} elseif (preg_match('/(videos.kaltura)\.com\b/i', $video_url, $vresult)) {
// for kaltura
$id = WpmfHelper::getKalturaVideoIdFromUrl($video_url);
$partner_id = 5944002;
$thumb_url = 'http://cdnsecakmi.kaltura.com/p/' . $partner_id . '/thumbnail/entry_id/' . $id . '/width/2560/height/1920';
}
if (!empty($thumb_url)) {
wp_send_json(array('status' => true, 'thumb_url' => $thumb_url));
}
wp_send_json(array('status' => false));
}
/**
* Fires after attachment post meta is copied
*
* @param integer $original_attachment_id The ID of the source/original attachment.
* @param integer $attachment_id The ID of the duplicated attachment.
*
* @return void
*/
public function wpmlAfterCopyAttachedFilePostmeta($original_attachment_id, $attachment_id)
{
$terms = wp_get_post_terms($original_attachment_id, WPMF_TAXO, array('fields' => 'ids'));
if (!empty($terms)) {
foreach ($terms as $id_term) {
wp_set_object_terms($attachment_id, $id_term, WPMF_TAXO, true);
$this->addSizeFiletype($attachment_id);
}
}
}
/**
* Added media file translation
*
* @param integer $original_attachment_id The ID of the source/original attachment.
* @param string $file Absolute path to file.
* @param string $translated_language_code Attachment language code.
*
* @return void
*/
public function wpmlAddedMediaFileTranslation($original_attachment_id, $file, $translated_language_code)
{
global $sitepress;
$attachment_translations = $sitepress->get_element_translations($original_attachment_id, 'post_attachment', true, true);
if (is_array($attachment_translations)) {
foreach ($attachment_translations as $attachment_translation) {
if ($attachment_translation->language_code === $translated_language_code) {
$terms = wp_get_post_terms($original_attachment_id, WPMF_TAXO, array('fields' => 'ids'));
if (!empty($terms)) {
foreach ($terms as $id_term) {
wp_set_object_terms($attachment_translation->element_id, $id_term, WPMF_TAXO, true);
$this->addSizeFiletype($attachment_translation->element_id);
}
}
}
}
}
}
/**
* Sync folders/files structure in all languages
*
* @param integer $attachment_id ID of media file
* @param integer $duplicated_attachment_id ID of duplicate media file
*
* @return void
*/
public function mediaSetFilesToFolderWpml($attachment_id, $duplicated_attachment_id)
{
$terms = wp_get_post_terms($attachment_id, WPMF_TAXO, array('fields' => 'ids'));
if (!empty($terms)) {
foreach ($terms as $id_term) {
wp_set_object_terms($duplicated_attachment_id, $id_term, WPMF_TAXO, true);
$this->addSizeFiletype($duplicated_attachment_id);
/**
* Set attachment folder after upload with WPML plugin
*
* @param integer Attachment ID
* @param integer Target folder
* @param array Extra informations
*
* @ignore Hook already documented
*/
do_action('wpmf_attachment_set_folder', $duplicated_attachment_id, $id_term, array('trigger' => 'upload'));
}
}
}
/**
* Sync folders/files structure in all languages
*
* @param integer $attachment_id ID of media file
* @param integer $duplicated_attachment_id ID of duplicate media file
* @param string $lang Current language
*
* @return void
*/
public function pllTranslateMedia($attachment_id, $duplicated_attachment_id, $lang)
{
$terms = wp_get_post_terms($attachment_id, WPMF_TAXO, array('fields' => 'ids'));
if (!empty($terms)) {
foreach ($terms as $id_term) {
wp_set_object_terms($duplicated_attachment_id, $id_term, WPMF_TAXO, true);
$this->addSizeFiletype($duplicated_attachment_id);
/**
* Set attachment folder after upload with WPML plugin
*
* @param integer Attachment ID
* @param integer Target folder
* @param array Extra informations
*
* @ignore Hook already documented
*/
do_action('wpmf_attachment_set_folder', $duplicated_attachment_id, $id_term, array('trigger' => 'upload'));
}
}
}
/**
* Filters the attachment data prepared for JavaScript.
* Base on /wp-includes/media.php
*
* @param array $response Array of prepared attachment data.
* @param integer|object $attachment Attachment ID or object.
* @param array $meta Array of attachment meta data.
*
* @return mixed $response
*/
public function svgsResponseForSvg($response, $attachment, $meta)
{
if ($response['mime'] === 'image/svg+xml' && empty($response['sizes'])) {
$svg_path = get_attached_file($attachment->ID);
if (!file_exists($svg_path)) {
// If SVG is external, use the URL instead of the path
$svg_path = $response['url'];
}
if (!file_exists($svg_path)) {
return $response;
}
$dimensions = $this->svgsGetDimensions($svg_path);
$response['sizes'] = array(
'full' => array(
'url' => $response['url'],
'width' => $dimensions->width,
'height' => $dimensions->height,
'orientation' => $dimensions->width > $dimensions->height ? 'landscape' : 'portrait'
)
);
}
return $response;
}
/**
* Get dimension svg file
*
* @param string $svg Path of svg
*
* @return object width and height
*/
public function svgsGetDimensions($svg)
{
$svg = simplexml_load_file($svg);
if ($svg === false) {
$width = '0';
$height = '0';
} else {
$attributes = $svg->attributes();
$width = (string) $attributes->width;
$height = (string) $attributes->height;
}
return (object) array('width' => $width, 'height' => $height);
}
/**
* Filters list of allowed mime types and file extensions.
*
* @param array $mimes Mime types keyed by the file extension regex corresponding to
* those types. 'swf' and 'exe' removed from full list. 'htm|html' also
* removed depending on '$user' capabilities.
*
* @return array $mimes
*/
public function allowMimeTypes($mimes = array())
{
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
$mimes['xlsm'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$mimes['json'] = 'application/json';
$mimes['avif'] = 'image/avif';
return $mimes;
}
/**
* Filters the "real" file type of the given file.
*
* @param array $checked File data array containing 'ext', 'type', and
* 'proper_filename' keys.
* @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 $mimes Key is the file extension with value as the mime type.
*
* @return array
*/
public function avifUploadCheck($checked, $file, $filename, $mimes)
{
if (!$checked['type']) {
$check_filetype = wp_check_filetype($filename, $mimes);
$ext = $check_filetype['ext'];
$type = $check_filetype['type'];
$proper_filename = $filename;
if ($type && 0 === strpos($type, 'image/') && $ext !== 'avif') {
$ext = false;
$type = false;
}
$checked = compact('ext', 'type', 'proper_filename');
}
return $checked;
}
/**
* Filters the "real" file type of the given file.
*
* @param array $checked File data array containing 'ext', 'type', and
* 'proper_filename' keys.
* @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 $mimes Key is the file extension with value as the mime type.
*
* @return array
*/
public function svgsUploadCheck($checked, $file, $filename, $mimes)
{
if (!$checked['type']) {
$check_filetype = wp_check_filetype($filename, $mimes);
$ext = $check_filetype['ext'];
$type = $check_filetype['type'];
$proper_filename = $filename;
if ($type && 0 === strpos($type, 'image/') && $ext !== 'svg') {
$ext = false;
$type = false;
}
$checked = compact('ext', 'type', 'proper_filename');
}
return $checked;
}
/**
* Mime Check fix for WP 4.7.1 / 4.7.2
*
* @param array $data File data
* @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 $mimes Array of mime types keyed by their file extension regex.
*
* @return array
*/
public function svgsAllowSvgUpload($data, $file, $filename, $mimes)
{
global $wp_version;
if ($wp_version !== '4.7.1' || $wp_version !== '4.7.2') {
return $data;
}
$filetype = wp_check_filetype($filename, $mimes);
return array(
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
);
}
/**
* Ajax get gallery image
*
* @return void
*/
public function galleryGetImage()
{
if (empty($_POST['wpmf_nonce'])
|| !wp_verify_nonce($_POST['wpmf_nonce'], 'wpmf_nonce')) {
die();
}
/**
* Filter check capability of current user when get gallery image
*
* @param boolean The current user has the given capability
* @param string Action name
*
* @return boolean
*
* @ignore Hook already documented
*/
$wpmf_capability = apply_filters('wpmf_user_can', current_user_can('upload_files'), 'gallery_sort_image');
if (!$wpmf_capability) {
wp_send_json(false);
}
if (!empty($_POST['ids']) && isset($_POST['wpmf_orderby']) && isset($_POST['wpmf_order'])) {
$ids = $_POST['ids'];
$wpmf_orderby = $_POST['wpmf_orderby'];
$wpmf_order = $_POST['wpmf_order'];
if ($wpmf_orderby === 'title' || $wpmf_orderby === 'date') {
$wpmf_orderby = 'post_' . $wpmf_orderby;
// query attachment by orderby and order
$args = array(
'posts_per_page' => - 1,
'post_type' => 'attachment',
'post__in' => $ids,
'post_status' => 'any',
'orderby' => $wpmf_orderby,
'order' => $wpmf_order
);
$query = new WP_Query($args);
$posts = $query->get_posts();
wp_send_json($posts);
}
}
wp_send_json(false);
}
/**
* Load styles
*
* @return void
*/
public function loadAssetsMediaUpload()
{
wp_enqueue_style(
'wpmf-style',
plugins_url('/assets/css/style.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_register_script(
'wpmf-base',
plugins_url('/assets/js/script.js', dirname(__FILE__)),
array('jquery', 'plupload'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-base');
wp_register_script(
'wpmf-folder-upload',
plugins_url('/assets/js/folder_upload.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-folder-upload');
wp_register_script(
'wpmf-folder-tree',
plugins_url('/assets/js/folder_tree.js', dirname(__FILE__)),
array('wpmf-base'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-folder-tree');
$params = $this->localizeScript();
wp_localize_script('wpmf-base', 'wpmf', $params);
}
/**
* Load styles
*
* @return void
*/
public function loadAssets()
{
global $typenow, $current_screen;
if (WpmfHelper::isForThisPostType($typenow) && 'edit' === $current_screen->base) {
return;
}
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('jquery-ui-draggable');
wp_enqueue_script('jquery-ui-droppable');
wp_enqueue_style(
'wpmf-material-icon',
plugins_url('/assets/css/google-material-icon.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
if (!get_option('_wpmf_import_order_notice_flag', false)) {
wp_enqueue_script(
'import-custom-order',
plugins_url('assets/js/imports/import_custom_order.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
}
wp_enqueue_style(
'wpmf-jaofiletree',
plugins_url('/assets/css/jaofiletree.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-style',
plugins_url('/assets/css/style.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-mdl',
plugins_url('/assets/css/modal-dialog/mdl-jquery-modal-dialog.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-deep_orange',
plugins_url('/assets/css/modal-dialog/material.deep_orange-amber.min.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-style-tippy',
plugins_url('/assets/js/tippy/tippy.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_script(
'wpmf-material',
plugins_url('/assets/js/modal-dialog/material.min.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
wp_enqueue_script(
'wpmf-mdl',
plugins_url('/assets/js/modal-dialog/mdl-jquery-modal-dialog.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-gallery-popup-style',
plugins_url('/assets/css/display-gallery/magnific-popup.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-tagify-style',
plugins_url('/assets/css/tagify.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_script(
'wpmf-gallery-popup',
plugins_url('/assets/js/display-gallery/jquery.magnific-popup.min.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION,
true
);
global $current_screen;
if (isset($current_screen) && $current_screen->id !== 'forminator_page_forminator-cform-wizard' && $current_screen->id !== 'post') {
wp_enqueue_style(
'wpmfselect2',
plugins_url('/assets/select2/select2.min.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_script(
'wpmfselect2',
plugins_url('/assets/select2/select2.min.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
}
wp_register_script(
'wpmf-tagify',
plugins_url('/assets/js/tagify.js', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_enqueue_script('wpmf-tagify');
wp_enqueue_script('resumable', plugins_url('/assets/js/resumable.js', dirname(__FILE__)), array('jquery'), WPMF_VERSION);
wp_register_script(
'wpmf-base',
plugins_url('/assets/js/script.js', dirname(__FILE__)),
array('jquery', 'plupload'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-base');
wp_enqueue_script(
'wpmf-scrollbar',
plugins_url('/assets/js/scrollbar/jquery.scrollbar.min.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
wp_enqueue_style(
'wpmf-scrollbar',
plugins_url('/assets/js/scrollbar/jquery.scrollbar.css', dirname(__FILE__)),
array(),
WPMF_VERSION
);
wp_register_script(
'wpmf-folder-tree',
plugins_url('/assets/js/folder_tree.js', dirname(__FILE__)),
array('wpmf-base'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-folder-tree');
wp_register_script(
'wpmf-folder-snackbar',
plugins_url('/assets/js/snackbar.js', dirname(__FILE__)),
array('wpmf-base'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-folder-snackbar');
wp_register_script(
'duplicate-image',
plugins_url('assets/js/duplicate-image.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION,
true
);
wp_register_script(
'wpmf-media-filters',
plugins_url('/assets/js/media-filters.js', dirname(__FILE__)),
array('jquery', 'plupload'),
WPMF_VERSION
);
wp_enqueue_script('wpmf-media-filters');
wp_enqueue_script(
'wpmf-tippy-core',
plugins_url('/assets/js/tippy/tippy-core.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
wp_enqueue_script(
'wpmf-tippy',
plugins_url('/assets/js/tippy/tippy.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
$active_media = get_option('wpmf_active_media');
if ((!empty($active_media) && (current_user_can('administrator') || current_user_can('editor'))) || empty($active_media)) {
wp_enqueue_script(
'wpmf-assign-tree',
plugins_url('/assets/js/assign_image_folder_tree.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
}
if (is_plugin_active('wp-media-folder-addon/wp-media-folder-addon.php') && $this->user_full_access) {
wp_enqueue_script(
'wpmf-import-cloud-tree',
plugins_url('/assets/js/imports/import_cloud_tree.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
}
$params = $this->localizeScript();
wp_localize_script('wpmf-base', 'wpmf', $params);
wp_enqueue_script('wplink');
wp_enqueue_style('editor-buttons');
}
/**
* Enqueue styles and scripts for gutenberg
*
* @return void
*/
public function addEditorAssets()
{
wp_enqueue_style(
'wpmf_gallery_blocks',
WPMF_PLUGIN_URL . 'assets/js/blocks/style.css',
array(),
WPMF_VERSION
);
}
/**
* Load style and script
*
* @return void
*/
public function adminPageTableScript()
{
global $pagenow;
/**
* Filter check capability of current user when load assets
*
* @param boolean The current user has the given capability
* @param string Action name
*
* @return boolean
*
* @ignore Hook already documented
*/
$wpmf_capability = apply_filters('wpmf_user_can', current_user_can('upload_files'), 'load_script_style');
if ($wpmf_capability) {
if ($pagenow === 'upload.php' || $pagenow === 'edit-tags.php') {
$mode = get_user_option('media_library_mode', get_current_user_id()) ? get_user_option('media_library_mode', get_current_user_id()) : 'grid';
if ($mode === 'list') {
$this->loadAssets();
}
} elseif ($pagenow === 'media-new.php') {
$this->loadAssetsMediaUpload();
// Add current folder to hidden fields on media-new.php page
add_filter('upload_post_params', function ($params) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
if (isset($_GET['wpmf-folder'])) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
$params['wpmf_folder'] = (int) $_GET['wpmf-folder'];
}
return $params;
}, 1, 1);
}
}
}
/**
* Includes styles and some scripts
*
* @return void
*/
public function mediaPageTableScript()
{
/**
* Filter check capability of current user to load assets
*
* @param boolean The current user has the given capability
* @param string Action name
*
* @return boolean
*
* @ignore Hook already documented
*/
$wpmf_capability = apply_filters('wpmf_user_can', current_user_can('upload_files'), 'load_script_style');
if ($wpmf_capability) {
$this->loadAssets();
}
}
/**
* Parse Size
*
* @param integer $size Site input
*
* @return float
*/
public function parseSize($size)
{
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is
// the power of magnitude to multiply a kilobyte by.
return round(floatval($size) * pow(1024, stripos('bkmgtpezy', $unit[0])));
} else {
return round(floatval($size));
}
}
/**
* Localize a script.
* Works only if the script has already been added.
*
* @return array
*/
public function localizeScript()
{
global $pagenow, $wp_roles, $wpdb;
$option_override = get_option('wpmf_option_override');
$option_duplicate = get_option('wpmf_option_duplicate');
$active_media_access = (int)get_option('wpmf_active_media');
if ($pagenow === 'upload.php') {
$categorytype = $this->getFiletype();
// get count file archive
$count_zip = $this->countExt('application');
// get count file pdf
$count_pdf = $this->countExt('application/pdf');
} else {
$categorytype = '';
$count_zip = 0;
$count_pdf = 0;
}
$parse_url = parse_url(site_url());
$host = md5($parse_url['host']);
// get some options
$terms = $this->getAttachmentTerms();
$parents_array = $this->getParrentsArray($terms['attachment_terms']);
$usegellery = get_option('wpmf_usegellery');
$get_plugin_active = json_encode(get_option('active_plugins'));
$option_media_remove = get_option('wpmf_option_media_remove');
$s_dimensions = get_option('wpmf_selected_dimension');
$size = json_decode($s_dimensions);
$s_weights = get_option('wpmf_weight_selected');
$weight = json_decode($s_weights);
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
// get param sort media
if (isset($_GET['orderby']) && isset($_GET['order'])) {
$media_order = $_GET['orderby'] . '|' . $_GET['order'];
} else {
if (isset($_GET['media-order-media'])) {
$media_order = $_GET['media-order-media'];
} else {
$media_order = 'all';
}
}
if (!isset($_GET['attachment_types'])) {
if (isset($_COOKIE['wpmf_post_mime_type' . $host]) && $_COOKIE['wpmf_post_mime_type' . $host] !== '' && $_COOKIE['wpmf_post_mime_type' . $host] !== 'all') {
$attachment_types = $_COOKIE['wpmf_post_mime_type' . $host];
} else {
$attachment_types = 'all';
}
} else {
$attachment_types = (isset($_GET['attachment_types'])) ? $_GET['attachment_types'] : (($pagenow === 'upload.php') ? '' : 'all');
}
if (strpos($attachment_types, 'uploaded') !== false) {
$attachment_types = explode(',', $attachment_types);
$key = array_search('uploaded', $attachment_types);
unset($attachment_types[$key]);
$attachment_types = implode(',', $attachment_types);
}
if (strpos($attachment_types, 'trash') !== false) {
$library_mode = get_user_meta(get_current_user_id(), $wpdb->prefix . 'media_library_mode', true);
if (!empty($library_mode) && $library_mode === 'list') {
if (empty($_GET['attachment-filter'])) {
$attachment_types = 'all';
} elseif ($_GET['attachment-filter'] === 'trash') {
$attachment_types = 'trash';
}
}
}
if (!isset($_GET['attachment_dates'])) {
if (isset($_COOKIE['wpmf_wpmf_date' . $host]) && $_COOKIE['wpmf_wpmf_date' . $host] !== '' && $_COOKIE['wpmf_wpmf_date' . $host] !== '0') {
$attachment_dates = $_COOKIE['wpmf_wpmf_date' . $host];
} else {
$attachment_dates = 'all';
}
} else {
$attachment_dates = (isset($_GET['attachment_dates'])) ? $_GET['attachment_dates'] : 'all';
}
if (!isset($_GET['attachment_sizes'])) {
if (isset($_COOKIE['wpmf_wpmf_size' . $host]) && $_COOKIE['wpmf_wpmf_size' . $host] !== '' && $_COOKIE['wpmf_wpmf_size' . $host] !== 'all') {
$attachment_sizes = $_COOKIE['wpmf_wpmf_size' . $host];
} else {
$attachment_sizes = 'all';
}
} else {
$attachment_sizes = (isset($_GET['attachment_sizes'])) ? $_GET['attachment_sizes'] : 'all';
}
if (!isset($_GET['attachment_weights'])) {
if (isset($_COOKIE['wpmf_wpmf_weight' . $host]) && $_COOKIE['wpmf_wpmf_weight' . $host] !== '' && $_COOKIE['wpmf_wpmf_weight' . $host] !== 'all') {
$attachment_weights = $_COOKIE['wpmf_wpmf_weight' . $host];
} else {
$attachment_weights = 'all';
}
} else {
$attachment_weights = (isset($_GET['attachment_weights'])) ? $_GET['attachment_weights'] : 'all';
}
// get param sort folder
$folder_order = (isset($_GET['folder_order'])) ? $_GET['folder_order'] : 'all';
$wpmf_order_f = isset($_GET['folder_order']) ? $_GET['folder_order'] : '';
$display_own_media = (isset($_GET['wpmf-display-media-filters']) && $_GET['wpmf-display-media-filters'] === 'yes') ? 'yes' : 'all';
$display_all_media = (!empty($_GET['wpmf_all_media'])) ? 1 : 0;
$filter_media_type = (!empty($_GET['attachment-filter'])) ? $_GET['attachment-filter'] : '';
// phpcs:enable
$option_countfiles = get_option('wpmf_option_countfiles');
if (!empty($option_countfiles) && $terms['role'] !== 'administrator') {
$option_countfiles = 0;
$show_folder_count = apply_filters('wpmf_show_folder_count', false);
if ($show_folder_count) {
$option_countfiles = 1;
}
}
$option_hoverimg = get_option('wpmf_option_hoverimg');
$cloud_endpoint = get_option('wpmf_cloud_endpoint');
if (empty($cloud_endpoint)) {
$cloud_endpoint = 'aws3';
}
$aws3config = get_option('_wpmfAddon_'. $cloud_endpoint .'_config');
$aws3_label = (isset($aws3config) && isset($aws3config['attachment_label']) && (int) $aws3config['attachment_label'] === 1) ? 1 : 0;
$root_media_root = get_term_by('id', $this->folderRootId, WPMF_TAXO);
$root_media = (empty($root_media_root)) ? 0 : $root_media_root->term_id;
$hide_tree = wpmfGetOption('hide_tree');
/**
* Filter to set limit of the folder number loaded
*
* @param integer Limit folder number
*
* @return integer
*/
$limit_folders_number = apply_filters('wpmf_limit_folders', 99999);
$enable_folders = wpmfGetOption('enable_folders');
$remote_video = wpmfGetOption('hide_remote_video');
$remote_video = ((int)$remote_video === 1);
/**
* Filter check capability of current user to load assets
*
* @param boolean The current user has the given capability
* @param string Action name
*
* @return boolean
*
* @ignore Hook already documented
*/
$remote_video = apply_filters('wpmf_user_can', $remote_video, 'hide_remote_video');
$show_folder_id = wpmfGetOption('show_folder_id');
$enable_download_media = wpmfGetOption('enable_download_media');
// get colors folder option
$colors_option = wpmfGetOption('folder_color');
// get default gallery config
$gallery_configs = wpmfGetOption('gallery_settings');
// get cloud sync settings
$sync_method = wpmfGetOption('sync_method');
$sync_periodicity = wpmfGetOption('sync_periodicity');
$cloudNameSyncing = get_option('wpmf_cloud_name_syncing');
$cloud_endpoint = get_option('wpmf_cloud_endpoint');
if (empty($cloud_endpoint)) {
$cloud_endpoint = 'aws3';
}
$configs = get_option('_wpmfAddon_'. $cloud_endpoint .'_config');
$root_media_count = wpmfGetOption('root_media_count');
$roles = $wp_roles->roles;
$role_in = array();
foreach ($roles as $role_name => $r) {
if (isset($r['capabilities']['upload_files']) && $r['capabilities']['upload_files']) {
$role_in[] = $role_name;
}
}
unset($roles['administrator']);
$args = array (
'role__in' => $role_in,
'order' => 'ASC',
'orderby' => 'display_name',
'fields' => array('ID', 'display_name')
);
$wp_user_query = new WP_User_Query($args);
$users = $wp_user_query->get_results();
$serverUploadLimit = min(
10 * 1024 * 1024, // Maximum for chunks size is 10MB if other settings is greater than 10MB
$this->parseSize(ini_get('upload_max_filesize')),
$this->parseSize(ini_get('post_max_size'))
);
global $current_user; //$current_user->allcaps
if (!empty($current_user->ID)) {
$enable_permissions_settings = ((isset($current_user->allcaps['wpmf_enable_permissions_settings']) && $current_user->allcaps['wpmf_enable_permissions_settings']) || in_array('administrator', $current_user->roles));
}
$enable_all_files_button = in_array('administrator', $current_user->roles) || !$active_media_access ;
/**
* Filter to enable "Display all files" button for specific user roles
*
* @return boolean
*/
$show_all_files_button = apply_filters('wpmf_enable_all_files_button', $enable_all_files_button) ? 1 : 0;
$l18n = $this->translation();
$vars = array(
'site_url' => site_url(),
'host' => $host,
'media_new_url' => admin_url('media-new.php'),
'plugin_url_image' => WPMF_PLUGIN_URL . 'assets/images/',
'serverUploadLimit' => $serverUploadLimit,
'roles' => $roles,
'users' => $users,
'override' => (int) $option_override,
'duplicate' => (int) $option_duplicate,
'wpmf_file' => $categorytype,//
'wpmfcount_zip' => $count_zip,//
'wpmfcount_pdf' => $count_pdf, //
'wpmf_categories' => $terms['attachment_terms'],
'wpmf_categories_order' => $terms['attachment_terms_order'],
'parents_array' => $parents_array, //
'taxo' => WPMF_TAXO,
'wpmf_role' => $terms['role'],
'enable_permissions_settings' => $enable_permissions_settings,
'wpmf_active_media' => (int) $terms['wpmf_active_media'],
'access_type' => $terms['access_type'],
'term_root_username' => $terms['term_root_username'],
'term_root_id' => $terms['term_root_id'],
'wpmf_pagenow' => $terms['wpmf_pagenow'],
'base' => $terms['base'],
'usegellery' => (int) $usegellery,
'get_plugin_active' => $get_plugin_active,
'wpmf_post_type' => $terms['wpmf_post_type'],
'wpmf_current_userid' => get_current_user_id(),
'wpmf_post_mime_type' => $terms['post_mime_types'],
'wpmf_type' => $terms['post_type'],
'usefilter' => (int) $terms['useorder'],
'wpmf_remove_media' => (int) $option_media_remove,
'ajaxurl' => admin_url('admin-ajax.php'),
'wpmf_size' => $size,
'size' => $attachment_sizes,
'attachment_dates' => $attachment_dates,
'attachment_types' => $attachment_types,
'wpmf_weight' => $weight,
'weight' => $attachment_weights,
'wpmf_order_media' => $media_order,
'folder_order' => $folder_order,
'display_own_media' => $display_own_media,
'display_all_media' => $display_all_media,
'filter_media_type' => $filter_media_type,
'wpmf_order_f' => $wpmf_order_f,
'option_countfiles' => (int) $option_countfiles,
'option_hoverimg' => (int) $option_hoverimg,
'aws3_label' => (int) $aws3_label,
'root_media_root' => $root_media,
'parent' => $terms['parent'],
'colors' => $colors_option,
'hide_tree' => $hide_tree,
'limit_folders_number' => $limit_folders_number,
'enable_folders' => $enable_folders,
'show_folder_id' => ((int) $show_folder_id === 1) ? true : false,
'enable_download_media' => ((int) $enable_download_media === 1) ? true : false,
'root_media_count' => ((int) $root_media_count === 1) ? true : false,
'hide_remote_video' => $remote_video,
'gallery_configs' => $gallery_configs,
'sync_method' => $sync_method,
'sync_periodicity' => (int) $sync_periodicity,
'cloudNameSyncing' => $cloudNameSyncing,
'wpmf_addon_active' => (is_plugin_active('wp-media-folder-addon/wp-media-folder-addon.php')) ? 1 : 0,
'wpmf_nonce' => wp_create_nonce('wpmf_nonce'),
'img_url' => WPMF_PLUGIN_URL . 'assets/images/',
'copy_files_to_bucket' => (!empty($configs['copy_files_to_bucket']) && is_plugin_active('wp-media-folder-addon/wp-media-folder-addon.php')) ? 1 : 0,
'hide_own_media_button' => current_user_can('wpmf_hide_own_media_button') ? 1 : 0,
'show_all_files_button' => $show_all_files_button
);
return array('l18n' => $l18n, 'vars' => $vars);
}
/**
* Get translation string
*
* @return array
*/
public function translation()
{
$l18n = array(
'upload_text' => __('Less than a min', 'wpmf'),
'empty_url' => __('Please add a video URL', 'wpmf'),
'empty_thumbnail' => __('Please add a thumbnail', 'wpmf'),
'add_video' => __('Add a video', 'wpmf'),
'question_quit_video_edit' => __('Are you sure you want to quit the video edition?', 'wpmf'),
'video_url' => __('Paste video URL: https://www.youtube.com/watch...', 'wpmf'),
'or' => __('or', 'wpmf'),
'select_from_library' => __('Select from Library', 'wpmf'),
'download_folder' => __('Downloading folder', 'wpmf'),
'download_zip' => __('ZIP Folder', 'wpmf'),
'download_sub' => __('ZIP Folder & Subfolder', 'wpmf'),
'uploaded' => __('Uploaded:', 'wpmf'),
'total_size' => __('Total size:', 'wpmf'),
'bulk_select' => __('Bulk select folders', 'wpmf'),
'add_media' => __('Add media', 'wpmf'),
'view_media' => __('View media', 'wpmf'),
'move_media' => __('Move media', 'wpmf'),
'remove_media' => __('Remove media', 'wpmf'),
'update_media' => __('Update media', 'wpmf'),
'view_folder' => __('View folder', 'wpmf'),
'add_folder' => __('Add Folder', 'wpmf'),
'update_folder' => __('Update folder', 'wpmf'),
'remove_folder' => __('Remove folder', 'wpmf'),
'inherit_folder' => __('Inherit permissions', 'wpmf'),
'permissions_list_of' => __('Permission lists of', 'wpmf'),
'folder' => __('folder', 'wpmf'),
'user' => __('User', 'wpmf'),
'role' => __('Role', 'wpmf'),
'add_role' => __('Add another role permission', 'wpmf'),
'add_user' => __('Add another user permission', 'wpmf'),
'change_folder' => __('Move to / Multi folders', 'wpmf'),
'create_folder' => __('Add new folder', 'wpmf'),
'load_more' => __('Load More', 'wpmf'),
'refresh' => __('Refresh', 'wpmf'),
'new_folder' => __('New Folder', 'wpmf'),
'media_folder' => __('Media Library', 'wpmf'),
'promt' => __('New folder name:', 'wpmf'),
'edit_file_lb' => __('Please enter a new name for the item:', 'wpmf'),
'edit_media' => __('Edit media', 'wpmf'),
'title_media' => __('Title', 'wpmf'),
'caption_media' => __('Caption', 'wpmf'),
'alt_media' => __('Alternative Text', 'wpmf'),
'desc_media' => __('Description', 'wpmf'),
'new_folder_tree' => __('NEW FOLDER', 'wpmf'),
'alert_add' => __('A folder already exists here with the same name. Please try with another name, thanks :)', 'wpmf'),
'alert_delete_file' => __('Are you sure to want to delete this file?', 'wpmf'),
'update_file_msg' => __('Update failed. Please try with another name, thanks :)', 'wpmf'),
'alert_delete' => __('Are you sure to want to delete this folder?', 'wpmf'),
'delete_multiple_folder' => __('Are you sure to want to delete %d folder? Note that some folders contain subfolders or files.', 'wpmf'),
'alert_delete_all' => __('Are you sure to want to delete this folder? Note that this folder contain subfolders or files.', 'wpmf'),
'alert_delete1' => __('This folder contains media and/or subfolders, please delete them before or activate the setting that allows to remove a folder with its media', 'wpmf'),
'display_own_media' => __('Display only my own medias', 'wpmf'),
'create_gallery_folder' => __('Create a gallery from folder', 'wpmf'),
'home' => __('Media Library', 'wpmf'),
'youarehere' => __('You are here', 'wpmf'),
'back' => __('Back', 'wpmf'),
'dragdrop' => __('Drag and Drop me hover a folder', 'wpmf'),
'pdf' => __('PDF', 'wpmf'),
'zip' => __('Zip & archives', 'wpmf'),
'other' => __('Other', 'wpmf'),
'link_to' => __('Link To', 'wpmf'),
'error_replace' => __('To replace a media and keep the link to this media working,it must be in the same format, ie. jpg > jpg, zip > zip Thanks!', 'wpmf'),
'uploaded_to_this' => __('Uploaded to this ', 'wpmf'),
'mimetype' => __('All media items', 'wpmf'),
'replace' => __('Replace', 'wpmf'),
'duplicate_text' => __('Duplicate', 'wpmf'),
'wpmf_undo' => __('Undo.', 'wpmf'),
'wpmf_undo_remove' => __('Folder removed.', 'wpmf'),
'files_moved' => __('files moved.', 'wpmf'),
'files_moving' => __('files moving...', 'wpmf'),
'wpmf_undo_movefolder' => __('Moved a folder.', 'wpmf'),
'wpmf_undo_editfolder' => __('Folder name updated', 'wpmf'),
'wpmf_file_replace' => __('File replaced!', 'wpmf'),
'file_uploading' => __('File upload on the way...', 'wpmf'),
'folder_uploading' => __('Folder upload on the way...', 'wpmf'),
'uploading' => __('Uploading', 'wpmf'),
'syncing_with_cloud' => __('Cloud syncing on the way...', 'wpmf'),
'wpmf_undofilter' => __('Filter applied', 'wpmf'),
'wpmf_remove_filter' => __('Media filters removed', 'wpmf'),
'cancel' => __('Cancel', 'wpmf'),
'create' => __('Create', 'wpmf'),
'add' => __('Add', 'wpmf'),
'add_tag' => __('Add tags', 'wpmf'),
'create_or_select_tag' => __('Create or select tags', 'wpmf'),
'save' => __('Save', 'wpmf'),
'save_close' => __('Save and close', 'wpmf'),
'ok' => __('OK', 'wpmf'),
'delete' => __('Delete', 'wpmf'),
'remove' => __('Remove', 'wpmf'),
'get_url_file' => __('Get URL', 'wpmf'),
'download' => __('Download', 'wpmf'),
'edit_folder' => __('Rename', 'wpmf'),
'proceed' => __('proceed', 'wpmf'),
'move_confirm_msg' => __('The size of your file is larger than 20MB, processing may take time depending on your server configuration', 'wpmf'),
'copy_folder_id' => __('Copy folder ID: ', 'wpmf'),
'copy_folderID_msg' => __('Folder ID copied to clipboard', 'wpmf'),
'success_copy_shortcode' => __('Gallery shortcode copied!', 'wpmf'),
'success_copy' => __('OK it\'s copied!', 'wpmf'),
'change_color' => __('Change color', 'wpmf'),
'permissions_setting' => __('Permissions settings', 'wpmf'),
'change_thumbnail' => __('Change thumbnail', 'wpmf'),
'add_image' => __('Add thumbnail', 'wpmf'),
'edit_file' => __('Edit', 'wpmf'),
'empty_video_thumbnail' => __('Please add a thumbnail for video', 'wpmf'),
'information' => __('Information', 'wpmf'),
'cannot_copy' => __('Cannot copy text', 'wpmf'),
'unable_copy' => __('Unable to copy.', 'wpmf'),
'clear_filters' => __('Clear filters and sorting', 'wpmf'),
'label_filter_order' => __('Filter or order media', 'wpmf'),
'label_remove_filter' => __('Remove all filters', 'wpmf'),
'wpmf_remove_file' => __('Media removed', 'wpmf'),
'wpmf_addfolder' => __('Folder added', 'wpmf'),
'media_uploaded' => __('New file(s) uploaded', 'wpmf'),
'folder_uploaded' => __('New folder(s) uploaded', 'wpmf'),
'wpmf_folder_adding' => __('Adding folder...', 'wpmf'),
'wpmf_folder_deleting' => __('Removing folder...', 'wpmf'),
'folder_editing' => __('Editing folder...', 'wpmf'),
'folder_moving' => __('Moving folder...', 'wpmf'),
'folder_moving_text' => __('Moving folder', 'wpmf'),
'file_moving_text' => __('Moving file', 'wpmf'),
'moving' => __('Moving', 'wpmf'),
'files' => __('files', 'wpmf'),
'file' => __('file', 'wpmf'),
'file_moving' => __('Moving file...', 'wpmf'),
'file_moved' => __('File moved', 'wpmf'),
'video_uploaded' => __('New video uploaded', 'wpmf'),
'assign_tree_label' => __('Media folders selection', 'wpmf'),
'label_assign_tree' => __('Select the folders where the media belong', 'wpmf'),
'label_apply' => __('Apply', 'wpmf'),
'folder_selection' => __('New folder selection applied to media', 'wpmf'),
'all_size_label' => __('All sizes', 'wpmf'),
'all_weight_label' => __('All weight', 'wpmf'),
'order_folder_label' => __('Sort folder', 'wpmf'),
'order_img_label' => __('Sort media', 'wpmf'),
'sort_media' => __('Default sorting', 'wpmf'),
'media_type' => __('Media type', 'wpmf'),
'date' => __('Date', 'wpmf'),
'lang_size' => __('Minimum size', 'wpmf'),
'lang_weight' => __('Weight range', 'wpmf'),
'remote_video_lb_box' => __('Copy Youtube, Vimeo or Dailymotion video URL', 'wpmf'),
'remote_video' => __('Add Remote Video', 'wpmf'),
'upload_folder_label' => __('Upload folder', 'wpmf'),
'select_folder_label' => __('Select folder:', 'wpmf'),
'filesize_label' => __('File size:', 'wpmf'),
'dimensions_label' => __('Dimensions:', 'wpmf'),
'no_media_label' => __('No', 'wpmf'),
'yes_media_label' => __('Yes', 'wpmf'),
'filter_label' => __('Filtering', 'wpmf'),
'sort_label' => __('Sorting', 'wpmf'),
'order_folder' => array(
'name-ASC' => __('Name (Ascending)', 'wpmf'),
'name-DESC' => __('Name (Descending)', 'wpmf'),
'id-ASC' => __('ID (Ascending)', 'wpmf'),
'id-DESC' => __('ID (Descending)', 'wpmf'),
'custom' => __('Custom order', 'wpmf'),
), // List of available ordering type for folders
'order_media' => array(
'date|asc' => __('Date (Ascending)', 'wpmf'),
'date|desc' => __('Date (Descending)', 'wpmf'),
'title|asc' => __('Title (Ascending)', 'wpmf'),
'title|desc' => __('Title (Descending)', 'wpmf'),
'size|asc' => __('Size (Ascending)', 'wpmf'),
'size|desc' => __('Size (Descending)', 'wpmf'),
'filetype|asc' => __('File type (Ascending)', 'wpmf'),
'filetype|desc' => __('File type (Descending)', 'wpmf'),
'custom' => __('Custom order', 'wpmf'),
), // List of available ordering type for attachements
'colorlists' => array(
'#ac725e' => __('Chocolate ice cream', 'wpmf'),
'#d06b64' => __('Old brick red', 'wpmf'),
'#f83a22' => __('Cardinal', 'wpmf'),
'#fa573c' => __('Wild strawberries', 'wpmf'),
'#ff7537' => __('Mars orange', 'wpmf'),
'#ffad46' => __('Yellow cab', 'wpmf'),
'#42d692' => __('Spearmint', 'wpmf'),
'#16a765' => __('Vern fern', 'wpmf'),
'#7bd148' => __('Asparagus', 'wpmf'),
'#b3dc6c' => __('Slime green', 'wpmf'),
'#fbe983' => __('Desert sand', 'wpmf'),
'#fad165' => __('Macaroni', 'wpmf'),
'#92e1c0' => __('Sea foam', 'wpmf'),
'#9fe1e7' => __('Pool', 'wpmf'),
'#9fc6e7' => __('Denim', 'wpmf'),
'#4986e7' => __('Rainy sky', 'wpmf'),
'#9a9cff' => __('Blue velvet', 'wpmf'),
'#b99aff' => __('Purple dino', 'wpmf'),
'#8f8f8f' => __('Mouse', 'wpmf'),
'#cabdbf' => __('Mountain grey', 'wpmf'),
'#cca6ac' => __('Earthworm', 'wpmf'),
'#f691b2' => __('Bubble gum', 'wpmf'),
'#cd74e6' => __('Purple rain', 'wpmf'),
'#a47ae2' => __('Toy eggplant', 'wpmf'),
), // colorlists
'placegolder_color' => __('Custom color #8f8f8f', 'wpmf'),
'bgcolorerror' => __('Change background folder has failed', 'wpmf'),
'search_folder' => __('Search folders...', 'wpmf'),
'copy_url' => __('Media URL copied!', 'wpmf'),
'reload_media' => __('Refresh media library', 'wpmf'),
'msg_upload_folder' => __('You are uploading media to folder: ', 'wpmf'),
'addon_ajax_button' => __('Use ajax link', 'wpmf'),
'sync_drive' => __('Run full synchronization', 'wpmf'),
'move_file_fail' => __('Sorry, Media & Folders can only be moved to the same cloud or media system (Google Drive to Google Drive, WordPress media to WordPress media...)', 'wpmf'),
'import_cloud' => __('Import to library', 'wpmf'),
'insert_pdfembed' => __('Insert PDF Embed', 'wpmf'),
'insert_image_lightbox' => __('Insert Image Lightbox', 'wpmf'),
'import' => __('Import', 'wpmf'),
'import_cloud_title' => __('Import this file to media library', 'wpmf'),
'import_google_photo_title' => __('Import Google Photos to Wordpress', 'wpmf'),
'import_album_as_new_folder' => __('Import as new folder', 'wpmf'),
'importing_cloud_file' => __('Cloud file(s) importing...', 'wpmf'),
'import_cloud_btn' => __('Import to media library', 'wpmf'),
'hover_cloud_syncing' => esc_html__('Cloud syncing on the way', 'wpmf'),
'selected_photos' => esc_html__('Selected Photos', 'wpmf'),
'album' => esc_html__('Selected Album', 'wpmf'),
'import_source' => esc_html__('Import Source', 'wpmf'),
'importing_goolge_photo_album' => esc_html__('Photo album importing...', 'wpmf'),
'importing_goolge_photo' => esc_html__('Importing Google photos...', 'wpmf'),
'copy_file_to_s3' => esc_html__('Copy this file to Storage', 'wpmf'),
'bulk_copy_files_to_s3' => esc_html__('Upload files to Storage', 'wpmf'),
'uploading_files_to_s3' => esc_html__('File(s) uploading to Storage', 'wpmf'),
'removing_files_from_local' => esc_html__('File(s) removing from local', 'wpmf'),
'display_all_files' => esc_html__('Display all files', 'wpmf'),
'queue_sync_alert' => esc_html__('Media will be synchronized in background', 'wpmf'),
'gallery_image_size' => esc_html__('Gallery image size', 'wpmf'),
'columns' => esc_html__('Columns', 'wpmf'),
'lightbox_size' => esc_html__('Lightbox size', 'wpmf'),
'action_on_click' => esc_html__('Action on click', 'wpmf'),
'orderby' => esc_html__('Order by', 'wpmf'),
'custom' => esc_html__('Custom', 'wpmf'),
'random' => esc_html__('Random', 'wpmf'),
'title' => esc_html__('Title', 'wpmf'),
'order' => esc_html__('Order', 'wpmf'),
'ascending' => esc_html__('Ascending', 'wpmf'),
'descending' => esc_html__('Descending', 'wpmf'),
'update_with_new_folder' => esc_html__('Update with new folder content', 'wpmf'),
'yes' => esc_html__('Yes', 'wpmf'),
'no' => esc_html__('No', 'wpmf'),
'autoplay' => esc_html__('Autoplay', 'wpmf'),
'crop_image' => esc_html__('Crop Image', 'wpmf'),
'border' => esc_html__('Border', 'wpmf'),
'border_radius' => esc_html__('Border radius', 'wpmf'),
'border_radius_desc' => esc_html__('Add rounded corners to the gallery items.', 'wpmf'),
'border_style' => esc_html__('Border style', 'wpmf'),
'border_color' => esc_html__('Border color', 'wpmf'),
'border_width' => esc_html__('Border width', 'wpmf'),
'margin' => esc_html__('Margin', 'wpmf'),
'gutter' => esc_html__('Gutter', 'wpmf'),
'shadow' => esc_html__('Shadow', 'wpmf'),
'shadow_h' => esc_html__('Shadow H offset', 'wpmf'),
'shadow_v' => esc_html__('Shadow V offset', 'wpmf'),
'shadow_blur' => esc_html__('Shadow blur', 'wpmf'),
'shadow_spread' => esc_html__('Shadow Spread', 'wpmf'),
'shadow_color' => esc_html__('Shadow Color', 'wpmf'),
'color_settings' => esc_html__('Color Settings', 'wpmf'),
'image_settings' => esc_html__('Image Settings', 'wpmf'),
'caption' => esc_html__('Caption', 'wpmf'),
'custom_link' => esc_html__('Custom link', 'wpmf'),
'link_target' => esc_html__('Link target', 'wpmf'),
'same_window' => esc_html__('Same Window', 'wpmf'),
'new_window' => esc_html__('New Window', 'wpmf'),
'default' => esc_html__('Default', 'wpmf'),
'masonry' => esc_html__('Masonry', 'wpmf'),
'portfolio' => esc_html__('Portfolio', 'wpmf'),
'slider' => esc_html__('Slider', 'wpmf'),
'lightbox' => esc_html__('Lightbox', 'wpmf'),
'attachment_page' => esc_html__('Attachment Page', 'wpmf'),
'gallery_settings' => esc_html__('Gallery Settings', 'wpmf'),
'media_gallery' => esc_html__('WP Media Folder Gallery', 'wpmf'),
'create_gallery' => esc_html__('CREATE GALLERY', 'wpmf'),
'media_gallery_desc' => esc_html__('Load images from media folder, from your media library or just upload new images', 'wpmf'),
'media_download_desc' => esc_html__('WP Media Folder media download. Select a media and transform it into a download button', 'wpmf'),
'upload' => esc_html__('Upload', 'wpmf'),
'theme' => esc_html__('Theme', 'wpmf'),
'select_folder' => esc_html__('Select a folder', 'wpmf'),
'select_role' => esc_html__('Select a role', 'wpmf'),
'select_user' => esc_html__('Select a user', 'wpmf'),
'remove_image' => esc_html__('Remove image', 'wpmf'),
'folder_no_image' => esc_html__('Ooups, this folder does not have any images...', 'wpmf'),
'none' => esc_html__('None', 'wpmf'),
'solid' => esc_html__('Solid', 'wpmf'),
'dotted' => esc_html__('Dotted', 'wpmf'),
'dashed' => esc_html__('Dashed', 'wpmf'),
'double' => esc_html__('Double', 'wpmf'),
'groove' => esc_html__('Groove', 'wpmf'),
'ridge' => esc_html__('Ridge', 'wpmf'),
'inset' => esc_html__('Inset', 'wpmf'),
'outset' => esc_html__('Outset', 'wpmf'),
'edit_gallery' => esc_html__('Edit Gallery', 'wpmf'),
'upload_an_image' => esc_html__('Upload an image', 'wpmf'),
'mv_local_cloud_msg' => esc_html__('Moving %d files from server to cloud', 'wpmf'),
'search_no_result' => esc_html__('Sorry, no folder found', 'wpmf'),
'by_role' => esc_html__('By Role', 'wpmf'),
'by_user' => esc_html__('By User', 'wpmf'),
'remove_file_permission_msg' => esc_html__('You do not have permission to delete this file. Refresh folder to see image again', 'wpmf'),
'remove_file_permission_msg1' => esc_html__('You do not have permission to delete this file', 'wpmf'),
'update_file_permission_msg' => esc_html__('You do not have permission to update this file', 'wpmf'),
'select_file_required' => esc_html__('Please select file to do this action', 'wpmf'),
'cannot_download' => esc_html__('This file cannot be downloaded.', 'wpmf')
);
return $l18n;
}
/**
* Get parrents folder array
*
* @param array $attachment_terms All wpmf categories
*
* @return array
*/
public function getParrentsArray($attachment_terms)
{
$wcat = isset($_GET['wcat']) ? $_GET['wcat'] : '0'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
$parents = array();
$pCat = (int) $wcat;
while ((int) $pCat !== 0) {
$parents[] = $pCat;
$pCat = (int) $attachment_terms[$pCat]['parent_id'];
}
$parents_array = array_reverse($parents);
return $parents_array;
}
/**
* Get all params
*
* @param string $from Call from
*
* @return array
*/
public function getAttachmentTerms($from = '')
{
global $pagenow, $current_user, $current_screen, $sitepress;
if (isset($current_screen->base)) {
$base = $current_screen->base;
} else {
$base = '';
}
$cf_count_files = get_option('wpmf_option_countfiles');
$enable_count = ((int) $cf_count_files === 1) ? true : false;
// get categories
$attachment_terms = array();
$args = array(
'hide_empty' => false,
'taxonomy' => WPMF_TAXO,
'pll_get_terms_not_translated' => 1
);
/**
* Filter to custom aguments for get all categories
*
* @param array Agument
*
* @return array
*/
$args = apply_filters('wpmf_get_categories_args', $args);
if ($sitepress) {
remove_filter('get_terms_args', array($sitepress, 'get_terms_args_filter'));
$filter_removed = remove_filter('get_term', array($sitepress, 'get_term_adjust_id'));
remove_filter('terms_clauses', array($sitepress, 'terms_clauses'));
$terms = get_categories($args);
add_filter('terms_clauses', array($sitepress, 'terms_clauses'), 10, 4);
if ($filter_removed) {
add_filter('get_term', array($sitepress, 'get_term_adjust_id'), 1, 1);
}
add_filter('get_terms_args', array($sitepress, 'get_terms_args_filter'), 10, 2);
} else {
$terms = get_categories($args);
}
if ($from === 'builder') {
$terms = WpmfHelper::parentSort($terms);
} else {
$terms = WpmfHelper::parentSort($terms, $enable_count);
}
$attachment_terms_order = array();
$access_type = get_option('wpmf_create_folder');
$wpmf_active_media = get_option('wpmf_active_media');
$role = WpmfHelper::getRoles(get_current_user_id());
$term_root_username = '';
$parent = 0;
$root_folder = $this->getFolderInfos(0, $enable_count, true);
$ancestors = array();
if ($access_type === 'user' && $current_user->ID) {
$user_folder = get_term_by('slug', sanitize_title($current_user->data->user_login) . '-wpmf', WPMF_TAXO);
if (!empty($user_folder)) {
$ancestors = get_ancestors($user_folder->term_id, WPMF_TAXO, 'taxonomy');
}
}
/* role != administrator or enable option 'Display only media by User/User' */
if (!$this->user_full_access) {
// get all childs cloud folder
$cloud_user_folders = array();
$cloud_types = array('google_drive', 'dropbox', 'onedrive', 'onedrive_business', 'nextcloud');
foreach ($cloud_types as $cloud_type) {
//isLoadAllChildsCloud
if (WpmfHelper::isConnected($cloud_type)) {
if ($cloud_type === 'google_drive') {
$options = get_option('_wpmfAddon_cloud_config');
} elseif ($cloud_type === 'dropbox') {
$options = get_option('_wpmfAddon_dropbox_config');
} elseif ($cloud_type === 'onedrive') {
$options = get_option('_wpmfAddon_onedrive_config');
} elseif ($cloud_type === 'onedrive_business') {
$options = get_option('_wpmfAddon_onedrive_business_config');
} elseif ($cloud_type === 'nextcloud') {
$options = get_option('_wpmfAddon_nextcloud_config');
}
if (!empty($options['access_by']) && $options['access_by'] === 'user') {
$slug = $current_user->user_login . '-wpmf-' . $cloud_type;
} else {
$slug = $role . '-wpmf-role-' . $cloud_type;
}
$cloud_root_id = get_term_by('slug', $slug, WPMF_TAXO);
if ($cloud_root_id) {
if (WpmfHelper::isLoadAllChildsCloud($cloud_type)) {
if (!empty($cloud_root_id)) {
$cloud_folder_childs = get_term_children($cloud_root_id->term_id, WPMF_TAXO);
$cloud_user_folders = array_merge($cloud_user_folders, $cloud_folder_childs);
$cloud_user_folders[] = $cloud_root_id->term_id;
}
} else {
$cloud_user_folders[] = $cloud_root_id->term_id;
}
}
}
}
foreach ($terms as $term) {
// check is load childrent folders for local and cloud
if (in_array($term->term_id, $ancestors)) {
$is_access = true;
} else {
$is_access = WpmfHelper::getAccess($term->term_id, get_current_user_id(), 'view_folder');
}
if ($is_access) {
$attachment_terms_order[$term->term_id] = $term;
}
}
} else { // role == administrator or disable option 'Display only media by User/User'
$exclude = $this->getDriveFolderExcludes();
foreach ($terms as $term) {
if ((int) $term->term_id === (int) $this->folderRootId) {
continue;
}
if (in_array($term->name, $exclude) && (int) $term->parent === 0) {
continue;
}
// Todo: Upon disconnection, remove cloud folder data from the database. This will bypass the unnecessary 'exclude' check, enhancing overall performance
if (false && defined('WPMFAD_PLUGIN_DIR')) {
$type = $this->getTermMeta($term->term_id, 'wpmf_drive_type');
if ((in_array('Dropbox', $exclude) && $type === 'dropbox')
|| (in_array('Google Drive', $exclude) && $type === 'google_drive')
|| (in_array('Onedrive', $exclude) && $type === 'onedrive')
|| (in_array('Onedrive Business', $exclude) && $type === 'onedrive_business')
|| (in_array('Nextcloud', $exclude) && $type === 'nextcloud')) {
continue;
}
}
$attachment_terms_order[$term->term_id] = $term;
}
}
$attachment_terms = $this->getMultiFolderInfos($attachment_terms_order);
$attachment_terms_order = array_keys($attachment_terms_order);
$attachment_terms[0] = $root_folder;
array_unshift($attachment_terms_order, 0);
$post_mime_types = get_post_mime_types();
$useorder = get_option('wpmf_useorder');
// get post type
global $post;
if (!empty($post) && !empty($post->post_type)) {
$post_type = $post->post_type;
} else {
$post_type = '';
}
if (in_array('js_composer/js_composer.php', get_option('active_plugins'))) {
$wpmf_post_type = 1;
} else {
$wpmf_post_type = 0;
}
return array(
'role' => $role,
'wpmf_active_media' => (int) $wpmf_active_media,
'access_type' => $access_type,
'term_root_username' => $term_root_username,
'term_root_id' => 0,
'attachment_terms' => $attachment_terms,
'attachment_terms_order' => $attachment_terms_order,
'wpmf_pagenow' => $pagenow,
'base' => $base,
'post_mime_types' => $post_mime_types,
'useorder' => (int) $useorder,
'post_type' => $post_type,
'wpmf_post_type' => $wpmf_post_type,
'parent' => $parent
);
}
/**
* Get folder infos
*
* @param array $terms List folder details
*
* @return array
*/
public function getMultiFolderInfos($terms)
{
if (!$terms) {
return array();
}
$term_ids = array_keys($terms);
$return = array();
$drive_types = array();
if (defined('WPMFAD_PLUGIN_DIR')) {
$drive_types = $this->getDriveType($term_ids);
}
$orders = $this->getTermMeta($term_ids, 'wpmf_order');
foreach ($terms as $term_id => $term) {
// get custom order folder
$details = array(
'id' => $term->term_id,
'label' => $term->name,
'lower_label' => strtolower($term->name),
'slug' => $term->slug,
'parent_id' => $term->category_parent,
'depth' => $term->depth,
'term_group' => $term->term_group,
'order' => isset($orders[$term_id]) ? $orders[$term_id] : '',
'drive_type' => isset($drive_types[$term_id]) ? $drive_types[$term_id] : ''
);
// $view_media = WpmfHelper::getAccess($term->term_id, get_current_user_id(), 'view_media');
if (isset($term->files_count)) {
$details['files_count'] = $term->files_count;
$details['count_all'] = $term->count_all;
}
$return[$term_id] = $details;
}
return $return;
}
/**
* Get folder infos
*
* @param object $term Folder details
* @param boolean $enable_count Enable count
* @param boolean $isRoot Is root folder
* @param integer $parent Parent folder ID
* @param integer|string $depth Depth
*
* @return array
*/
public function getFolderInfos($term, $enable_count = false, $isRoot = false, $parent = '', $depth = '')
{
if ($isRoot) {
$details = array(
'id' => 0,
'label' => __('Media Library', 'wpmf'),
'lower_label' => __('Media Library', 'wpmf'),
'slug' => '',
'parent_id' => 0
);
if ($enable_count) {
$details['files_count'] = WpmfHelper::getRootFolderCount($this->folderRootId);
}
} else {
// get custom order folder
$order = $this->getOrderFolder($term->term_id);
$drive_type = '';
if (defined('WPMFAD_PLUGIN_DIR')) {
$drive_type = $this->getTermMeta($term->term_id, 'wpmf_drive_root_type');
if (empty($drive_type)) {
$drive_type = $this->getTermMeta($term->term_id, 'wpmf_drive_type');
}
}
if ($depth !== '') {
if ($depth === 'down') {
$depth = (int)$term->depth - 1;
}
} else {
$depth = $term->depth;
}
$details = array(
'id' => $term->term_id,
'label' => $term->name,
'lower_label' => strtolower($term->name),
'slug' => $term->slug,
'parent_id' => ($parent !== '') ? 0 : $term->category_parent,
'depth' => ($parent !== '') ? 0 : $depth,
'term_group' => $term->term_group,
'order' => $order,
'drive_type' => !empty($drive_type) ? $drive_type : ''
);
$view_media = WpmfHelper::getAccess($term->term_id, get_current_user_id(), 'view_media');
if (isset($term->files_count)) {
$details['files_count'] = $term->files_count;
$details['count_all'] = $term->count_all;
}
}
return $details;
}
/**
* Get `term_id` and `meta_value` of term meta by meta_key `wpmf_drive_root_type` or `wpmf_drive_type` if `wpmf_drive_root_type` is empty
*
* @param integer|array $term_id Term ID
*
* @return string|array
*/
public function getDriveType($term_id)
{
global $wpdb;
if (is_array($term_id)) {
$results = array();
$term_id = implode(',', $term_id);
}
$rows = $wpdb->get_results($wpdb->prepare(
'SELECT DISTINCT tm.term_id, COALESCE(
(SELECT tm_root_type.meta_value from '. $wpdb->prefix . 'termmeta AS tm_root_type
Where tm.term_id = tm_root_type.term_id AND tm_root_type.meta_key = %s),
(SELECT tm_drive_type.meta_value from '. $wpdb->prefix . 'termmeta AS tm_drive_type
Where tm.term_id = tm_drive_type.term_id AND tm_drive_type.meta_key = %s)
) AS meta_value
FROM '. $wpdb->prefix . 'termmeta AS tm WHERE tm.term_id IN ('.$term_id.')', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
array('wpmf_drive_root_type', 'wpmf_drive_type')
));
foreach ($rows as $row) {
$results[$row->term_id] = $row->meta_value;
}
return $results;
}
/**
* Get term meta value by $wpdb->get_var to reduce memory useage in big termmeta table.
*
* @param integer|array $term_id Term ID
* @param string $meta_key Meta key
*
* @return string|array
*/
public function getTermMeta($term_id, $meta_key)
{
global $wpdb;
if (is_array($term_id)) {
$results = array();
$term_id = implode(',', $term_id);
$rows = $wpdb->get_results($wpdb->prepare(
'SELECT term_id, meta_value FROM ' . $wpdb->prefix . 'termmeta WHERE term_id IN ('.$term_id.') AND meta_key = %s', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
array($meta_key)
));
foreach ($rows as $row) {
$results[$row->term_id] = $row->meta_value;
}
return $results;
}
return $wpdb->get_var($wpdb->prepare('SELECT meta_value FROM ' . $wpdb->prefix . 'termmeta WHERE term_id=%s AND meta_key=%s', array($term_id, $meta_key)));
}
/**
* Get custom order folder
*
* @param integer $term_id Id of folder
*
* @return integer|mixed
*/
public function getOrderFolder($term_id)
{
$order = $this->getTermMeta($term_id, 'wpmf_order');
if (empty($order)) {
$order = 0;
}
return $order;
}
/**
* Show notice of import size for files
*
* @return void
*/
public function showNoticeImportSize()
{
global $wpdb;
$total = $wpdb->get_var($wpdb->prepare('SELECT COUNT(posts.ID) as total FROM ' . $wpdb->prefix . 'posts as posts
WHERE posts.post_type = %s', array('attachment')));
if ($total > 5000) {
wp_enqueue_script(
'wpmfimport-size-filetype',
plugins_url('/assets/js/imports/import_size_filetype.js', dirname(__FILE__)),
array('jquery'),
WPMF_VERSION
);
$vars = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'wpmf_nonce' => wp_create_nonce('wpmf_nonce')
);
$params = array('l18n' => array(), 'vars' => $vars);
wp_localize_script('wpmfimport-size-filetype', 'wpmfimport', $params);
echo '
'
. '
'
. esc_html__('Your website has a large file library (>5000 files).
WP Media Folder needs to index all of them to run smoothly.
It may take few minutes... keep the window open and keep cool :)', 'wpmf')
. '
' . esc_html__('Run synchronization now', 'wpmf') . '
'
. '
'
. '
';
}
}
/**
* Add NextGEN galleries notice
*
* @return void
*/
public function showNoticeImportGallery()
{
/**
* Filter check capability of current user to show notice import gallery
*
* @param boolean The current user has the given capability
* @param string Action name
*
* @return boolean
*
* @ignore Hook already documented
*/
$wpmf_capability = apply_filters('wpmf_user_can', current_user_can('manage_options'), 'notice_import_gallery');
if ($wpmf_capability) {
echo '