Gravatar Import

Last modified by Vincent Massol on 2021/03/18 11:28

cogSet Gravatar images for users with no avatar defined
TypeSnippet
Category
Developed by

Vincent Massol

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

The following script does:

  • List users not having an avatar set in their profile
  • Query Gravatar.com for an image based on their email (size asked is 120x120 pixels)
  • If no image is found on Gravatar.com ask Gravatar to generate an image (by default in the script below it's a "monster" image)
  • Set the Gravatar image in the user profil (when confirm=1 is passed in the URL)
  • If no email is found in the user profile use the user's fullname to generate the "monster" image

This script should be improved to compute users not having an avatar in a single HQL/XWQL query - Right now we load all users in the wiki which is performance-costly especially for large wikis with lots of users.

{{groovy}}
// Find all users with no avatar
println "Looking for Gravatars for users who don't have any avatar set in their profile:"

if (request.getParameter("confirm") == "1") {
println "|=Gravatar|=User Name|=Status"
} else {
println "|=Gravatar|=User Name"
}

services.query.xwql("from doc.object(XWiki.XWikiUsers) as user").execute().each() {
def userDoc = xwiki.getDocument(it)
def userObj = userDoc.getObject("XWiki.XWikiUsers")
def avatarProp = userObj.getProperty("avatar")
if (avatarProp == null || avatarProp.getValue().trim().length() == 0) {
  // Get their email and if there's one try to find a gravatar
  def email = userObj.getProperty("email").getValue()
  if (email.trim().length() == 0) {
    email = it
   }
  def hash = org.apache.commons.codec.digest.DigestUtils.md5Hex(email)
  def url = "http://www.gravatar.com/avatar/${hash}?d=monsterid&s=120"
  if (request.getParameter("confirm") == "1") {
    userDoc.addAttachment("gravatar.png", new java.net.URL(url).openStream())
    userObj.set("avatar", "gravatar.png")
    userDoc.save("Set Gravatar as avatar", true)
    println "|[[image:${url}]]|[[${it}]]|Gravatar imported into profile!"
   } else {
    println "|[[image:${url}]]|[[${it}]]"
   }
 }
}
{{/groovy}}

Example

Here's an example of running this script on a site:

gravatar.png

Tags:
     

Get Connected