Recommended Posts

If you've ever needed to insert links to a large number of files within CKEditor you may have found that the standard PW link modal is a somewhat slow way to do it.

This module provides a quicker way to insert links to files on the page being edited. You can insert a link to an individual file, or insert an unordered list of links to all files on the page with a single click.

CKEditor Link Files

Adds a menu to CKEditor to allow the quick insertion of links to files on the page being edited.

link-files

Features

  • Hover a menu item to see the "Description" of the corresponding file (if present).
  • Click a menu item to insert a link to the corresponding file at the current cursor position. The filename is used as the link text.
  • If you Alt-click a menu item the file description is used as the link text (with fallback to filename if no description entered).
  • If text is currently selected in the editor then the selected text is used as the link text.
  • Click "* Insert links to all files *" to insert an unordered list of links to all files on the page. Also works with the Alt-click option.
  • Menu is built via AJAX so newly uploaded files are included in the menu without the page needing to be saved. However, descriptions are not available for newly uploaded files until the page is saved.

Installation

Install the CKEditor Link Files module.

For any CKEditor field where you want the "Insert link to file" dropdown menu to appear in the CKEditor toolbar, visit the field settings and add "LinkFilesMenu" to the "CKEditor Toolbar" settings field.

 

http://modules.processwire.com/modules/cke-link-files/

https://github.com/Toutouwai/CkeLinkFiles

  • Like 18

Share this post


Link to post
Share on other sites

Hi Robin,
I added "LinkFilesMenu" to the "CKEditor Toolbar" settings field and the icon appear in the toolbar.  But it doesn't show the pdf files when I click the icon. No dropdown.
Do I have to name the file-field in a special way?
It's a multi-language site.

Share this post


Link to post
Share on other sites

@Nick Belane, you don't need to name file fields in any special way. There should still be a dropdown even when there are no files that can be linked to. See screenshot:

2018-02-05_115209.png.6885e77e9ff6aad35501ef99e550bc17.png

So if you are not getting a dropdown then my guess is that there could be a Javascript error. Do you see any JS errors in the console panel of your browser dev tools?

I don't know anything about multi-language sites sorry (no demand for them in my country). Maybe someone else can confirm if the module works or not with multi-language?

Share this post


Link to post
Share on other sites

I went to test on a ML site, but I don't actually even see the button and I do get these JS errors.

image.png.70411dcffa0d53a439f0493e7b2c319f.png

 

This is my settings:

image.png.d7454b8712d9b14a3e86b9edbb1e9e34.png

 

Let me know if there is anything I can do to debug.

  • Like 1

Share this post


Link to post
Share on other sites

@Nick Belane, the issue with multi-language fields is hopefully fixed in v0.1.2. Please update and let me know if you are still seeing an issue.

Thanks @adrian for debugging help.

  • Like 1

Share this post


Link to post
Share on other sites
52 minutes ago, Nick Belane said:

now it works in Chrome but not in FF (58.0.1).

It's working here in Firefox, and it's unlikely that there will be a difference between browsers in how that JS works.

I think it must be a caching issue. Please visit Modules > Site and click "Refresh", and then scroll down and click "Clear compiled files".

  • Like 3

Share this post


Link to post
Share on other sites

Hi @Robin S, would you mind if I add this to AOS? I've made some changes, eg. display description + filename in the menu (if there's no description, use the basename without extension), and hide the menu when clicking outside of it. The latter is handy on a multilanguage site as the menu doesn't stay open when clicking to another language tab. Of course this happens only if you don't click on a menu item. I also plan to make it more ML-friendly by adjusting the description per language (some day).

  • Like 2

Share this post


Link to post
Share on other sites
59 minutes ago, tpr said:

would you mind if I add this to AOS?

No, I don't mind. Go right ahead.

  • Like 3

Share this post


Link to post
Share on other sites

Thanks, will do. I've just finished making it multilanguage-ready but need to check first on non-ML site too, though the way it's set up I don't expect any issue. I ended up adding multiple divs to the DOM containing the list of files, one for each language (#link-files-menu, #link-files-menu__1088, and so on). Then on menu toolbar click I get the current lang ID of the editor (from data-configname and ckeditor ID) and show/hide the corresponding menu.

Update: see here

  • Like 4

Share this post


Link to post
Share on other sites

