protected function open_element_contextual_menu($name, $filemanagerelement = false) {

        // If a filemanager is specified we restrict the search to the descendants of this particular filemanager form element.
        $containernode = false;
        $exceptionmsg = '"'.$name.'" element can not be found';
        if ($filemanagerelement) {
            $containernode = $this->get_filepicker_node($filemanagerelement);
            $exceptionmsg = 'The "'.$filemanagerelement.'" filemanager ' . $exceptionmsg;
            $locatorprefix = "//div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content ')]";
        } else {
            $locatorprefix = "//div[contains(concat(' ', normalize-space(@class), ' '), ' fp-repo-items ')]" .
                             "//descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content ')]";
        }

        $exception = new ExpectationException($exceptionmsg, $this->getSession());

        // Avoid quote-related problems.
        $name = behat_context_helper::escape($name);

        // Get a filepicker/filemanager element (folder or file).
        try {

            // First we look at the folder as we need to click on the contextual menu otherwise it would be opened.
            $node = $this->find(
                'xpath',
                $locatorprefix .
                    "//descendant::*[self::div | self::a][contains(concat(' ', normalize-space(@class), ' '), ' fp-file ')]" .
                    "[contains(concat(' ', normalize-space(@class), ' '), ' fp-folder ')]" .
                    "[normalize-space(.)=$name]" .
                    "//descendant::a[contains(concat(' ', normalize-space(@class), ' '), ' fp-contextmenu ')]",
                $exception,
                $containernode
            );

        } catch (ExpectationException $e) {

            // Here the contextual menu is hidden, we click on the thumbnail.
            $node = $this->find(
                'xpath',
                $locatorprefix .
                "//descendant::*[self::div | self::a][contains(concat(' ', normalize-space(@class), ' '), ' fp-file ')]" .
                "[normalize-space(.)=$name]" .
                "//descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-filename-field ')]",
                false,
                $containernode
            );
        }

        // Click opens the contextual menu when clicking on files.
        $this->ensure_node_is_visible($node);
        $node->click();
    }