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