This is great Robin!

Is there any way to make the description (if available) the default text for the link rather than the filename? I can handle the alt+ trick, but won't be able to teach that to 60+ users. It would be great if it were an option, same with setting a default target for the generated links (we always have files open in a new tab).

Share this post


Link to post
Share on other sites
Posted (edited)
4 hours ago, Arcturus said:

Is there any way to make the description (if available) the default text for the link rather than the filename?

@Arcturus, this module's functionality has been merged into AdminOnSteroids. If you are a user of that module it might be better to post your request in the support thread for AOS.

If you're not an AOS user then I guess I could make a config option to reverse the click/Alt-click behaviour. Let me know.

4 hours ago, Arcturus said:

It would be great if it were an option, same with setting a default target for the generated links (we always have files open in a new tab).

I'm not keen to go down this road. There are a large number of attributes a link can potentially have and I don't want to try and support them all. This module is intended as a time-saving tool for power-users who are tasked with loading/editing large amounts of content - I have in mind the superuser who must do an initial loading of content supplied by a client. The module isn't intended to be a full replacement of the PW link dialog. For anything beyond what this module provides I suggest you use the link dialog, or perhaps a textformatter module to apply link attributes like target in a systematic way. TBH, if my clients were 60+ and not all that computer literate I would have them stick to the core link dialog so they don't have to learn something new.

Edit: you can also add a target attribute to internal file links via a simple piece of jQuery on the front-end:

// Add target attribute to internal file links
$('a[href^="/site/assets/files/"]').attr('target', '_blank');

 

Edited by Robin S
Added jQuery snippet

Share this post


Link to post
Share on other sites

Thanks for getting back to me. I'm not using AOS, but I can understand why you wouldn't want to maintain a separate project. No problem though, it only took me a few minutes to apply both of my desired changes to your existing plugin.  

For anyone else who's interested, here are the altered lines (91-96) from plugin.js

			} else if(use_description && $(this).attr('title').length) {
				text = $(this).text();
			} else {
				text = $(this).attr('title');
			}
			html = '<a href="' + $(this).data('url') + '" target="_blank">' + text + '</a>'

Those 60+ users are coming over to PW from ExpressionEngine, so this will be an entirely new process to them anyway. But much easier for me to teach them now. ;)

Share this post


Link to post
Share on other sites
2 minutes ago, Arcturus said:

Those 60+ users are coming over to PW from ExpressionEngine, so this will be an entirely new process to them anyway.

What I meant is that they have to learn how to use the core link dialog regardless because I'm sure they'll need to create non-file links, and then they have to also learn a different method if using this module for file links.

5 minutes ago, Arcturus said:

No problem though, it only took me a few minutes to apply both of my desired changes to your existing plugin.

Glad you have it working how you like. This module isn't likely to get many updates now that it is merged into AOS, but bear in mind if you do see an update available you will need to either avoid updating or reapply your changes to the updated module files.

Share this post


Link to post
Share on other sites

Thanks a lot for sharing this useful plugin and it proved it very useful and understability and all is really worth useful .

Share this post


Link to post
Share on other sites

I've created a module based almost entirely on this module, and my problem occurs both with my new module and the original. So even though CKE Insert Links has been incorporated into AOS, this seems the best place to post.

My new module allows users to insert links from a list of page names. It is little more than the original module with some renaming of functions and variables, and getting a list of pages rather than a list of attached files; then the menu is displayed in a CKE dialog rather than from the toolbar.

My new module and CKE Insert Links work fine in Firefox for all users, and work in Chrome for superusers. But they fail in Chrome (and Edge on early testing) if the user is not a superuser.

The failure manifests itself with CKE Insert Links as the menu showing "No files for this page", and in my module with the equivalent error message.

I have debugged as far as finding that the problem seems to be with the $.getJSON() function in plugin.js, which is failing to return anything. In the code below, if(data.length) is evaluating to false.

Note that the new code is very close to the original module, with functions and variables renamed.

