Overview
  • Namespace
  • Class

Namespaces

  • MatthiasWeb
    • RealMediaLibrary
      • api
      • attachment
      • base
      • comp
        • complexquery
      • folder
      • general
      • metadata
      • order
      • rest
      • usersettings
  • None

Classes

  • MatthiasWeb\RealMediaLibrary\attachment\CountCache
  • MatthiasWeb\RealMediaLibrary\attachment\CustomField
  • MatthiasWeb\RealMediaLibrary\attachment\Filter
  • MatthiasWeb\RealMediaLibrary\attachment\Permissions
  • MatthiasWeb\RealMediaLibrary\attachment\Shortcut
  • MatthiasWeb\RealMediaLibrary\attachment\Structure
  • MatthiasWeb\RealMediaLibrary\attachment\Upload
  • MatthiasWeb\RealMediaLibrary\base\Assets
  • MatthiasWeb\RealMediaLibrary\base\Base
  • MatthiasWeb\RealMediaLibrary\base\Core
  • MatthiasWeb\RealMediaLibrary\comp\complexquery\ComplexQuery
  • MatthiasWeb\RealMediaLibrary\comp\complexquery\ResetNames
  • MatthiasWeb\RealMediaLibrary\comp\ExImport
  • MatthiasWeb\RealMediaLibrary\comp\PageBuilders
  • MatthiasWeb\RealMediaLibrary\comp\PolyLang
  • MatthiasWeb\RealMediaLibrary\comp\WPML
  • MatthiasWeb\RealMediaLibrary\folder\BaseFolder
  • MatthiasWeb\RealMediaLibrary\folder\Collection
  • MatthiasWeb\RealMediaLibrary\folder\Creatable
  • MatthiasWeb\RealMediaLibrary\folder\CRUD
  • MatthiasWeb\RealMediaLibrary\folder\Folder
  • MatthiasWeb\RealMediaLibrary\folder\Gallery
  • MatthiasWeb\RealMediaLibrary\folder\Root
  • MatthiasWeb\RealMediaLibrary\general\Activator
  • MatthiasWeb\RealMediaLibrary\general\Assets
  • MatthiasWeb\RealMediaLibrary\general\Core
  • MatthiasWeb\RealMediaLibrary\general\FolderShortcode
  • MatthiasWeb\RealMediaLibrary\general\Lang
  • MatthiasWeb\RealMediaLibrary\general\Migration
  • MatthiasWeb\RealMediaLibrary\general\Options
  • MatthiasWeb\RealMediaLibrary\general\QueryCount
  • MatthiasWeb\RealMediaLibrary\general\Util
  • MatthiasWeb\RealMediaLibrary\general\View
  • MatthiasWeb\RealMediaLibrary\metadata\CoverImage
  • MatthiasWeb\RealMediaLibrary\metadata\Description
  • MatthiasWeb\RealMediaLibrary\metadata\Meta
  • MatthiasWeb\RealMediaLibrary\order\GalleryOrder
  • MatthiasWeb\RealMediaLibrary\order\Sortable
  • MatthiasWeb\RealMediaLibrary\rest\Attachment
  • MatthiasWeb\RealMediaLibrary\rest\Folder
  • MatthiasWeb\RealMediaLibrary\rest\Reset
  • MatthiasWeb\RealMediaLibrary\rest\Service
  • MatthiasWeb\RealMediaLibrary\usersettings\Demo

Interfaces

  • MatthiasWeb\RealMediaLibrary\api\IFolder
  • MatthiasWeb\RealMediaLibrary\api\IFolderActions
  • MatthiasWeb\RealMediaLibrary\api\IFolderContent
  • MatthiasWeb\RealMediaLibrary\api\IMetadata
  • MatthiasWeb\RealMediaLibrary\api\IStructure
  • MatthiasWeb\RealMediaLibrary\api\IUserSettings

Exceptions

  • MatthiasWeb\RealMediaLibrary\general\FolderAlreadyExistsException

