Developer / API

Functions, Interfaces, Helpers

Under construction

This page is under construction. That means it is not finished yet, for example the filters and actions of RML are missing. Also, the API is only available in english language.

Folder helper functions

Working with folders

You will find these functions in wp-content/plugins/real-media-library/inc/api/folders.php.

function is_rml_folder($obj)

Checks, if a given variable is an implementation of the IFolder interface.

  • @param $obj Object or int (ID)
  • @return boolean

 

function wp_rml_get_parent_id($id)

Get the parent ID of a given folder id.

  • @param $id The id of the folder, collection, ...
  • @return int or null

 

function wp_rml_objects()

Get all available folders, collections, galleries, ...

  • @return Array of IFolder objects

 

function wp_rml_root_childs()

Gets the first level childs of the media library.

  • @return Array of IFolder objects

 

function wp_rml_select_tree($inputName, $selected, $tree = null, $extraClasses = "")

Returns a .rml-root-list with an given tree. The selected folder id is saved automatically in a hidden input type.

  • @param inputName the name for the hidden input type and the name for the list
  • @param selected the selected folder id (saved also in hidden input type)
  • @param tree Array of IFolder objects (default is the root tree)
  • @param extraClasses classes for the rml root list container
  • @return Formatted HTML string

Note #1: The select tree has a javascript callback when it is initalized. You can bind it with this snippet:

window.rml.hooks.register("customList", function(obj, $) {
	//if (obj.hasClass("my-extra-class")) {
		alert(obj.html());
	//}
});

Note #2: If you want to use the select tree after a DOM change (ajax, for example: Modal dialog in visual editor) please call the javascript function window.rml.library.customLists() to affect the initalization referred to Note #1.

$folder = wp_rml_get_by_absolute_path("demo"); // IFolder object
$children = $folder->getChildren();
echo wp_rml_select_tree("example", false, $children);
function wp_rml_create($name, $parent, $type, $restrictions = array(), $supress_validation = false, $return_existing_id = false)

Creates a folder. At first it checks if a folder in parent already exists. Then it checks if the given type is allowed in the parent.

  • @param $name String Name of the folder
  • @param $parent int ID of the parent (_wp_rml_root() for root)
  • @param $type integer 0|1|2 @see Folder.class.inc
  • @param $restrictions Restrictions for this folder, see Permissions. The restrictions of the parent folder are also the restrictions for the new folder (restrictions ending with ">").
  • @param $supress_validation Supress the permission validation
  • @param $return_existing_id If true and the folder already exists, then return the ID of the existing folder
  • @return int (ID) when successfully or array with error strings

 

function wp_rml_create_or_return_existing_id($name, $parent, $type, $restrictions = array(), $supress_validation = false)

Wrapper function for wp_rml_create().

  • @return int (ID) of the created OR existing folder or array with errors strings

 

function wp_rml_rename($name, $id, $supress_validation = false)

Renames a folder and then checks, if there is no duplicate folder in the parent folder.

  • @param $name String New name of the folder
  • @param $id The ID of the folder
  • @param $supress_validation Supress the permission validation
  • @return true or array with error strings

 

function wp_rml_delete($id, $supress_validation = false)
  • Deletes a folder by ID.
  • @param $id The ID of the folder
  • @param $supress_validation Supress the permission validation
  • @return true or array with error string

 

function wp_rml_update_count($folders = null, $attachments = null)

Handle the count cache for the folders. This should avoid a lack SQL subquery which loads data from the posts table.

  • @param $folders Array of folders ID, if null then all folders with cnt = NULL are updated
  • @param $attachments Array of attachments ID, is merged with $folders if given

 

function wp_rml_dropdown($selected, $disabled, $useAll = true)

This functions returns a HTML formatted string which contains <options> elements with all folders, collections and galleries.

  • @param $selected The selected item
    "": "All Files"
    _wp_rml_root(): "Root"
    int: Folder ID
  • @param $disabled array Defines, which folder types are disabled (@see ./real-media-library.php for Constant-Types)
    Default disabled is RML_TYPE_COLLECTION
  • @param $useAll boolean Defines, if "All Files" should be showed
  • @return String
