/**
   * Evaluates the expression.
   *
   * @param env the calling environment.
   * @return the expression value.
   */
  @Override
  public Value eval(Env env) {
    Value qThis = env.getThis();

    QuercusClass cls = qThis.getQuercusClass();

    if (cls == null) {
      env.error(L.l("no calling class found"), getLocation());

      return NullValue.NULL;
    }

    StringValue methodName = _methodName.evalStringValue(env);
    int hash = methodName.hashCodeCaseInsensitive();

    Value[] values = evalArgs(env, _args);

    env.pushCall(this, cls, values);

    try {
      env.checkTimeout();

      return cls.callMethod(env, qThis, methodName, hash, values);
    } finally {
      env.popCall();
    }
  }
  /**
   * Converts node tree to a valid xml string.
   *
   * @return xml string
   */
  public final Value asXML(Env env, @Optional Value filename) {
    Value value = toXML(env);

    if (!value.isString()) {
      return value;
    }

    StringValue str = value.toStringValue(env);

    if (filename.isDefault()) {
      return str;
    } else {
      Path path = env.lookupPwd(filename);

      OutputStream os = null;

      try {
        os = path.openWrite();

        str.writeTo(os);

        return BooleanValue.TRUE;
      } catch (IOException e) {
        env.warning(e);

        return BooleanValue.FALSE;
      } finally {
        if (os != null) {
          IoUtil.close(os);
        }
      }
    }
  }
Beispiel #3
0
  public void execute(Path path) throws IOException {
    QuercusPage page = parse(path);

    WriteStream os = new WriteStream(StdoutStream.create());

    os.setNewlineString("\n");
    os.setEncoding("iso-8859-1");

    Env env = createEnv(page, os, null, null);
    env.start();

    try {
      env.execute();
    } catch (QuercusDieException e) {
      log.log(Level.FINER, e.toString(), e);
    } catch (QuercusExitException e) {
      log.log(Level.FINER, e.toString(), e);
    } catch (QuercusErrorException e) {
      log.log(Level.FINER, e.toString(), e);
    } finally {
      env.close();

      os.flush();
    }
  }
  private boolean setLobParameter(Env env, int index, Value value) {
    if (_preparedStmt == null) {
      return false;
    }

    try {
      if (value == null || value.isNull()) {
        _preparedStmt.setObject(index, null);
      } else if (value.isString()) {
        _preparedStmt.setBinaryStream(index, value.toInputStream(), value.length());
      } else {
        InputStream inputStream = value.toInputStream();

        if (inputStream == null) {
          env.warning(
              L.l(
                  "type {0} ({1}) for parameter index {2} cannot be used for lob",
                  value.getType(), value.getClass(), index));
          return false;
        }

        int length = -1;

        if (value instanceof FileReadValue) {
          length = (int) ((FileReadValue) value).getLength();

          if (length <= 0) length = -1;
        }

        if (length < 0) {
          TempBuffer tempBuffer = TempBuffer.allocate();

          try {
            byte[] bytes = new byte[1024];

            int len;

            while ((len = inputStream.read(bytes, 0, 1024)) != -1) tempBuffer.write(bytes, 0, len);
          } catch (IOException e) {
            env.warning(e);
            return false;
          }

          TempReadStream tempReadStream = new TempReadStream(tempBuffer);
          tempReadStream.setFreeWhenDone(true);

          _preparedStmt.setBinaryStream(
              index, new ReadStream(tempReadStream), tempBuffer.getLength());
        } else {
          _preparedStmt.setBinaryStream(index, inputStream, length);
        }
      }
    } catch (SQLException e) {
      setError(env, e);
      return false;
    }

    return true;
  }
Beispiel #5
0
  public static Value __construct(Env env, @Optional String queueName) {
    JMSQueue queue = JMSModule.message_get_queue(env, queueName, null);

    if (queue == null) {
      env.warning(L.l("'{0}' is an unknown JMSQueue", queueName));
      return NullValue.NULL;
    }

    return env.wrapJava(queue);
  }
