Example #1
0
Variant yaf_route_map_instance(const Object& data, 
        const Variant& controller_prefer, const Variant& delim)
{
    Object o;
    if (data.isNull()) {
        Array arr = Array::Create();
        arr.append(controller_prefer);
        arr.append(delim);

        o = createObject("Yaf_Route_Map", arr) ;
    } else {
        o = data;
    }

    if (controller_prefer.isBoolean()) {
        auto ptr_prefer = o->o_realProp(YAF_ROUTE_MAP_VAR_NAME_CTL_PREFER, 
            ObjectData::RealPropUnchecked, "Yaf_Route_Map");
        *ptr_prefer = controller_prefer;
    }

    if (delim.isString()) {
        auto ptr_delim = o->o_realProp(YAF_ROUTE_MAP_VAR_NAME_DELIMETER, 
            ObjectData::RealPropUnchecked, "Yaf_Route_Map");
        *ptr_delim = delim;
    }

    return o;
}
Example #2
0
Variant c_XMLReader::t_expand(const Object& basenode /* = null */) {
  p_DOMDocument doc;
  xmlDocPtr docp = nullptr;

  if (!basenode.isNull()) {
    c_DOMNode *dombasenode = basenode.getTyped<c_DOMNode>();
    doc = dombasenode->doc();
    docp = (xmlDocPtr) doc->m_node;
    if (docp == nullptr) {
      raise_warning("Invalid State Error");
      return false;
    }
  } else {
    doc = (p_DOMDocument) SystemLib::AllocDOMDocumentObject();
  }

  if (m_ptr) {
    xmlNodePtr node = xmlTextReaderExpand(m_ptr);
    if (node == nullptr) {
      raise_warning("An Error Occurred while expanding");
      return false;
    } else {
      xmlNodePtr nodec = xmlDocCopyNode(node, docp, 1);
      if (nodec == nullptr) {
        raise_notice("Cannot expand this node type");
        return false;
      } else {
        return php_dom_create_object(nodec, doc, false);
      }
    }
  }

  raise_warning("Load Data before trying to read");
  return false;
}
Example #3
0
Variant f_readgzfile(CStrRef filename, bool use_include_path /* = false */) {
  Object stream = f_gzopen(filename, "rb", use_include_path);
  if (stream.isNull()) {
    return false;
  }
  return f_gzpassthru(stream);
}
Example #4
0
Object c_GenMapWaitHandle::ti_create(const Variant& dependencies) {
  if (UNLIKELY(!dependencies.isObject() ||
      dependencies.getObjectData()->getCollectionType() !=
        Collection::MapType)) {
    Object e(SystemLib::AllocInvalidArgumentExceptionObject(
      "Expected dependencies to be an instance of Map"));
    throw e;
  }
  assert(dependencies.getObjectData()->instanceof(c_Map::classof()));
  auto deps = p_Map::attach(c_Map::Clone(dependencies.getObjectData()));
  for (ssize_t iter_pos = deps->iter_begin();
       deps->iter_valid(iter_pos);
       iter_pos = deps->iter_next(iter_pos)) {

    auto* current = tvAssertCell(deps->iter_value(iter_pos));
    if (UNLIKELY(!c_WaitHandle::fromCell(current))) {
      Object e(SystemLib::AllocInvalidArgumentExceptionObject(
        "Expected dependencies to be a map of WaitHandle instances"));
      throw e;
    }
  }

  Object exception;
  for (ssize_t iter_pos = deps->iter_begin();
       deps->iter_valid(iter_pos);
       iter_pos = deps->iter_next(iter_pos)) {

    auto* current = tvAssertCell(deps->iter_value(iter_pos));
    assert(current->m_type == KindOfObject);
    assert(current->m_data.pobj->instanceof(c_WaitHandle::classof()));
    auto child = static_cast<c_WaitHandle*>(current->m_data.pobj);

    if (child->isSucceeded()) {
      auto k = deps->iter_key(iter_pos);
      deps->set(k.asCell(), &child->getResult());
    } else if (child->isFailed()) {
      putException(exception, child->getException());
    } else {
      assert(child->instanceof(c_WaitableWaitHandle::classof()));
      auto child_wh = static_cast<c_WaitableWaitHandle*>(child);

      p_GenMapWaitHandle my_wh = NEWOBJ(c_GenMapWaitHandle)();
      my_wh->initialize(exception, deps.get(), iter_pos, child_wh);

      AsioSession* session = AsioSession::Get();
      if (UNLIKELY(session->hasOnGenMapCreateCallback())) {
        session->onGenMapCreate(my_wh.get(), dependencies);
      }

      return my_wh;
    }
  }

  if (exception.isNull()) {
    return Object::attach(c_StaticWaitHandle::CreateSucceeded(
      make_tv<KindOfObject>(deps.detach())));
  } else {
    return Object::attach(c_StaticWaitHandle::CreateFailed(exception.detach()));
  }
}
Example #5
0
GDALPDFObject* GDALPDFArrayPoppler::Get(int nIndex)
{
    if (nIndex < 0 || nIndex >= GetLength())
        return NULL;

    int nOldSize = (int)m_v.size();
    if (nIndex >= nOldSize)
    {
        m_v.resize(nIndex+1);
        for(int i=nOldSize;i<=nIndex;i++)
        {
            m_v[i] = NULL;
        }
    }

    if (m_v[nIndex] != NULL)
        return m_v[nIndex];

    Object* po = new Object;
    if (m_poArray->get(nIndex, po) && !po->isNull())
    {
        GDALPDFObjectPoppler* poObj = new GDALPDFObjectPoppler(po, TRUE);
        m_v[nIndex] = poObj;
        return poObj;
    }
    else
    {
        delete po;
        return NULL;
    }
}
Variant yaf_route_rewrite_instance( const Object& object,
        const Variant& match, const Array& route, const Variant& verify)
{
    Object o;
    if (object.isNull()) {
        Array params = Array::Create();
        params.append(match);
        params.append(route);
        params.append(verify);

        o = createObject("Yaf_Route_Rewrite", params);
    }  else {
        o = object;
    }

    auto ptr_match = o->o_realProp(YAF_ROUTE_PROPETY_NAME_MATCH,
                    ObjectData::RealPropUnchecked, "Yaf_Route_Rewrite");

    auto ptr_route = o->o_realProp(YAF_ROUTE_PROPETY_NAME_ROUTE,
                    ObjectData::RealPropUnchecked, "Yaf_Route_Rewrite");

    auto ptr_verify = o->o_realProp(YAF_ROUTE_PROPETY_NAME_VERIFY,
                    ObjectData::RealPropUnchecked, "Yaf_Route_Rewrite");

    *ptr_match = match;
    *ptr_route = route;
    *ptr_verify = verify;

    return o;
}
Example #7
0
void CmdInterrupt::sendImpl(DebuggerThriftBuffer &thrift) {
  DebuggerCommand::sendImpl(thrift);
  thrift.write(m_interrupt);
  thrift.write(m_program);
  thrift.write(m_errorMsg);
  thrift.write(m_threadId);
  thrift.write(m_pendingJump);
  if (m_site) {
    thrift.write(true);
    thrift.write(m_site->getFile());
    thrift.write(m_site->getLine0());
    thrift.write(m_site->getChar0());
    thrift.write(m_site->getLine1());
    thrift.write(m_site->getChar1());
    thrift.write(m_site->getNamespace());
    thrift.write(m_site->getClass());
    thrift.write(m_site->getFunction());
    Object e = m_site->getException();
    if (e.isNull()) {
      thrift.write("");
    } else {
      thrift.write(e->o_getClassName());
    }
    thrift.write(DebuggerClient::FormatVariable(e));
  } else {
    thrift.write(false);
  }
  BreakPointInfo::SendImpl(m_matched, thrift);
}
Example #8
0
bool AnnotWriter::HasEmbeddedContent(Object* page) {
	ASSERT(page && page->isDict());
	Object obj;
	bool embedded = !(page->dictLookupNF("Contents", &obj) &&
		(obj.isArray() || obj.isRef() || obj.isNull()));
	obj.free();
	return embedded;
}
Object c_GenArrayWaitHandle::ti_create(const char* cls, CArrRef dependencies) {
    Array deps = dependencies->copy();
    for (ssize_t iter_pos = deps->iter_begin();
            iter_pos != ArrayData::invalid_index;
            iter_pos = deps->iter_advance(iter_pos)) {

        TypedValue* current = deps->nvGetValueRef(iter_pos);
        if (UNLIKELY(current->m_type == KindOfRef)) {
            tvUnbox(current);
        }

        if (!c_WaitHandle::fromTypedValue(current) &&
                !IS_NULL_TYPE(current->m_type)) {
            Object e(SystemLib::AllocInvalidArgumentExceptionObject(
                         "Expected dependencies to be an array of WaitHandle instances"));
            throw e;
        }
    }

    Object exception;
    for (ssize_t iter_pos = deps->iter_begin();
            iter_pos != ArrayData::invalid_index;
            iter_pos = deps->iter_advance(iter_pos)) {

        TypedValue* current = deps->nvGetValueRef(iter_pos);
        if (IS_NULL_TYPE(current->m_type)) {
            // {uninit,null} yields null
            tvWriteNull(current);
            continue;
        }

        assert(current->m_type == KindOfObject);
        assert(dynamic_cast<c_WaitHandle*>(current->m_data.pobj));
        auto child = static_cast<c_WaitHandle*>(current->m_data.pobj);

        if (child->isSucceeded()) {
            tvSetIgnoreRef(child->getResult(), current);
        } else if (child->isFailed()) {
            putException(exception, child->getException());
        } else {
            assert(dynamic_cast<c_WaitableWaitHandle*>(child));
            auto child_wh = static_cast<c_WaitableWaitHandle*>(child);

            c_GenArrayWaitHandle* my_wh = NEWOBJ(c_GenArrayWaitHandle)();
            my_wh->initialize(exception, deps, iter_pos, child_wh);
            return my_wh;
        }
    }

    if (exception.isNull()) {
        TypedValue tv;
        tv.m_type = KindOfArray;
        tv.m_data.parr = deps.get();
        return c_StaticResultWaitHandle::Create(&tv);
    } else {
        return c_StaticExceptionWaitHandle::Create(exception.get());
    }
}
Example #10
0
int64_t f_hphp_splfileobject_fwrite(CObjRef obj, CStrRef str, int64_t length) {
  SplFileObject *fileObject = get_splfileobject(obj);
  Object file = fileObject->getFile();
  if (!file.isNull()) {
    File *f = file.getTyped<File>();
    return f->write(str, length);
  }
  return -1;
}
Example #11
0
bool same(const Variant& v1, const Object& v2) {
  bool null1 = v1.isNull();
  bool null2 = v2.isNull();
  if (null1 && null2) return true;
  if (null1 || null2) return false;
  if (!v1.isObject()) return false;
  auto const od = v1.getObjectData();
  return od == v2.get();
}
DOM::Node KJS::toNode(const Value& val)
{
  Object obj = Object::dynamicCast(val);
  if (obj.isNull() || !obj.inherits(&DOMNode::info))
    return DOM::Node();

  const DOMNode *dobj = static_cast<const DOMNode*>(obj.imp());
  return dobj->toNode();
}
 static void HHVM_METHOD(EventHttpRequest, sendReply, int64_t code, const String &reason, const Object &buf) {
     EventHttpRequestResourceData *event_http_request_resource_data = FETCH_RESOURCE(this_, EventHttpRequestResourceData, s_event_http_request);
     if(buf.isNull()){
         evhttp_send_reply((evhttp_request_t *) event_http_request_resource_data->getInternalResourceData(), code, reason.c_str(), NULL);
         return;
     }
     InternalResourceData *event_buffer_resource_data = FETCH_RESOURCE(buf, InternalResourceData, s_event_buffer);
     evhttp_send_reply((evhttp_request_t *) event_http_request_resource_data->getInternalResourceData(), code, reason.c_str(), (event_buffer_t *) event_buffer_resource_data->getInternalResourceData());
 }
