001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.convert;
016    
017    import com.liferay.counter.service.CounterLocalServiceUtil;
018    import com.liferay.portal.NoSuchResourceActionException;
019    import com.liferay.portal.convert.util.PermissionView;
020    import com.liferay.portal.convert.util.ResourcePermissionView;
021    import com.liferay.portal.kernel.dao.db.DB;
022    import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
023    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
024    import com.liferay.portal.kernel.dao.orm.QueryUtil;
025    import com.liferay.portal.kernel.exception.PortalException;
026    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
027    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedWriter;
028    import com.liferay.portal.kernel.log.Log;
029    import com.liferay.portal.kernel.log.LogFactoryUtil;
030    import com.liferay.portal.kernel.util.FileUtil;
031    import com.liferay.portal.kernel.util.GetterUtil;
032    import com.liferay.portal.kernel.util.MultiValueMap;
033    import com.liferay.portal.kernel.util.MultiValueMapFactoryUtil;
034    import com.liferay.portal.kernel.util.PropsKeys;
035    import com.liferay.portal.kernel.util.ReleaseInfo;
036    import com.liferay.portal.kernel.util.StringPool;
037    import com.liferay.portal.kernel.util.StringUtil;
038    import com.liferay.portal.kernel.util.Tuple;
039    import com.liferay.portal.kernel.util.UnmodifiableList;
040    import com.liferay.portal.kernel.util.Validator;
041    import com.liferay.portal.model.Company;
042    import com.liferay.portal.model.Group;
043    import com.liferay.portal.model.Release;
044    import com.liferay.portal.model.ReleaseConstants;
045    import com.liferay.portal.model.ResourceAction;
046    import com.liferay.portal.model.ResourceCode;
047    import com.liferay.portal.model.ResourceConstants;
048    import com.liferay.portal.model.ResourcePermission;
049    import com.liferay.portal.model.Role;
050    import com.liferay.portal.model.RoleConstants;
051    import com.liferay.portal.model.impl.PermissionModelImpl;
052    import com.liferay.portal.model.impl.ResourceCodeModelImpl;
053    import com.liferay.portal.model.impl.ResourceModelImpl;
054    import com.liferay.portal.model.impl.ResourcePermissionModelImpl;
055    import com.liferay.portal.model.impl.RoleModelImpl;
056    import com.liferay.portal.security.permission.PermissionCacheUtil;
057    import com.liferay.portal.security.permission.ResourceActionsUtil;
058    import com.liferay.portal.service.ClassNameLocalServiceUtil;
059    import com.liferay.portal.service.CompanyLocalServiceUtil;
060    import com.liferay.portal.service.GroupLocalServiceUtil;
061    import com.liferay.portal.service.ReleaseLocalServiceUtil;
062    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
063    import com.liferay.portal.service.ResourceBlockLocalServiceUtil;
064    import com.liferay.portal.service.ResourceCodeLocalServiceUtil;
065    import com.liferay.portal.service.RoleLocalServiceUtil;
066    import com.liferay.portal.service.UserLocalServiceUtil;
067    import com.liferay.portal.service.persistence.BatchSessionUtil;
068    import com.liferay.portal.upgrade.util.Table;
069    import com.liferay.portal.util.MaintenanceUtil;
070    import com.liferay.portal.util.PropsValues;
071    import com.liferay.portal.util.ShutdownUtil;
072    import com.liferay.portlet.bookmarks.model.BookmarksEntry;
073    import com.liferay.portlet.bookmarks.model.BookmarksFolder;
074    import com.liferay.portlet.bookmarks.service.BookmarksEntryLocalServiceUtil;
075    import com.liferay.portlet.bookmarks.service.BookmarksFolderLocalServiceUtil;
076    
077    import java.io.FileReader;
078    import java.io.FileWriter;
079    import java.io.Writer;
080    
081    import java.sql.Connection;
082    import java.sql.PreparedStatement;
083    import java.sql.ResultSet;
084    import java.sql.Types;
085    
086    import java.util.ArrayList;
087    import java.util.Collections;
088    import java.util.HashMap;
089    import java.util.HashSet;
090    import java.util.List;
091    import java.util.Map;
092    import java.util.Set;
093    
094    /**
095     * <p>
096     * This class converts all existing permissions from the legacy permissions
097     * algorithm to the latest algorithm.
098     * </p>
099     *
100     * @author Alexander Chow
101     * @author Joshua Steven Rodriguez
102     */
103    public class ConvertPermissionAlgorithm extends ConvertProcess {
104    
105            @Override
106            public String getDescription() {
107                    return "convert-legacy-permission-algorithm";
108            }
109    
110            @Override
111            public String[] getParameterNames() {
112                    return new String[] {"generate-custom-roles=checkbox"};
113            }
114    
115            @Override
116            public boolean isEnabled() {
117                    boolean enabled = false;
118    
119                    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 6) {
120                            enabled = true;
121                    }
122    
123                    return enabled;
124            }
125    
126            protected String convertGuestUsers(String legacyFile) throws Exception {
127                    UnsyncBufferedReader legacyFileReader = new UnsyncBufferedReader(
128                            new FileReader(legacyFile));
129    
130                    Writer legacyFileUpdatedWriter = new UnsyncBufferedWriter(
131                            new FileWriter(legacyFile + _UPDATED));
132                    Writer legacyFileExtRolesPermissionsWriter = new UnsyncBufferedWriter(
133                            new FileWriter(legacyFile + _EXT_ROLES_PERMIMISSIONS));
134    
135                    try {
136                            String line = null;
137    
138                            while (Validator.isNotNull(line = legacyFileReader.readLine())) {
139                                    String[] values = StringUtil.split(line);
140    
141                                    long companyId = PermissionView.getCompanyId(values);
142                                    long permissionId = PermissionView.getPermissionId(values);
143                                    int scope = PermissionView.getScopeId(values);
144                                    long userId = PermissionView.getPrimaryKey(values);
145    
146                                    if ((scope == ResourceConstants.SCOPE_INDIVIDUAL) &&
147                                            _guestUsersSet.contains(userId)) {
148    
149                                            long roleId = _guestRolesMap.get(companyId).getRoleId();
150    
151                                            String key = roleId + "_" + permissionId;
152    
153                                            if (_rolesPermissions.contains(key)) {
154                                                    continue;
155                                            }
156                                            else {
157                                                    _rolesPermissions.add(key);
158                                            }
159    
160                                            legacyFileExtRolesPermissionsWriter.write(
161                                                    roleId + "," + permissionId + "\n");
162                                    }
163                                    else {
164                                            legacyFileUpdatedWriter.write(line + "\n");
165                                    }
166                            }
167                    }
168                    finally {
169                            legacyFileReader.close();
170    
171                            legacyFileUpdatedWriter.close();
172                            legacyFileExtRolesPermissionsWriter.close();
173                    }
174    
175                    Table table = new Table(
176                            "Roles_Permissions",
177                            new Object[][] {
178                                    {"roleId", Types.BIGINT}, {"permissionId", Types.BIGINT}
179                            });
180    
181                    table.populateTable(legacyFile + _EXT_ROLES_PERMIMISSIONS);
182    
183                    FileUtil.delete(legacyFile);
184                    FileUtil.delete(legacyFile + _EXT_ROLES_PERMIMISSIONS);
185    
186                    return legacyFile + _UPDATED;
187            }
188    
189            protected void convertPermissions(
190                            int type, String legacyName, String[] primKeys, String newName,
191                            Object[][] newColumns)
192                    throws Exception {
193    
194                    MaintenanceUtil.appendStatus("Processing " + legacyName);
195    
196                    Table legacyTable = new PermissionView(legacyName, primKeys);
197    
198                    String legacyFile = legacyTable.generateTempFile();
199    
200                    if (legacyFile == null) {
201                            return;
202                    }
203    
204                    if (type == RoleConstants.TYPE_REGULAR) {
205                            legacyFile = convertGuestUsers(legacyFile);
206    
207                            MaintenanceUtil.appendStatus(
208                                    "Converted guest users to guest roles");
209                    }
210    
211                    convertRoles(legacyFile, type, newName, newColumns);
212    
213                    MaintenanceUtil.appendStatus("Converted roles for " + legacyName);
214    
215                    DB db = DBFactoryUtil.getDB();
216    
217                    db.runSQL(legacyTable.getDeleteSQL());
218    
219                    FileUtil.delete(legacyFile);
220            }
221    
222            protected void convertResourceBlock() throws Exception {
223                    List<String> actionIds = ResourceActionsUtil.getModelResourceActions(
224                            BookmarksEntry.class.getName());
225    
226                    List<BookmarksEntry> entries =
227                            BookmarksEntryLocalServiceUtil.getBookmarksEntries(
228                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS);
229    
230                    for (BookmarksEntry entry : entries) {
231                            Role ownerRole = RoleLocalServiceUtil.getRole(
232                                    entry.getCompanyId(), RoleConstants.OWNER);
233    
234                            ResourceBlockLocalServiceUtil.setIndividualScopePermissions(
235                                    entry.getCompanyId(), entry.getGroupId(),
236                                    BookmarksEntry.class.getName(), entry, ownerRole.getRoleId(),
237                                    actionIds);
238                    }
239    
240                    actionIds = ResourceActionsUtil.getModelResourceActions(
241                            BookmarksFolder.class.getName());
242    
243                    List<BookmarksFolder> folders =
244                            BookmarksFolderLocalServiceUtil.getBookmarksFolders(
245                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS);
246    
247                    for (BookmarksFolder folder : folders) {
248                            Role ownerRole = RoleLocalServiceUtil.getRole(
249                                    folder.getCompanyId(), RoleConstants.OWNER);
250    
251                            ResourceBlockLocalServiceUtil.setIndividualScopePermissions(
252                                    folder.getCompanyId(), folder.getGroupId(),
253                                    BookmarksFolder.class.getName(), folder, ownerRole.getRoleId(),
254                                    actionIds);
255                    }
256            }
257    
258            protected void convertResourcePermission(Writer writer, String name)
259                    throws Exception {
260    
261                    ResourcePermissionView resourcePermissionView =
262                            new ResourcePermissionView(name);
263    
264                    UnsyncBufferedReader resourcePermissionReader = null;
265    
266                    String resourcePermissionFile =
267                            resourcePermissionView.generateTempFile();
268    
269                    if (resourcePermissionFile == null) {
270                            return;
271                    }
272    
273                    MultiValueMap<Tuple, String> mvp =
274                            (MultiValueMap<Tuple, String>)
275                                    MultiValueMapFactoryUtil.getMultiValueMap(
276                                            _CONVERT_RESOURCE_PERMISSION);
277    
278                    try {
279                            resourcePermissionReader = new UnsyncBufferedReader(
280                                    new FileReader(resourcePermissionFile));
281    
282                            String line = null;
283    
284                            while (Validator.isNotNull(
285                                                    line = resourcePermissionReader.readLine())) {
286    
287                                    String[] values = StringUtil.split(line);
288    
289                                    String actionId = ResourcePermissionView.getActionId(values);
290                                    long companyId = ResourcePermissionView.getCompanyId(values);
291                                    int scope = ResourcePermissionView.getScope(values);
292                                    String primKey = ResourcePermissionView.getPrimaryKey(values);
293                                    long roleId = ResourcePermissionView.getRoleId(values);
294    
295                                    mvp.put(new Tuple(companyId, scope, primKey, roleId), actionId);
296                            }
297                    }
298                    finally {
299                            if (resourcePermissionReader != null) {
300                                    resourcePermissionReader.close();
301                            }
302    
303                            FileUtil.delete(resourcePermissionFile);
304                    }
305    
306                    for (Tuple key : mvp.keySet()) {
307                            long resourcePermissionId = CounterLocalServiceUtil.increment(
308                                    ResourcePermission.class.getName());
309    
310                            long companyId = (Long)key.getObject(0);
311                            int scope = (Integer)key.getObject(1);
312                            String primKey = (String)key.getObject(2);
313                            long roleId = (Long)key.getObject(3);
314    
315                            long actionIds = 0;
316    
317                            for (String actionId : mvp.getAll(key)) {
318                                    try {
319                                            ResourceAction resourceAction =
320                                                    ResourceActionLocalServiceUtil.getResourceAction(
321                                                            name, actionId);
322    
323                                            actionIds |= resourceAction.getBitwiseValue();
324                                    }
325                                    catch (NoSuchResourceActionException nsrae) {
326                                            if (_log.isWarnEnabled()) {
327                                                    String msg = nsrae.getMessage();
328    
329                                                    _log.warn("Could not find resource action " + msg);
330                                            }
331                                    }
332                            }
333    
334                            writer.append(resourcePermissionId + StringPool.COMMA);
335                            writer.append(companyId + StringPool.COMMA);
336                            writer.append(name + StringPool.COMMA);
337                            writer.append(scope + StringPool.COMMA);
338                            writer.append(primKey + StringPool.COMMA);
339                            writer.append(roleId + StringPool.COMMA);
340                            writer.append(0 + StringPool.COMMA);
341                            writer.append(actionIds + StringPool.COMMA + StringPool.NEW_LINE);
342                    }
343            }
344    
345            protected void convertRoles(
346                            String legacyFile, int type, String newName, Object[][] newColumns)
347                    throws Exception {
348    
349                    UnsyncBufferedReader legacyFileReader = new UnsyncBufferedReader(
350                            new FileReader(legacyFile));
351    
352                    Writer legacyFileExtRoleWriter = new UnsyncBufferedWriter(
353                            new FileWriter(legacyFile + _EXT_ROLE));
354                    Writer legacyFileExtRolesPermissionsWriter = new UnsyncBufferedWriter(
355                            new FileWriter(legacyFile + _EXT_ROLES_PERMIMISSIONS));
356                    Writer legacyFileExtOtherRolesWriter = new UnsyncBufferedWriter(
357                            new FileWriter(legacyFile + _EXT_OTHER_ROLES));
358    
359                    try {
360    
361                            // Group by resource id
362    
363                            MultiValueMap<Long, String[]> mvp =
364                                    (MultiValueMap<Long, String[]>)
365                                            MultiValueMapFactoryUtil.getMultiValueMap(_CONVERT_ROLES);
366    
367                            String line = null;
368    
369                            while (Validator.isNotNull(line = legacyFileReader.readLine())) {
370                                    String[] values = StringUtil.split(line);
371    
372                                    long resourceId = PermissionView.getResourceId(values);
373    
374                                    mvp.put(resourceId, values);
375                            }
376    
377                            // Assign role for each grouping
378    
379                            for (Long key : mvp.keySet()) {
380                                    List<String[]> valuesList = new ArrayList<String[]>(
381                                            mvp.getAll(key));
382    
383                                    String[] values = valuesList.get(0);
384    
385                                    long companyId = PermissionView.getCompanyId(values);
386                                    long groupId = PermissionView.getPrimaryKey(values);
387                                    String name = PermissionView.getNameId(values);
388                                    int scope = PermissionView.getScopeId(values);
389    
390                                    // Group action ids and permission ids
391    
392                                    List<String> actionsIds = new ArrayList<String>();
393                                    List<Long> permissionIds = new ArrayList<Long>();
394    
395                                    for (String[] curValues : valuesList) {
396                                            String actionId = PermissionView.getActionId(curValues);
397                                            long permissionId = PermissionView.getPermissionId(
398                                                    curValues);
399    
400                                            actionsIds.add(actionId);
401                                            permissionIds.add(permissionId);
402                                    }
403    
404                                    // Look for owner and system roles
405    
406                                    if ((type != RoleConstants.TYPE_ORGANIZATION) &&
407                                            (scope == ResourceConstants.SCOPE_INDIVIDUAL)) {
408    
409                                            // Find default actions
410    
411                                            List<String> defaultActions = null;
412    
413                                            if (type == RoleConstants.TYPE_REGULAR) {
414                                                    defaultActions = ResourceActionsUtil.getResourceActions(
415                                                            name);
416                                            }
417                                            else {
418                                                    defaultActions =
419                                                            ResourceActionsUtil.getResourceGroupDefaultActions(
420                                                                    name);
421                                            }
422    
423                                            // Resolve owner and system roles
424    
425                                            Role defaultRole = null;
426    
427                                            if (type == RoleConstants.TYPE_REGULAR) {
428                                                    if (defaultActions instanceof UnmodifiableList) {
429                                                            defaultActions = new ArrayList<String>(
430                                                                    defaultActions);
431                                                    }
432    
433                                                    Collections.sort(actionsIds);
434                                                    Collections.sort(defaultActions);
435    
436                                                    if (defaultActions.equals(actionsIds)) {
437                                                            defaultRole = _ownerRolesMap.get(companyId);
438                                                    }
439                                            }
440                                            else {
441                                                    if (defaultActions.containsAll(actionsIds)) {
442                                                            Role[] defaultRoles = _defaultRolesMap.get(
443                                                                    companyId);
444    
445                                                            Group group = _groupsMap.get(groupId);
446    
447                                                            if (group == null) {
448                                                                    continue;
449                                                            }
450    
451                                                            if (group.isOrganization()) {
452                                                                    defaultRole = defaultRoles[0];
453                                                            }
454                                                            else if (group.isRegularSite()) {
455                                                                    defaultRole = defaultRoles[2];
456                                                            }
457                                                            else if (group.isUser() || group.isUserGroup()) {
458                                                                    defaultRole = defaultRoles[1];
459                                                            }
460                                                    }
461                                            }
462    
463                                            if (defaultRole != null) {
464                                                    long roleId = defaultRole.getRoleId();
465    
466                                                    for (Long permissionId : permissionIds) {
467                                                            String curKey = roleId + "_" + permissionId;
468    
469                                                            if (_rolesPermissions.contains(curKey)) {
470                                                                    continue;
471                                                            }
472                                                            else {
473                                                                    _rolesPermissions.add(curKey);
474                                                            }
475    
476                                                            legacyFileExtRolesPermissionsWriter.write(
477                                                                    roleId + "," + permissionId + ",\n");
478                                                    }
479    
480                                                    continue;
481                                            }
482                                    }
483    
484                                    if (isGenerateCustomRoles()) {
485    
486                                            // Role_
487    
488                                            long roleId = CounterLocalServiceUtil.increment();
489    
490                                            String roleName = StringUtil.upperCaseFirstLetter(
491                                                    RoleConstants.getTypeLabel(type));
492    
493                                            roleName += " " + StringUtil.toHexString(roleId);
494    
495                                            String[] roleColumns = new String[] {
496                                                    String.valueOf(roleId), String.valueOf(companyId),
497                                                    String.valueOf(
498                                                            ClassNameLocalServiceUtil.getClassNameId(
499                                                                    Role.class)),
500                                                    String.valueOf(roleId), roleName, StringPool.BLANK,
501                                                    "Autogenerated role from portal upgrade",
502                                                    String.valueOf(type), "lfr-permission-algorithm-5"
503                                            };
504    
505                                            for (int i = 0; i < roleColumns.length; i++) {
506                                                    legacyFileExtRoleWriter.write(
507                                                            roleColumns[i] + StringPool.COMMA);
508    
509                                                    if (i == (roleColumns.length - 1)) {
510                                                            legacyFileExtRoleWriter.write(StringPool.NEW_LINE);
511                                                    }
512                                            }
513    
514                                            // Roles_Permissions
515    
516                                            for (Long permissionId : permissionIds) {
517                                                    String curKey = roleId + "_" + permissionId;
518    
519                                                    if (_rolesPermissions.contains(curKey)) {
520                                                            continue;
521                                                    }
522                                                    else {
523                                                            _rolesPermissions.add(curKey);
524                                                    }
525    
526                                                    legacyFileExtRolesPermissionsWriter.write(
527                                                            roleId + "," + permissionId + ",\n");
528                                            }
529    
530                                            // Others_Roles
531    
532                                            for (int i = 0; i < newColumns.length - 1; i++) {
533                                                    legacyFileExtOtherRolesWriter.write(
534                                                            values[i] + StringPool.COMMA);
535                                            }
536    
537                                            legacyFileExtOtherRolesWriter.write(roleId + ",\n");
538                                    }
539                            }
540                    }
541                    finally {
542                            legacyFileReader.close();
543    
544                            legacyFileExtRoleWriter.close();
545                            legacyFileExtRolesPermissionsWriter.close();
546                            legacyFileExtOtherRolesWriter.close();
547                    }
548    
549                    // Role_
550    
551                    Table roleTable = new Table(
552                            RoleModelImpl.TABLE_NAME, RoleModelImpl.TABLE_COLUMNS);
553    
554                    roleTable.populateTable(legacyFile + _EXT_ROLE);
555    
556                    // Roles_Permissions
557    
558                    Table rolesPermissionsTable = new Table(
559                            "Roles_Permissions",
560                            new Object[][] {
561                                    {"roleId", Types.BIGINT}, {"permissionId", Types.BIGINT}
562                            });
563    
564                    rolesPermissionsTable.populateTable(
565                            legacyFile + _EXT_ROLES_PERMIMISSIONS);
566    
567                    // Others_Roles
568    
569                    Table othersRolesTable = new Table(newName, newColumns);
570    
571                    othersRolesTable.populateTable(legacyFile + _EXT_OTHER_ROLES);
572    
573                    // Clean up
574    
575                    FileUtil.delete(legacyFile + _EXT_ROLE);
576                    FileUtil.delete(legacyFile + _EXT_ROLES_PERMIMISSIONS);
577                    FileUtil.delete(legacyFile + _EXT_OTHER_ROLES);
578            }
579    
580            protected void convertToBitwise() throws Exception {
581    
582                    // ResourceAction and ResourcePermission
583    
584                    MaintenanceUtil.appendStatus(
585                            "Generating ResourceAction and ResourcePermission data");
586    
587                    Table table = new Table(
588                            ResourceCodeModelImpl.TABLE_NAME,
589                            new Object[][] {
590                                    {"name", new Integer(Types.VARCHAR)}
591                            });
592    
593                    table.setSelectSQL(
594                            "SELECT name FROM " + ResourceCodeModelImpl.TABLE_NAME +
595                                    " GROUP BY name");
596    
597                    String tempFile = table.generateTempFile();
598    
599                    UnsyncBufferedReader resourceNameReader = new UnsyncBufferedReader(
600                            new FileReader(tempFile));
601    
602                    Writer resourcePermissionWriter = new UnsyncBufferedWriter(
603                            new FileWriter(tempFile + _EXT_RESOURCE_PERMISSION));
604    
605                    PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 6;
606    
607                    try {
608                            String line = null;
609    
610                            while (Validator.isNotNull(line = resourceNameReader.readLine())) {
611                                    String[] values = StringUtil.split(line);
612    
613                                    if (values.length == 0) {
614                                            continue;
615                                    }
616    
617                                    String name = values[0];
618    
619                                    List<String> defaultActionIds =
620                                            ResourceActionsUtil.getResourceActions(name);
621    
622                                    ResourceActionLocalServiceUtil.checkResourceActions(
623                                            name, defaultActionIds);
624    
625                                    convertResourcePermission(resourcePermissionWriter, name);
626                            }
627    
628                            resourcePermissionWriter.close();
629    
630                            MaintenanceUtil.appendStatus("Updating ResourcePermission table");
631    
632                            Table resourcePermissionTable = new Table(
633                                    ResourcePermissionModelImpl.TABLE_NAME,
634                                    ResourcePermissionModelImpl.TABLE_COLUMNS);
635    
636                            resourcePermissionTable.populateTable(
637                                    tempFile + _EXT_RESOURCE_PERMISSION);
638                    }
639                    catch (Exception e) {
640                            PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 5;
641    
642                            throw e;
643                    }
644                    finally {
645                            resourceNameReader.close();
646    
647                            resourcePermissionWriter.close();
648    
649                            FileUtil.delete(tempFile);
650                            FileUtil.delete(tempFile + _EXT_RESOURCE_PERMISSION);
651                    }
652    
653                    // Clean up
654    
655                    MaintenanceUtil.appendStatus("Cleaning up legacy tables");
656    
657                    DB db = DBFactoryUtil.getDB();
658    
659                    db.runSQL("DELETE FROM " + ResourceCodeModelImpl.TABLE_NAME);
660                    db.runSQL("DELETE FROM " + PermissionModelImpl.TABLE_NAME);
661                    db.runSQL("DELETE FROM " + ResourceModelImpl.TABLE_NAME);
662                    db.runSQL("DELETE FROM Roles_Permissions");
663    
664                    Release release = null;
665    
666                    try {
667                            release = ReleaseLocalServiceUtil.getRelease(
668                                    ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME,
669                                    ReleaseInfo.getParentBuildNumber());
670                    }
671                    catch (PortalException pe) {
672                            release = ReleaseLocalServiceUtil.addRelease(
673                                    ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME,
674                                    ReleaseInfo.getParentBuildNumber());
675                    }
676    
677                    ReleaseLocalServiceUtil.updateRelease(
678                            release.getReleaseId(), ReleaseInfo.getBuildNumber(),
679                            ReleaseInfo.getBuildDate(), false);
680    
681                    MaintenanceUtil.appendStatus("Converted to bitwise permission");
682            }
683    
684            protected void convertToRBAC() throws Exception {
685                    initializeRBAC();
686    
687                    // Groups_Permissions
688    
689                    convertPermissions(
690                            RoleConstants.TYPE_SITE, "Groups_Permissions",
691                            new String[] {"groupId"}, "Groups_Roles",
692                            new Object[][] {
693                                    {"groupId", Types.BIGINT}, {"roleId", Types.BIGINT}
694                            });
695    
696                    // OrgGroupPermission
697    
698                    convertPermissions(
699                            RoleConstants.TYPE_ORGANIZATION, "OrgGroupPermission",
700                            new String[] {"organizationId", "groupId"}, "OrgGroupRole",
701                            new Object[][] {
702                                    {"organizationId", Types.BIGINT}, {"groupId", Types.BIGINT},
703                                    {"roleId", Types.BIGINT}
704                            });
705    
706                    // Users_Permissions
707    
708                    convertPermissions(
709                            RoleConstants.TYPE_REGULAR, "Users_Permissions",
710                            new String[] {"userId"}, "Users_Roles",
711                            new Object[][] {
712                                    {"userId", Types.BIGINT}, {"roleId", Types.BIGINT}
713                            });
714    
715                    // Clean up
716    
717                    PermissionCacheUtil.clearCache();
718    
719                    PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 5;
720    
721                    MaintenanceUtil.appendStatus("Converted to RBAC permission");
722            }
723    
724            @Override
725            protected void doConvert() throws Exception {
726                    try {
727                            BatchSessionUtil.setEnabled(true);
728    
729                            initialize();
730    
731                            if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
732                                    convertToRBAC();
733                            }
734    
735                            convertToBitwise();
736    
737                            convertResourceBlock();
738    
739                            MaintenanceUtil.appendStatus(
740                                    "Please set " + PropsKeys.PERMISSIONS_USER_CHECK_ALGORITHM +
741                                            " in your portal-ext.properties to 6 and restart server");
742                    }
743                    finally {
744                            ShutdownUtil.shutdown(0);
745                    }
746            }
747    
748            protected void initialize() throws Exception {
749    
750                    // Resource actions for unknown portlets
751    
752                    List<ResourceCode> resourceCodes =
753                            ResourceCodeLocalServiceUtil.getResourceCodes(
754                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS);
755    
756                    for (ResourceCode resourceCode : resourceCodes) {
757                            String name = resourceCode.getName();
758    
759                            if (!name.contains(StringPool.PERIOD)) {
760                                    ResourceActionsUtil.getPortletResourceActions(name);
761                            }
762                    }
763            }
764    
765            protected void initializeRBAC() throws Exception {
766    
767                    // System roles and default users
768    
769                    List<Company> companies = CompanyLocalServiceUtil.getCompanies();
770    
771                    for (Company company : companies) {
772                            long companyId = company.getCompanyId();
773    
774                            _defaultRolesMap.put(
775                                    companyId,
776                                    new Role[] {
777                                            RoleLocalServiceUtil.getRole(
778                                                    companyId, RoleConstants.ORGANIZATION_USER),
779                                            RoleLocalServiceUtil.getRole(
780                                                    companyId, RoleConstants.POWER_USER),
781                                            RoleLocalServiceUtil.getRole(
782                                                    companyId, RoleConstants.SITE_MEMBER)
783                                            }
784                                    );
785    
786                            Role guestRole = RoleLocalServiceUtil.getRole(
787                                    companyId, RoleConstants.GUEST);
788    
789                            _guestRolesMap.put(companyId, guestRole);
790    
791                            Role ownerRole = RoleLocalServiceUtil.getRole(
792                                    companyId, RoleConstants.OWNER);
793    
794                            _ownerRolesMap.put(companyId, ownerRole);
795    
796                            long defaultUserId = UserLocalServiceUtil.getDefaultUserId(
797                                    companyId);
798    
799                            _guestUsersSet.add(defaultUserId);
800                    }
801    
802                    // Roles_Permissions
803    
804                    Connection con = null;
805                    PreparedStatement ps = null;
806                    ResultSet rs = null;
807    
808                    try {
809                            con = DataAccess.getConnection();
810    
811                            ps = con.prepareStatement("SELECT * FROM Roles_Permissions");
812    
813                            rs = ps.executeQuery();
814    
815                            while (rs.next()) {
816                                    long roleId = rs.getLong("roleId");
817                                    long permissionId = rs.getLong("permissionId");
818    
819                                    _rolesPermissions.add(roleId + "_" + permissionId);
820                            }
821                    }
822                    finally {
823                            DataAccess.cleanUp(con, ps, rs);
824                    }
825    
826                    // Groups
827    
828                    List<Group> groups = GroupLocalServiceUtil.getGroups(
829                            QueryUtil.ALL_POS, QueryUtil.ALL_POS);
830    
831                    for (Group group : groups) {
832                            _groupsMap.put(group.getGroupId(), group);
833                    }
834            }
835    
836            protected boolean isGenerateCustomRoles() {
837                    String[] parameterValues = getParameterValues();
838    
839                    return GetterUtil.getBoolean(parameterValues[0]);
840            }
841    
842            private static final String _CONVERT_RESOURCE_PERMISSION =
843                    PropsKeys.MULTI_VALUE_MAP + ConvertPermissionAlgorithm.class.getName() +
844                            ".convertResourcePermission";
845    
846            private static final String _CONVERT_ROLES =
847                    PropsKeys.MULTI_VALUE_MAP + ConvertPermissionAlgorithm.class.getName() +
848                            ".convertRoles";
849    
850            private static final String _EXT_OTHER_ROLES = ".others_roles";
851    
852            private static final String _EXT_RESOURCE_PERMISSION =
853                    ".resource_permission";
854    
855            private static final String _EXT_ROLE = ".role";
856    
857            private static final String _EXT_ROLES_PERMIMISSIONS = ".roles_permissions";
858    
859            private static final String _UPDATED = ".updated";
860    
861            private static Log _log = LogFactoryUtil.getLog(
862                    ConvertPermissionAlgorithm.class);
863    
864            private Map<Long, Role[]> _defaultRolesMap = new HashMap<Long, Role[]>();
865            private Map<Long, Group> _groupsMap = new HashMap<Long, Group>();
866            private Map<Long, Role> _guestRolesMap = new HashMap<Long, Role>();
867            private Set<Long> _guestUsersSet = new HashSet<Long>();
868            private Map<Long, Role> _ownerRolesMap = new HashMap<Long, Role>();
869            private Set<String> _rolesPermissions = new HashSet<String>();
870    
871    }