Functions

  • _wp_rml_active
  • _wp_rml_root
  • _wp_rml_sanitize
  • _wp_rml_sanitize_filename
  • add_media_folder_meta
  • add_rml_meta_box
  • add_rml_user_settings_box
  • delete_media_folder_meta
  • delete_media_folder_meta_by_key
  • get_media_folder_meta
  • is_rml_folder
  • rml_skip_php_admin_notice
  • rml_skip_rest_admin_notice
  • rml_skip_wp_admin_notice
  • truncate_media_folder_meta
  • update_media_folder_meta
  • wp_attachment_ensure_source_file
  • wp_attachment_folder
  • wp_attachment_get_shortcuts
  • wp_attachment_has_shortcuts
  • wp_attachment_is_shortcut
  • wp_attachment_order_update
  • wp_rml_create
  • wp_rml_create_all_children_sql
  • wp_rml_create_all_parents_sql
  • wp_rml_create_or_return_existing_id
  • wp_rml_create_shortcuts
  • wp_rml_created_shortcuts_last_ids
  • wp_rml_delete
  • wp_rml_dropdown
  • wp_rml_dropdown_collection
  • wp_rml_dropdown_gallery
  • wp_rml_dropdown_gallery_or_collection
  • wp_rml_get_attachments
  • wp_rml_get_by_absolute_path
  • wp_rml_get_by_id
  • wp_rml_get_object_by_id
  • wp_rml_get_parent_id
  • wp_rml_is_type
  • wp_rml_move
  • wp_rml_objects
  • wp_rml_register_creatable
  • wp_rml_rename
  • wp_rml_root_childs
  • wp_rml_structure
  • wp_rml_structure_reset
  • wp_rml_update_count
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 
<?php
namespace MatthiasWeb\RealMediaLibrary\general;
use MatthiasWeb\RealMediaLibrary\attachment;
use MatthiasWeb\RealMediaLibrary\folder;
use MatthiasWeb\RealMediaLibrary\general;
use MatthiasWeb\RealMediaLibrary\base;

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

/**
 * Util.
 */
class Util extends base\Base {
    
    private static $me = null;

    private function __construct() {
        // Silence is golden.
    }
    
    /**
     * Query multiple sql statements.
     * 
     * @param string... $args SQL statements
     */
    public function query() {
        global $wpdb;
        
        if (is_array(func_get_arg(0))) {
            $sqls = func_get_arg(0);
        }else{
            $sqls = func_get_args();
        }
        
        foreach ($sqls as $param) {
            $wpdb->query($param);
        }
    }
    
    public function doActionAnyParentHas($folder, $action, $args = null) {
        global $wpdb;
        if (!is_rml_folder($folder)) {
            return;
        }
        
        /**
         * Add a condition after a defined action ($action) to check if any parent has a metadata.
         * It also includes the self folder so you can check for own folder metadata.
         * <strong>Note:</strong> All found parents are grouped and passed through an action
         * RML/$action/AnyParentHasMeta/$meta_key so you can execute your command. The allowed
         * $actions are:
         * <ul>
         *  <li>"Folder/Insert": Items are moved to the folder (see RML/Item/MoveFinished action for $args)</li>
         *  <li>Your action: Please contact Real Media Library developer to request another action</li>
         * </ul>
         * 
         * @param {string[]} $conditions The conditions which are joined together with OR
         * @param {IFolder} $folder The IFolder object
         * @param {arguments[]} $args The referenced arguments
         * @example <caption>Add a condition</caption>
         * $conditions[] = $wpdb->prepare("rmlmeta.meta_key = 'myMeta' AND rmlmeta.meta_value = %s", "test");
         * @returns {string[]} The conditions
         * @see IFolder::anyParentHasMetadata()
         * @see wp_rml_create_all_parents_sql()
         * @see RML/$action/AnyParentHasMeta/$meta_key
         * @hook RML/$action/AnyParentHasMeta
         * @since 3.3
         */
        $conditions = apply_filters("RML/" . $action . "/AnyParentHasMeta", array(), $folder, $args);
        if (count($conditions) > 0) {
            $sql = wp_rml_create_all_parents_sql($folder, true, null, array(
                "fields" => "rmlmeta.meta_id AS id, rmlmeta.realmedialibrary_id AS folderId, rmlmeta.meta_key, rmlmeta.meta_value AS value",
                "join" => "JOIN " . $this->getTableName("meta") . " rmlmeta ON rmlmeta.realmedialibrary_id = rmldata.id",
                "afterWhere" => "AND ((" . implode(") OR (", $conditions) . "))"
            ));
            
            if ($sql !== false) {
                $rows = $this->group_by($wpdb->get_results($sql, ARRAY_A), "meta_key");
                foreach ($rows as $meta_key => $metas) {
                    /**
                     * This action is called for the results of the RML/$action/AnyParentHasMeta filter.
                     * <strong>Note:</strong> The allowed $actions are: See RML/$action/AnyParentHasMeta
                     * 
                     * @param {array} $metas Result array for this meta key, similar to IFolder::anyParentHasMetadata result
                     * @param {IFolder} $folder The IFolder object
                     * @param {arguments[]} $args The referenced arguments which are also passed to RML/$action/AnyParentHasMeta
                     * @param {array} $all_metas All found metas grouped by meta_key so you can check for multiple meta_keys
                     * @see RML/$action/AnyParentHasMeta
                     * @hook RML/$action/AnyParentHasMeta/$meta_key
                     * @since 3.3
                     */
                    do_action("RML/" . $action . "/AnyParentHasMeta/" . $meta_key, $metas, $folder, $args, $rows);
                }
            }
        }
    }
    