Example #14
0
Object &FrameInjection::getThis() {
  if (m_object.get() && m_object->o_getId()) {
    return m_object;
  }

  static Object s_black_hole_object;
  ASSERT(s_black_hole_object.isNull()); // in case callers modified me
  s_black_hole_object.reset();
  return s_black_hole_object;
}
Object c_GenVectorWaitHandle::ti_create(const Variant& dependencies) {
  if (UNLIKELY(!dependencies.isObject() ||
      dependencies.getObjectData()->getCollectionType() !=
        Collection::VectorType)) {
    Object e(SystemLib::AllocInvalidArgumentExceptionObject(
      "Expected dependencies to be an instance of Vector"));
    throw e;
  }
  assert(dependencies.getObjectData()->instanceof(c_Vector::classof()));
  auto deps = SmartObject<c_Vector>::attach(
    c_Vector::Clone(dependencies.getObjectData()));
  for (int64_t iter_pos = 0; iter_pos < deps->size(); ++iter_pos) {
    Cell* current = deps->at(iter_pos);

    if (UNLIKELY(!c_WaitHandle::fromCell(current))) {
      Object e(SystemLib::AllocInvalidArgumentExceptionObject(
        "Expected dependencies to be a vector of WaitHandle instances"));
      throw e;
    }
  }

  Object exception;
  for (int64_t iter_pos = 0; iter_pos < deps->size(); ++iter_pos) {

    auto current = tvAssertCell(deps->at(iter_pos));
    assert(current->m_type == KindOfObject);
    assert(current->m_data.pobj->instanceof(c_WaitHandle::classof()));
    auto child = static_cast<c_WaitHandle*>(current->m_data.pobj);

    if (child->isSucceeded()) {
      auto result = child->getResult();
      deps->set(iter_pos, &result);
    } else if (child->isFailed()) {
      putException(exception, child->getException());
    } else {
      assert(child->instanceof(c_WaitableWaitHandle::classof()));
      auto child_wh = static_cast<c_WaitableWaitHandle*>(child);

      SmartObject<c_GenVectorWaitHandle> my_wh(newobj<c_GenVectorWaitHandle>());
      my_wh->initialize(exception, deps.get(), iter_pos, child_wh);
      AsioSession* session = AsioSession::Get();
      if (UNLIKELY(session->hasOnGenVectorCreateCallback())) {
        session->onGenVectorCreate(my_wh.get(), dependencies);
      }
      return my_wh;
    }
  }

  if (exception.isNull()) {
    return Object::attach(c_StaticWaitHandle::CreateSucceeded(
      make_tv<KindOfObject>(deps.detach())));
  } else {
    return Object::attach(c_StaticWaitHandle::CreateFailed(exception.detach()));
  }
}
Example #16
0
void c_DateTime::t___construct(const String& time /*= "now"*/,
                               const Object& timezone /*= null_object*/) {
  m_dt = NEWOBJ(DateTime)(TimeStamp::Current());
  if (!time.empty()) {
    m_dt->fromString(time, c_DateTimeZone::unwrap(timezone));
  } else if (!timezone.isNull()) {
    // We still have to tell the underlying DateTime the timezone incase they
    // call setTimestamp or something else later
    m_dt->setTimezone(c_DateTimeZone::unwrap(timezone));
  }
}
Example #17
0
Variant f_gzfile(CStrRef filename, bool use_include_path /* = false */) {
  Object stream = f_gzopen(filename, "rb", use_include_path);
  if (stream.isNull()) {
    return false;
  }

  Array ret;
  Variant line;
  while (!same(line = f_gzgets(stream), false)) {
    ret.append(line);
  }
  return ret;
}
Variant StaticMethodExpression::eval(VariableEnvironment &env) const {
  SET_LINE;
  // Static method expressions can be object method expressions inside
  // of a method when an object is available and the object's class inherits.
  // Super slow.
  String cname = m_cname->get(env);
  bool sp = m_cname->isSp();
  String name(m_name->get(env));
  Variant &vco = env.currentObject();
  Object co;
  if (!vco.isNull()) co = vco.toObject();
  bool withinClass = !co.isNull() && co->o_instanceof(cname.data());
  bool foundClass;
  const MethodStatement *ms = RequestEvalState::findMethod(cname.data(),
                                                           name.data(),
                                                           foundClass);
  if (withinClass) {
    if (m_construct) {
      String name = cname;
      while (true) {
        ClassEvalState *ces = RequestEvalState::findClassState(name.data());
        if (!ces) {
          // possibly built in
          cname = name;
          break;
        }
        // Ugly but needed to populate the method table for the parent
        ces->initializeInstance();
        ms = ces->getConstructor();
        if (ms) break;
        name = ces->getClass()->parent().c_str();
        if (name.empty()) break;
      }
    }
    if (!ms) {
      Array params = getParams(env);
      EvalFrameInjection::EvalStaticClassNameHelper helper(cname, sp);
      return ref(co->o_invoke_ex(cname, name, params));
    } else if (!(ms->getModifiers() & ClassStatement::Static)) {
      EvalFrameInjection::EvalStaticClassNameHelper helper(cname, sp);
      return ref(ms->invokeInstanceDirect(co, env, this));
    }
  }
  if (ms) {
    EvalFrameInjection::EvalStaticClassNameHelper helper(cname, sp);
    return ref(ms->invokeStaticDirect(cname.data(), env, this));
  }
  Array params = getParams(env);
  EvalFrameInjection::EvalStaticClassNameHelper helper(cname, sp);
  return ref(invoke_static_method(cname.data(), name.data(), params));
}
Example #19
0
		bool
		get(T& value, const std::string& optionExpression, int at) const
		{
			Object o = getObject(optionExpression, at);
			if(o.isNull())
			{
				return false;
			}

			convert(value, o, optionExpression);

			o.decref();
			return true;
		} // get[at]
