Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pathlib import Path
- import re
- # Directory containing the PHP files
- ROOT_DIRECTORY = Path(r"C:\Users\Mayank\Documents\GitHub\ERP")
- # Output text file
- OUTPUT_FILE = ROOT_DIRECTORY / "php_search_results.txt"
- # Exclude files when any folder in their path contains these terms
- EXCLUDED_FOLDER_TERMS = ("tcpdf", "phpqrcode")
- # Case-insensitive search patterns
- SEARCH_PATTERNS = {
- "href and location on same line": re.compile(
- r"(?=.*\bhref\b)(?=.*\blocation\b)",
- re.IGNORECASE,
- ),
- "window.location.href": re.compile(
- r"\bwindow\s*\.\s*location\s*\.\s*href\b",
- re.IGNORECASE,
- ),
- "Location:": re.compile(
- r"\blocation\s*:",
- re.IGNORECASE,
- ),
- }
- def is_excluded(file_path: Path) -> bool:
- """Return True when a folder in the path contains an excluded term."""
- relative_parts = file_path.relative_to(ROOT_DIRECTORY).parts[:-1]
- return any(
- excluded_term in folder_name.lower()
- for folder_name in relative_parts
- for excluded_term in EXCLUDED_FOLDER_TERMS
- )
- def find_matching_patterns(line: str) -> list[str]:
- """Return the names of all patterns matched by a line."""
- return [
- pattern_name
- for pattern_name, pattern in SEARCH_PATTERNS.items()
- if pattern.search(line)
- ]
- def search_php_files() -> None:
- if not ROOT_DIRECTORY.exists():
- raise FileNotFoundError(
- f"Directory does not exist: {ROOT_DIRECTORY}"
- )
- matched_files = 0
- matched_lines = 0
- scanned_files = 0
- with OUTPUT_FILE.open("w", encoding="utf-8") as output:
- output.write(f"Search directory: {ROOT_DIRECTORY}\n")
- output.write(
- "Excluded folder terms: "
- + ", ".join(EXCLUDED_FOLDER_TERMS)
- + "\n"
- )
- output.write("=" * 100 + "\n\n")
- for php_file in ROOT_DIRECTORY.rglob("*.php"):
- if not php_file.is_file() or is_excluded(php_file):
- continue
- scanned_files += 1
- file_matches = []
- try:
- # errors="replace" prevents one badly encoded file
- # from stopping the entire search.
- with php_file.open(
- "r",
- encoding="utf-8",
- errors="replace",
- ) as source_file:
- for line_number, line in enumerate(source_file, start=1):
- matched_patterns = find_matching_patterns(line)
- if matched_patterns:
- file_matches.append(
- (
- line_number,
- line.rstrip("\r\n"),
- matched_patterns,
- )
- )
- except OSError as error:
- output.write(f"ERROR READING: {php_file}\n")
- output.write(f"{error}\n")
- output.write("-" * 100 + "\n\n")
- continue
- if not file_matches:
- continue
- matched_files += 1
- matched_lines += len(file_matches)
- output.write(f"File: {php_file}\n")
- output.write(
- f"Relative path: {php_file.relative_to(ROOT_DIRECTORY)}\n"
- )
- output.write("-" * 100 + "\n")
- for line_number, line_text, matched_patterns in file_matches:
- output.write(
- f"Line {line_number} "
- f"[{', '.join(matched_patterns)}]\n"
- )
- output.write(f"{line_text}\n\n")
- output.write("=" * 100 + "\n\n")
- output.write("\nSUMMARY\n")
- output.write("-" * 100 + "\n")
- output.write(f"PHP files scanned: {scanned_files}\n")
- output.write(f"Files containing matches: {matched_files}\n")
- output.write(f"Matching lines: {matched_lines}\n")
- print("Search completed.")
- print(f"PHP files scanned: {scanned_files}")
- print(f"Files containing matches: {matched_files}")
- print(f"Matching lines: {matched_lines}")
- print(f"Results exported to: {OUTPUT_FILE}")
- if __name__ == "__main__":
- try:
- search_php_files()
- except Exception as error:
- print(f"Search failed: {error}")
Advertisement
Add Comment
Please, Sign In to add comment