Beispiel #6
0
  private GettextDomainMap getDomains(Env env)
  {
    Object val = env.getSpecialValue("caucho.gettext_domains");

    if (val == null) {
      val = new GettextDomainMap();

      env.setSpecialValue("caucho.gettext_domains", val);
    }
    
    return (GettextDomainMap) val;
  }
Beispiel #7
0
  private static SimpleXMLElement buildNode(
      Env env,
      QuercusClass cls,
      SimpleXMLElement parent,
      Node node,
      String namespace,
      boolean isPrefix) {
    if (node.getNodeType() == Node.TEXT_NODE) {
      String value = node.getNodeValue();

      if (parent != null) {
        parent.addChild(new SimpleXMLText(env, cls, env.createString(value)));

        if (!isWhitespace(value)) parent.addText(env.createString(value));
      }

      return parent;
    }

    /*
    NamedNodeMap attrMap = node.getAttributes();
    Node namespaceAttr = attrMap.getNamedItem("xmlns");

    if (namespaceAttr != null)
      namespace = namespaceAttr.getNodeValue();
    */

    SimpleXMLElement elt = new SimpleXMLElement(env, cls, parent, node.getNodeName(), namespace);

    if (parent != null) parent.addChild(elt);

    NamedNodeMap attrs = node.getAttributes();

    if (attrs != null) {
      int length = attrs.getLength();

      for (int i = 0; i < length; i++) {
        Attr attr = (Attr) attrs.item(i);

        if (attr.getName().startsWith("xmlns")) {
          elt.addNamespaceAttribute(env, attr.getName(), attr.getValue());
        } else {
          elt.addAttribute(env, attr.getName(), env.createString(attr.getValue()), namespace);
        }
      }
    }

    for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
      buildNode(env, cls, elt, child, namespace, isPrefix);
    }

    return elt;
  }
Beispiel #8
0
  @EntrySet
  public Set<Map.Entry<Value, Value>> entrySet() {
    LinkedHashMap<Value, Value> map = new LinkedHashMap<Value, Value>();

    if (_attributes != null) {
      ArrayValue array = new ArrayValueImpl();

      for (SimpleXMLElement attr : _attributes) {
        StringValue value = attr._text;

        array.put(_env.createString(attr._name), value);
      }

      map.put(_env.createString("@attributes"), array);
    }

    boolean hasElement = false;
    if (_children != null) {
      for (SimpleXMLElement child : _children) {
        if (!child.isElement()) continue;

        hasElement = true;

        StringValue name = _env.createString(child.getName());
        Value oldChild = map.get(name);
        Value childValue;

        if (child._text != null) childValue = child._text;
        else childValue = wrapJava(_env, _cls, child);

        if (oldChild == null) {
          map.put(name, childValue);
        } else if (oldChild.isArray()) {
          ArrayValue array = (ArrayValue) oldChild;

          array.append(childValue);
        } else {
          ArrayValue array = new ArrayValueImpl();
          array.append(oldChild);
          array.append(childValue);

          map.put(name, array);
        }
      }
    }

    if (!hasElement && _text != null) {
      map.put(LongValue.ZERO, _text);
    }

    return map.entrySet();
  }
Beispiel #9
0
  /**
   * Returns a new instance based on the xml from 'data'.
   *
   * @param env
   * @param data xml data
   * @param options
   * @param dataIsUrl
   * @param namespaceV
   * @param isPrefix
   */
  public static Value __construct(
      Env env,
      Value data,
      @Optional int options,
      @Optional boolean dataIsUrl,
      @Optional Value namespaceV,
      @Optional boolean isPrefix) {
    QuercusClass cls = env.getCallingClass();

    if (cls == null) cls = env.getClass("SimpleXMLElement");

    return create(env, cls, data, options, dataIsUrl, namespaceV, isPrefix);
  }
Beispiel #10
0
  private void getNamespaces(Env env, ArrayValue array) {
    if (_namespaceMap != null) {
      for (Map.Entry<String, String> entry : _namespaceMap.entrySet()) {
        StringValue name = env.createString(entry.getKey());
        StringValue uri = env.createString(entry.getValue());

        SimpleXMLAttribute attr = new SimpleXMLAttribute(env, _cls, this, entry.getKey());
        attr.setText(uri);

        array.append(name, env.wrapJava(attr));
      }
    }
  }