    /**
     * Build a tree from an array.
     * 
     * @see https://stackoverflow.com/questions/8840319/build-a-tree-from-a-flat-array-in-php
     */
    public function buildTree(&$elements, $parentId = -1, $keyParent = 'parent', $key = 'id', $keyChildren = 'children') {
        $branch = array();
        foreach ($elements as &$element) {
            if ($element[$keyParent] == $parentId) {
                $children = $this->buildTree($elements, $element[$key], $keyParent, $key, $keyChildren);
                if ($children) {
                    $element[$keyChildren] = $children;
                }
                $branch[$element[$key]] = $element;
                unset($element);
            }
        }
        return $branch;
    }
    
    /**
     * Clears an array of a tree of the parent and id values.
     *
     * @param array $tree The result of this::buildTree
     * @param string[] $clear
     * @parma string $keyChildren
     */
    public function clearTree(&$tree, $clear = array(), $keyChildren = 'children') {
        foreach ($tree as &$node) {
            foreach ($clear as $c) {
                if (isset($node[$c])) {
                    unset($node[$c]);
                }
            }
            if (isset($node[$keyChildren])) {
                $this->clearTree($node[$keyChildren], $clear, $keyChildren);
                $node[$keyChildren] = array_values($node[$keyChildren]);
            }
        }
        return array_values($tree);
    }
    
    public function group_by($array, $key) {
        $return = array();
        foreach($array as $val) {
            $return[$val[$key]][] = $val;
        }
        return $return;
    }
    
