Search in sources :

Example 1 with StringLiteralExpression

use of com.jetbrains.php.lang.psi.elements.StringLiteralExpression in project phpinspectionsea by kalessil.

the class NonSecureCryptUsageInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpFunctionCall(@NotNull FunctionReference reference) {
            final String functionName = reference.getName();
            if (functionName == null || !functionName.equals("crypt")) {
                return;
            }
            final PsiElement[] arguments = reference.getParameters();
            if ((arguments.length != 1 && arguments.length != 2) || !this.isFromRootNamespace(reference)) {
                return;
            }
            /* Case 1: suggest providing blowfish as the 2nd parameter*/
            if (arguments.length == 1) {
                holder.registerProblem(reference, messageWeakSalt);
                return;
            }
            /* try resolving 2nd parameter, skip if failed, it contains injections or length is not as expected */
            final String saltValue = this.resolveSalt(arguments[1]);
            if (null == saltValue || saltValue.length() < 4) {
                return;
            }
            /* Case 2: using $2a$; use $2y$ instead - http://php.net/security/crypt_blowfish.php*/
            if (saltValue.startsWith("$2a$")) {
                holder.registerProblem(reference, messageInsecureSalt, ProblemHighlightType.GENERIC_ERROR);
                return;
            }
            /* Case 3: -> password_hash(PASSWORD_BCRYPT) in PHP 5.5+ */
            final boolean isBlowfish = saltValue.startsWith("$2y$") || saltValue.startsWith("$2x$");
            if (isBlowfish) {
                PhpLanguageLevel php = PhpProjectConfigurationFacade.getInstance(holder.getProject()).getLanguageLevel();
                if (php.compareTo(PhpLanguageLevel.PHP550) >= 0) {
                    holder.registerProblem(reference, messagePasswordHash, ProblemHighlightType.WEAK_WARNING);
                }
            }
        }

        @Nullable
        private String resolveSalt(@NotNull PsiElement expression) {
            /* collect possible value for further analysis */
            final Set<PsiElement> discovered = PossibleValuesDiscoveryUtil.discover(expression);
            if (discovered.size() != 1) {
                discovered.clear();
                return null;
            }
            /* simplify workflow by handling one expression */
            final PsiElement saltExpression = discovered.iterator().next();
            final StringBuilder resolvedSaltValue = new StringBuilder();
            discovered.clear();
            /*  resolve string literals and concatenations */
            PsiElement current = saltExpression;
            while (current instanceof ConcatenationExpression) {
                final ConcatenationExpression concat = (ConcatenationExpression) current;
                final PsiElement right = ExpressionSemanticUtil.getExpressionTroughParenthesis(concat.getRightOperand());
                final StringLiteralExpression part = ExpressionSemanticUtil.resolveAsStringLiteral(right);
                resolvedSaltValue.insert(0, part == null ? "<?>" : part.getContents());
                current = ExpressionSemanticUtil.getExpressionTroughParenthesis(concat.getLeftOperand());
            }
            /* don't forget to add the last element */
            if (null != current) {
                final StringLiteralExpression lastPart = ExpressionSemanticUtil.resolveAsStringLiteral(current);
                resolvedSaltValue.insert(0, null == lastPart ? "<?>" : lastPart.getContents());
            }
            return resolvedSaltValue.toString();
        }
    };
}
Also used : BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) FunctionReference(com.jetbrains.php.lang.psi.elements.FunctionReference) ConcatenationExpression(com.jetbrains.php.lang.psi.elements.ConcatenationExpression) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) PhpLanguageLevel(com.jetbrains.php.config.PhpLanguageLevel) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with StringLiteralExpression

use of com.jetbrains.php.lang.psi.elements.StringLiteralExpression in project phpinspectionsea by kalessil.