Object c_GenVectorWaitHandle::ti_create(CVarRef dependencies) {
  if (UNLIKELY(!dependencies.instanceof(c_Vector::s_cls))) {
    Object e(SystemLib::AllocInvalidArgumentExceptionObject(
      "Expected dependencies to be an instance of Vector"));
    throw e;
  }
  assert(dynamic_cast<c_Vector*>(dependencies.getObjectData()));
  p_Vector deps = static_cast<c_Vector*>(dependencies.getObjectData())->clone();
  for (int64_t iter_pos = 0; iter_pos < deps->size(); ++iter_pos) {
    Cell* current = deps->at(iter_pos);

    if (UNLIKELY(!c_WaitHandle::fromCell(current))) {
      Object e(SystemLib::AllocInvalidArgumentExceptionObject(
        "Expected dependencies to be a vector of WaitHandle instances"));
      throw e;
    }
  }

  Object exception;
  for (int64_t iter_pos = 0; iter_pos < deps->size(); ++iter_pos) {

    Cell* current = tvAssertCell(deps->at(iter_pos));
    assert(current->m_type == KindOfObject);
    assert(dynamic_cast<c_WaitHandle*>(current->m_data.pobj));
    auto child = static_cast<c_WaitHandle*>(current->m_data.pobj);

    if (child->isSucceeded()) {
      cellSet(child->getResult(), *current);
    } else if (child->isFailed()) {
      putException(exception, child->getException());
    } else {
      assert(dynamic_cast<c_WaitableWaitHandle*>(child));
      auto child_wh = static_cast<c_WaitableWaitHandle*>(child);

      p_GenVectorWaitHandle my_wh = NEWOBJ(c_GenVectorWaitHandle)();
      my_wh->initialize(exception, deps.get(), iter_pos, child_wh);
      AsioSession* session = AsioSession::Get();
      if (UNLIKELY(session->hasOnGenVectorCreateCallback())) {
        session->onGenVectorCreate(my_wh.get(), dependencies);
      }
      return my_wh;
    }
  }

  if (exception.isNull()) {
    return c_StaticResultWaitHandle::Create(make_tv<KindOfObject>(deps.get()));
  } else {
    return c_StaticExceptionWaitHandle::Create(exception.get());
  }
}
Example #21
0
		bool
		get(View& value, const std::string& optionExpression) const
		{
			Object o = getObject(optionExpression);
			if(o.isNull())
			{
				return false;
			}

			checkIsNotNone<View>(o, optionExpression);

			o.decref();

			value = View(*this, optionExpression);
			return true;
		} // get