echo "<select>";
echo wp_rml_dropdown("", array(RML_TYPE_ROOT));
echo "</select>";

function wp_rml_is_type($folder, $allowed)

Determines, if a Folder is a special folder type.

  • @param $folder folderCreatable or int
  • @param $allowed array Defines, which folder types are allowed (@see ./real-media-library.php for Constant-Types)
  • @return boolean

 

function wp_rml_get_object_by_id($id, $allowed = null)

This functions checks if a specific folder exists by ID and is a given allowed RML Folder Type. If the given folder is _wp_rml_root() you will get the first level folders.

  • @param $id int Folder ID
  • @param $allowed array Defines, which folder types are allowed (@see ./real-media-library.php for Constant-Types) If it is null, all folder types are allowed.
  • @param $mustBeFolderObject Defines if the function may return the wp_rml_root_childs result
  • @param $nullForRoot If set to false and $id == -1 then the Root instance is returned
  • @return IFolder object or NULL

 

function wp_rml_get_by_absolute_path($path, $allowed = null)

This functions checks if a specific folder exists by absolute path and is a given allowed RML Folder Type.

  • @param $path string Folder Absolute Path
  • @param $allowed array Defines, which folder types are allowed (@see ./real-media-library.php for Constant-Types) If it is null, all folder types are allowed.
  • @return IFolder object or NULL

 

function _wp_rml_root()

Get the parent root folder for a given blog id.

  • @return int

 

function wp_rml_structure_reset($root = null, $fetchData = true)

ATTENTION: This function will be declared as deprecated soon, because it is planned to automatically reset the structure data / reset folder data (lazy loading  of Folder objects).

 

Attachment helper functions

Working with attachments and their folder relationship

You will find these functions in wp-content/plugins/real-media-library/inc/api/attachment.php.

function wp_rml_get_attachments($fid, $order = null, $orderby = null)

This function is similar to the the IFolder::read() interface. For the other parameters have a look at the IFolder interface / Folder objects.

  • @param $fid The folder ID

 

function wp_attachment_folder($attachmentId, $default = null)

Returns the folder id of an given attachment or more than one attachment (array). If you pass an array as attachment ids, then the default value does not work, only for single queries.

  • @param $attachmentId The attachment ID, if you pass an array you get an array of folder IDs
  • @param $default If no folder was found for this, this value is returned for the attachment
  • @return Folder ID or $default or Array

 

function wp_attachment_order_update($folderId, $attachmentId, $nextId, $lastIdInView = false)

Moves an attachment before another given attachment in the order table.

  • @param $folderId The folder id where the attachment exists
  • @param $attachmentId The attachment which should be moved
  • @param $nextId The attachment next to the currentId, if it is false the currentId should be moved to the end of table.
  • @param $lastIdInView (optional) If you have pagination, you can pass the last id from this view
  • @return true or array with error strings

 

function wp_rml_move($to, $ids, $supress_validation = false)

Move or copy a set of attachments to a specific folder

  • @param $to Folder ID, if folder not exists then root will be
  • @param $ids Array of attachment ids
  • @param $supress_validation Supress the permission validation
  • @param $isShortcut Determines, if the ID's are copies @experimental AND NOT FINISHED YET!
  • @return true or Array with errors

IFolder interface

Working with folder objects

You will find the interface in wp-content/plugins/real-media-library/inc/api/IFolder.interface.php.

Every folder, collection or gallery is an implementation of the IFolder interface. You can retrieve folder objects with helper functions, for example wp_rml_get_object_by_id() (look helper functions). Note: Also the root ("Unorganized") is a folder and implements this interface. Usually, the root acts as "-1" but you should use the _wp_rml_root() function to get the root id. So, every folder object has the following methods you can work with:

$folderObj->read($order = null, $orderby = null);

Fetch all attachment ids currently in this folder. It uses the default WP_Query to fetch the ids.

  • @param $order The order "ASC" or "DESC"
  • @param $orderby Use "rml" to get ids ordered by custom order
  • @return array of post ids

 

$folderObj->hasChildren($slug, $isSlug = true, $returnObject = false);

Checks, if this folder has a children with the name.

  • @param $slug String Slug or Name of folder
  • @param $isSlug boolean Set it to false, if the passed slug is not santizied
  • @param $returnObject If set to true and a children with this name is found, then return the object for this folder
  • @return boolean

 