the class FileFunctionMissUseInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpFunctionCall(@NotNull FunctionReference reference) {
            final String functionName = reference.getName();
            if (functionName == null || !functionName.equals("file")) {
                return;
            }
            final PsiElement[] arguments = reference.getParameters();
            if (arguments.length != 1) {
                return;
            }
            /* function can be silenced, get parent for this case; validate parent structure */
            PsiElement parent = reference.getParent();
            if (parent instanceof UnaryExpression) {
                final PsiElement operation = ((UnaryExpression) parent).getOperation();
                if (OpenapiTypesUtil.is(operation, PhpTokenTypes.opSILENCE)) {
                    parent = parent.getParent();
                }
            }
            if (!(parent instanceof ParameterList) || !OpenapiTypesUtil.isFunctionReference(parent.getParent())) {
                return;
            }
            /* validate parent functions' name (implode or join) and amount of arguments */
            final FunctionReference parentReference = (FunctionReference) parent.getParent();
            final String parentName = parentReference.getName();
            if (parentName == null || (!parentName.equals("implode") && !parentName.equals("join"))) {
                return;
            }
            final PsiElement[] parentParams = parentReference.getParameters();
            if (parentParams.length != 2) {
                return;
            }
            /* validate if glue is not empty */
            final StringLiteralExpression glue = ExpressionSemanticUtil.resolveAsStringLiteral(parentParams[0]);
            if (glue != null && !glue.getContents().isEmpty()) {
                return;
            }
            final String message = String.format(messagePattern, arguments[0].getText());
            holder.registerProblem(parentReference, message, ProblemHighlightType.GENERIC_ERROR, new TheLocalFix());
        }
    };
}
Also used : BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) FunctionReference(com.jetbrains.php.lang.psi.elements.FunctionReference) ParameterList(com.jetbrains.php.lang.psi.elements.ParameterList) UnaryExpression(com.jetbrains.php.lang.psi.elements.UnaryExpression) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with StringLiteralExpression

use of com.jetbrains.php.lang.psi.elements.StringLiteralExpression in project yii2support by nvlad.

the class PhpUtil method getArrayKeys.

@NotNull
public static Collection<String> getArrayKeys(ArrayCreationExpression array) {
    final HashSet<String> result = new HashSet<>();
    Iterable<ArrayHashElement> items = array.getHashElements();
    for (ArrayHashElement item : items) {
        if (item.getKey() != null && item.getKey() instanceof StringLiteralExpression) {
            result.add(((StringLiteralExpression) item.getKey()).getContents());
        }
    }
    return result;
}
Also used : StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) ArrayHashElement(com.jetbrains.php.lang.psi.elements.ArrayHashElement) HashSet(java.util.HashSet) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with StringLiteralExpression

use of com.jetbrains.php.lang.psi.elements.StringLiteralExpression in project yii2support by nvlad.

the class MissedViewInspection method buildVisitor.

