filemodule.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 2,844 行 · 第 1/5 页

JAVA
2,844
字号
                    break;        case '/':          if (! ((inSquareBrackets || inCurlyBrackets) &&                  ((flags & FNM_PATHNAME) != 0))) {            globRegex.append(ch);            if (inSquareBrackets)              bracketCount++;          }          // don't include '/' in the brackets when FNM_PATHNAME is specified          break;        case '+':        case '(':        case ')':        case '$':        case '.':        case '|':          // escape regex special characters that are not glob           // special characters          globRegex.append('\\');          globRegex.append(ch);          if (inSquareBrackets)            bracketCount++;          break;        case '\\':          if ((flags & FNM_NOESCAPE) != 0)            globRegex.append('\\');          globRegex.append(ch);          if (inSquareBrackets)            bracketCount++;          break;        case '[':          inSquareBrackets = true;          globRegex.append(ch);          break;        case ']':          inSquareBrackets = false;          if (bracketCount == 0)            return null;          globRegex.append(ch);          break;        case '{':          if (inSquareBrackets || inCurlyBrackets) {            globRegex.append(ch);            if (inSquareBrackets)              bracketCount++;          } else if (brace) {            globRegex.append('(');            inCurlyBrackets = true;          } else {            globRegex.append('\\');            globRegex.append(ch);          }          break;        case '}':          if (inSquareBrackets) {            globRegex.append(ch);            bracketCount++;          } else if (brace && inCurlyBrackets) {            globRegex.append(')');            inCurlyBrackets = false;          } else {            globRegex.append('\\');            globRegex.append(ch);          }          break;        case ',':          if (brace && inCurlyBrackets)            globRegex.append('|');          else            globRegex.append(ch);          break;        default:          globRegex.append(ch);          if (inSquareBrackets)            bracketCount++;          break;      }      lastCh = ch;    }    return globRegex.toString();  }      /**   * Returns true if the given string matches the given glob pattern.   */  public static boolean fnmatch(Env env, String pattern, String string,                                 @Optional int flags)  {    if (pattern == null || string == null)      return false;    if ((flags & FNM_CASEFOLD) != 0) {      string = string.toLowerCase();      pattern = pattern.toLowerCase();    }    // match "leading" periods exactly (i.e. no wildcards)    if ((flags & FNM_PERIOD) != 0) {       if (string.length() > 0 && string.charAt(0) == '.'){        if (! (pattern.length() > 0 && pattern.charAt(0) == '.'))          return false;        string = string.substring(1);        pattern = pattern.substring(1);      } else if ((flags & FNM_PATHNAME) != 0) {        // special case: if the string starts with '/.', then the pattern        // must also start with exactly that.        if ((string.length() >= 2) &&           (string.charAt(0) == '/') && (string.charAt(1) == '.')) {          if (! ((pattern.length() >= 2) &&                 (pattern.charAt(0) == '/') && (pattern.charAt(1) == '.')))            return false;          string = string.substring(2);          pattern = pattern.substring(2);        }      }     }    String globRegex = globToRegex(pattern, flags, false);    if (globRegex == null)      return false;    return string.matches(globRegex.toString());  }  private static ProtocolWrapper getProtocolWrapper(Env env,						    StringValue pathName)  {    ArrayValue url = (ArrayValue) UrlModule.parse_url(env, pathName);    Value scheme = url.get(env.createString("scheme"));    if (scheme == UnsetValue.UNSET)      return null;    return StreamModule.getWrapper(scheme.toString());  }  /**   * Opens a file.   *   * @param filename the path to the file to open   * @param mode the mode the file should be opened as.   * @param useIncludePath if true, search the current include path   */  @ReturnNullAsFalse  public static BinaryStream fopen(Env env,				   StringValue filename,				   String mode,				   @Optional boolean useIncludePath,				   @Optional Value context)  {    if (filename.length() == 0) {      env.warning(L.l("file name must not be null"));      return null;    }    if (mode == null || mode.length() == 0) {      env.warning(L.l("fopen mode must not be null"));      return null;    }    // XXX: context    try {      ProtocolWrapper wrapper = getProtocolWrapper(env, filename);      if (wrapper != null) {        long options = 0;        if (useIncludePath)          options = StreamModule.STREAM_USE_PATH;                   return wrapper.fopen(env, filename,                                  env.createString(mode),                                  LongValue.create(options));      }      Path path = env.getPwd().lookup(filename.toString());      if (! env.isAllowUrlFopen() && isUrl(path)) {        String msg = (L.l("not allowed to fopen url {0}", path.getURL()));        env.error(msg);        return null;      }            if (mode.startsWith("r")) {        if (useIncludePath)          path = env.lookupInclude(filename.toString());        if (path == null) {          env.warning(L.l("{0} cannot be read", filename));          return null;	}	// server/2l80        /* else if (! path.exists()) {          env.warning(L.l("{0} cannot be read", path.getFullPath()));          return null;        }	  */        try {          BinaryInput input;          if (mode.startsWith("r+"))            input = new FileInputOutput(env, path);          else            input = new FileInput(env, path);          return input;        } catch (IOException e) {                    log.log(Level.FINE, e.toString(), e);          env.warning(L.l("{0} cannot be read", path.getFullPath()));          return null;        }      }      else if (mode.startsWith("w")) {        try {          if (mode.startsWith("w+"))             return new FileInputOutput(env, path, false, true);          else            return new FileOutput(env, path);        } catch (IOException e) {                    log.log(Level.FINE, e.toString(), e);          env.warning(L.l("{0} cannot be written", path.getFullPath()));          return null;        }      }      else if (mode.startsWith("a")) {        try {          if (mode.startsWith("a+"))            return new FileInputOutput(env, path, true, false);          else            return new FileOutput(env, path, true);        } catch (IOException e) {                    log.log(Level.FINE, e.toString(), e);          env.warning(L.l("{0} cannot be written", path.getFullPath()));          return null;        }      }      else if (mode.startsWith("x")) {        if (path.exists()) {          env.warning(L.l("{0} already exist", filename));                    return null;        }                if (mode.startsWith("x+"))          return new FileInputOutput(env, path);        else           return new FileOutput(env, path);      }      env.warning(L.l("bad mode `{0}'", mode));      return null;    } catch (IOException e) {      log.log(Level.FINE, e.toString(), e);      env.warning(L.l("{0} can't be opened.\n{1}",            filename, e.toString()));      return null;    }  }    private static boolean isUrl(Path path)  {    String scheme = path.getScheme();        if ("".equals(scheme)        || "file".equals(scheme)        || "memory".equals(scheme))      return false;        // XXX: too restrictive for filters    return ! "php".equals(scheme)           || path.toString().startsWith("php://filter");  }  /**   * Output the filepointer data to the output stream.   */  public Value fpassthru(Env env, @NotNull BinaryInput is)  {    // php/1635    try {      if (is == null)	return BooleanValue.FALSE;      WriteStream out = env.getOut();      long writeLength = out.writeStream(is.getInputStream());      return LongValue.create(writeLength);    } catch (IOException e) {      throw new QuercusModuleException(e);    }  }  /**   * Parses a comma-separated-value line from a file.   *   * @param file the file to read   * @param delimiter optional comma replacement   * @param enclosure optional quote replacement   */  public Value fputcsv(Env env,                       @NotNull BinaryOutput os,                       @NotNull ArrayValue value,                       @Optional StringValue delimiter,                       @Optional StringValue enclosure)  {    // php/1636    try {      if (os == null)	return BooleanValue.FALSE;      if (value == null)	return BooleanValue.FALSE;      char comma = ',';      char quote = '\"';      if (delimiter != null && delimiter.length() > 0)	comma = delimiter.charAt(0);      if (enclosure != null && enclosure.length() > 0)	quote = enclosure.charAt(0);      int writeLength = 0;      boolean isFirst = true;      for (Value data : value.values()) {	if (! isFirst) {	  os.print(comma);	  writeLength++;	}	isFirst = false;	StringValue s = data.toStringValue();	int strlen = s.length();	writeLength++;	os.print(quote);	for (int i = 0; i < strlen; i++) {	  char ch = s.charAt(i);	  if (ch != quote) {	    os.print(ch);	    writeLength++;	  }	  else {	    os.print(quote);	    os.print(quote);	    writeLength += 2;	  }	}	os.print(quote);	writeLength++;      }      os.print("\n");      writeLength++;      return LongValue.create(writeLength);    } catch (IOException e) {      throw new QuercusModuleException(e);    }  }  /**   * Writes a string to the file.   */  public static Value fputs(Env env,			    BinaryOutput os,			    InputStream value,			    @Optional("0x7fffffff") int length)  {    return fwrite(env, os, value, length);  }  /**   * Reads content from a file.   *   * @param is the file   */  public static Value fread(Env env,			    @NotNull BinaryInput is,			    int length)  {    if (is == null)      return BooleanValue.FALSE;    if (length < 0)      length = Integer.MAX_VALUE;    StringValue sb = env.createBinaryBuilder();    sb.appendRead(is, length);    return sb;  }  /**   * Reads and parses a line.   */  public static Value fscanf(Env env,                             @NotNull BinaryInput is,                             StringValue format,                             @Optional Value []args)  {    try {      if (is == null)        return BooleanValue.FALSE;      StringValue value = is.readLine(Integer.MAX_VALUE);      if (value == null)        return BooleanValue.FALSE;      return StringModule.sscanf(env, value, format, args);    } catch (IOException e) {      throw new QuercusModuleException(e);    }  }  /**   * Sets the current position.   *   * @param is the stream to test   * @return 0 on success, -1 on error.   */  public static Value fseek(Env env,			    @NotNull BinaryStream binaryStream,			    long offset,			    @Optional("SEEK_SET") int whence)  {    if (binaryStream == null)      return LongValue.MINUS_ONE;    long position = binaryStream.seek(offset, whence);    if (position < 0)      return LongValue.MINUS_ONE;    else      return LongValue.ZERO;  }  /**   * Returns the status of the given file pointer.   */  public static Value fstat(Env env, @NotNull BinaryStream stream)  {    if (stream == null)      return BooleanValue.FALSE;        return stream.stat();  }  /**   * Returns the current position.   *   * @param file the stream to test   * @return position in file or FALSE on error.   */  public static Value ftell(Env env,			    @NotNull BinaryStream binaryStream)  {    if (binaryStream == null)      return BooleanValue.FALSE;    long pos = binaryStream.getPosition();    if (pos < 0)      return BooleanValue.FALSE;    return LongValue.create(pos);  }  /**   * Truncates a file.   */  public static boolean ftruncate(Env env,                                   @NotNull BinaryOutput handle,                                   long size)  {    if (handle instanceof FileOutput) {      Path path = ((FileOutput) handle).getPath();      try {        return path.truncate(size);      } catch (IOException e) {        return false;      }    }    return false;  }  /**   * Writes a string to the file.   */  public static Value fwrite(Env env,			     @NotNull BinaryOutput os,			     InputStream value,			     @Optional("0x7fffffff") int length)  {    try {      if (os == null)        return BooleanValue.FALSE;      return LongValue.create(os.write(value, length));    } catch (IOException e) {      throw new QuercusModuleException(e);    }  }  private static ArrayValue globImpl(Env env, String pattern, int flags,                                      Path path, String prefix,                                     ArrayValue result)  {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?