Example #22
0
		bool
		get(View& value, const std::string& optionExpression, int at) const
		{
			Object o = getObject(optionExpression, at);
			if(o.isNull())
			{
				return false;
			}

			o.decref();

			std::stringstream element;
			element << optionExpression << "[" << at << "]";
			checkIsNotNone<View>(o, element.str());

			value = View(*this, optionExpression, at);
			return true;
		} // get
Example #23
0
GDALPDFObject* GDALPDFDictionaryPoppler::Get(const char* pszKey)
{
    std::map<CPLString, GDALPDFObject*>::iterator oIter = m_map.find(pszKey);
    if (oIter != m_map.end())
        return oIter->second;

    Object* po = new Object;
    if (m_poDict->lookup((char*)pszKey, po) && !po->isNull())
    {
         GDALPDFObjectPoppler* poObj = new GDALPDFObjectPoppler(po, TRUE);
         m_map[pszKey] = poObj;
         return poObj;
    }
    else
    {
        delete po;
        return NULL;
    }
}
  req::ptr<StreamFilter> createInstance(const char* php_func,
                                        req::ptr<File> stream,
                                        const String& filter,
                                        const Variant& params) {
    auto class_name = m_registeredFilters.rvalAt(filter).asCStrRef();
    Class* class_ = Unit::getClass(class_name.get(), true);
    Object obj = Object();

    if (LIKELY(class_ != nullptr)) {
      PackedArrayInit ctor_args(3);
      ctor_args.append(Variant(stream));
      ctor_args.append(filter);
      ctor_args.append(params);
      obj = Object::attach(
        g_context->createObject(class_name.get(), ctor_args.toArray())
      );
      auto created = obj->o_invoke(s_onCreate, Array::Create());
      /* - true: documented value for success
       * - null: undocumented default successful value
       * - false: documented value for failure
       */
      if (!(created.isNull() || created.toBoolean())) {
        obj.reset();
      }
    } else {
      raise_warning("%s: user-filter \"%s\" requires class \"%s\", but that "
                    "class " "is not defined",
                    php_func,
                    filter.data(),
                    class_name.data());
      // Fall through, as to match Zend, the warning below should also be raised
    }

    if (obj.isNull()) {
      raise_warning("%s: unable to create or locate filter \"%s\"",
                    php_func,
                    filter.data());
      return nullptr;
    }

    return req::make<StreamFilter>(obj, stream);
  }
