Invitation

De SupraWiki

Predefinição:Include reference="Invitation.InvitationCommon" /

Predefinição:Include reference="Invitation.InvitationMembersCommon" /

Predefinição:Velocity

* Invitation Application
* This script is only for sending messages and users who are not allowed to send mail need not have access to
* view this page.
*
* Macros in this script don't rely on any variables except those which are passed to them and the following:
*
* $doc the com.xpn.xwiki.api.Document object representing the document containing this code.
* $msg the internationalization message provider containing a get(String) and a get(String, List) function
* $xcontext the com.xpn.xwiki.Context object for this request
* $xwiki an object of the com.xpn.xwiki.api.XWiki class.
*
* Macros also depend on other macros but only other macros which are contained in this script.
*
* This script relies on the following documents:
*
* InvitationCommon
*
* InvitationMembersCommon
* 
*
* This script is affected by the following documents:
*
* InvitationMessages stores all of the mail message objects. If this does not exist it will be created.
*                    May be changed in the configuration.
*
* InvitationMailClass the class for mail message objects. May be changed in the configuration.
*
* InvitationConfig configuration for this code. Contains an XObject of the class defined in this document.
*                  If it does not exist it will be created with default values.
*
*###
  1. if($xcontext.getUser() == 'XWiki.XWikiGuest')
 ## Only members should ever have access to this document, enforce this through XWiki permissions system,
 ## this is a last effort in the event of incorrect settings.
 #stop
  1. end
    1. is the user a mail admin TODO: change this.
  2. set($isAdmin = $hasEdit)
    1. Load config and mail.
  3. set($config = {})
  4. loadInvitationConfig($config)
  5. set($mail = {})
  6. set($emailContainer = $xwiki.getDocumentAsAuthor($config.get('emailContainer')))
  7. loadInvitationMail($config, $emailContainer, $mail)
    1. Load CSS

$xwiki.get('ssx').use($config.get('commonPage'))

    1. Don't load comments, history, etc.
  1. set ($displayDocExtra = false)
  2. displayInvitationHeader($request.getParameterMap(), $config)
    1. ---------------------------------------------------------------------
    2. Decide what we should do.
    3. ---------------------------------------------------------------------
  3. if($xcontext.getAction() != 'view')
 ## The administration application includes this page so we will not do anything.
  1. elseif(!$isAdmin && "#isUserReportedSpammer($mail.values())" != 'false')
 ## The current user has been reported as a spammer, they are not allowed to send more mail until
 ## the situation has been investigated.
 ## A message which you sent was reported as spam and your privilege to send mail has been suspended...
 (%id="invitation-permission-error"%)(((Predefinição:Error$services.localization.render('xe.invitation.userIsReportedSpammer')Predefinição:/error)))
 ##
  1. elseif(!$isAdmin
       && $config.get('allowUsersOfOtherWikis') != '1'
       && $doc.getWiki() != $xwiki.getDocument($xcontext.getUser()).getWiki())
 ## Users of other subwikis are not allowed to send mail.
 (%id="invitation-permission-error"%)(((Predefinição:Error$services.localization.render('xe.invitation.onlyMembersCanSendMail')
 $services.localization.render('xe.invitation.youAreAMemberOfOtherWiki', [$xwiki.getDocument($xcontext.getUser()).getWiki()])Predefinição:/error)))
  1. else
 ## The user is authorized to send mail <-------------------------------------------------------
 ## Get the list of email addresses to send to.
 #set($userMaySendToMultiple = ($isAdmin || $config.get('usersMaySendToMultiple') == '1'))
 #set($recipientString = $escapetool.xml("$!request.get('recipients')"))
 #set($recipients = [])
 #getRecipients($recipientString, $userMaySendToMultiple, $recipients)
 ##
 ## get subject line and message body if allowed...
 #set($userMayPersonalizeMessage = ($isAdmin || $config.get('usersMayPersonalizeMessage') == '1'))
 #if($userMayPersonalizeMessage)
   #set($subjectLine = $request.get('subjectLine'))
   #set($messageBody = $request.get('messageBody'))
 #else
   #set($subjectLine = )
   #set($messageBody = )
 #end
 ##
 #if("$!request.get('sendMail')" != 
     && $request.getMethod().toLowerCase() == 'post'
     && ${services.csrf.isTokenValid("$!{request.getParameter('form_token')}")})
   #generateAndSendMail($config,
                        $recipients,
                        $subjectLine,
                        $messageBody)
   ## Reload mail so footer information is correct.
   #set($mail = {})
   #loadInvitationMail($config, $emailContainer, $mail)
 #else
   ## The user wants to write and preview a message.
   #displayForm($recipientString,
                $subjectLine,
                $messageBody,
                $userMaySendToMultiple,
                $userMayPersonalizeMessage)
   #set($messages = [])
   ## No recipients (,) because we are just creating it to preview.
   #set($emailContainer = $xwiki.getDocumentAsAuthor($config.get('emailContainer')))
   #generateMailFromTemplate($config.get('subjectLineTemplate'),
                             $config.get('messageBodyTemplate'),
                             $config.get('emailClass'),
                             [],
                             $config.get('emailRegex'),
                             $subjectLine,
                             $messageBody,
                             $messages,
                             $emailContainer)
   #set($invalidAddresses = [])
   #validateAddressFormat($recipients, $config.get('emailRegex'), $invalidAddresses)
   #displayMessage($messages.get(0), $recipients, $invalidAddresses)
 #end
 #invitationFooter($mail, $request.getParameterMap(), $isAdmin, $config)
  1. end##if user has permission to send
    1. ---------------------------------------------------------------------
    2. The macros (Nothing below this point is run directly)
    3. ---------------------------------------------------------------------