$folderObj->getType();

Return the type for the given folder. For example: 0 = Folder, 1 = Collection, 2 = Gallery, 4 = Unorganised

  • @return int

 

$folderObj->getAllowedChildrenTypes();

Checks, if a children type is allowed here.

  • @return Array with allowed types or TRUE for all types allowed

 

$folderObj->getId();

Get the autogenerated ID

  • @return int

 

$folderObj->getParent();

Get the parent ID

  • @return int

 

$folderObj->getName();

Get the name

  • @return string

 

$folderObj->getSlug($force = false);

Returns a santitized title for the folder. If the slug is empty or forced to, it will be updated in the database, too.

  • @param $force Forces to regenerate the slug
  • @return string

 

$folderObj->getPath($implode = "/");

Creates a absolute path without slugging' the names.

  • @param $implode Delimitter for the folder names
  • @return string

 

$folderObj->getAbsolutePath($force = false);

Creates a absolute path. If the absolute path is empty or forced to, it will be updated in the database, too.

  • @param $force Forces to regenerate the absolute path
  • @return string

 

$folderObj->getCnt($forceReload = false);

Gets the count of the files in this folder.

  • @return int

 

$folderObj->getChildren();

Returns childrens of this folder.

  • @return array of folder objects which implements IFolder

 

$folderObj->getOrder();

Get the order.

  • @return int

 

$folderObj->getRestrictions();

Get the restrictions of this folder. For more details have a look at the Permissions class.

  • @return array

 

$folderObj->getRestrictionsCount();

Get the count of the restrictions.

  • @return int

 

$folderObj->is($folder_type);

Check if the folder object is a given type.

  • @param $folder_type (@see ./real-media-library.php for Constant-Types)
  • @return boolean

 

WP_Query

Reading attachments from folders

As you know the WP_Query class of wordpress you can query every post type with different parameters. Real Media Library provides two additional parameters for the WP_Query, which you can simply use:

  • rml_folder: This parameters expects an integer / numeric and represent the ID of the folder. If you want to query the unogranized folder, you should use the result of _wp_rml_root() function.
  • orderby: This parameters expects an string. If you want to order by the user defined order (created with drag & drop in the media library), you should use the value "rml".
$query = new WP_Query(array(
	'post_status' => 'inherit',
	'post_type' => 'attachment',
	'rml_folder' => 4,
	'orderby' => "rml"
));

 

Permissions

Give folders permissions to restrict some actions

Every folder can be created with restrictions. This can be useful, if another plugin is handling a folder (like WP/LR sync). For example, you can restrict to create subfolders in a given folder. You are able to create / set restrictions for folders by two ways:

  • wp_rml_create() (see folder helper functions)
  • or IFolder::setRestrictions() (see folder object)

The restrictions can be passed as simple array like array("cre"). The following restrictions are available:

  • par: Restrict to change the parent id
  • rea: Restrict to rearrange the hierarchical levels of all subfolders (it is downwards all subfolders!) and can not be inherited
  • cre: Restrict to create new subfolders
  • ins: Restrict to insert/upload new attachments, automatically moved to root if upload
  • ren: Restrict to rename the folder
  • del: Restrict to delete the folder
  • mov: Restrict to move files outside the folder

Note: You can append a ">" after each permission so it is inherited in each created subfolder: "cre>", "ins>", ...

 

IMetadata interface

Manage meta data for folders

Folder details

Click on the arrow down icon to open the meta data box for a selected folder.

You will find the helper functions in wp-content/plugins/real-media-library/inc/api/meta.php.
The meta helper functions helps you to create, read, update or delete meta data of a folder.

function get_media_folder_meta( $folder_id, $key = '', $single = false )

Retrieve folder meta field for a folder.

  • @param int $folder_id Folder ID.
  • @param string $key Optional. The meta key to retrieve. By default, returns data for all keys. Default empty.
  • @param bool $single Optional. Whether to return a single value. Default false.
  • @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.

 

function add_media_folder_meta( $folder_id, $meta_key, $meta_value, $unique = false )

Add meta data field to a folder.