function addReferencesDialogMenu(page_id) {

  	// Adds data for dialog menu to DOM
  
	$('#link-references-dialog').remove();
	var ajax_url = config.urls.admin + 'module/edit?name=CkeLinkRefsDialog&pid=' + page_id;

 	var $list = $('<ul></ul>');
	$.getJSON(ajax_url).done(function(data) {

		if(data.length) {
			$.each(data, function(index, value) {
				$list.append( $('<li title="' + value.description + '">' + value.insertionvalues + '</li>') );
			});
		} else {
			$list.append( $('<li title="' + config.CkeLinkRefsDialog.no_references_text + '">' + config.CkeLinkRefsDialog.no_references_text + '</li>') );
			//$list.append( $('<li class="no-references" title="' + config.CkeLinkRefsDialog.no_references_text + '">NO DATA</li>') );
		}
	});

	$('body').append( $('<div id="link-references-dialog"></div>').append($list) );
}

The AJAX response section of the .module file is as follows. Again, just like the original, except the middle section that gets page info instead of attached-file info.
 

public function ajaxResponse(HookEvent $event) {

    // Must be AJAX request, must be for this module, must include pid GET variable
    if(!$this->config->ajax || $this->input->get->name !== $this->className() || !$this->input->get->pid) return;
    $page = $this->pages->get( (int) $this->input->get->pid );
    if(!$page->editable) return;
    $event->replace = true;
    $event->cancelHooks    = true;
    $result = array();
    
    // Get all relevant pages
    $referencePages = wire('pages')->find('template=reference');
    
    // Build array of page info for menu
    foreach($referencePages as $refPage) {
        $pageUrl = $refPage->url;
        $pageTitle = $refPage->title;
        $pageTitleArr = explode("|", str_replace("). ",")|",$pageTitle));
        $result[] = array(
            'description'=> $this->truncate($pageTitle, 60),
            'insertionvalues' => $pageTitleArr[0]."|".$pageUrl
        );
    }

    $event->return = json_encode($result);
}


I am unable to understand how or why superuser permissions (or absence of such permissions) have any effect.

Any help gratefully received!

  • Like 1

Share this post


Link to post
Share on other sites
10 hours ago, BillH said:

The failure manifests itself with CKE Insert Links as the menu showing "No files for this page", and in my module with the equivalent error message.

Thanks for reporting this issue. It should be fixed in v0.1.5 of CKEditor Link Files. If you check the changes in this commit you can apply something similar in your module.

@tpr, this issue will affect the version included in AdminOnSteroids too. I thought a hook before module edit would trigger before the access control kicks in but it seems not. Sort of obvious in hindsight. I really didn't want to have to add a page just for the AJAX response so went looking for some other process to hook into. I settled on ProcessLogin::executeLogout as this is one process module/method that should be accessible for any user. You might want to update AOS with a similar fix.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for getting back to me. I'll have a go with the changes this afternoon.

Share this post


Link to post
Share on other sites

Excellent. All works fine now. Thanks @Robin S.