* Generate and send an email message.
*
* $messages (List<XObject>) a list of invitation email messages.
*
* $config (XObject) configuration for the inviter.
*
* $emailContainer (Document) the document contaning the mail message.
*###
  1. macro(generateAndSendMail, $config, $recipients, $messageSubject, $messageContent)
 #set($messages = [])
 #set($emailContainer = $xwiki.getDocumentAsAuthor($config.get('emailContainer')))
 #generateMailFromTemplate($config.get('subjectLineTemplate'),
                           $config.get('messageBodyTemplate'),
                           $config.get('emailClass'),
                           $recipients,
                           $config.get('emailRegex'),
                           $messageSubject,
                           $messageContent,
                           $messages,
                           $emailContainer)
 ##
 #if($messages.size() > 0)
   #sendMail($messages, $config, $emailContainer)
   #set($errors = [])
   #foreach($message in $messages)
     #set($status = $message.getProperty('status').getValue())
     #if($status != 'pending')
       #set($discard = $errors.add($message))
     #end
   #end
   (%class="invitation"%)(((
     (%id="invitation-action-message"%)(((##
     #if($errors.size() > 0)
       ## An error has occured while sending the message.
       Predefinição:Error$services.localization.render('xe.invitation.errorWhileSending')Predefinição:/error##
     #else
       ## Your message has been sent.
       Predefinição:Info$services.localization.render('xe.invitation.successSending')Predefinição:/info##
     #end
     )))
     #displayMessageTable($messages, ['sentDate', 'recipient', 'status'])
    )))
   #displayMessage($messages.get(0), $recipients)
 #else


   (%id="invitation-action-message"%)(((Predefinição:Error$services.localization.render('xe.invitation.noValidMessagesToSend')Predefinição:/error)))
 #end
  1. end
* Send an email message.
*
* $messages (List<XObject>) a list of invitation email messages.
*
* $config (XObject) configuration for the inviter.
*
* $emailContainer (Document) the document contaning the mail messages.
*###
  1. macro(sendMail, $messages, $config, $emailContainer)
 ##
 ## Get mail sender plugin.
 #set($sender = $xwiki.get('mailsender'))
 ##
 ## If parameters are set in the local config, use them, otherwise use global defaults.
 #set($senderConfig = $sender.createMailConfiguration($xwiki))
 #if("$!config.get('smtp_server')" != )
   $senderConfig.setHost($config.get('smtp_server'))##
 #end
 #if("$!config.get('smtp_port')" != )
   $senderConfig.setPort($mathtool.toInteger($config.get('smtp_port')))##
 #end
 #if("$!config.get('smtp_server_username')" != )
   $senderConfig.setSmtpUsername($config.get('smtp_server_username'))##
 #end
 #if("$config.containsKey('smtp_server_password')" != )
   $senderConfig.setSmtpPassword($config.get('smtp_server_password'))##
 #end
 #if("$config.containsKey('javamail_extra_props')" != )
   $senderConfig.setExtraProperties($config.get('javamail_extra_props'))##
 #end
 ##
 #foreach($message in $messages)
   #set($mailObj = $sender.createMail())
   ##
   #if("$config.get('from_address')" != )
     $mailObj.setFrom($config.get('from_address'))##
   #end
   ##
   ## Set recipients
   #set($recipient = $message.getProperty('recipient').getValue())##
   $mailObj.setTo($recipient)##
   ##
   ## Set the subject line and message body.
   $mailObj.setSubject($message.getProperty('subjectLine').getValue())##
   ##
   ## If text part is not set then we get an NPE when trying to craft a multipart message.
   $mailObj.setTextPart()##
   ## Put all in email div so that we can apply CSS only to the email and not to the preview.