Example #25
0
Object ExpressionParser::evaluate(QString expression) {
    QStringList parts = expression.split(".");
    QString str(parts.at(0));
    str.replace('/', '.');
    str.replace(" ", "");
    str.replace("()", "");
    Class cls = Class::forName(str);
    if (parts.size() == 1) {
        return cls;
    }
    Object obj = cls.getStaticFieldContent(parts.at(1));
    for (int nextField = 2; nextField < parts.size(); nextField++) {
        if (obj.isNull()) {
            throw JNIException("Dereferenced NULL at position: " % QString::number(nextField));
        }
        Class objClass = obj.getClass();
        QString fieldName = convertFieldName(obj, parts.at(nextField));
        obj = objClass.getFieldContent(fieldName, obj);
    }
    return obj;
}
Example #26
0
  Resource createInstance(const char* php_func,
                          const Resource& stream,
                          const String& filter,
                          CVarRef params) {
    auto class_name = m_registeredFilters.rvalAt(filter).asCStrRef();
    Class* class_ = Unit::lookupClass(class_name.get());
    Object obj = null_object;

    if (LIKELY(class_ != nullptr)) {
      ArrayInit ctor_args(3);
      ctor_args.set(stream);
      ctor_args.set(filter);
      ctor_args.set(params);
      obj = g_context->createObject(class_name.get(), ctor_args.toArray());
      auto created = obj->o_invoke(s_onCreate, Array::Create());
      /* - true: documented value for success
       * - null: undocumented default successful value
       * - false: documented value for failure
       */
      if (!(created.isNull() || created.toBoolean())) {
        obj = null_object;
      }
    } else {
      raise_warning("%s: user-filter \"%s\" requires class \"%s\", but that "
                    "class " "is not defined",
                    php_func,
                    filter->data(),
                    class_name->data());
      // Fall through, as to match Zend, the warning below should also be raised
    }

    if (obj.isNull()) {
      raise_warning("%s: unable to create or locate filter \"%s\"",
                    php_func,
                    filter->data());
      return null_resource;
    }

    return Resource(NEWOBJ(StreamFilter)(obj));
  }