@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean isOnTheFly) {
    return new PhpElementVisitor() {

        @Override
        public void visitPhpMethodReference(MethodReference reference) {
            if (!ViewUtil.isValidRenderMethod(reference)) {
                return;
            }
            if (ArrayUtil.contains(reference.getName(), ViewUtil.renderMethods)) {
                if (reference.getParameters().length > 0) {
                    final PsiElement pathParameter = reference.getParameters()[0];
                    final ViewResolve resolve = ViewUtil.resolveView(pathParameter);
                    if (resolve == null) {
                        return;
                    }
                    String key = resolve.key;
                    if (Files.getFileExtension(key).isEmpty()) {
                        key = key + '.' + Yii2SupportSettings.getInstance(reference.getProject()).defaultViewExtension;
                    }
                    final Project project = reference.getProject();
                    final Collection<ViewInfo> views = FileBasedIndex.getInstance().getValues(ViewFileIndex.identity, key, GlobalSearchScope.projectScope(project));
                    final String application = YiiApplicationUtils.getApplicationName(reference.getContainingFile());
                    final boolean localViewSearch;
                    final String value = PhpUtil.getValue(pathParameter);
                    if (resolve.from == ViewResolveFrom.View) {
                        localViewSearch = !value.startsWith("@") && !value.startsWith("//");
                    } else {
                        localViewSearch = false;
                    }
                    views.removeIf(view -> {
                        if (!application.equals(view.application)) {
                            return true;
                        }
                        return localViewSearch && !resolve.theme.equals(view.theme);
                    });
                    if (views.size() != 0) {
                        return;
                    }
                    if (pathParameter instanceof StringLiteralExpression) {
                        Collection<String> paths = ViewUtil.viewResolveToPaths(resolve, project);
                        if (!paths.iterator().hasNext()) {
                            return;
                        }
                        VirtualFile yiiRoot = YiiApplicationUtils.getYiiRootVirtualFile(project);
                        if (yiiRoot == null) {
                            return;
                        }
                        int projectUrlLength = project.getBaseDir().getUrl().length();
                        String yiiRootUrl = yiiRoot.getUrl();
                        String path;
                        if (projectUrlLength > yiiRootUrl.length()) {
                            path = paths.iterator().next();
                        } else {
                            path = yiiRootUrl.substring(projectUrlLength) + paths.iterator().next();
                        }
                        final String viewNotFoundMessage = "View file for \"" + value + "\" not found in \"" + path + "\".";
                        final MissedViewLocalQuickFix quickFix = new MissedViewLocalQuickFix(value, path, RenderUtil.getViewArguments(reference));
                        final PsiElement stringPart = pathParameter.findElementAt(1);
                        if (stringPart != null) {
                            problemsHolder.registerProblem(stringPart, viewNotFoundMessage, quickFix);
                        }
                    }
                }
            }
        }
    };
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PhpElementVisitor(com.jetbrains.php.lang.psi.visitors.PhpElementVisitor) StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) ViewResolve(com.nvlad.yii2support.views.entities.ViewResolve) ViewInfo(com.nvlad.yii2support.views.entities.ViewInfo) Project(com.intellij.openapi.project.Project) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with StringLiteralExpression

use of com.jetbrains.php.lang.psi.elements.StringLiteralExpression in project idea-php-typo3-plugin by cedricziel.

the class IconAnnotator method annotate.

@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {
    if (!(psiElement instanceof StringLiteralExpression)) {
        return;
    }
    StringLiteralExpression literalExpression = (StringLiteralExpression) psiElement;
    String value = literalExpression.getContents();
    if (value.isEmpty()) {
        return;
    }
    PsiElement methodReference = PsiTreeUtil.getParentOfType(psiElement, MethodReference.class);
    if (PhpElementsUtil.isMethodWithFirstStringOrFieldReference(methodReference, "getIcon")) {
        annotateIconUsage(psiElement, annotationHolder, value);
    }
}
Also used : StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) PsiElement(com.intellij.psi.PsiElement)

Aggregations

StringLiteralExpression (com.jetbrains.php.lang.psi.elements.StringLiteralExpression)39 PsiElement (com.intellij.psi.PsiElement)35 NotNull (org.jetbrains.annotations.NotNull)28 BasePhpElementVisitor (com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor)18 FunctionReference (com.jetbrains.php.lang.psi.elements.FunctionReference)16 HashSet (java.util.HashSet)8 PhpElementVisitor (com.jetbrains.php.lang.psi.visitors.PhpElementVisitor)7 ProblemsHolder (com.intellij.codeInspection.ProblemsHolder)6 PsiElementVisitor (com.intellij.psi.PsiElementVisitor)6 ArrayCreationExpression (com.jetbrains.php.lang.psi.elements.ArrayCreationExpression)6 PhpPsiElement (com.jetbrains.php.lang.psi.elements.PhpPsiElement)6 Set (java.util.Set)6 Project (com.intellij.openapi.project.Project)5 PhpElementTypes (com.jetbrains.php.lang.parser.PhpElementTypes)5 GroupNames (com.intellij.codeInsight.daemon.GroupNames)4 PlatformPatterns (com.intellij.patterns.PlatformPatterns)4 PsiFile (com.intellij.psi.PsiFile)4 FilenameIndex (com.intellij.psi.search.FilenameIndex)4 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)4 IElementType (com.intellij.psi.tree.IElementType)4