$mailObj.setHtmlPart("

$message.getProperty('messageBody').getValue()

")##

   ##
   ## Send the message
   #if("$sender.sendMail($mailObj, $senderConfig)" != 0)
     #setMessageStatus($message, 'sendingFailed')##
   #else
     #setMessageStatus($message, 'pending', $services.localization.render('xe.invitation.messageSentLogEntry'))##
   #end
 #end
 ## Comment = "Added Email Message(s)."
 $emailContainer.saveAsAuthor($services.localization.render('xe.invitation.sendMail.addMessageSaveComment'))
  1. end
* Generate invitation XObjects from a template, user input, and a set of recipients.
*
* $subjectLineTemplate (String) this will be evaluated as velocity and placed in the email subject line.
*                               You may refer to $messageID and $subjectLine in the code.
*
* $messageBodyTemplate (String) this will be evaluated as velocity and placed in the email message body.
*                               You may refer to $messageID, $messageBody, You may also use xwiki2.0 syntax
*                               in the template.
*
* $emailClass (String) the document name of the XClass representing email messages.
*
* $recipients (List<String>) email addresses to send this message to.
*
* $emailRegex (String) the regular expression to validate the email addresses against. Undefined behavior will result
*                      from an invalid expression.
*
* $userSuppliedSubject (String) the message subject. This can be modified or ignored by the template.
*
* $userSuppliedContent (String) the message content. This can be modified or ignored by the template.
*
* $messages (List<XObject>) this list will be populated with mail objects for each recipient.
*
* $emailContainer (Document) the document where the mail object will be stored for later review.
*###
  1. macro(generateMailFromTemplate, $subjectLineTemplate, $messageBodyTemplate, $emailClass, $recipients, $emailRegex,
                                $userSuppliedSubject, $userSuppliedContent, $messages, $emailContainer)
 #if($recipients && $recipients.size() > 0)
   #set($sendTo = [])
   #set($discard = $sendTo.addAll($recipients))
   #set($invalid = [])
   #validateAddressFormat($recipients, $emailRegex, $invalid)
   #set($discard = $sendTo.removeAll($invalid))
   #set($messageGroupID = $mathtool.getRandom())
 #else
   ## If we're just doing a test run, no recipients but we still want to generate a message.
   #set($sendTo = [])
 #end
 ##
 #foreach($recipient in $sendTo)
   #set($message = $emailContainer.newObject($emailClass))
   $message.set('sendingUser', $xcontext.getUser())##
   $message.set('sentDate', )##
   $message.set('messageGroupID', $messageGroupID)##
   $message.set('recipient', $recipient)##
   ## Set the message id to a random number string, set it to $messageID variable so it can be used by the template.
   #set($messageID = "$mathtool.getRandom().toString().replaceAll('\.',)##
                      $mathtool.getRandom().toString().replaceAll('\.',)##
                      $mathtool.getRandom().toString().replaceAll('\.',)")
   $message.set('messageID', $messageID)##
   ##
   ## Need to make $subjectLine and $messageBody available to $doc.getRenderedContent.
   #set($subjectLine = "$!userSuppliedSubject")
   #set($messageBody = "$!userSuppliedContent")
   ##
   ## If the subject line provided by the user is empty then there will be trailing whitespace.
   ## xe.invitation.emailContent.subjectLine={0} has invited you to join {1} {2}
   #set($subjectLineWithWhitespace = "$doc.getRenderedContent($subjectLineTemplate, 'xwiki/2.0', 'plain/1.0')")
   ##
   ## Generate the message from the template - html in the subject line is ignored by the mail client.
   $message.set('subjectLine', $subjectLineWithWhitespace.trim())##
   $message.set('messageBody', "$doc.getRenderedContent($messageBodyTemplate, 'xwiki/2.0')")##
   #set($discard = $messages.add($message))
 #end
  1. end
* Check the format of an email address against a regular expression.
*
* $allAddresses (List<String>) The list of addresses to validate.
*
* $emailRegex (String) The regular expression to validate the email addresses agains. Undefined behavior will result
*                      from an invalid expression.
*
* $invalidAddresses (List<String>) this List will be populated with addresses from $allAddresses which are invalid.
*###
  1. macro(validateAddressFormat, $allAddresses, $emailRegex, $invalidAddresses)
 ## Perl/javascript regexes look like /^.*/
 ## java does not like the / at beginning and end.
 #if($emailRegex.length() > 1)
   #set($emailRegexInternal = $emailRegex.substring(1, $mathtool.add($emailRegex.length(), -1)))
 #else
   ## I don't expect this but want to maintain compatibility.
   #set($emailRegexInternal = $emailRegex)
 #end
 #foreach($address in $allAddresses)
   #if("$!address" == )
     ## Empty address, do nothing.
   #elseif($regextool.find($address, $emailRegexInternal).size() == 0)
     #set($discard = $invalidAddresses.add($address))
   #end
 #end
  1. end
* Display a form for typing up an invitation email.
*
* $recipientString (String) what should be filled in to the field for recipients.
*
* $subjectLine (String) what should be put in the subject line by default.
*
* $messageBody (String) what should be put in the content of the message by default.
*
* $userMaySendToMultiple (Boolean) true if the current user has permission send to multiple addresses at once.
*
* $userMayPersonalizeMessage (Boolean) true if the user may add their own subject line and message content.
*###
  1. macro(displayForm, $recipientString, $subjectLine, $messageBody, $userMaySendToMultiple, $userMayPersonalizeMessage)
 Predefinição:Html clean="false" wiki="false"
 <form id="invitation-sender-form" action="$doc.getURL('view')" method="post" class="invitation">
## Who you are inviting:
<label for="recipients">$services.localization.render('xe.invitation.toLabel')</label>
## If the user has edit access on this document, then we should allow them to send to multiple email addresses. #if($userMaySendToMultiple)
<textarea cols="75" name="recipients" rows="3" id="recipients">## $!recipientString## </textarea>
#else
<input type="text" size="54" name="recipients" id="recipients" value="$!recipientString" />
#end #if($userMayPersonalizeMessage) ## Subject line:
<label for="subjectLine">$services.localization.render('xe.invitation.subjectLabel')</label>
<input type="text" size="54" name="subjectLine" id="subjectLine" value="$!escapetool.xml($!subjectLine)" />
## Invitation message:
<label for="messageBody">$services.localization.render('xe.invitation.contentLabel')</label>
<textarea cols="75" name="messageBody" rows="10" id="messageBody">## $!escapetool.xml($!messageBody)## </textarea>
#end
    
     ## Preview
     <input type="submit" class="button" name="preview" value="$services.localization.render('xe.invitation.displayForm.preview')" />
    
    
     ## Send Mail
     <input type="submit" class="button" name="sendMail" value="$services.localization.render('xe.invitation.displayForm.sendMail')" />
    
 </form>
 Predefinição:/html
  1. end
* Has mail sent by the current user been reported as spam?
* will return 'false' if not otherwise will return 'true'
* if a message was reported as spam but an admin has marked the situation
* as handled then this macro will return 'false'
*
* $messages (Collection<XObject>) objects representing all email messages.
*###
  1. macro(isUserReportedSpammer, $messages)
 #set($out = 'false')
 #foreach($message in $messages)
    #if($message.getProperty('sendingUser').getValue() == $xcontext.getUser()
         && $message.getProperty('status').getValue() == 'reported')
    ##
      #set($out = 'true')
    #end
 #end
 $out##
  1. end
* Get the list of recipients from the user input string.
* Splits on space but is tolerent of commas.
* Each email in the list may only appear in the output once (no duplicates.)
*
* $recipientString (String) the String input by the user eg: "[email protected] [email protected]"
*
* $userMaySendToMultiple (Boolean) is the user allowed to send to multiple addresses at once?
*
* $recipientsOut (List<String>) is populated with one or more email addresses.
*###
  1. macro(getRecipients, $recipientString, $userMaySendToMultiple, $recipientsOut)
 #if($userMaySendToMultiple)
   #set($recipientsArray = $recipientString.replaceAll(', ', ' ').split(' '))
   #set($recipientMap = {})
   #foreach($recip in $recipientsArray)
     #set($discard = $recipientMap.put($recip, 0))
   #end
   #set($discard = $recipientsOut.addAll($recipientMap.keySet()))
 #else
   ## If the user can't edit this page, we won't let them sent to multiple addresses.
   #set($discard = $recipientsOut.add($recipientString))
 #end
  1. end

Predefinição:/velocity