Beispiel #11
0
  /** Connects to the underlying database. */
  @Override
  protected ConnectionEntry connectImpl(
      Env env,
      String host,
      String userName,
      String password,
      String dbname,
      int port,
      String socket,
      int flags,
      String driver,
      String url,
      boolean isNewLink) {
    if (isConnected()) {
      env.warning(L.l("Connection is already opened to '{0}'", this));
      return null;
    }

    try {

      if (host == null || host.equals("")) {
        host = "localhost";
      }

      if (driver == null || driver.equals("")) {
        driver = "org.postgresql.Driver";
      }

      if (url == null || url.equals("")) {
        url = "jdbc:postgresql://" + host + ":" + port + "/" + dbname;
      }

      ConnectionEntry jConn;

      jConn = env.getConnection(driver, url, userName, password, !isNewLink);

      return jConn;
    } catch (SQLException e) {
      env.warning("A link to the server could not be established. " + e.toString());
      env.setSpecialValue("postgres.connectErrno", LongValue.create(e.getErrorCode()));
      env.setSpecialValue("postgres.connectError", env.createString(e.getMessage()));

      log.log(Level.FINE, e.toString(), e);

      return null;
    } catch (Exception e) {
      env.warning("A link to the server could not be established. " + e.toString());
      env.setSpecialValue("postgres.connectError", env.createString(e.getMessage()));

      log.log(Level.FINE, e.toString(), e);
      return null;
    }
  }
  /**
   * Evaluates the expression.
   *
   * @param env the calling environment.
   * @return the expression value.
   */
  @Override
  public Var evalVar(Env env) {
    // quercus/0d1k
    Value value = env.getThis();

    return value.getThisFieldVar(env, _nameExpr.evalStringValue(env));
  }
Beispiel #13
0
  /** Adds a namespace attribute to this node. */
  protected void addNamespaceAttribute(Env env, String name, String namespace) {
    if (namespace == null || "".equals(namespace)) return;

    if (_attributes == null) _attributes = new ArrayList<SimpleXMLElement>();

    SimpleXMLAttribute attr =
        new SimpleXMLNamespaceAttribute(env, _cls, this, name, "", env.createString(namespace));

    int p = name.indexOf(':');
    if (p > 0) {
      String prefix = name.substring(p + 1);
      addNamespace(prefix, namespace);
    } else {
      if (_namespace == null) _namespace = namespace;

      addNamespace("", namespace);
    }

    for (int i = _attributes.size() - 1; i >= 0; i--) {
      SimpleXMLElement oldAttr = _attributes.get(i);

      if (oldAttr.getName().equals(name) && oldAttr.getNamespace().equals(namespace)) {
        _attributes.set(i, attr);
        return;
      }
    }

    _attributes.add(attr);
  }
Beispiel #14
0
  public StringValue toXML(Env env) {
    StringValue sb = env.createBinaryBuilder();

    toXMLImpl(sb);

    return sb;
  }
Beispiel #15
0
  public SplFileInfo(Env env, StringValue fileName) {
    _path = env.lookupPwd(fileName);

    _parent = _path.getParent();

    _fileName = _path.getTail();
  }
Beispiel #16
0
  /**
   * Retrieves the plural translation for msgid1.
   * 
   * @param env
   * @param domain
   * @param category
   * @param msgid1
   * @param msgid2
   *
   * @return translation found, else msgid1 if n == 1, else msgid2
   */
  private StringValue translate(Env env,
                                GettextDomain domain,
                                CharSequence category,
                                StringValue msgid1,
                                StringValue msgid2,
                                int quantity,
                                Value []args)
  {
    Locale locale = env.getLocaleInfo().getMessages().getLocale();

    GettextResource resource = getResource(env,
                                           domain.getPath(),
                                           locale,
                                           category,
                                           domain.getName());

    StringValue unicodeTranslation
      = resource.getTranslation(msgid1, quantity);

    if (unicodeTranslation == null)
      unicodeTranslation = errorReturn(msgid1, msgid2, quantity);

    StringValue translation = msgid1.create(env, unicodeTranslation, domain.getCharset());
    
    return format(env, translation, args);
  }
  public static Filter getFilter(Env env, Value filterIdV) {
    int filterId;

    int defaultFilterId = FILTER_UNSAFE_RAW;

    if (filterIdV.isDefault()) {
      // XXX: lookup in ini
      filterId = defaultFilterId;
    } else if (filterIdV.isArray()) {
      Value value = filterIdV.get(env.createString("filter"));

      if (value.isNull()) {
        filterId = defaultFilterId;
      } else {
        filterId = value.toInt();
      }
    } else {
      filterId = filterIdV.toInt();
    }

    Filter filter = _filterMap.get(filterId);

    if (filter == null) {
      throw new UnimplementedException(
          L.l("filter not implemented: {0} ({1})", filterIdV, filterId));
    }

    return filter;
  }
