Dave Ward 6ebc200a0e Merged V3.4-TEAM to HEAD
26804: Fixed line endings and removed sundry svn:mime-type properties after merge rev 26779
   26805: Merged BRANCHES/V3.4/ to BRANCHES/V3.4-TEAM:
      26803: Fixes: ALF-8138, adds a i18n property for a ToDo list's attachment title.
   26817: Fixes: ALF-7813 - Mini Calendar now highlights all events rather than only the ones valid for the current view.
   26821: Fixed ALF-7889: Auditable data should not change during archive and restore
    - NodeService archive (private method) and restore (public method) switch off cm:auditable behaviour
    - This is system-wide and not configurable
   26823: ALF-8152 - Simple view: incorrect file type icon
   26826: GDoc: Collections are now being correctly created in GDoc when document is checked out
   
   26829: Change initial load event back to onContentReady to keep Firefox & Firebug happy.
   26830: ALF-8151 - Filetype icon or is incorrectly displayed at the Content I'm editing dashlet. (Copied mappings across from alfresco.js)
   26833: Fixed ALF-8060 "Collaborator can't edit created links by other users"
   26836: Fix for ALF-8126
   26837: Fixes ALF-8124: Override default BitRock NLS readme strings
   26840: Fixed ALF-8127 "Inconsistence between Create and Edit user page"
   26841: Fix for ALF-1044. (Searching for groups whose names contain regex reserved chars.)
     The fix was to add [] as reserved chars to the RegEx SimpleLanguageDef. Thanks AndyH.
   26844: Fixed ALF-8000, ALF-7997, ALF-8108 and ALF-7721. Partial fix for ALF-8156. All these issues relate to admin console form configuration.
   26845: Fix for ALF-8181 - Admin console - sometimes displays the 'previous' tool, one step behind mouse click
   26854: Fixed ALF-8179: The new HTML email templates are bootstrapped with a mimetype of text/html they should be text/plain as they are freemarker files. Being plain text allows the content to be edited without TinyMCE corrupting the raw source. I also made all the templates inline editable.
   
   NOTE: To see these changes you must start with a clean database as these changes are only applied during initial bootstrap.
   26865: Merged V3.4-BUG-FIX to V3.4-TEAM
      26864: ALF-8025: JMX forms will no longer persist invalid values and subsystem auto-start errors are non-fatal
         - Errors on bootstrap subsystem startup are logged and absorbed. So should still always be possible to bring the server up to a level where its configuration can be corrected
         - The JMX setAttributes() method, which sets multiple attributes at once, is now handled differently from an individual setAttribute()
         - It attempts to restart the subsystem with the new properties. If successful these are persisted and a reload message is broadcast across the cluster. If unsuccessful it rolls back to the old properties and restarts the subsystem with those. Then the error is passed on to the caller.
         - Unit tested through JMX by AuthenticationChainTest
   26871: Refactor of fix to ALF-7888 to address clarified/extended requirements.
     After discussions with various engineers & the product manager, it has been agreed that sites should not appear in the recycle bin as they cannot be recovered from there. This is not a change to existing behaviour.
     However, formerly sites were only hard-deleted if deleted via the SiteService & remained archivable via the Explorer client and presumably other protocols such as CIFS.
     Now sites will by default not be deletable at all. So any attempt to delete a site via Explorer, CIFS etc will fail with an exception. This is achieved with a policy/behaviour on Site deletion.
     But that behaviour is disabled within the SiteService.deleteSite thus allowing deletion (and hard deletion at that) via that service only.
     End result is that admins can't accidentally delete sites as most interfaces prevent it and Share allows it after the normal warning dialogs.
   
     Had to tweak the SiteLoadPatch to delete a site via the SiteService rather than the NodeService.
   26873: Merged BRANCHES/V3.4 to BRANCHES/V3.4-TEAM:
      26860: ALF-7101 and ALF-7866 - don't show the rules options to collaborators, as they shouldn't be able to create/manage rules
   26874: Previous check-in (svn r. 26871 for ALF-7888) slightly broke the sample site for Team.
   Refactored the SiteLoadPatch to fix that.
   26875: ALF-7835 - args["itemTitle"] and args["page"] are already decoded, so don't try to decodeURIComponent them a second time when building the activity feed, otherwise it'll fail with special characters
   26893: Fixed ALF-7821 & ALF-7967 by making the OpenOffice read-only as it's all pre-installed for Team and shouldn't be editable. Also removed the (Subsystem) from the OpenOffice label.
   
   Also updated forms to remove the 'operations' button and move back to a Save/Cancel button as since Dave's changes to setAttributes() all the logic (including rollback of invalid properties) is now handled, meaning we no longer have to call the start() operation on the MBean.
   26901: Merged V3.4 to V3.4-TEAM
      26900: ALF-8180: The installer shouldn't randomly delete a directory called tomcat that it didn't create
         - Fix provided by Bitrock
   26905: Fix for ALF-8207 - Themes are not translated (not resolving title ids)
   26910: Fixed ALF-8206 "ES - Layout dashlets"
   26913: ALF-7838 - When paging the comments, do the reverse ordering before we page, rather than after
   26920: More on ALF-7004. The notification templates (used in the send email action of a rule) now follow the look and feel of the mockups Linton did originally.
   
   For this to work the MailActionExcecuter action needed the shareUrl, as all other email sending processes go through this action they no longer need to pass the shareUrl in. There was some inconsistency in how the URL was structured (sometimes with a trailing slash, sometimes not) so this has been cleaned up, which did mean more template updates.
   
   As before, this will require a clean database to see the updated templates.
   26921: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      26349: ALF-6062 - Add sorting by display name to the Group REST APIs that support paging
      26375: ALF-6062 - Make sorting of groups in the rest API case insensitive.
      26376: Correct long-incorrect indent and style stuff (at Gav's request)
      26402: ALF-6062 - Paging and Sorting (Case Insensitive) for the Groups REST APIs
      26423: ALF-6062 - Support sorting and paging of the child authorities and users of a group in the REST API, where previously only child groups were sortable and pageable
   26924: Some of ALF-8223: Added form config for GoogleDocs properties currently present on MBean
   26931: ALF-8092 - Convert the archived nodes webscript to the new style paging, which fixes an array index issue
   26933: Fixed ALF-8156: Too many detailed options for filesystem configuration in Admin Console
   
   Also made the position of 'enabled' properties consistent i.e. the first thing in the form/section.
   26937: Build fix for FeedCleanerTest. Also a refactoring of the Site deletion prevention behaviour for ALF-7888.
   This pattern should now be reusable outside the site service.
   
   I took my BeforeDeleteNode behaviour off the st:site node type. It was registered in SiteAspect.java.
   This was causing the test case failure as when I disabled behaviours on a site node before deletion, I was
   disabling all behaviours, including the necessary FeedCleaner behaviour.
   
   Added new aspect cm:undeletable
   Sites now have cm:undeletable as a mandatory aspect
   
   The BeforeDeleteNode behaviour that was attached to sites is now attached to cm:undeletable in UndeletableAspect.java
   
   site-services-context.xml defines an undeletableAspect bean which registers the behaviour on cm:undeletable.
   This could perhaps be moved into the NodeService. Will discuss on Monday.
   
   26938: Fixes ALF-8196: Ensure that WebView title bar link is updated as soon as its set
   26940: Fix for ALF-8036. Incorrect permissions copied when copying folder with permissions from one site to another.
     Permissions on nodes held within share sites are now cleaned after a move or a copy to a different share site.
     Cleaning in this context means permissions relating to the old site are removed and permission inheritance is turned on again. In this way the relocated nodes will look like they have just been uploaded, as requested in the issue comments.
     A new method in the SiteService stack (cleanSitePermissions) is used to initiate this clean-up from the move-to, copy-to slingshot webscripts.
     This is delegated to a new class/bean SitesPermissionCleaner which encapsulates the clean-up operation.
     The cleanup must be recursive as there could be nodes anywhere within the relocated tree which have permissions directly set on them. The tree is walked using nodeDAOs for efficiency. The cleanup is performed with aclDAOs, again for efficiency.
   
     This fix was developed on 3.4.2, but was backed out of there and is now checked in (effectively for the first time) on Team. This check-in will need to be merged to 3.4.3 at some point.
   26941: Updating svn properties on root associated with check-in 26940 for ALF-8036.
   Sorry. I forgot to check these in a moment ago.
   
   26949: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      26945: ALF-3554 / ALF-8257 - Adding rules to a node applies a marker aspect, so update the Rules Service to remove this when all removes are deleted.
   26950: Fix failing tests caused by r26920. Now that we rely on the Mail Action Executor to set the share URL for the templates, it's no longer available at the mock level when not calling the MailActionExecutor. Switch to a different model variable to check
   26954: ALF-8232 - Paging controls in doclib can overlay on top of sorting controls at 1024 screen res when 8+ pages are present
   26955: Follow-up to r26954 (ALF-8232). Remove local i18n messages for Links component.
   26956: Fixed ALF-8223 "Google integration needs Admin Console to configure options"
   26963: Fixed ALF-8223 "Google integration needs Admin Console to configure options"
   26964: Fixed ALF-8226 "ES FR DE Site pages in Customise Site to be spaced"
   - tested in FF3.5, SF3 & IE6,7,8
   26966: Added missing theme ID string
   26968: Merged V3.4-BUG-FIX to V3.4-TEAM
      26967: Fix for ALF-8259 - Static Asset Cache use of the /res resource servlet has overwritten the cachecontrol values set by the filter.
   26969: Moving the cm:undeletable aspect out of the SiteService and into the NodeService. Loosely related to ALF-7888.
   The cm:deletable aspect has been renamed to sys:undeletable.
   The class which registers the default behaviour, UndeletableAspect, has been moved into repo/node.
   Various minor changes in model files & spring config required.
   26970: ALF-8267 - Data Lists: search for user should not require minimum characters
   26971: Fixed ALF-8280 "ALL LANG - conversor pdf2swf - untranslated"
   26976: ALF-8271 - "Repository" appears as a destination when creating/editing linked rules in Doc Library.
   Rules picker now switches available modes based on whether Repository browsing is allowed or not. Removed reference to non-existent file. Also made rules picker sensitive to changing picker mode or site.
   26977: Fixes: ALF-7812: Adds support for multiday events.
   26978: Fixes: ALF-6107 - Fixes Tab order isses with Add event form.
   26979: Fix for ALF-8264. My Tasks incorrect capitalization.
   26991: ALF-8276 - "Select" dialog when adding items to workflow shows more information than in should
   26992: Fix for ALF-8288 - ES - Typo in serach result and also variable doesn't seem to work. Translation error, corrupted {0} strings pattern.
   26993: ALF-8148 - Details page Permissions incorrectly shows No privileges
   26994: Follow-up to r26993 (ALF-8148) for folders.
   26995: ALF-8265 - Data Lists: inconsistent capitalization; tooltip text is wordy
   26998: Fixes ALF-8091: Decode page URLs when removing dynamic welcome dashlets
   27000: Merged V3.4-BUG-FIX to V3.4-TEAM
      26999: Update to correct latest spring-webscripts-api jar
   27001: Fixes: ALF-8119 (IE8 bugs) & ALF-8118 - Clears event data from form.
   27005: Fixes: ALF-8168 - JSON encoding issue in Calendar API
   27025: Slight tweak to login dialog for iOS user usability
   27026: Fixes ALF-7764: Remove fade effect on title bar actions in IE to ensure correct image rendering
   27035: ALF-8314 - Document Library: Comment displays poorly when first word of comment is short.
   27040: Fix for ALF-8126 - Incorrect title of Transformer ImageMagick - missed labels
   27076: Merged V3.4-BUG-FIX to V3.4-TEAM
      26668: Fixes ALF-7920: Updated Linux/OSX config to add support for missing TIFF files in ImageMagic (dependant upon r26667 in ALF-BINARIES)
   27084: Merged V3.4 to V3.4-TEAM
      27083: ALF-8124: Corrected ${} placeholders in Japanese installer strings
   27091: Merged V3.4 to V3.4-TEAM
      26834: Fixes ALF-7904, ALF-8063: BitRock config updates
   27093: Fix for ALF-8308. Cannot like a folder that has rules defined for it.
     Added a necessary fix which prevents the exception being thrown.
   27094: Fixed ALF-8223: Google integration needs Admin Console to configure options.
   
   Also fixed a couple of other strings broken in a previous commit.
   27102: Further fix for ALF-8223: Google integration needs Admin Console to configure options. Removed application name to leave just enabled checkbox, username and password fields.
   27105: Fixed ALF-8277 & ALF-8253: Tooltips are not translated
   
   The JMX attribute description is no longer returned by the form processor as 99% of the time they don't contain anything useful and they are not localised.
   27106: Fix for ALF-8321: Cancel workflows move it to trashcan
   27115: ALF-7826, ALF-7949, ALF-8180, ALF-7904, ALF-8063: Reconciled project-team.xml with changes in project.xml
   27118: Merged V3.4-BUG-FIX to V3.4-TEAM
      26669: Fixes ALF-7987: Ensure rollback directories are removed on uninstall
   27119: ALF-8128: Propagate Team project name into Linux installer builder
   27137: Merged V3.4 to V3.4-TEAM
      27136: Installer string updates from Gloria
   27140: Temporary workaround to prevent rules running on cm:rating nodes (which happened for 'liked' folders ALF-8308 & ALF-8382)
   
   27162: Fixed ALF-8427 "Language packs: It's impossible to view any version of the wiki page if it contains native characters"
   27166: Updates to the invitation email templates following delivery of new l10n files.
   These changes were 'hand-merged' due to missing styling markup in the delivered l10n files.
   The new files had all styling markup removed.
   
   For the record, here's what I did:
   
   I compared the new and old files foreach {de, es, fr, it, ja} and found that all changes were short, simple and easy to merge.
   So I pasted in the main content div from the new l10n files, leaving all other styling markup (meaning css) unchanged.
   For the record, here's what diff says changed in this check-in:
   
   DE
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              hat Sie eingeladen, als ${args["inviteeSiteRole"]} an der Site  ${args["siteName"]} teilzunehmen.</p>
   ---
   >                                              hat Sie eingeladen, mit der Rolle ${args["inviteeSiteRole"]} an der Site <b>${args["siteName"]}</b> teilzunehmen.</p>
   62,63c62,63
   <                                              <br />Benutzername: ${args["inviteeUserName"]}
   <                                              <br />Passwort: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Benutzername: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Passwort: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Wir legen Ihnen nahe, das Passwort bei der ersten Anmeldung zu ändern.
   ---
   >                                              <p><b>Wir legen Ihnen nahe, das Passwort bei der ersten Anmeldung zu ändern.</b><br />
   
   ES
   52,53c52,53
   <                                              <p>Hola ${inviteePerson.properties["cm:firstName"]!""}:</p>
   <                                              
   ---
   >                                              <p>Hola, ${inviteePerson.properties["cm:firstName"]!""}:</p>
   > 
   55c55
   <                                              le ha invitado a unirse al sitio ${args["siteName"]} con el rol de ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              le ha invitado a unirse al sitio <b>${args["siteName"]}</b> con el rol de ${args["inviteeSiteRole"]}.</p>
   62,63c62,63
   <                                              <br />Nombre de usuario: ${args["inviteeUserName"]}
   <                                              <br />Contraseña: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nombre de usuario: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Contraseña: <b>${args["inviteeGenPassword"]}</b>
   66,67c66,67
   <                                              <p>Le recomendamos que cambie la contraseña la primera vez que inicie una sesión.
   <                                              Para hacerlo, vaya a <b>Mi Perfil</b> y seleccione <b>Cambiar contraseña</b>.</p>
   ---
   >                                              <p><b>Le recomendamos que cambie la contraseña la primera vez que inicie sesión.</b><br />
   >                                              Para hacerlo, vaya a <b>Mi perfil</b> y seleccione <b>Cambiar contraseña</b>.</p>
   
   FR
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              vous invite à rejoindre le site ${args["siteName"]} avec un rôle de ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              vous invite à rejoindre le site <b>${args["siteName"]}</b> avec un rôle de ${args["inviteeSiteRole"]}.</p>
   62,63c62,63
   <                                              <br />Nom d'utilisateur : ${args["inviteeUserName"]}
   <                                              <br />Mot de passe : ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nom d'utilisateur : <b>${args["inviteeUserName"]}</b>
   >                                              <br />Mot de passe : <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Nous vous conseillons vivement de modifier votre mot de passe lors de votre première connexion.
   ---
   >                                              <p><b>Nous vous conseillons vivement de modifier votre mot de passe lors de votre première connexion.</b><br />
   70c70
   <                                              <p>Si vous souhaitez décliner l'invitation de ${inviterPerson.properties["cm:firstName"]!""} cliquez sur ce lien :<br />
   ---
   >                                              <p>Si vous souhaitez décliner l'invitation de ${inviterPerson.properties["cm:firstName"]!""}’, cliquez sur ce lien :<br />
   
   
   IT
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              ti ha  inviatato a partecipare al sito ${args["siteName"]} con il ruolo di ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              sei stato inviatato a partecipare al sito <b>${args["siteName"]}</b> con il ruolo di ${args["inviteeSiteRole"]}.</p>
   57c57
   <                                              <p>Fare clic sul collegamento per accettare l’invito dell'${inviterPerson.properties["cm:firstName"]!""}':<br />
   ---
   >                                              <p>Fare clic sul collegamento per accettare ${inviterPerson.properties["cm:firstName"]!""}'s l'invito:<br />
   62,63c62,63
   <                                              <br />Nome utente: ${args["inviteeUserName"]}
   <                                              <br />Password: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nome utente: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Password: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Si consiglia di cambiare la password quando si effettua l'eccesso per la prima volta.
   ---
   >                                              <p><b>Si consiglia di cambiare la password quando si effettua l'eccesso per la prima volta.</b><br />
   70c70
   <                                              <p>Per rifiutare l’invito dell’${inviterPerson.properties["cm:firstName"]!""}, fare clic su questo collegamento:<br />
   ---
   >                                              <p>Per rifiutare ${inviterPerson.properties["cm:firstName"]!""}’s l'invito, fare clic su questo collegamento:<br />
   
   
   JA
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              ????${args["siteName"]} ??????${args["inviteeSiteRole"]}?????????????????????</p>
   ---
   >                                              ????<b>${args["siteName"]}</b> ????? ${args["inviteeSiteRole"]} ????????????????????</p>
   62,63c62,63
   <                                              <br />????: ${args["inviteeUserName"]}
   <                                              <br />?????: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />????: <b>${args["inviteeUserName"]}</b>
   >                                              <br />?????: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>?????????????????????????????
   ---
   >                                              <p><b>?????????????????????????????</b><br />
   
   27172: Fixed ALF-7856 "Team: DocLib action displaying incorrect tooltip text"
   27339: ALF-8330 - ALL LANG - "Assigned To" in Data List created displays untranslated
   27340: Fixes Encoding issue in L10N files.
   27471: Fix for ALF-8150 - check for visibility before applying focus to element for IE.
   27499: Drop one and two of updates from translators based on rev26820
   27501: ALF-8151 - Filetype icon or is incorrectly displayed at the Content I'm editing dashlet
   27507: ALF-8478: Default repeat interval for activity email notifications should be 1 day
   27520: Fixed ALF-8329 "Consumer can add comments to files, folders, links and blogs"
   27527: Fixes ALF-8409: Ensure that UTF-8 encoded characters in file names can be uploaded to folders (that may also contain UTF-8 encoded characters) via DND in FireFox 3.6
   27531: Merged V3.4-BUG-FIX to V3.4-TEAM
      27525: Merged V3.4 to V3.4-BUG-FIX
         27120: Resolve ALF-8187: Transaction retries of CMIS webscripts failing
   27543: Fixed ALF-8464 "Start Workflow: Search for groups still requires minimum 1 character"
   27562: Merged V3.4-BUG-FIX to V3.4-TEAM
      27560: Fix for ALF-8434 - AVMRemoteStore not setting UTF-8 response encoding for some methods
   27572: Fixes: ALF-7596 - Config values not being correctly read in FTL
   27573: Fixed ALF-8504: Non-admin users are warned about license expiry too soon
    - ALF-8502 Adjust admin warning period from 30 to 21 days
    - ALF-7259 RTEAM 33: RepoAdmin Web Script to report Red/Amber/Green
   27592: Fixes: ALF-8444 - JA properties file in incorrect location.
   27594: ALF-8508 - Document Library: Google Docs actions not correct
   27596: Fixed ALF-8484	"Consumer and Contributor should not be able to choose button "Revert" of the document"
   27598: Annotated properties file to indicate which text is exposed to the UI and therefore needs translating. Needed for: ALF-8442
   27615: Fix for ALF-8501 - License warning box needs to be toned down in colour
   27616: Tweak for IE
   27617: Fixes: ALF-8423 - string missed in earlier merge
   27619: ALF-7904: Synchronize alfresco-customteam-settings.xml with alfresco-customstack-postgres-settings.xml!
   27625: ALF-7518 - Update Team Help and Tutorial URLs once finalised. * DO NOT MERGE *
   Note: version.edition cannot be used as a placeholder due to the mismatch between "edition=Enterprise" and help URL containing "team"
   27626: Change default value for "useTitle" to true for Site DocLib
   27648: Fix for ALF-8552
   27649: Fixed ALF-8495: Alfresco Logo is incorrectly displayed in notify user letter
   
   Usual note with these checkins applies, clean database will be required to see the updated templates.
   27650: Fixed ALF-8425: Select Tags button is missing at the Edit Properties page for msg files
   27664: Issue checking in XSLX Google Docs (related to ALF-8580)
   
   27667: ALF-7518 - Update Team Help and Tutorial URLs once finalised
   New tutorial URL for Share, now hosted within main docs system; uh-tutorial.html topic page.
   27683: Merged BRANCHES/DEV/dwebsterTeam to BRANCHES/V3.4-TEAM:
      27675: DE: Drop 3 & 4 for Team translations based on r27552
      27676: ES: Drop 3 & 4 for Team translations based on r27552
      27677: FR: Drop 3 & 4 for Team translations based on r27552
      27678: IT: Drop 3 & 4 for Team translations based on r27552
      27679: JA: Drop 3 & 4 for Team translations based on r27552
      27680: L10N updates to system-messages.properties (for License messages exposed to UI)
   27686: Fixes: ALF-8266
   27694: Change related to ALF-8556. Sometimes Google Docs cannot be checked out.
   This change was suggested by Roy. cm:failedThumbnail nodes were deleted onUpdateProperties. Now they are only deleted if there are no locks preventing their deletion (e.g. due to being checked out.)
   27710: Fixed ALF-7721: There are no field rescrtictions on 'Edit: Fileservers' form and ALF-8558: There is no pattern for Username field in Google Docs
   27711: ALF-8590 - Check Out for some documents is not working
   ALF-8591 - CheckIn form Google docs for some documents is not working
   
   Google Docs-specific filter code added to Manage Aspects UI to remove "gd:googleEditable from the list of addable aspects unless the file's mimetype is supported (i.e. txt, doc, xls, ppt). Google Docs enabled ootb in team-config.
   27713: GDoc - Fix for checkout of .odt files (see ALF-8599)
   
   27723: Added back theme name string that was removed in rev 26971
   27740: Updates from Gloria following bundle completeness analysis.
   27755: Removed extra unused Japanese translation files.
   27756: ALF-8207 - ALL LANG - Themes are not translated
   27759: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      27758: Merged BRANCHES/V3.4 to BRANCHES/DEV/V3.4-BUG-FIX:
           27757: Fix for ALF-8430.
   27761: JA Updates from Gloria following bundle completeness analysis.
   27767: Fixes: ALF-8279 - reloads translation Gloria sent.
   27768: ALF-8213 - Manage My Subscription link now directs to team.alfresco.com - tooltip from label added
   27769: Fixes ALF-8652: Add removed quotes and revert translations back to correct language
   27770: Fixes: ALF-8228: Column widening needed
   27771: Initial commit of these translated files from Gloria.
   27772: ALF-8555 - Incorrect behavior of enabling Google docs (Really: Forms get submitted twice in certain circumstances)
   27773: ALF-8329 - Consumer can add comments to files, folders, links and blogs
   Fixed: 8. Open details page for file and try to add comment --> comment added successfully;
   27774: Spanish Gender Changes following review from Gloria.
   27779: Final fixes from L10N completeness check.
   27792: Remove debugging code from r27772
   27804: ALF-8207 - ALL LANG - SpringSurf issue with default theme definition
   27826: Manually reverts (to a version prior to r27683) a file in each language that was incorrectly supplied in English, and ensures they match the current EN properties.
   27827: Fixes: ALF-8210
   27843: Fix for ALF-8449 - ALL LANG - site themes are not translated (Customise Site page)
   27873: Merged V3.4 to V3.4-TEAM:
      27871: Fixes ALF-8124: Ensure Spanish locale for installer shows product name correctly
   27883: Implementation of ALF-8737 Support for thumbnailing/previewing of additional mimetypes (Adobe). Also video/audio playbac
   k.
   
   This check in enables thumbnails for Adobe Photoshop, recent Adobe Illustrator files and previews for Adobe Photoshop, recent Adobe Illustrator files
   as well as metadata extraction for Adobe Illustrator files (PDF-based formats).
   
   It also enables video playback of .m4v files, where the browser supports it.
   I have also added placeholder icons for .m4v files.
   Adobe Photoshop (.psd) files are handled by ImageMagick. However our existing ImageMagick-based content transformer excludes most mimetypes that don't start with "image/". By allowing "application/photoshop" to be accepted, that transformer
    will now perform thumbnails and previews.
   Recent Adobe Illustrator file formats are pdf files and so can use the PDF transformers/extractors i.e. PDFRenderer and 
   PDFBox and pdf2swf.
   I have added a new complex transformer for .ai files which uses the existing PDF/ImageMagick component transformers.
   
   New JUnit test cases for these transforms.
   
   As part of testing, we discovered that IE9 will not play mp3s of mimetype == audio/x-mpeg, only audio/mpeg.
   The latter is the correct mimetype, the former is out of date, but Alfresco was using the former. So we've updated that MIME type in various places in the code.
   27888: Google Docs 
     - Updated client google doc api jars
     - Fixes ALF-8592: Incorrect behavior on permissions for Google docs
   
   27894: Minor fixes for iOS:
   . overflow content shown by default in dashlets
   . doclib long filenames no longer cause screen to resize
   . ipad css overrides
   . YUI dialogs no longer jump around the page during text entry input
   27904: Minor fixes for iOS usability:
   . Drag&drop doclist help removed for mobile devices
   . Create New DataList shows list as full height (not scrollable)
   . Removed default webkit inner shadow from input fields
   27915: Minor fixes for iOS usability: Forced scrollbar appearance on overflowed div elements


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@27939 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2011-05-20 13:30:26 +00:00

1917 lines
74 KiB
Java

/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.site;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.activities.ActivityType;
import org.alfresco.repo.admin.SysAdminParams;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.search.impl.lucene.LuceneQueryParser;
import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.tenant.TenantAdminService;
import org.alfresco.repo.tenant.TenantService;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.activities.ActivityService;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.model.FileNotFoundException;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.PropertyCheck;
import org.alfresco.util.PropertyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* Site Service Implementation. Also bootstraps the site AVM and DM stores.
*
* @author Roy Wetherall
*/
public class SiteServiceImpl implements SiteService, SiteModel
{
/** Logger */
private static Log logger = LogFactory.getLog(SiteServiceImpl.class);
/** The DM store where site's are kept */
public static final StoreRef SITE_STORE = new StoreRef("workspace://SpacesStore");
/** Activity tool */
private static final String ACTIVITY_TOOL = "siteService";
private static final String SITE_PREFIX = "site_";
private static final String GROUP_SITE_PREFIX = PermissionService.GROUP_PREFIX + SITE_PREFIX;
private static final int GROUP_PREFIX_LENGTH = PermissionService.GROUP_PREFIX.length();
private static final int GROUP_SITE_PREFIX_LENGTH = GROUP_SITE_PREFIX.length();
/** Site home ref cache (Tennant aware) */
private Map<String, NodeRef> siteHomeRefs = new ConcurrentHashMap<String, NodeRef>(4);
/** Site node ref cache (Tennant aware) */
private Map<String, NodeRef> siteNodeRefs = new ConcurrentHashMap<String, NodeRef>(256);
private String sitesXPath;
/** Messages */
private static final String MSG_UNABLE_TO_CREATE = "site_service.unable_to_create";
private static final String MSG_VISIBILITY_GROUP_MISSING = "site_service.visibility_group_missing";
private static final String MSG_CAN_NOT_UPDATE = "site_service.can_not_update";
private static final String MSG_CAN_NOT_DELETE = "site_service.can_not_delete";
private static final String MSG_SITE_NO_EXIST = "site_service.site_no_exist";
private static final String MSG_CAN_NOT_REMOVE_MSHIP = "site_service.can_not_remove_membership";
private static final String MSG_DO_NOT_CHANGE_MGR = "site_service.do_not_change_manager";
private static final String MSG_CAN_NOT_CHANGE_MSHIP="site_service.can_not_change_membership";
private static final String MSG_SITE_CONTAINER_NOT_FOLDER = "site_service.site_container_not_folder";
/* Services */
private NodeService nodeService;
private FileFolderService fileFolderService;
private SearchService searchService;
private NamespaceService namespaceService;
private PermissionService permissionService;
private ActivityService activityService;
private PersonService personService;
private AuthenticationContext authenticationContext;
private TaggingService taggingService;
private AuthorityService authorityService;
private DictionaryService dictionaryService;
private TenantService tenantService;
private TenantAdminService tenantAdminService;
private RetryingTransactionHelper retryingTransactionHelper;
private Comparator<String> roleComparator;
private SysAdminParams sysAdminParams;
private BehaviourFilter behaviourFilter;
private SitesPermissionCleaner sitesPermissionsCleaner;
/**
* Set the path to the location of the sites root folder. For example:
* <pre>
* ./app:company_home/st:sites
* </pre>
* @param sitesXPath a valid XPath
*/
public void setSitesXPath(String sitesXPath)
{
this.sitesXPath = sitesXPath;
}
/**
* Set node service
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* Set file folder service
*/
public void setFileFolderService(FileFolderService fileFolderService)
{
this.fileFolderService = fileFolderService;
}
/**
* Set search service
*/
public void setSearchService(SearchService searchService)
{
this.searchService = searchService;
}
/**
* Set Namespace service
*/
public void setNamespaceService(NamespaceService namespaceService)
{
this.namespaceService = namespaceService;
}
/**
* Set permission service
*/
public void setPermissionService(PermissionService permissionService)
{
this.permissionService = permissionService;
}
/**
* Set activity service
*/
public void setActivityService(ActivityService activityService)
{
this.activityService = activityService;
}
/**
* Set person service
*/
public void setPersonService(PersonService personService)
{
this.personService = personService;
}
/**
* Set authentication component
*/
public void setAuthenticationContext(
AuthenticationContext authenticationContext)
{
this.authenticationContext = authenticationContext;
}
/**
* Set the tagging service
*/
public void setTaggingService(TaggingService taggingService)
{
this.taggingService = taggingService;
}
/**
* Set the authority service
*/
public void setAuthorityService(AuthorityService authorityService)
{
this.authorityService = authorityService;
}
/**
* Set the dictionary service
*
* @param dictionaryService dictionary service
*/
public void setDictionaryService(DictionaryService dictionaryService)
{
this.dictionaryService = dictionaryService;
}
/**
* Set the tenant service
*
* @param tenantService tenant service
*/
public void setTenantService(TenantService tenantService)
{
this.tenantService = tenantService;
}
/**
* Sets the tenant admin service
*/
public void setTenantAdminService(TenantAdminService tenantAdminService)
{
this.tenantAdminService = tenantAdminService;
}
/**
* Sets helper that provides transaction callbacks
*/
public void setTransactionHelper(RetryingTransactionHelper retryingTransactionHelper)
{
this.retryingTransactionHelper = retryingTransactionHelper;
}
public void setRoleComparator(Comparator<String> roleComparator)
{
this.roleComparator = roleComparator;
}
public void setSysAdminParams(SysAdminParams sysAdminParams)
{
this.sysAdminParams = sysAdminParams;
}
public void setBehaviourFilter(BehaviourFilter behaviourFilter)
{
this.behaviourFilter = behaviourFilter;
}
public void setSitesPermissionsCleaner(SitesPermissionCleaner sitesPermissionsCleaner)
{
this.sitesPermissionsCleaner = sitesPermissionsCleaner;
}
public Comparator<String> getRoleComparator()
{
return roleComparator;
}
/**
* Checks that all necessary properties and services have been provided.
*/
public void init()
{
PropertyCheck.mandatory(this, "nodeService", nodeService);
PropertyCheck.mandatory(this, "fileFolderService", fileFolderService);
PropertyCheck.mandatory(this, "searchService", searchService);
PropertyCheck.mandatory(this, "namespaceService", namespaceService);
PropertyCheck.mandatory(this, "permissionService", permissionService);
PropertyCheck.mandatory(this, "authenticationContext", authenticationContext);
PropertyCheck.mandatory(this, "personService", personService);
PropertyCheck.mandatory(this, "activityService", activityService);
PropertyCheck.mandatory(this, "taggingService", taggingService);
PropertyCheck.mandatory(this, "authorityService", authorityService);
PropertyCheck.mandatory(this, "sitesXPath", sitesXPath);
}
/*
* (non-Javadoc)
* @see org.alfresco.service.cmr.site.SiteService#hasCreateSitePermissions()
*/
public boolean hasCreateSitePermissions()
{
final NodeRef siteRoot = getSiteRoot();
if (siteRoot == null)
{
throw new SiteServiceException("No root sites folder exists");
}
boolean result = permissionService.hasPermission(siteRoot, PermissionService.CONTRIBUTOR).equals(AccessStatus.ALLOWED);
return result;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#createSite(java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean)
*/
public SiteInfo createSite(final String sitePreset,
String passedShortName,
final String title,
final String description,
final boolean isPublic)
{
// Determine the site visibility
SiteVisibility visibility = SiteVisibility.PRIVATE;
if (isPublic == true)
{
visibility = SiteVisibility.PUBLIC;
}
// Create the site
return createSite(sitePreset, passedShortName, title, description, visibility);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#createSite(java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean)
*/
public SiteInfo createSite(final String sitePreset,
String passedShortName,
final String title,
final String description,
final SiteVisibility visibility)
{
// Remove spaces from shortName
final String shortName = passedShortName.replaceAll(" ", "");
/**
* Check that the site does not already exist
*/
// Check to see if we already have a site of this name
NodeRef existingSite = getSiteNodeRef(shortName);
if (existingSite != null)
{
// Throw an exception since we have a duplicate site name
throw new SiteServiceException(MSG_UNABLE_TO_CREATE, new Object[]{shortName});
}
// Get the site parent node reference
NodeRef siteParent = getSiteParent(shortName);
if (siteParent == null)
{
throw new SiteServiceException("No root sites folder exists");
}
// Create the site node
PropertyMap properties = new PropertyMap(4);
properties.put(ContentModel.PROP_NAME, shortName);
properties.put(SiteModel.PROP_SITE_PRESET, sitePreset);
properties.put(SiteModel.PROP_SITE_VISIBILITY, visibility.toString());
properties.put(ContentModel.PROP_TITLE, title);
properties.put(ContentModel.PROP_DESCRIPTION, description);
final NodeRef siteNodeRef = this.nodeService.createNode(
siteParent,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
shortName), SiteModel.TYPE_SITE, properties)
.getChildRef();
// Make the new site a tag scope
this.taggingService.addTagScope(siteNodeRef);
// Clear the sites inherited permissions
this.permissionService.setInheritParentPermissions(siteNodeRef, false);
// Get the current user
final String currentUser = authenticationContext.getCurrentUserName();
// Create the relevant groups and assign permissions
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public String doWork() throws Exception
{
Set<String> shareZones = new HashSet<String>(2, 1.0f);
shareZones.add(AuthorityService.ZONE_APP_SHARE);
shareZones.add(AuthorityService.ZONE_AUTH_ALFRESCO);
// Create the site's groups
String siteGroup = authorityService
.createAuthority(AuthorityType.GROUP, getSiteGroup(shortName, false), shortName, shareZones);
Set<String> permissions = permissionService.getSettablePermissions(SiteModel.TYPE_SITE);
for (String permission : permissions)
{
// Create a group for the permission
String permissionGroup = authorityService.createAuthority(AuthorityType.GROUP, getSiteRoleGroup(
shortName, permission, false), shortName, shareZones);
authorityService.addAuthority(siteGroup, permissionGroup);
// Assign the group the relevant permission on the site
permissionService.setPermission(siteNodeRef, permissionGroup, permission, true);
}
// Set the memberships details
// - give all authorities site consumer if site is public
// - give all authorities read properties if site is moderated
// - give all authorities read permission on permissions so
// memberships can be calculated
// - add the current user to the site manager group
if (SiteVisibility.PUBLIC.equals(visibility) == true)
{
// From Alfresco 3.4 the 'site public' group is configurable. Out of the box it is
// GROUP_EVERYONE so unconfigured behaviour is unchanged. But from 3.4 admins
// can change the value of property site.public.group via JMX/properties files
// to be another group of their choosing.
// This then is the group that is given SiteConsumer access to newly created sites.
final String sitePublicGroup = sysAdminParams.getSitePublicGroup();
boolean groupExists = authorityService.authorityExists(sitePublicGroup);
if (!PermissionService.ALL_AUTHORITIES.equals(sitePublicGroup) && !groupExists)
{
// If the group does not exist, we cannot create the site.
throw new SiteServiceException(MSG_VISIBILITY_GROUP_MISSING, new Object[]{sitePublicGroup});
}
permissionService.setPermission(siteNodeRef, sitePublicGroup, SITE_CONSUMER, true);
}
else if (SiteVisibility.MODERATED.equals(visibility) == true)
{
// for moderated site EVERYONE has consumer access but site components do not.
permissionService.setPermission(siteNodeRef, PermissionService.ALL_AUTHORITIES, SITE_CONSUMER, true);
}
permissionService.setPermission(siteNodeRef,
PermissionService.ALL_AUTHORITIES,
PermissionService.READ_PERMISSIONS, true);
authorityService.addAuthority(getSiteRoleGroup(shortName,
SiteModel.SITE_MANAGER, true), currentUser);
// Return nothing
return null;
}
}, AuthenticationUtil.getSystemUserName());
// Return created site information
Map<QName, Serializable> customProperties = getSiteCustomProperties(siteNodeRef);
SiteInfo siteInfo = new SiteInfoImpl(sitePreset, shortName, title, description, visibility, customProperties, siteNodeRef);
return siteInfo;
}
/**
* Gets a map containing the site's custom properties
*
* @return Map<QName, Serializable> map containing the custom properties of the site
*/
private Map<QName, Serializable> getSiteCustomProperties(Map<QName, Serializable> properties)
{
Map<QName, Serializable> customProperties = new HashMap<QName, Serializable>(4);
for (Map.Entry<QName, Serializable> entry : properties.entrySet())
{
if (entry.getKey().getNamespaceURI().equals(SITE_CUSTOM_PROPERTY_URL) == true)
{
customProperties.put(entry.getKey(), entry.getValue());
}
}
return customProperties;
}
/**
* Gets a map containing the site's custom properties
*
* @return Map<QName, Serializable> map containing the custom properties of the site
*/
private Map<QName, Serializable> getSiteCustomProperties(NodeRef siteNodeRef)
{
Map<QName, Serializable> customProperties = new HashMap<QName, Serializable>(4);
Map<QName, Serializable> properties = nodeService.getProperties(siteNodeRef);
for (Map.Entry<QName, Serializable> entry : properties.entrySet())
{
if (entry.getKey().getNamespaceURI().equals(SITE_CUSTOM_PROPERTY_URL) == true)
{
customProperties.put(entry.getKey(), entry.getValue());
}
}
return customProperties;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getSiteGroup(java.lang.String)
*/
public String getSiteGroup(String shortName)
{
return getSiteGroup(shortName, true);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getSiteRoleGroup(java.lang.String,
* java.lang.String)
*/
public String getSiteRoleGroup(String shortName, String role)
{
return getSiteRoleGroup(shortName, role, true);
}
/**
* Helper method to get the name of the site group
*
* @param shortName site short name
* @return String site group name
*/
public String getSiteGroup(String shortName, boolean withGroupPrefix)
{
StringBuffer sb = new StringBuffer(64);
if (withGroupPrefix == true)
{
sb.append(PermissionService.GROUP_PREFIX);
}
sb.append(SITE_PREFIX);
sb.append(shortName);
return sb.toString();
}
/**
* Helper method to get the name of the site permission group
*
* @param shortName site short name
* @param permission permission name
* @param withGroupPrefix - should the name have the GROUP_ prefix?
* @return String site permission group name
*/
public String getSiteRoleGroup(String shortName, String permission, boolean withGroupPrefix)
{
return getSiteGroup(shortName, withGroupPrefix) + '_' + permission;
}
/**
* Gets a sites parent folder based on it's short name
*
* @param shortName site short name
* @return NodeRef the site's parent
*/
private NodeRef getSiteParent(String shortName)
{
// TODO: For now just return the site root, later we may build folder
// structure based on the shortname to spread the sites about
return getSiteRoot();
}
/**
* Get the node reference that is the site root
*
* @return NodeRef node reference
*/
private NodeRef getSiteRoot()
{
String tenantDomain = tenantAdminService.getCurrentUserDomain();
NodeRef siteHomeRef = siteHomeRefs.get(tenantDomain);
if (siteHomeRef == null)
{
siteHomeRef = AuthenticationUtil.runAs(new RunAsWork<NodeRef>()
{
public NodeRef doWork() throws Exception
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Exception
{
NodeRef result = null;
// Get the root 'sites' folder
NodeRef rootNodeRef = nodeService.getRootNode(SITE_STORE);
List<NodeRef> results = searchService.selectNodes(
rootNodeRef,
sitesXPath,
null,
namespaceService,
false,
SearchService.LANGUAGE_XPATH);
if (results.size() != 0)
{
result = results.get(0);
}
return result;
}
}, true);
}
}, AuthenticationUtil.getSystemUserName());
siteHomeRefs.put(tenantDomain, siteHomeRef);
}
return siteHomeRef;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#listSites(java.lang.String, java.lang.String)
*/
public List<SiteInfo> listSites(String nameFilter, String sitePresetFilter)
{
return listSites(nameFilter, sitePresetFilter, 0);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#listSites(java.lang.String, java.lang.String, int)
*/
public List<SiteInfo> listSites(String nameFilter, String sitePresetFilter, int size)
{
List<SiteInfo> result;
NodeRef siteRoot = getSiteRoot();
if (siteRoot == null)
{
result = Collections.emptyList();
}
else
{
if (nameFilter != null && nameFilter.length() != 0 || sitePresetFilter != null && sitePresetFilter.length() > 0)
{
// get the sites that match the specified names
StringBuilder query = new StringBuilder(128);
query.append("+PARENT:\"").append(siteRoot.toString())
.append("\" +(");
if (nameFilter != null && nameFilter.length() > 0)
{
String escNameFilter = LuceneQueryParser.escape(nameFilter.replace('"', ' '));
query.append(" @cm\\:name:\"*" + escNameFilter + "*\"")
.append(" @cm\\:title:\"" + escNameFilter + "\"")
.append(" @cm\\:description:\"" + escNameFilter + "\"");
}
if (sitePresetFilter != null && sitePresetFilter.length() > 0)
{
String escPresetFilter = LuceneQueryParser.escape(sitePresetFilter.replace('"', ' '));
query.append(" @st\\:sitePreset:\"" + escPresetFilter + "\"");
}
query.append(")");
ResultSet results = this.searchService.query(
siteRoot.getStoreRef(),
SearchService.LANGUAGE_LUCENE,
query.toString(),
null);
try
{
result = new ArrayList<SiteInfo>(results.length());
for (NodeRef site : results.getNodeRefs())
{
// Ignore any node type that is not a "site"
QName siteClassName = this.nodeService.getType(site);
if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE) == true)
{
result.add(createSiteInfo(site));
// break on max size limit reached
if (result.size() == size) break;
}
}
}
finally
{
results.close();
}
}
else
{
// Get ALL sites - this may be a very slow operation if there are many sites...
List<ChildAssociationRef> assocs = this.nodeService.getChildAssocs(
siteRoot, ContentModel.ASSOC_CONTAINS,
RegexQNamePattern.MATCH_ALL);
result = new ArrayList<SiteInfo>(assocs.size());
for (ChildAssociationRef assoc : assocs)
{
// Ignore any node type that is not a "site"
NodeRef site = assoc.getChildRef();
QName siteClassName = this.nodeService.getType(site);
if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE) == true)
{
result.add(createSiteInfo(site));
// break on max size limit reached
if (result.size() == size) break;
}
}
}
}
return result;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#listSites(java.lang.String)
*/
public List<SiteInfo> listSites(final String userName)
{
// MT share - for activity service system callback
if (tenantService.isEnabled() && (AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser())) && tenantService.isTenantUser(userName))
{
final String tenantDomain = tenantService.getUserDomain(userName);
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<List<SiteInfo>>()
{
public List<SiteInfo> doWork() throws Exception
{
return listSitesImpl(userName);
}
}, tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain));
}
else
{
return listSitesImpl(userName);
}
}
private List<SiteInfo> listSitesImpl(String userName)
{
List<SiteInfo> result = null;
// get the Groups this user is contained within (at any level)
Set<String> groups = this.authorityService.getContainingAuthorities(null, userName, false);
Set<String> siteNames = new HashSet<String>(groups.size());
// purge non Site related Groups and strip the group name down to the site "shortName" it relates too
for (String group : groups)
{
if (group.startsWith(GROUP_SITE_PREFIX))
{
int roleIndex = group.lastIndexOf('_');
String siteName;
if (roleIndex + 1 <= GROUP_SITE_PREFIX_LENGTH)
{
// There is no role associated
siteName = group.substring(GROUP_SITE_PREFIX_LENGTH);
}
else
{
siteName = group.substring(GROUP_SITE_PREFIX_LENGTH, roleIndex);
}
siteNames.add(siteName);
}
}
// retrieve the site nodes based on the list from the containing site groups
NodeRef siteRoot = getSiteRoot();
if (siteRoot == null)
{
result = new ArrayList<SiteInfo>(0);
}
else
{
List<String> siteList = new ArrayList<String>(siteNames);
// ensure we do not trip over the getChildrenByName() 1000 item API limit!
if (siteList.size() > 1000)
{
siteList = siteList.subList(0, 1000);
}
List<ChildAssociationRef> assocs = this.nodeService.getChildrenByName(
siteRoot,
ContentModel.ASSOC_CONTAINS,
siteList);
result = new ArrayList<SiteInfo>(assocs.size());
for (ChildAssociationRef assoc : assocs)
{
// Ignore any node that is not a "site" type
NodeRef site = assoc.getChildRef();
QName siteClassName = this.nodeService.getType(site);
if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE))
{
result.add(createSiteInfo(site));
}
}
}
return result;
}
/**
* Creates a site information object given a site node reference
*
* @param siteNodeRef
* site node reference
* @return SiteInfo site information object
*/
private SiteInfo createSiteInfo(NodeRef siteNodeRef)
{
SiteInfo siteInfo = null;
if (this.permissionService.hasPermission(siteNodeRef, PermissionService.READ_PROPERTIES).equals(AccessStatus.ALLOWED))
{
// Get the properties
Map<QName, Serializable> properties = this.nodeService.getProperties(siteNodeRef);
String shortName = (String) properties.get(ContentModel.PROP_NAME);
String sitePreset = (String) properties.get(PROP_SITE_PRESET);
String title = (String) properties.get(ContentModel.PROP_TITLE);
String description = (String) properties.get(ContentModel.PROP_DESCRIPTION);
// Get the visibility of the site
SiteVisibility visibility = getSiteVisibility(siteNodeRef);
// Create and return the site information
Map<QName, Serializable> customProperties = getSiteCustomProperties(properties);
siteInfo = new SiteInfoImpl(sitePreset, shortName, title, description, visibility, customProperties, siteNodeRef);
}
return siteInfo;
}
/**
* Helper method to get the visibility of the site. If no value is present in the repository then it is calculated from the
* set permissions. This will maintain backwards compatibility with earlier versions of the service implementation.
*
* @param siteNodeRef site node reference
* @return SiteVisibility site visibility
*/
private SiteVisibility getSiteVisibility(NodeRef siteNodeRef)
{
SiteVisibility visibility = SiteVisibility.PRIVATE;
// Get the visibility value stored in the repo
String visibilityValue = (String)this.nodeService.getProperty(siteNodeRef, SiteModel.PROP_SITE_VISIBILITY);
// To maintain backwards compatibility calculate the visibility from the permissions
// if there is no value specified on the site node
if (visibilityValue == null)
{
// Examine each permission to see if this is a public site or not
Set<AccessPermission> permissions = this.permissionService.getAllSetPermissions(siteNodeRef);
for (AccessPermission permission : permissions)
{
if (permission.getAuthority().equals(PermissionService.ALL_AUTHORITIES) == true &&
permission.getPermission().equals(SITE_CONSUMER) == true)
{
visibility = SiteVisibility.PUBLIC;
break;
}
}
}
else
{
// Create the enum value from the string
visibility = SiteVisibility.valueOf(visibilityValue);
}
return visibility;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getSite(java.lang.String)
*/
public SiteInfo getSite(final String shortName)
{
// MT share - for activity service system callback
if (tenantService.isEnabled() && (AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser())) && tenantService.isTenantName(shortName))
{
final String tenantDomain = tenantService.getDomain(shortName);
final String sName = tenantService.getBaseName(shortName, true);
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<SiteInfo>()
{
public SiteInfo doWork() throws Exception
{
SiteInfo site = getSiteImpl(sName);
return new SiteInfoImpl(site.getSitePreset(), shortName, site.getTitle(), site.getDescription(), site.getVisibility(), site.getCustomProperties(), site.getNodeRef());
}
}, tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain));
}
else
{
return getSiteImpl(shortName);
}
}
/**
* Get the site implementation given a short name
*
* @param shortName
* @return
*/
private SiteInfo getSiteImpl(String shortName)
{
SiteInfo result = null;
// Get the site node
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef != null)
{
// Create the site info
result = createSiteInfo(siteNodeRef);
}
// Return the site information
return result;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getSite(org.alfresco.service.cmr.repository.NodeRef)
*/
public SiteInfo getSite(NodeRef nodeRef)
{
SiteInfo siteInfo = null;
NodeRef siteNodeRef = getSiteNodeRef(nodeRef);
if (siteNodeRef != null)
{
siteInfo = createSiteInfo(siteNodeRef);
}
return siteInfo;
}
/**
* This method gets the <code>st:site</code> NodeRef for the Share Site which contains the given NodeRef.
* If the given NodeRef is not contained within a Share Site, then <code>null</code> is returned.
*
* @param nodeRef the node whose containing site is to be found.
* @return NodeRef site node reference or null if node is not in a site
*/
private NodeRef getSiteNodeRef(NodeRef nodeRef)
{
NodeRef siteNodeRef = null;
QName nodeRefType = nodeService.getType(nodeRef);
if (dictionaryService.isSubClass(nodeRefType, TYPE_SITE) == true)
{
siteNodeRef = nodeRef;
}
else
{
ChildAssociationRef primaryParent = nodeService.getPrimaryParent(nodeRef);
if (primaryParent != null && primaryParent.getParentRef() != null)
{
siteNodeRef = getSiteNodeRef(primaryParent.getParentRef());
}
}
return siteNodeRef;
}
/**
* Gets the site's node reference based on its short name
*
* @param shortName short name
*
* @return NodeRef node reference
*/
private NodeRef getSiteNodeRef(final String shortName)
{
final String cacheKey = this.tenantAdminService.getCurrentUserDomain() + '_' + shortName;
NodeRef siteNodeRef = this.siteNodeRefs.get(cacheKey);
if (siteNodeRef != null)
{
// test for existance - and remove from cache if no longer exists
if (!this.nodeService.exists(siteNodeRef))
{
this.siteNodeRefs.remove(cacheKey);
siteNodeRef = null;
}
}
else
{
// not in cache - find and store
final NodeRef siteRoot = getSiteParent(shortName);
siteNodeRef = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<NodeRef>()
{
public NodeRef doWork() throws Exception
{
// the site "short name" directly maps to the cm:name property
NodeRef siteNodeRef = nodeService.getChildByName(siteRoot, ContentModel.ASSOC_CONTAINS, shortName);
// cache the result if found - null results will be required to ensure new sites are found later
if (siteNodeRef != null)
{
siteNodeRefs.put(cacheKey, siteNodeRef);
}
return siteNodeRef;
}
}, AuthenticationUtil.getSystemUserName());
}
return siteNodeRef;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#updateSite(org.alfresco.service.cmr.site.SiteInfo)
*/
public void updateSite(SiteInfo siteInfo)
{
String shortName = siteInfo.getShortName();
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_CAN_NOT_UPDATE, new Object[]{siteInfo.getShortName()});
}
// Get the sites properties
Map<QName, Serializable> properties = this.nodeService.getProperties(siteNodeRef);
// Update the properties of the site
// Note: the site preset and short name should never be updated!
properties.put(ContentModel.PROP_TITLE, siteInfo.getTitle());
properties.put(ContentModel.PROP_DESCRIPTION, siteInfo.getDescription());
// Update the isPublic flag
SiteVisibility currentVisibility = getSiteVisibility(siteNodeRef);
SiteVisibility updatedVisibility = siteInfo.getVisibility();
if (currentVisibility.equals(updatedVisibility) == false)
{
// visibility has changed
logger.debug("site:" + shortName + " visibility has changed from: " + currentVisibility + "to: " + updatedVisibility);
// visibility has changed.
// Remove current visibility permissions
if (SiteVisibility.PUBLIC.equals(currentVisibility) == true)
{
this.permissionService.deletePermission(siteNodeRef, PermissionService.ALL_AUTHORITIES, SITE_CONSUMER);
}
else if (SiteVisibility.MODERATED.equals(currentVisibility) == true)
{
this.permissionService.deletePermission(siteNodeRef, PermissionService.ALL_AUTHORITIES, SITE_CONSUMER);
/**
* update the containers
*/
List<FileInfo> folders = fileFolderService.listFolders(siteNodeRef);
for(FileInfo folder : folders)
{
NodeRef containerNodeRef = folder.getNodeRef();
this.permissionService.setInheritParentPermissions(containerNodeRef, true);
}
}
// Add new visibility permissions
if (SiteVisibility.PUBLIC.equals(updatedVisibility) == true)
{
this.permissionService.setPermission(siteNodeRef, PermissionService.ALL_AUTHORITIES, SITE_CONSUMER, true);
}
else if (SiteVisibility.MODERATED.equals(updatedVisibility) == true)
{
this.permissionService.setPermission(siteNodeRef, PermissionService.ALL_AUTHORITIES, SITE_CONSUMER, true);
/**
* update the containers
*/
List<FileInfo> folders = fileFolderService.listFolders(siteNodeRef);
for(FileInfo folder : folders)
{
NodeRef containerNodeRef = folder.getNodeRef();
setModeratedPermissions(shortName, containerNodeRef);
}
}
// Update the site node reference with the updated visibility value
properties.put(SiteModel.PROP_SITE_VISIBILITY, siteInfo.getVisibility().toString());
}
// Set the updated properties back onto the site node reference
this.nodeService.setProperties(siteNodeRef, properties);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#deleteSite(java.lang.String)
*/
public void deleteSite(final String shortName)
{
logger.debug("delete site :" + shortName);
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_CAN_NOT_DELETE, new Object[]{shortName});
}
// Delete the cached reference
String cacheKey = this.tenantAdminService.getCurrentUserDomain() + '_' + shortName;
this.siteNodeRefs.remove(cacheKey);
// The default behaviour is that sites cannot be deleted. But we disable that behaviour here
// in order to allow site deletion only via this service. Share calls this service for deletion.
//
// See ALF-7888 for some background on this issue
behaviourFilter.disableBehaviour(siteNodeRef, ContentModel.ASPECT_UNDELETABLE);
try
{
// Delete the site node, marking it as "not to be archived" on the way.
// The site node will be permanently deleted.
this.nodeService.addAspect(siteNodeRef, ContentModel.ASPECT_TEMPORARY, null);
this.nodeService.deleteNode(siteNodeRef);
}
finally
{
behaviourFilter.enableBehaviour(siteNodeRef, ContentModel.ASPECT_UNDELETABLE);
}
// Delete the associated groups
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
// Delete the master site group
authorityService.deleteAuthority(getSiteGroup(shortName, true), false);
// Iterate over the role related groups and delete then
Set<String> permissions = permissionService.getSettablePermissions(SiteModel.TYPE_SITE);
for (String permission : permissions)
{
String siteRoleGroup = getSiteRoleGroup(shortName, permission, true);
authorityService.deleteAuthority(siteRoleGroup);
}
return null;
}
}, AuthenticationUtil.getSystemUserName());
logger.debug("site deleted :" + shortName);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#listMembers(java.lang.String, java.lang.String, java.lang.String, int)
*/
public Map<String, String> listMembers(String shortName, String nameFilter, String roleFilter, int size)
{
return listMembers(shortName, nameFilter, roleFilter, size, false);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#listMembers(String, String, String, int, boolean)
*/
public Map<String, String> listMembers(String shortName, final String nameFilter, final String roleFilter, final int size, final boolean collapseGroups)
{
// MT share - for activity service system callback
if (tenantService.isEnabled() && (AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser())) && tenantService.isTenantName(shortName))
{
final String tenantDomain = tenantService.getDomain(shortName);
final String sName = tenantService.getBaseName(shortName, true);
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Map<String, String>>()
{
public Map<String, String> doWork() throws Exception
{
return listMembersImpl(sName, nameFilter, roleFilter, size, collapseGroups);
}
}, tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain));
}
else
{
return listMembersImpl(shortName, nameFilter, roleFilter, size, collapseGroups);
}
}
private Map<String, String> listMembersImpl(String shortName, String nameFilter, String roleFilter, int size, boolean collapseGroups)
{
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// build an array of name filter tokens pre lowercased to test against person properties
String[] nameFilters = new String[0];
if (nameFilter != null && nameFilter.length() != 0)
{
StringTokenizer t = new StringTokenizer(nameFilter, " ");
nameFilters = new String[t.countTokens()];
for (int i=0; t.hasMoreTokens(); i++)
{
nameFilters[i] = t.nextToken().toLowerCase();
}
}
Map<String, String> members = new HashMap<String, String>(32);
Set<String> permissions = this.permissionService.getSettablePermissions(SiteModel.TYPE_SITE);
for (String permission : permissions)
{
if (roleFilter == null || roleFilter.length() == 0 || roleFilter.equals(permission))
{
String groupName = getSiteRoleGroup(shortName, permission, true);
Set<String> users = this.authorityService.getContainedAuthorities(AuthorityType.USER, groupName, true);
for (String user : users)
{
boolean addUser = true;
if (nameFilter != null && nameFilter.length() != 0 && !nameFilter.equals(user))
{
// found a filter - does it match person first/last name?
addUser = matchPerson(nameFilters, user);
}
if (addUser)
{
// Add the user and their permission to the returned map
members.put(user, permission);
// break on max size limit reached
if (members.size() == size) break;
}
}
Set<String> groups = this.authorityService.getContainedAuthorities(AuthorityType.GROUP, groupName, true);
for (String group : groups)
{
if (collapseGroups == false)
{
if (nameFilter != null && nameFilter.length() != 0)
{
// found a filter - does it match Group name part?
if (group.substring(GROUP_PREFIX_LENGTH).toLowerCase().contains(nameFilter.toLowerCase()))
{
members.put(group, permission);
}
}
else
{
// No name filter add this group
members.put(group, permission);
}
}
else
{
Set<String> subUsers = this.authorityService.getContainedAuthorities(AuthorityType.USER, group, false);
for (String subUser : subUsers)
{
boolean addUser = true;
if (nameFilter != null && nameFilter.length() != 0 && !nameFilter.equals(subUser))
{
// found a filter - does it match person first/last name?
addUser = matchPerson(nameFilters, subUser);
}
if (addUser)
{
// Add the collapsed user into the members list if they do not already appear in the list
if (members.containsKey(subUser) == false)
{
members.put(subUser, permission);
}
// break on max size limit reached
if (members.size() == size) break;
}
}
}
}
}
}
return members;
}
/**
* Helper to match name filters to Person properties
*
* @param filter
* @param username
* @return
*/
private boolean matchPerson(final String[] nameFilters, final String username)
{
boolean addUser = false;
String query = "+TYPE:\"cm:person\" +@cm\\:userName:\"" + username + "\"";
SearchParameters searchParameters = new SearchParameters();
searchParameters.setLanguage(SearchService.LANGUAGE_LUCENE);
searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
searchParameters.setQuery(query);
ResultSet resultSet = this.searchService.query(searchParameters);
try
{
if (resultSet.length() != 0)
{
ResultSetRow row = resultSet.getRow(0);
Map<String, Serializable> values = row.getValues();
String firstName = (String)values.get(ContentModel.PROP_FIRSTNAME.toString());
String lastName = (String)values.get(ContentModel.PROP_LASTNAME.toString());
final String lowFirstName = (firstName != null ? firstName.toLowerCase() : "");
final String lowLastName = (lastName != null ? lastName.toLowerCase() : "");
for (int i=0; i<nameFilters.length; i++)
{
if (lowFirstName.indexOf(nameFilters[i]) != -1)
{
addUser = true;
break;
}
else if (lowLastName.indexOf(nameFilters[i]) != -1)
{
addUser = true;
break;
}
}
}
}
finally
{
resultSet.close();
}
return addUser;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getMembersRole(java.lang.String,
* java.lang.String)
*/
public String getMembersRole(String shortName, String authorityName)
{
String result = null;
List<String> roles = getMembersRoles(shortName, authorityName);
if (roles.size() != 0)
{
if (roles.size() > 1 && roleComparator != null)
{
// Need to sort the roles into the most important first.
SortedSet<String> sortedRoles = new TreeSet<String>(roleComparator);
for (String role : roles)
{
sortedRoles.add(role);
}
result = sortedRoles.first();
}
else
{
// don't search on precedence or only one result
result = roles.get(0);
}
}
return result;
}
public List<String> getMembersRoles(String shortName, String authorityName)
{
List<String> result = new ArrayList<String>(5);
List<String> groups = getPermissionGroups(shortName, authorityName);
for (String group : groups)
{
int index = group.lastIndexOf('_');
if (index != -1)
{
result.add(group.substring(index + 1));
}
}
return result;
}
/**
* Helper method to get the permission groups for a given authority on a site.
* Returns empty List if the user does not have a explicit membership to the site.
*
* A user permission will take precedence over a permission obtained via a group.
*
* @param siteShortName site short name
* @param authorityName authority name
* @return List<String> Permission groups, empty list if no explicit membership set
*/
private List<String> getPermissionGroups(String siteShortName, String authorityName)
{
List<String> fullResult = new ArrayList<String>(5);
Set<String> roles = this.permissionService.getSettablePermissions(SiteModel.TYPE_SITE);
// First use the authority's cached recursive group memberships to answer the question quickly
Set<String> authorityGroups = this.authorityService.getContainingAuthorities(AuthorityType.GROUP,
authorityName, false);
for (String role : roles)
{
String roleGroup = getSiteRoleGroup(siteShortName, role, true);
if (authorityGroups.contains(roleGroup))
{
fullResult.add(roleGroup);
}
}
// Unfortunately, due to direct membership taking precendence, we can't answer the question quickly if more than one role has been inherited
if (fullResult.size() <= 1)
{
return fullResult;
}
// Check direct group memberships
List<String> result = new ArrayList<String>(5);
authorityGroups = this.authorityService.getContainingAuthorities(AuthorityType.GROUP,
authorityName, true);
for (String role : roles)
{
String roleGroup = getSiteRoleGroup(siteShortName, role, true);
if (authorityGroups.contains(roleGroup))
{
result.add(roleGroup);
}
}
// If there are user permissions then they take priority
return result.size() > 0 ? result : fullResult;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getSiteRoles()
*/
public List<String> getSiteRoles()
{
Set<String> permissions = permissionService
.getSettablePermissions(SiteModel.TYPE_SITE);
return new ArrayList<String>(permissions);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#isMember(java.lang.String, java.lang.String)
*/
public boolean isMember(String shortName, String authorityName)
{
return (!getPermissionGroups(shortName, authorityName).isEmpty());
}
/**
* @see org.alfresco.service.cmr.site.SiteService#removeMembership(java.lang.String, java.lang.String)
*/
public void removeMembership(final String shortName, final String authorityName)
{
final NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// TODO what do we do about the user if they are in a group that has
// rights to the site?
// Get the current user
String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
// Get the user current role
final String role = getMembersRole(shortName, authorityName);
if (role != null)
{
// Check that we are not about to remove the last site manager
checkLastManagerRemoval(shortName, authorityName, role);
// If ...
// -- the current user has change permissions rights on the site
// or
// -- the user is ourselves
if ((currentUserName.equals(authorityName) == true) ||
(permissionService.hasPermission(siteNodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED))
{
// Run as system user
AuthenticationUtil.runAs(
new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
// Remove the user from the current permission
// group
String currentGroup = getSiteRoleGroup(shortName, role, true);
authorityService.removeAuthority(currentGroup, authorityName);
return null;
}
}, AuthenticationUtil.SYSTEM_USER_NAME);
// Raise events
AuthorityType authorityType = AuthorityType.getAuthorityType(authorityName);
if (authorityType == AuthorityType.USER)
{
activityService.postActivity(
ActivityType.SITE_USER_REMOVED, shortName,
ACTIVITY_TOOL, getActivityUserData(authorityName, ""));
}
else if (authorityType == AuthorityType.GROUP)
{
activityService.postActivity(
ActivityType.SITE_GROUP_REMOVED, shortName,
ACTIVITY_TOOL, getActivityGroupData(authorityName, ""));
}
}
else
{
// Throw an exception
throw new SiteServiceException(MSG_CAN_NOT_REMOVE_MSHIP, new Object[]{shortName});
}
}
else
{
// Throw an exception
throw new SiteServiceException(MSG_CAN_NOT_REMOVE_MSHIP, new Object[]{shortName});
}
}
/**
* @see org.alfresco.service.cmr.site.SiteService#setMembership(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void setMembership(final String shortName,
final String authorityName,
final String role)
{
final NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// Get the user's current role
final String currentRole = getMembersRole(shortName, authorityName);
// Do nothing if the role of the user is not being changed
if (currentRole == null || role.equals(currentRole) == false)
{
// TODO if this is the only site manager do not down grade their
// permissions
// Get the visibility of the site
SiteVisibility visibility = getSiteVisibility(siteNodeRef);
// If we are ...
// -- the current user has change permissions rights on the site
// or we are ...
// -- referring to a public site and
// -- the role being set is consumer and
// -- the user being added is ourselves and
// -- the member does not already have permissions
// ... then we can set the permissions as system user
final String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
if ((permissionService.hasPermission(siteNodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED) ||
(SiteVisibility.PUBLIC.equals(visibility) == true &&
role.equals(SiteModel.SITE_CONSUMER) == true &&
authorityName.equals(currentUserName) == true &&
currentRole == null))
{
// Check that we are not about to remove the last site manager
checkLastManagerRemoval(shortName, authorityName, currentRole);
// Run as system user
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
{
public Object doWork() throws Exception
{
if (currentRole != null)
{
// Remove the user from the current
// permission group
String currentGroup = getSiteRoleGroup(shortName, currentRole, true);
authorityService.removeAuthority(currentGroup, authorityName);
}
// Add the user to the new permission group
String newGroup = getSiteRoleGroup(shortName, role, true);
authorityService.addAuthority(newGroup, authorityName);
return null;
}
}, AuthenticationUtil.SYSTEM_USER_NAME);
if (currentRole == null)
{
AuthorityType authorityType = AuthorityType.getAuthorityType(authorityName);
if (authorityType == AuthorityType.USER)
{
activityService.postActivity(
ActivityType.SITE_USER_JOINED, shortName,
ACTIVITY_TOOL, getActivityUserData(authorityName, role));
}
else if (authorityType == AuthorityType.GROUP)
{
activityService.postActivity(
ActivityType.SITE_GROUP_ADDED, shortName,
ACTIVITY_TOOL, getActivityGroupData(authorityName, role));
}
}
else
{
AuthorityType authorityType = AuthorityType.getAuthorityType(authorityName);
if (authorityType == AuthorityType.USER)
{
activityService.postActivity(
ActivityType.SITE_USER_ROLE_UPDATE, shortName,
ACTIVITY_TOOL, getActivityUserData(authorityName, role));
}
else if (authorityType == AuthorityType.GROUP)
{
activityService.postActivity(
ActivityType.SITE_GROUP_ROLE_UPDATE, shortName,
ACTIVITY_TOOL, getActivityGroupData(authorityName, role));
}
}
}
else
{
// Raise a permission exception
throw new SiteServiceException(MSG_CAN_NOT_CHANGE_MSHIP, new Object[]{shortName});
}
}
}
/**
* @see org.alfresco.service.cmr.site.SiteService#createContainer(java.lang.String,
* java.lang.String, org.alfresco.service.namespace.QName,
* java.util.Map)
*/
public NodeRef createContainer(String shortName,
String componentId,
QName containerType,
Map<QName, Serializable> containerProperties)
{
// Check for the component id
ParameterCheck.mandatoryString("componentId", componentId);
// retrieve site
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// Update the isPublic flag
SiteVisibility siteVisibility = getSiteVisibility(siteNodeRef);
// retrieve component folder within site
NodeRef containerNodeRef = null;
try
{
containerNodeRef = findContainer(siteNodeRef, componentId);
}
catch (FileNotFoundException e)
{
}
// create the container node reference
if (containerNodeRef == null)
{
if (containerType == null)
{
containerType = ContentModel.TYPE_FOLDER;
}
// create component folder
FileInfo fileInfo = fileFolderService.create(siteNodeRef,
componentId, containerType);
// Get the created container
containerNodeRef = fileInfo.getNodeRef();
// Set the properties if they have been provided
if (containerProperties != null)
{
Map<QName, Serializable> props = this.nodeService
.getProperties(containerNodeRef);
props.putAll(containerProperties);
this.nodeService.setProperties(containerNodeRef, props);
}
// Add the container aspect
Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(1, 1.0f);
aspectProps.put(SiteModel.PROP_COMPONENT_ID, componentId);
this.nodeService.addAspect(containerNodeRef, ASPECT_SITE_CONTAINER,
aspectProps);
// Set permissions on the container
if(SiteVisibility.MODERATED.equals(siteVisibility))
{
setModeratedPermissions(shortName, containerNodeRef);
}
// Make the container a tag scope
this.taggingService.addTagScope(containerNodeRef);
}
return containerNodeRef;
}
/**
* This method recursively cleans the site permissions on the specified NodeRef and all its primary
* descendants. This consists of
* <ul>
* <li>the removal of all site permissions pertaining to a site other than the containingSite</li>
* </ul>
* If the containingSite is <code>null</code> then the targetNode's current containing site is used.
*
* @param targetNode
* @param containingSite the site which the site is a member of. If <code>null</code>, it will be calculated.
*/
@Override
public void cleanSitePermissions(final NodeRef targetNode, SiteInfo containingSite)
{
this.sitesPermissionsCleaner.cleanSitePermissions(targetNode, containingSite);
}
/**
* Moderated sites have separate ACLs on each component and don't inherit from the
* site which has consumer role for everyone.
*/
private void setModeratedPermissions(String shortName, NodeRef containerNodeRef)
{
Set<String> permissions = permissionService.getSettablePermissions(SiteModel.TYPE_SITE);
for (String permission : permissions)
{
String permissionGroup = getSiteRoleGroup(shortName, permission, true);
// Assign the group the relevant permission on the site
permissionService.setPermission(containerNodeRef, permissionGroup, permission, true);
}
permissionService.setPermission(containerNodeRef,
PermissionService.ALL_AUTHORITIES,
PermissionService.READ_PERMISSIONS, true);
this.permissionService.setInheritParentPermissions(containerNodeRef, false);
}
/**
* @see org.alfresco.service.cmr.site.SiteService#getContainer(java.lang.String)
*/
public NodeRef getContainer(String shortName, String componentId)
{
ParameterCheck.mandatoryString("componentId", componentId);
// retrieve site
NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// retrieve component folder within site
// NOTE: component id is used for folder name
NodeRef containerNodeRef = null;
try
{
containerNodeRef = findContainer(siteNodeRef, componentId);
}
catch (FileNotFoundException e)
{
}
return containerNodeRef;
}
/**
* @see org.alfresco.service.cmr.site.SiteService#hasContainer(java.lang.String)
*/
public boolean hasContainer(final String shortName, final String componentId)
{
ParameterCheck.mandatoryString("componentId", componentId);
// retrieve site
final NodeRef siteNodeRef = getSiteNodeRef(shortName);
if (siteNodeRef == null)
{
throw new SiteServiceException(MSG_SITE_NO_EXIST, new Object[]{shortName});
}
// retrieve component folder within site
// NOTE: component id is used for folder name
boolean hasContainer = false;
NodeRef containerRef = AuthenticationUtil.runAs(new RunAsWork<NodeRef>()
{
public NodeRef doWork() throws Exception
{
return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Exception
{
try
{
return findContainer(siteNodeRef, componentId);
}
catch (FileNotFoundException e)
{
return null;
}
}
}, true);
}
}, AuthenticationUtil.getSystemUserName());
if(containerRef != null)
{
hasContainer = true;
}
return hasContainer;
}
/**
* Locate site "container" folder for component
*
* @param siteNodeRef
* site
* @param componentId
* component id
* @return "container" node ref, if it exists
* @throws FileNotFoundException
*/
private NodeRef findContainer(NodeRef siteNodeRef, String componentId)
throws FileNotFoundException
{
List<String> paths = new ArrayList<String>(1);
paths.add(componentId);
FileInfo fileInfo = fileFolderService.resolveNamePath(siteNodeRef,
paths);
if (!fileInfo.isFolder())
{
throw new SiteServiceException(MSG_SITE_CONTAINER_NOT_FOLDER, new Object[]{fileInfo.getName()});
}
return fileInfo.getNodeRef();
}
/**
* Helper method to get the activity data for a user
*
* @param userName user name
* @param role role
* @return
*/
private String getActivityUserData(String userName, String role)
{
String memberFN = "";
String memberLN = "";
NodeRef person = personService.getPerson(userName);
if (person != null)
{
memberFN = (String) nodeService.getProperty(person,
ContentModel.PROP_FIRSTNAME);
memberLN = (String) nodeService.getProperty(person,
ContentModel.PROP_LASTNAME);
}
try
{
JSONObject activityData = new JSONObject();
activityData.put("role", role);
activityData.put("memberUserName", userName);
activityData.put("memberFirstName", memberFN);
activityData.put("memberLastName", memberLN);
activityData.put("title", (memberFN + " " + memberLN + " ("
+ userName + ")").trim());
return activityData.toString();
} catch (JSONException je)
{
// log error, subsume exception
logger.error("Failed to get activity data: " + je);
return "";
}
}
/**
* Helper method to get the activity data for a group
*
* @param groupName user name
* @param role role
* @return Activity data in JSON format
*/
private String getActivityGroupData(String groupName, String role)
{
try
{
JSONObject activityData = new JSONObject();
activityData.put("role", role);
activityData.put("groupName", groupName);
return activityData.toString();
}
catch (JSONException je)
{
// log error, subsume exception
logger.error("Failed to get activity data: " + je);
return "";
}
}
/**
* Helper to check that we are not removing the last Site Manager from a site
*
* @param shortName
* @param authorityName
* @param role
*/
private void checkLastManagerRemoval(final String shortName, final String authorityName, final String role)
{
// Check that we are not about to remove the last site manager
if (SiteModel.SITE_MANAGER.equals(role) == true)
{
String mgrGroup = getSiteRoleGroup(shortName, SITE_MANAGER, true);
Set<String> siteUserMangers = this.authorityService.getContainedAuthorities(
AuthorityType.USER, mgrGroup, true);
if (siteUserMangers.size() <= 1)
{
Set<String> siteGroupManagers = this.authorityService.getContainedAuthorities(
AuthorityType.GROUP, mgrGroup, true);
if (siteUserMangers.size() + siteGroupManagers.size() == 1)
{
throw new SiteServiceException(MSG_DO_NOT_CHANGE_MGR, new Object[] {authorityName});
}
}
}
}
}