    /**
     * Fixing the missing isShortcut parameter in wp_realmedialibrary_posts
     * when SC is given in the guid.
     */
    public function fixIsShortcutInPosts() {
        $this->debug("Fixing the isShortcut parameter in posts table...", __METHOD__);
        
        global $wpdb;
        $table_name_posts = $this->getTableName("posts");
        $result = $wpdb->get_results("SELECT rmlp.*, p.guid FROM $table_name_posts rmlp
        INNER JOIN $wpdb->posts p ON rmlp.attachment = p.ID
        WHERE rmlp.isShortcut = 0 AND p.guid LIKE '%?sc=%'", ARRAY_A);
        
        $this->debug("Found " . count($result) . " rows", __METHOD__);
        foreach ($result as $row) {
            preg_match('/\?sc=([0-9]+)$/', $row["guid"], $matches);
            if (isset($matches) && is_array($matches) && isset($matches[1])) {
                $sc = (int) $matches[1];
                $sql = $wpdb->query($wpdb->prepare("UPDATE $table_name_posts SET isShortcut = %d WHERE attachment = %d AND fid = %d AND isShortcut = %d",
                    $sc, $row["attachment"], $row["fid"], $row["isShortcut"]));
            }
        }
    }
    
    /**
     * Allows to reset all names with slugs and absolute pathes.
     */
    public function resetAllSlugsAndAbsolutePathes($remap = null) {
        global $wpdb;
        $this->debug("Start resetting names, slugs and absolute pathes...", __METHOD__);
        
        // Read rows
        $table_name = $this->getTableName();
        $sql = "SELECT t1.id, t2.name FROM ( SELECT t0.r_init AS id, IF(t0.reset_r = 1, (@r := t0.r_init), (@r := (select parent from $table_name where id = @r))) AS r, IF(t0.reset_r = 1, (@l := 1), (@l := @l + 1)) AS lvl FROM (SELECT m0.id as counter, m1.id AS r_init, ((SELECT min(id) FROM $table_name) = m0.id) AS reset_r FROM $table_name m0, $table_name m1 ORDER BY r_init, counter) t0 ORDER BY t0.r_init, t0.counter ) t1 INNER JOIN $table_name t2 ON t2.id = t1.r WHERE r <> -1 ORDER BY id, lvl DESC";
        $rows = $wpdb->get_results($sql, ARRAY_A); // folder|folderparentpart|name
        if (count($rows) > 0) {
            // Create migration table
            $table_name_reset = $this->getTableName("resetnames");
            $this->getCore()->getActivator()->install(false, array($this, "resetAllSlugsAndAbsolutePathesTable"));
            
            // Clear already created resets
            $wpdb->query("DELETE FROM " . $table_name_reset);
            
            // Get rows and create
            $rows = $this->group_by($rows, "id");
            $sqlInserts = array();
            foreach ($rows as $fid => $parts) {
                $names = array();
                foreach ($parts as $part) {
                    $names[] = $part["name"];
                }
                if ($remap !== null) {
                    $names = array_map($remap, $names);
                }
                $slugs = array_map("_wp_rml_sanitize", $names);
                
                $partCount = count($names);
                $lastIdx = $partCount - 1;
                
                // Updateable columns
                $name = $names[$lastIdx];
                $slug = $slugs[$lastIdx];
                $absolutePath = implode("/", $slugs);
                
                // Add to update statement
                if (!empty($name)) {
                    $sqlInserts[] = $wpdb->prepare("%d,%s,%s,%s", $fid, $name, $slug, $absolutePath);
                }
            }
            
            // Create SQL INSERT statements
            $chunks = array_chunk($sqlInserts, 150);
            foreach ($chunks as $sqlInsert) {
                $sql = "INSERT INTO $table_name_reset VALUES (" . implode("),(", $sqlInserts) . ")";
                $wpdb->query($sql);
            }
            
            // Create UPDATE statement
            $wpdb->query("UPDATE $table_name AS rml
                LEFT JOIN $table_name_reset AS rmlnew ON rml.id = rmlnew.id
                SET rml.name = rmlnew.name, rml.slug = rmlnew.slug, rml.absolute = rmlnew.absolute");
            
            // Clear again
            //$wpdb->query("DELETE FROM " . $table_name_reset);
        }
        
        // Resolve duplicate slugs
        $this->debug("Reset finished", __METHOD__);
        $dups = $wpdb->get_results("SELECT rml.id, rml.slug
            FROM $table_name rml
            INNER JOIN (
             SELECT rmlSlug.slug
                FROM $table_name rmlSlug
                GROUP BY rmlSlug.slug
                HAVING COUNT( id ) > 1
            ) j ON rml.slug = j.slug", ARRAY_A);
        if (count($dups) > 0) {
            $this->debug("Resolving duplicate slugs...", __METHOD__);
            foreach ($this->group_by($dups, "slug") as $dupIds) {
                for ($i = 1; $i < count($dupIds); $i++) {
                    $folder = wp_rml_get_object_by_id($dupIds[$i]["id"]);
                    if ($folder !== null) {
                        $folder->updateThisAndChildrensAbsolutePath();
                    }
                }
            }
        }
    }
    
    public function resetAllSlugsAndAbsolutePathesTable() {
        $this->debug("Create reset table...", __METHOD__);
        $table_name = $this->getTableName("resetnames");
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL,
            name tinytext NOT NULL,
            slug text DEFAULT '' NOT NULL,
            absolute text DEFAULT '' NOT NULL,
            UNIQUE KEY id (id)
        ) $charset_collate;";
        dbDelta( $sql );
    }
    
    /**
     * @see wp_rml_create_all_parents_sql
     */
    public static function createSQLForAllParents($folder, $includeSelf = false, $until = null, $options = null) {
        global $wpdb;
        
        // Get folder id
        $folderId = $folder instanceof folder\Creatable ? $folder->getId() : $folder;
        if (!is_numeric($folderId)) {
            return false;
        }
        
        // Parse options
        $options = array_merge(array(
            "fields" => "rmldata.*, rmltmp.lvl AS lvlup",
            "join" => "",
            "where" => "rmltmp.lvl > " . ($includeSelf === true ? "-1" : "0"),
            "afterWhere" => "",
            "orderby" => "rmltmp.lvl ASC",
            "limit" => ""
        ), $options === null ? array() : $options);
        
        $table_name = general\Core::getInstance()->getTableName();
        return $wpdb->prepare("SELECT " . $options["fields"] . "
            FROM ( SELECT @r AS _id, (SELECT @r := parent FROM $table_name WHERE id = _id) AS parent, @l := @l + 1 AS lvl
                    FROM (SELECT @r := %d, @l := -1) vars, $table_name m
                    WHERE @r <> %d) rmltmp
            JOIN $table_name rmldata ON rmltmp._id = rmldata.id " . $options["join"] . "
            WHERE " . $options["where"] . " " . $options["afterWhere"] . "
            ORDER BY " . $options["orderby"] . " " . $options["limit"], $folderId, $until == null ? _wp_rml_root() : $until);
    }
    
    /**
     * @see wp_rml_create_all_children_sql
     */
    public static function createSQLForAllChildren($folder, $includeSelf = false, $options = null) {
        global $wpdb;
        
        // Get folder id
        $folderId = $folder instanceof folder\Creatable ? $folder->getId() : $folder;
        if (!is_numeric($folderId)) {
            return false;
        }
        
        // Parse options
        $options = array_merge(array(
            "fields" => "rmldata.*",
            "join" => "",
            "where" => $wpdb->prepare("rmldata._parent = %d", $folderId)
                        . ($includeSelf === true ? "" : $wpdb->prepare(" AND rmldata.id != %d", $folderId)),
            "afterWhere" => "",
            "orderby" => "rmldata.parent, rmldata.ord",
            "limit" => ""
        ), $options === null ? array() : $options);
        
        $table_name = general\Core::getInstance()->getTableName();
        return "SELECT " . $options["fields"] . "
            FROM (SELECT t0.*,
                IF(t0._r_reset = 1, (@r := t0._r_init), (@r := (SELECT m3.parent FROM $table_name m3 WHERE id = @r))) AS _parent,
                IF(t0._r_reset = 1, (@l := 0), (@l := @l + 1)) AS lvldown
              FROM 
                (SELECT m1.*, m0.id AS _r_counter, m1.id AS _r_init,
                   ((SELECT MIN(m2.id) FROM $table_name m2) = m0.id) AS _r_reset 
                 FROM $table_name m0 JOIN $table_name m1) t0 
              ORDER BY t0._r_init, t0._r_counter) rmldata
            " . $options["join"] . "
            WHERE " . $options["where"] . " " . $options["afterWhere"] . "
            ORDER BY " . $options["orderby"] . " " . $options["limit"];
    }
    
    public function esc_sql_name($name) {
        return str_replace( "`", "``", $name );
    }
    
    public static function getInstance() {
        if (self::$me == null) {
            self::$me = new Util();
        }
        return self::$me;
    }
}

?>
API documentation generated by ApiGen