Beispiel #18
0
 private static StringValue format(Env env,
                             StringValue msg,
                             Value []args)
 {
   if (args.length == 0)
     return msg;
   
   StringValue sb;
   
   if (msg.isUnicode())
     sb = env.createUnicodeBuilder();
   else
     sb = env.createBinaryBuilder();
   
   return formatImpl(env, msg, args, sb);
 }
Beispiel #19
0
 @SuppressWarnings("unchecked")
 public Value unmarshal(Env env, Object value) {
   // XXX: need test
   return ((JavaClassDef<Object>)
           env.getQuercus().getJavaClassDefinition(value.getClass().getName()))
       .wrap(env, value);
 }
Beispiel #20
0
  /**
   * Runs an XPath expression on this node.
   *
   * @param env
   * @param expression
   * @return array of results
   * @throws XPathExpressionException
   */
  public Value xpath(Env env, String expression) {
    try {
      XPath xpath = XPathFactory.newInstance().newXPath();

      InputSource is = new InputSource(asXML(env).toInputStream());
      NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);

      int nodeLength = nodes.getLength();

      if (nodeLength == 0) return NullValue.NULL;

      // There are matching nodes
      ArrayValue result = new ArrayValueImpl();
      for (int i = 0; i < nodeLength; i++) {
        Node node = nodes.item(i);

        boolean isPrefix = node.getPrefix() != null;

        SimpleXMLElement xml =
            buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix);

        result.put(wrapJava(env, _cls, xml));
      }

      return result;
    } catch (XPathExpressionException e) {
      env.warning(e);
      log.log(Level.FINE, e.getMessage());

      return NullValue.NULL;
    }
  }
Beispiel #21
0
  /**
   * Sets the field metadata cursor to the given offset. The next call to mysqli_fetch_field() will
   * retrieve the field definition of the column associated with that offset.
   *
   * @param env the PHP executing environment
   * @return previous value of field cursor
   */
  public boolean field_seek(Env env, int offset) {
    boolean success = setFieldOffset(offset);

    if (!success) env.invalidArgument("field", offset);

    return success;
  }
  /**
   * Evaluates the expression.
   *
   * @param env the calling environment.
   * @return the expression value.
   */
  @Override
  public Value evalAssignRef(Env env, Value value) {
    Value obj = env.getThis();

    obj.putThisField(env, _nameExpr.evalStringValue(env), value);

    return value;
  }
Beispiel #23
0
  /** Reads in a string until NULL or EOF encountered. */
  private StringValue readOriginalString() throws IOException {
    StringValue sb = _env.createUnicodeBuilder();

    for (int ch = _in.read(); ch > 0; ch = _in.read()) {
      sb.append((char) ch);
    }

    return sb;
  }
  /** Reads into a binary builder. */
  @Override
  public StringValue read(int length) throws IOException {
    if (_is == null) return null;

    StringValue bb = _env.createBinaryBuilder();

    if (bb.appendRead(_is, length) > 0) return bb;
    else return null;
  }