B.t.w., if anyone is reading this thread, ignore the remarks in my first post about different browsers. I was just getting in a muddle with how I was logged in with each :-(

Also worth noting is that CKEditor Link Files works in a really neat way and is great for adapting if you want to insert PW content into CKEditor text. I've actually built a couple of modules based on it, and have one or two more in mind!

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Rudy
      https://ckeditor.com/blog/CKEditor-5-v1.0.0-beta-released/
      Looks very clean. Hopefully we get to test it on PW soon.
       
    • By BitPoet
      As threatened in the Pub sub forum in the "What are you currently building?" thread, I've toyed around with Collabora CODE and built file editing capabilities for office documents (Libre-/OpenOffice formats and MS Office as well as a few really old file types) into a PW module.
      If you are running OwnCloud or NextCloud, you'll perhaps be familiar with the Collabora app for this purpose.
      LoolEditor
      Edit office files directly in ProcessWire
      Edit your docx, odt, pptx, xlsx or whatever office files you have stored in your file fields directly from ProcessWire's page editor. Upload, click the edit icon, make your changes and save. Can be enabled per field, even in template context.
      Currently supports opening and saving of office documents. Locking functionality is in development.
      See the README on GitHub for installation instructions. You should be reasonably experienced with configuring HTTPS and running docker images to get things set up quickly.
      Pull requests are welcome!
      Here is a short demonstration:

    • By Robin S
      An Images field allows you to:
      Rename images by clicking the filename in the edit panel or in list view. Replace images, keeping metadata and filename (when possible) by dropping a new image on the thumbnail in the edit panel. Introduced here. But neither of these things is possible in File fields, which prompted this module. The way that files are renamed or replaced in this module is not as slick as in the Images field but it gets the job done. The most time-consuming part was dealing with the UI differences of the core admin themes. @tpr, gives me even more respect for the work that must go into AdminOnSteroids.
      Most of the code to support the rename/replace features is already present in InputfieldFile - there is just no UI for it currently. So hopefully that means these features will be offered in the core soon and this module can become obsolete.
       
      Files Rename Replace
      Allows files to be renamed or replaced in Page Edit.

      Usage
      Install the Files Rename Replace module.
      If you want to limit the module to certain roles only, select the roles in the module config. If no roles are selected then any role may rename/replace files.
      In Page Edit, click "Rename/Replace" for a file...
      Rename
      Use the text input to edit the existing name (excluding file extension).
      Replace
      Use the "Replace with" select to choose a replacement file from the same field. On page save the file will be replaced with the file you selected. Metadata (description, tags) will be retained, and the filename also if the file extensions are the same.
      Tip: newly uploaded files will appear in the "Replace with" select after the page has been saved.
       
      https://github.com/Toutouwai/FilesRenameReplace
      http://modules.processwire.com/modules/files-rename-replace/
    • By d'Hinnisdaël
      So I decided to wade into module development and created a wrapper module around ImageOptim, a service that compresses and optimizes images in the cloud. ImageOptim currently handles JPG, PNG and GIF files and, depending on the settings you use, shaves off between 15% and 60% in filesize. Great for bandwidth and great for users, especially on mobile.
      This module handles the part of uploading images to ImageOptim via their official API, downloading the optimized version and storing it alongside the original image.
       

       
      Download & Info
      GitHub / Module directory / Readme / Usage
       
      Why ImageOptim?
      There are other image optimization services out there, some of them free, that have outstanding ProcessWire modules. A few things make ImageOptim the best tool for most of my customers: It's not free, i.e. it will probably be around for a while and offers support. However, it's cheaper than some of the bigger competitors like Cloudinary. And it does PNG compression better than any of the free services out there, especially those with alpha channels.
       
      Installation
      Install the module like any other ProcessWire module, by either copying the folder into your modules folder or installing it via the admin. See above for downloads links on GitHub and in the module directory.
       
      Requirements
      To be able to upload images to the service, allow_url_fopen must be set on the server. The module will abort installation if that's not the case.
      I have only tested the module on ProcessWire 3.x installations. I don't see why it shouldn't work in 2.x, if anyone wants to try it out and report back.
       
      ImageOptim account
      To compress images, you first need to sign up for an ImageOptim account. They offer free trials to try the service.
       
      Usage (manual optimization)
      Images can be optimized by calling the optimize() method on any image. You can pass an options array to set ImageOptim API parameters.
      $image->size(800,600)->optimize()->url $image->optimize(['quality' => 'low', 'dpr' => 2]) // Set quality to low and enable hi-dpi mode
      Automatic optimization
      The module also has an automatic mode that optimizes all image variations after resizing. This is the recommended way to use this module since it leaves the original image uncompressed, but optimizes all derivative images.
      $image->size(800,600)->url // nothing to do here; image is optimized automatically
      To change compression setting for single images, you can pass an options array along with the standard ImageResizer options. Passing false disables optimization.
      $image->size(800, 600, ['optimize' => 'medium']) $image->size(800, 600, ['optimize' => ['quality' => 'low', 'dpr' => 2]]) $image->size(800, 600, ['optimize' => false])
      For detailed usage instructions and all API parameters, see the usage instructions on GitHub.
       
      Filenames
      Optimized images will be suffixed, e.g. image.jpg becomes image.optim.jpg. You can configure the suffix in the module settings.
       
      Roadmap
      Asynchronous processing. Not really high on the list. Image variations need to be created anyway, so waiting a few seconds longer on first load is preferable to adding complexity to achieve async optimization. Optimize image variations created by other modules. CroppableImage comes to mind. I don't use any of these, so if somebody wants to help out and submit a pull request — all for it! Add a dedicated page in the setup menu with a dashboard and detailed statistics. ImageOptim's API is very barebones for now, so not sure if that's feasible or even necessary.
      Stability
      I've been using this module on production sites for some time now, without hiccups. If you do notice oddities, feel free to comment here or investigate and submit PRs.