Variant StaticMethodExpression::eval(VariableEnvironment &env) const {
  SET_LINE;
  // Static method expressions can be object method expressions inside
  // of a method when an object is available and the object's class inherits.
  // Super slow.
  String cname = getClassName(m_cname, env);
  FrameInjection::EvalStaticClassNameHelper helper
    (m_cname->getStatic(), cname, m_sp);

  String name(m_name->get(env));
  Variant &vco = env.currentObject();
  Object co;
  if (!vco.isNull()) co = vco.toObject();
  bool withinClass = !co.isNull() && co->o_instanceof(cname.data());
  bool foundClass;
  const MethodStatement *ms = RequestEvalState::findMethod(cname.data(),
                                                           name.data(),
                                                           foundClass);
  if (withinClass) {
    if (m_construct && !ms) {
      // In a class method doing __construct will go to the name constructor
      ms = RequestEvalState::findMethod(cname.data(),
                                        cname.data(),
                                        foundClass);
    }
    if (ms) {
      return ref(ms->invokeInstanceDirect(co, env, this));
    }
    return ref(co->o_invoke_ex(cname.data(), name.data(), getParams(env),
                               m_name->hashLwr()));

  }
  if (ms) {
    return ref(ms->invokeStaticDirect(cname.data(), env, this));
  }
  return ref(invoke_static_method(cname.data(), name.data(), getParams(env)));
}
Example #28
0
void Game::paint(SDL_Renderer * painter, const SDL_Rect & rect)
{
	if(toInvalidate) {
		resizeSpritesForLevel(rect);
		toInvalidate = false;
	}

	SDL_RenderClear(painter);

	Chthon::Point offset = Chthon::Point(
			rect.w - sokoban.width() * sprite_width,
			rect.h - sokoban.height() * sprite_height
			) / 2;
	for(int y = 0; y < sokoban.height(); ++y) {
		for(int x = 0; x < sokoban.width(); ++x) {
			Chthon::Point pos = offset + Chthon::Point(x * sprite_width, y * sprite_height);

			Cell cell = sokoban.getCellAt(x, y);
			int cellSprite = Sprites::SPACE;
			switch(cell.type) {
				case Cell::FLOOR: cellSprite = Sprites::FLOOR; break;
				case Cell::SLOT: cellSprite = Sprites::EMPTY_SLOT; break;
				case Cell::SPACE: cellSprite = Sprites::SPACE; break;
				case Cell::WALL: cellSprite = Sprites::WALL; break;
			}
			cellSprite = original_sprites.contains(cellSprite) ? cellSprite : Sprites::SPACE;

			SDL_Rect src_rect = original_sprites.getSpriteRect(cellSprite, cell.sprite);
			SDL_Rect dest_rect;
			dest_rect.x = pos.x;
			dest_rect.y = pos.y;
			dest_rect.w = sprite_width;
			dest_rect.h = sprite_height;
			SDL_RenderCopy(painter, original_sprites.getTileSet(), &src_rect, &dest_rect);

			Object object = sokoban.getObjectAt(x, y);
			if(!object.isNull()) {
				int objectSprite = Sprites::SPACE;
				switch(cell.type) {
					case Cell::FLOOR:
						if(object.is_player) {
							objectSprite = Sprites::PLAYER_ON_FLOOR;
						} else {
							objectSprite = Sprites::BOX_ON_FLOOR;
						}
						break;
					case Cell::SLOT:
						if(object.is_player) {
							objectSprite = Sprites::PLAYER_ON_SLOT;
						} else {
							objectSprite = Sprites::BOX_ON_SLOT;
						}
						break;
				}
				if(objectSprite != Sprites::SPACE && original_sprites.contains(objectSprite)) {
					SDL_Rect src_rect = original_sprites.getSpriteRect(objectSprite, object.sprite);
					SDL_RenderCopy(painter, original_sprites.getTileSet(), &src_rect, &dest_rect);
				}
			}
		}
	}
	if(target_mode) {
		Chthon::Point pos = offset + Chthon::Point(target.x * sprite_width, target.y * sprite_height);
		SDL_Rect src_rect = original_sprites.getSpriteRect(Sprites::CURSOR, 0);
		SDL_Rect dest_rect;
		dest_rect.x = pos.x;
		dest_rect.y = pos.y;
		dest_rect.w = sprite_width;
		dest_rect.h = sprite_height;
		SDL_RenderCopy(painter, original_sprites.getTileSet(), &src_rect, &dest_rect);
	}

	if(fader_in.is_active() || fader_out.is_active()) {
		if(fader_in.is_active()) {
			SDL_SetRenderDrawColor(painter, 0, 0, 0, 255 - fader_in.multiplied_value(255));
		} else {
			SDL_SetRenderDrawColor(painter, 0, 0, 0, fader_out.multiplied_value(255));
		}
		SDL_RenderFillRect(painter, &rect);
	}
}
Example #29
0
  bool setOption(long option, CVarRef value) {
    if (m_cp == NULL) {
      return false;
    }
    m_error_no = CURLE_OK;

    switch (option) {
    case CURLOPT_INFILESIZE:
    case CURLOPT_VERBOSE:
    case CURLOPT_HEADER:
    case CURLOPT_NOPROGRESS:
    case CURLOPT_NOBODY:
    case CURLOPT_FAILONERROR:
    case CURLOPT_UPLOAD:
    case CURLOPT_POST:
    case CURLOPT_FTPLISTONLY:
    case CURLOPT_FTPAPPEND:
    case CURLOPT_NETRC:
    case CURLOPT_PUT:
    case CURLOPT_TIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_TIMEOUT_MS:
#endif
    case CURLOPT_FTP_USE_EPSV:
    case CURLOPT_LOW_SPEED_LIMIT:
    case CURLOPT_SSLVERSION:
    case CURLOPT_LOW_SPEED_TIME:
    case CURLOPT_RESUME_FROM:
    case CURLOPT_TIMEVALUE:
    case CURLOPT_TIMECONDITION:
    case CURLOPT_TRANSFERTEXT:
    case CURLOPT_HTTPPROXYTUNNEL:
    case CURLOPT_FILETIME:
    case CURLOPT_MAXREDIRS:
    case CURLOPT_MAXCONNECTS:
    case CURLOPT_CLOSEPOLICY:
    case CURLOPT_FRESH_CONNECT:
    case CURLOPT_FORBID_REUSE:
    case CURLOPT_CONNECTTIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_CONNECTTIMEOUT_MS:
#endif
    case CURLOPT_SSL_VERIFYHOST:
    case CURLOPT_SSL_VERIFYPEER:
      //case CURLOPT_DNS_USE_GLOBAL_CACHE: not thread-safe when set to true
    case CURLOPT_NOSIGNAL:
    case CURLOPT_PROXYTYPE:
    case CURLOPT_BUFFERSIZE:
    case CURLOPT_HTTPGET:
    case CURLOPT_HTTP_VERSION:
    case CURLOPT_CRLF:
    case CURLOPT_DNS_CACHE_TIMEOUT:
    case CURLOPT_PROXYPORT:
    case CURLOPT_FTP_USE_EPRT:
    case CURLOPT_HTTPAUTH:
    case CURLOPT_PROXYAUTH:
    case CURLOPT_FTP_CREATE_MISSING_DIRS:
    case CURLOPT_FTPSSLAUTH:
    case CURLOPT_FTP_SSL:
    case CURLOPT_UNRESTRICTED_AUTH:
    case CURLOPT_PORT:
    case CURLOPT_AUTOREFERER:
    case CURLOPT_COOKIESESSION:
    case CURLOPT_TCP_NODELAY:
    case CURLOPT_IPRESOLVE:
    case CURLOPT_FOLLOWLOCATION:
      m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, value.toInt64());
      break;
    case CURLOPT_RETURNTRANSFER:
      m_write.method = value.toBoolean() ? PHP_CURL_RETURN : PHP_CURL_STDOUT;
      break;
    case CURLOPT_BINARYTRANSFER:
      m_write.type = value.toBoolean() ? PHP_CURL_BINARY : PHP_CURL_ASCII;
      break;
    case CURLOPT_PRIVATE:
    case CURLOPT_URL:
    case CURLOPT_PROXY:
    case CURLOPT_USERPWD:
    case CURLOPT_PROXYUSERPWD:
    case CURLOPT_RANGE:
    case CURLOPT_CUSTOMREQUEST:
    case CURLOPT_USERAGENT:
    case CURLOPT_FTPPORT:
    case CURLOPT_COOKIE:
    case CURLOPT_REFERER:
    case CURLOPT_INTERFACE:
    case CURLOPT_KRB4LEVEL:
    case CURLOPT_EGDSOCKET:
    case CURLOPT_CAINFO:
    case CURLOPT_CAPATH:
    case CURLOPT_SSL_CIPHER_LIST:
    case CURLOPT_SSLKEY:
    case CURLOPT_SSLKEYTYPE:
    case CURLOPT_SSLKEYPASSWD:
    case CURLOPT_SSLENGINE:
    case CURLOPT_SSLENGINE_DEFAULT:
    case CURLOPT_SSLCERTTYPE:
    case CURLOPT_ENCODING:
    case CURLOPT_COOKIEJAR:
    case CURLOPT_SSLCERT:
    case CURLOPT_RANDOM_FILE:
    case CURLOPT_COOKIEFILE:
      {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* Strings passed to libcurl as 'char *' arguments, are copied
           by the library... NOTE: before 7.17.0 strings were not copied. */
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, svalue.c_str());
#else
        char *copystr = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(copystr);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, copystr);