Folder meta data is called "Custom Fields" on the Administration Screen.

  • @param int $folder_id Folder ID.
  • @param string $meta_key Metadata name.
  • @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  • @param bool $unique Optional. Whether the same key should not be added. Default false.
  • @return int|false Meta ID on success, false on failure.

 

function update_media_folder_meta( $folder_id, $meta_key, $meta_value, $prev_value = '' )

Update folder meta field based on folder ID. Use the $prev_value parameter to differentiate between meta fields with the same key and folder ID. If the meta field for the folder does not exist, it will be added.

  • @param int $folder_id Folder ID.
  • @param string $meta_key Metadata key.
  • @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  • @param mixed $prev_value Optional. Previous value to check before removing. Default empty.
  • @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.

 

function delete_media_folder_meta( $folder_id, $meta_key, $meta_value = '' )

Remove metadata matching criteria from a folder. You can match based on the key, or key and value. Removing based on key and value, will keep from removing duplicate metadata with the same key. It also allows removing all metadata matching key, if needed.

  • @param int $folder_id Folder ID.
  • @param string $meta_key Metadata name.
  • @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar. Default empty.
  • @return bool True on success, false on failure.

 

function delete_media_folder_meta_by_key( $folder_meta_key )

Delete everything from folder meta matching meta key.

  • @param string $folder_meta_key Key to search for when deleting.
  • @return bool Whether the post meta key was deleted from the database.

 

function truncate_media_folder_meta($folder_id)

Remove all metas of a folder. Use this with caution!!

  • @param $folder_id Folder ID
  • @return result of $wpdb->query

 

function add_rml_meta_box($name, $obj, $hasScripts = false, $priority = 10)

Add a visible content to the folder details dialog. For this have a look at the IMetadata class itself below.

  • @param $name unique name for this meta box
  • @param $obj The object which implements IMetadata
  • @param $hasScripts boolean Load the resources if exists
  • @param $priority Priority for actions and filters
  • @see interface IMetadata
  • @called Call this function in the "init" action
  • @see action "init" of wordpress
  • @return boolean

The IMetadata interface based on an example:

You will find the interface in wp-content/plugins/real-media-library/inc/api/IMetadata.interface.php.
The interface helps you to create /output a visible part to the folder details dialog.

The below code shows a simple implementation of a "Description" input field to the folder details dialog. After you have successfully created the class, you can register it with the add_rml_meta_box() function.

<?php
namespace MatthiasWebRealMediaLibrarymetadata;
use MatthiasWebRealMediaLibrarygeneral;
use MatthiasWebRealMediaLibraryapi;

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

/**
 * Implements a description field.
 * 
 * @see inc/api/meta.php
 * @see interface IMetadata for more details
 */
class Description implements apiIMetadata {
 
 public function getDescription($folder_id) {
     return get_media_folder_meta($folder_id, "description", true);
 }
 
 /**
  * The input field.
  *
  * @see interface IMetadata
  */
 public function content($content, $folder) {
     $description = $this->getDescription($folder === null ? _wp_rml_root() : $folder->getId());
     $content .= '<tr>
     <th scope="row">' . __('Description') . '</th>
     <td>
     <textarea name="description" type="text" class="regular-text" style="width: 100%;box-sizing: border-box;">' . $description . '</textarea>
     </td>
     </tr>
     <tr class="rml-meta-margin"></tr>';
 
     return $content;
 }
 
 /**
  * Save the general infos: Name
  * 
  * @see interface IMetadata
  */
 public function save($response, $folder) {
     $toSaveFID = $folder === null ? _wp_rml_root() : $folder->getId();
     $description = $this->getDescription($toSaveFID);
 
     if (isset($_POST["description"])) {
         $newDesc = $_POST["description"];
         if ($newDesc != $description) {
             if (strlen($newDesc) > 0) {
                 update_media_folder_meta($toSaveFID, "description", $newDesc);
             }else{
                 // Delete it
                 delete_media_folder_meta($toSaveFID, "description");
             }
         }
     }
 
     return $response;
 }
 
 /**
 * The general scripts and styles.
 *
 * @see interface IMetadata
 */
 public function scripts() {
     // Silence is golden.
 }
}
TOP