Beispiel #25
0
  /** Loads the session from the backing. */
  public SessionArrayValue loadSession(Env env, String sessionId) {
    long now = env.getCurrentTime();

    SessionArrayValue session = _sessionManager.getSession(env, sessionId, now);

    if (session == null) session = _sessionManager.createSession(env, sessionId, now);

    return session;
  }
  public static StringValue getCanonicalName(Env env, String classContext, StringValue name) {
    ClassDef classDef = env.findClassDef(classContext);
    ClassField entry = classDef.getField(name);

    if (entry != null) {
      return entry.getCanonicalName();
    }

    return name;
  }
Beispiel #27
0
  /**
   * Evaluates the expression.
   *
   * @param env the calling environment.
   * @param ctx
   * @return the expression value.
   */
  @Override
  @Nonnull
  protected V<? extends ValueOrVar> _eval(Env env, FeatureExpr ctx) {
    QuercusClass cl = env.findClass(_className);

    if (cl == null) {
      env.error(L.l("no matching class {0}", _className), getLocation());
    }

    // qa/0954 - static calls pass the current $this
    Value qThis = env.getThis();

    StringValue methodName = _nameExpr.evalStringValue(env, ctx).getOne();

    V<? extends ValueOrVar>[] args = evalArgs(env, _args, ctx);
    int hash = methodName.hashCodeCaseInsensitive();

    return cl.callStaticMethod(env, ctx, qThis, methodName, hash, args).map((a) -> a.toValue());
  }
Beispiel #28
0
  protected static Value create(
      Env env,
      QuercusClass cls,
      Value data,
      int options,
      boolean dataIsUrl,
      Value namespaceV,
      boolean isPrefix) {
    if (data.length() == 0) {
      env.warning(L.l("xml data must have length greater than 0"));
      return BooleanValue.FALSE;
    }

    try {
      String namespace = null;

      if (!namespaceV.isNull()) namespace = namespaceV.toString();

      Node node = parse(env, data, options, dataIsUrl, namespace, isPrefix);

      if (node == null) {
        return BooleanValue.FALSE;
      }

      SimpleXMLElement elt = buildNode(env, cls, null, node, namespace, isPrefix);

      return wrapJava(env, cls, elt);

    } catch (IOException e) {
      env.warning(e);

      return BooleanValue.FALSE;
    } catch (ParserConfigurationException e) {
      env.warning(e);

      return BooleanValue.FALSE;
    } catch (SAXException e) {
      env.warning(e);

      return BooleanValue.FALSE;
    }
  }
Beispiel #29
0
  /**
   * Fetch a result row as an associative, a numeric array, or both.
   *
   * @param type one of MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH (default) By using the MYSQLI_ASSOC
   *     constant this function will behave identically to the mysqli_fetch_assoc(), while
   *     MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option
   *     MYSQLI_BOTH will create a single array with the attributes of both.
   * @return a result row as an associative, a numeric array, or both or null if there are no more
   *     rows in the result set
   */
  @ReturnNullAsFalse
  public ArrayValue fetch_array(Env env, @Optional("MYSQLI_BOTH") int type) {
    if (type != MysqliModule.MYSQLI_ASSOC
        && type != MysqliModule.MYSQLI_BOTH
        && type != MysqliModule.MYSQLI_NUM) {
      env.warning(L.l("invalid result_type"));
      return null;
    }

    return fetchArray(env, type);
  }
Beispiel #30
0
  private static Node parse(
      Env env, Value data, int options, boolean dataIsUrl, String namespace, boolean isPrefix)
      throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = null;

    if (dataIsUrl) {
      Path path = env.lookup(data.toStringValue());

      // PHP throws an Exception instead
      if (path == null) {
        log.log(Level.FINE, L.l("Cannot read file/URL '{0}'", data));
        env.warning(L.l("Cannot read file/URL '{0}'", data));

        return null;
      }

      ReadStream is = path.openRead();

      try {
        document = builder.parse(is);
      } finally {
        is.close();
      }
    } else {
      StringReader reader = new java.io.StringReader(data.toString());

      document = builder.parse(new InputSource(reader));
    }

    NodeList childList = document.getChildNodes();

    // php/1x70
    for (int i = 0; i < childList.getLength(); i++) {
      if (childList.item(i).getNodeType() == Node.ELEMENT_NODE) return childList.item(i);
    }

    return childList.item(0);
  }