#endif
        if (option == CURLOPT_URL) m_url = value;
      }
      break;
    case CURLOPT_FILE:
    case CURLOPT_INFILE:
    case CURLOPT_WRITEHEADER:
    case CURLOPT_STDERR:
      {
        if (!value.is(KindOfObject)) {
          return false;
        }

        Object obj = value.toObject();
        if (obj.isNull() || obj.getTyped<File>(true) == NULL) {
          return false;
        }

        switch (option) {
          case CURLOPT_FILE:
            m_write.fp = obj;
            m_write.method = PHP_CURL_FILE;
            break;
          case CURLOPT_WRITEHEADER:
            m_write_header.fp = obj;
            m_write_header.method = PHP_CURL_FILE;
            break;
          case CURLOPT_INFILE:
            m_read.fp = obj;
            m_emptyPost = false;
            break;
          default: {
            if (obj.getTyped<PlainFile>(true) == NULL) {
              return false;
            }
            FILE *fp = obj.getTyped<PlainFile>()->getStream();
            if (!fp) {
              return false;
            }
            m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, fp);
            break;
          }
        }
      }
      break;
    case CURLOPT_WRITEFUNCTION:
      m_write.callback = value;
      m_write.method = PHP_CURL_USER;
      break;
    case CURLOPT_READFUNCTION:
      m_read.callback = value;
      m_read.method = PHP_CURL_USER;
      m_emptyPost = false;
      break;
    case CURLOPT_HEADERFUNCTION:
      m_write_header.callback = value;
      m_write_header.method = PHP_CURL_USER;
      break;
    case CURLOPT_POSTFIELDS:
      m_emptyPost = false;
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_httppost *first = NULL;
        curl_httppost *last  = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();
          const char *postval = val.data();

          /* The arguments after _NAMELENGTH and _CONTENTSLENGTH
           * must be explicitly cast to long in curl_formadd
           * use since curl needs a long not an int. */
          if (*postval == '@') {
            ++postval;
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_FILE, postval,
               CURLFORM_END);
          } else {
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_COPYCONTENTS, postval,
               CURLFORM_CONTENTSLENGTH,(long)val.size(),
               CURLFORM_END);
          }
        }

        if (m_error_no != CURLE_OK) {
          return false;
        }

        m_to_free->post.push_back(first);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_HTTPPOST, first);

      } else {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS,
           but we have to provide size before */
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_COPYPOSTFIELDS,
                                      svalue.c_str());
#else
        char *post = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(post);

        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDS, post);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
#endif
      }
      break;
    case CURLOPT_HTTPHEADER:
    case CURLOPT_QUOTE:
    case CURLOPT_HTTP200ALIASES:
    case CURLOPT_POSTQUOTE:
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_slist *slist = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();

          slist = curl_slist_append(slist, val.c_str());
          if (!slist) {
            raise_warning("Could not build curl_slist");
            return false;
          }
        }

        m_to_free->slist.push_back(slist);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, slist);

      } else {
        raise_warning("You must pass either an object or an array with "
                      "the CURLOPT_HTTPHEADER, CURLOPT_QUOTE, "
                      "CURLOPT_HTTP200ALIASES and CURLOPT_POSTQUOTE "
                      "arguments");
        return false;
      }
      break;

    case CURLINFO_HEADER_OUT:
      if (value.toInt64() == 1) {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, curl_debug);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, (void *)this);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 1);
      } else {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, NULL);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, NULL);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 0);
      }
      break;

    default:
      m_error_no = CURLE_FAILED_INIT;
      throw_invalid_argument("option: %d", option);
      break;
    }

    m_opts.set(int64(option), value);

    return m_error_no == CURLE_OK;
  }
Example #30
0
/**
 * invokeHandler returns true if any autoload handlers were executed,
 * false otherwise. When this function returns true, it is the caller's
 * responsibility to check if the given class or interface exists.
 */
bool AutoloadHandler::invokeHandler(const String& className,
                                    bool forceSplStack /* = false */) {

  if (className.empty()) {
    return false;
  }

  if (!m_map.isNull()) {
    ClassExistsChecker ce;
    Result res = loadFromMap(className, s_class, true, ce);
    if (res == ContinueAutoloading) {
      if (ce(className)) return true;
    } else {
      if (res != Failure) return res == Success;
    }
  }
  // If we end up in a recursive autoload loop where we try to load the
  // same class twice, just fail the load to mimic PHP as many frameworks
  // rely on it unless we are forcing a restart (due to spl_autoload_call)
  // in which case autoload is allowed to be reentrant.
  if (!forceSplStack) {
    if (m_loading.exists(className)) { return false; }
    m_loading.add(className, className);
  } else {
    // We can still overflow the stack if there is a loop when using
    // spl_autoload_call directly, but this behavior matches the reference
    // implementation.
    m_loading.append(className);
  }

  // Make sure state is cleaned up from this load; autoloading of arbitrary
  // code below can throw
  SCOPE_EXIT {
    String l_className = m_loading.pop();
    assert(l_className == className);
  };

  Array params = PackedArrayInit(1).append(className).toArray();
  if (!m_spl_stack_inited && !forceSplStack) {
    if (function_exists(s___autoload)) {
      invoke(s___autoload, params, -1, true, false);
      return true;
    }
    return false;
  }
  if (!m_spl_stack_inited || m_handlers.empty()) {
    return false;
  }
  Object autoloadException;
  for (const HandlerBundle& hb : m_handlers) {
    try {
      vm_call_user_func_cufiter(*hb.m_cufIter, params);
    } catch (Object& ex) {
      assert(ex.instanceof(SystemLib::s_ExceptionClass));
      if (autoloadException.isNull()) {
        autoloadException = ex;
      } else {
        Object cur = ex;
        Variant next = cur->o_get(s_previous, false, s_exception);
        while (next.isObject()) {
          cur = next.toObject();
          next = cur->o_get(s_previous, false, s_exception);
        }
        cur->o_set(s_previous, autoloadException, s_exception);
        autoloadException = ex;
      }
    }
    if (Unit::lookupClass(className.get()) != nullptr) {
      break;
    }
  }
  if (!autoloadException.isNull()) {
    throw autoloadException;
  }
  return true;
}