void submitLoginPage(HTTPSClientSession& clientSession, NameValueCollection& cookies) { HTTPRequest request(HTTPRequest::HTTP_POST, "/royalgreenwich/sessions", HTTPMessage::HTTP_1_1); request.setCookies(cookies); HTTPResponse response; HTMLForm loginForm; loginForm.add("barcode", "28028005913354"); loginForm.add("pin", "3347"); loginForm.prepareSubmit(request); std::ostream& ostr = clientSession.sendRequest(request); loginForm.write(ostr); std::istream& rs = clientSession.receiveResponse(response); int statusCode = response.getStatus(); poco_information_f1(logger(), "Status %d", statusCode); std::vector<HTTPCookie> newCookies; response.getCookies(newCookies); for (HTTPCookie cookie : newCookies) { poco_information_f1(logger(), "Cookie %s", cookie.toString()); if (cookies.has(cookie.getName())) { cookies.set(cookie.getName(), cookie.getValue()); } else { cookies.add(cookie.getName(), cookie.getValue()); } } }
int main(int argc, char **argv) { // using `web` as provider URI uri("https://yboss.yahooapis.com/ysearch/web?q=cat"); // init the creds, I think the empty token and token secret are important OAuth10Credentials creds( "dj0yJmk9eGx5RzFQOVAwcDZpJmQ9WVdrOWVVUkhWamhwTkdVbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wYw--", "2bf8a4682c4948fb4f7add9598eef5f86b57cf93", "", ""); HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPathEtc()); // put the `q` as param HTMLForm params; params.set("q", "cat"); creds.authenticate(request, uri, params); std::string auth = request.get("Authorization"); std::cout << auth << std::endl; const Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); HTTPSClientSession session(uri.getHost(), uri.getPort(), context); session.sendRequest(request); HTTPResponse response; std::istream& rs = session.receiveResponse(response); std::cout << response.getStatus() << " " << response.getReason() << std::endl; StreamCopier::copyStream(rs, std::cout); return 0; }
HTMLEventStatus HTMLInputReset::DefaultEvent(HTMLEvent *pEvent) { HTMLEvent e; HTMLForm *pForm = Form(); HTMLDocument *pDoc = GetDocument(); int x = pEvent->data.position.x, y = pEvent->data.position.y; WebKey key; WEBC_DEBUG_ReceiveEvent(this, pEvent); switch (pEvent->type) { case HTML_EVENT_CLICK: if (pForm) { e.type = HTML_EVENT_RESET; e.data.position.x = x; e.data.position.y = y; e.elem = (HELEMENT_HANDLE)this; return (pForm->Event(&e)); } return (HTML_EVENT_STATUS_DONE); case HTML_EVENT_KEYDOWN: { HTMLEventStatus retval = DefaultInputKeyHandler(pEvent); if (retval != HTML_EVENT_STATUS_CONTINUE) { return (retval); } break; } case HTML_EVENT_KEYPRESS: key = pEvent->data.key; if (pForm && key == '\r') { e.type = HTML_EVENT_RESET; e.data.position.x = x; e.data.position.y = y; e.elem = (HELEMENT_HANDLE)this; HTMLEventStatus status = pForm->Event(&e); if (status == HTML_EVENT_STATUS_HALT) { return (status); } return (HTML_EVENT_STATUS_CONTINUE); } break; default: // ignore other event types break; } return (HTMLInputButton::DefaultEvent(pEvent)); }
void BundleInstallHandler::run() { ServiceRef::Ptr pInstallerRef = context()->registry().findByName(BundleInstallerService::SERVICE_NAME); AutoPtr<BundleInstallerService> pInstaller = pInstallerRef->castedInstance<BundleInstallerService>(); HTMLForm form; InstallPartHandler partHandler(form, pInstaller); form.load(request(), request().stream(), partHandler); std::string title; std::string backLink; std::string backLinkTitle; std::string symbolicName = form.get("symbolicName", ""); if (!symbolicName.empty()) { Bundle::Ptr pBundle = context()->findBundle(symbolicName); title = text("upgradeBundle"); title += ": "; title += symbolicName; backLink = bundlePath(symbolicName); backLinkTitle = text("bundle"); backLinkTitle += ": "; backLinkTitle += pBundle->name(); } else { title = text("installBundle"); backLink = bundle()->properties().getString("web.path"); backLinkTitle = text("installedBundles"); } beginPage(title, backLink, backLinkTitle); if (partHandler.installed()) { templat().clear(); templat().setString("symbolicName", partHandler.bundle()->symbolicName()); templat().setString("name", partHandler.bundle()->name()); sendTemplate("html.installComplete"); beginList(); item(text("id"), NumberFormatter::format(partHandler.bundle()->id())); item(text("symbolicName"), partHandler.bundle()->symbolicName()); item(text("version"), partHandler.bundle()->version().toString()); item(text("path"), partHandler.bundle()->path()); endList(); } else if (symbolicName.empty()) { sendTemplate("html.installForm"); } else { templat().clear(); templat().setString("symbolicName", symbolicName); sendTemplate("html.upgradeForm"); } endPage(); }
void HTMLFormTest::testSubmit2() { HTMLForm form; form.set("field1", "value1"); form.set("field2", "value 2"); form.set("field3", "value=3"); form.set("field4", "value&4"); HTTPRequest req("POST", "/form.cgi"); form.prepareSubmit(req); assert (req.getContentType() == HTMLForm::ENCODING_URL); }
void HTMLFormTest::testSubmit1() { HTMLForm form; form.set("field1", "value1"); form.set("field2", "value 2"); form.set("field3", "value=3"); form.set("field4", "value&4"); HTTPRequest req("GET", "/form.cgi"); form.prepareSubmit(req); assert (req.getURI() == "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); }
void HTMLFormTest::testWriteUrl() { HTMLForm form; form.set("field1", "value1"); form.set("field2", "value 2"); form.set("field3", "value=3"); form.set("field4", "value&4"); form.set("field5", "value+5"); std::ostringstream ostr; form.write(ostr); std::string s = ostr.str(); assert (s == "field1=value1&field2=value%202&field3=value%3D3&field4=value%264&field5=value%2B5"); }
void HTMLFormTest::testFieldLimitUrl() { HTTPRequest req("GET", "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); HTMLForm form; form.setFieldLimit(3); try { form.load(req); fail("field limit violated - must throw"); } catch (Poco::Net::HTMLFormException&) { } }
void HTMLFormTest::testFieldLimitMultipart() { std::istringstream istr( "\r\n" "--MIME_boundary_0123456789\r\n" "Content-Disposition: form-data; name=\"field1\"\r\n" "\r\n" "value1\r\n" "--MIME_boundary_0123456789\r\n" "Content-Disposition: form-data; name=\"field2\"\r\n" "\r\n" "value 2\r\n" "--MIME_boundary_0123456789\r\n" "Content-Disposition: form-data; name=\"field3\"\r\n" "\r\n" "value=3\r\n" "--MIME_boundary_0123456789\r\n" "Content-Disposition: form-data; name=\"field4\"\r\n" "\r\n" "value&4\r\n" "--MIME_boundary_0123456789\r\n" "Content-Disposition: file; name=\"attachment1\"; filename=\"att1.txt\"\r\n" "Content-Type: text/plain\r\n" "\r\n" "This is an attachment\r\n" "--MIME_boundary_0123456789--\r\n" ); HTTPRequest req("POST", "/form.cgi"); req.setContentType(HTMLForm::ENCODING_MULTIPART + "; boundary=\"MIME_boundary_0123456789\""); StringPartHandler sah; HTMLForm form; form.setFieldLimit(3); try { form.load(req, istr, sah); fail("field limit violated - must throw"); } catch (Poco::Net::HTMLFormException&) { } }
//------------------------------------------------------------- string API::doUpload( string image ){ if ( !bAuthenticated ){ ofLogWarning( "Not authenticated! Please call authenticate() with proper api key and secret" ); return ""; } else if ( currentPerms != FLICKR_WRITE ){ ofLogWarning( "You do not have proper permissions to upload! Please call authenticate() with permissions of ofxFlickr::FLICKR_WRITE" ); return ""; } map<string,string> args; args["api_key"] = api_key; args["auth_token"] = auth_token; string result; FilePartSource * fps = new FilePartSource(image, "image/jpeg"); try { // prepare session const URI uri( "https://" + api_base ); HTTPSClientSession session( uri.getHost(), uri.getPort() ); HTTPRequest req(HTTPRequest::HTTP_POST, "/services/upload/", HTTPMessage::HTTP_1_0); req.setContentType("multipart/form-data"); // setup form HTMLForm form; form.set("api_key", api_key); form.set("auth_token", auth_token); form.set("api_sig", apiSig( args )); form.setEncoding(HTMLForm::ENCODING_MULTIPART); form.addPart("photo", fps); form.prepareSubmit(req); std::ostringstream oszMessage; form.write(oszMessage); std::string szMessage = oszMessage.str(); req.setContentLength((int) szMessage.length() ); //session.setKeepAlive(true); // send form ostream & out = session.sendRequest(req) << szMessage; // get response HTTPResponse res; cout << res.getStatus() << " " << res.getReason() << endl; // print response istream &is = session.receiveResponse(res); StreamCopier::copyToString(is, result); } catch (Exception &ex) { cerr << "error? " + ex.displayText() <<endl; } string photoid; ofxXmlSettings xml; xml.loadFromBuffer(result); xml.pushTag("rsp");{ photoid = xml.getValue("photoid", ""); }; xml.popTag(); return photoid; }
HTMLEventStatus HTMLInputPassword::DefaultEvent(HTMLEvent *pEvent) // tbd { WEBC_UINT8 onlyBox = 1; WEBC_UINT8 hasSubmit = 0; HTMLElement *pElem = 0; HTMLInput *pSubmit = 0; vector_iterator it; WEBC_DEBUG_ReceiveEvent(this, pEvent); switch (pEvent->type) { case HTML_EVENT_CHANGE: break; case HTML_EVENT_EDIT: { HTMLForm *pForm = Form(); if (pForm) { pElem = (HTMLElement*)ObjectListGetFirst(pForm->GetFieldVector(), &it); while (pElem) { if ( (pElem->Type() == HTML_EDIT_STR_ELEMENT || pElem->Type() == HTML_EDITBOX_ELEMENT) && pElem != this) { onlyBox = 0; break; } if (pElem->Type() == HTML_BUTTON_ELEMENT && !hasSubmit) { hasSubmit = 1; pSubmit = (HTMLInput *)pElem; } pElem = (HTMLElement*)ObjectListGetNext(&it); } if (pSubmit && onlyBox) { HTMLEvent e; e.type = HTML_EVENT_SUBMIT; e.data.position.x = pEvent->data.position.x; e.data.position.y = pEvent->data.position.y; e.elem = (HELEMENT_HANDLE)pSubmit; return (pForm->Event(&e)); } } break; } case HTML_EVENT_FOCUS: { HTMLSetFlagFinder f(HELEM_FLAG_HAS_FOCUS, 1); FindElement(&f); SetFlag(HINPUT_FLAG_ACTIVE); Update(0,0); break; } case HTML_EVENT_UNFOCUS: { HTMLSetFlagFinder f(HELEM_FLAG_HAS_FOCUS, 0); FindElement(&f); ClearFlag(HINPUT_FLAG_ACTIVE); Update(0,0); break; } case HTML_EVENT_KEYDOWN: { HTMLEventStatus retval = DefaultInputKeyHandler(pEvent); if (retval != HTML_EVENT_STATUS_CONTINUE) { return (retval); } switch (pEvent->data.key) { case WGK_LNDN: case WGK_LNUP: case WGK_LEFT: case WGK_RIGHT: pEvent->flags |= HTML_EVENT_FLAG_CANCEL_BUBBLE; break; } break; } default: break; } return (HTMLInput::DefaultEvent(pEvent)); }
// ---------------------------------------------------------------------- ofxHttpResponse ofxHttpUtils::doPostForm(ofxHttpForm & form){ ofxHttpResponse response; try{ URI uri( form.action.c_str() ); std::string path(uri.getPathAndQuery()); if (path.empty()) path = "/"; //HTTPClientSession session(uri.getHost(), uri.getPort()); HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); if(auth.getUsername()!="") auth.authenticate(req); if(sendCookies){ for(unsigned i=0; i<cookies.size(); i++){ NameValueCollection reqCookies; reqCookies.add(cookies[i].getName(),cookies[i].getValue()); req.setCookies(reqCookies); } } for (unsigned int i = 0; i < form.headerIds.size(); ++i) { const std::string name = form.headerIds[i].c_str(); const std::string val = form.headerValues[i].c_str(); req.set(name, val); } HTTPResponse res; HTMLForm pocoForm; // create the form data to send if(form.formFiles.size()>0) { pocoForm.setEncoding(HTMLForm::ENCODING_MULTIPART); } else { pocoForm.setEncoding(HTMLForm::ENCODING_URL); } // form values for(unsigned i=0; i<form.formIds.size(); i++){ const std::string name = form.formIds[i].c_str(); const std::string val = form.formValues[i].c_str(); pocoForm.set(name, val); } map<string,string>::iterator it; for(it = form.formFiles.begin(); it!=form.formFiles.end(); it++){ string fileName = it->second.substr(it->second.find_last_of('/')+1); ofLogVerbose("ofxHttpUtils") << "adding file: " << fileName << " path: " << it->second; pocoForm.addPart(it->first,new FilePartSource(it->second)); } pocoForm.prepareSubmit(req); ofPtr<HTTPSession> session; istream * rs; if(uri.getScheme()=="https"){ HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context); httpsSession->setTimeout(Poco::Timespan(20,0)); pocoForm.write(httpsSession->sendRequest(req)); rs = &httpsSession->receiveResponse(res); session = ofPtr<HTTPSession>(httpsSession); }else{ HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort()); httpSession->setTimeout(Poco::Timespan(20,0)); pocoForm.write(httpSession->sendRequest(req)); rs = &httpSession->receiveResponse(res); session = ofPtr<HTTPSession>(httpSession); } response = ofxHttpResponse(res, *rs, form.action); if(sendCookies){ cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end()); } if(response.status>=300 && response.status<400){ Poco::URI uri(req.getURI()); uri.resolve(res.get("Location")); response.location = uri.toString(); } ofNotifyEvent(newResponseEvent, response, this); }catch (Exception& exc){ ofLogError("ofxHttpUtils") << "ofxHttpUtils error doPostForm -- " << form.action.c_str(); //ofNotifyEvent(notifyNewError, "time out", this); // for now print error, need to broadcast a response ofLogError("ofxHttpUtils") << exc.displayText(); response.status = -1; response.reasonForStatus = exc.displayText(); ofNotifyEvent(newResponseEvent, response, this); } return response; }
ofxHttpResponse ofxURLFileLoader::handleRequest(ofxHttpRequest request) { try { URI uri(request.url); std::string path(uri.getPathAndQuery()); if (path.empty()) path = "/"; HTTPClientSession session(uri.getHost(), uri.getPort()); string method; switch (request.method) { case HTTP_METHOD_GET: method = HTTPRequest::HTTP_GET; break; case HTTP_METHOD_POST: method = HTTPRequest::HTTP_POST; break; default: method = HTTPRequest::HTTP_GET; break; } HTTPRequest req(method, path, HTTPMessage::HTTP_1_1); session.setTimeout(Poco::Timespan(20,0)); if (!request.cookies.empty()) { NameValueCollection mvc; // cout << "request cookies:" << endl; for (vector<pair<string,string> >::iterator iter = request.cookies.begin();iter!=request.cookies.end();iter++) { mvc.add(iter->first, iter->second); // cout << iter->first << ": " << iter->second << endl; } req.setCookies(mvc); } if (request.nvc.empty() & request.files.empty()) { session.sendRequest(req); } else { HTMLForm pocoForm; // create the form data to send if(request.files.size()>0) pocoForm.setEncoding(HTMLForm::ENCODING_MULTIPART); else pocoForm.setEncoding(HTMLForm::ENCODING_URL); // form values for(unsigned i=0; i<request.nvc.size(); i++){ const std::string name = request.nvc[i].first.c_str(); const std::string val = request.nvc[i].second.c_str(); pocoForm.set(name, val); } map<string,string>::iterator it; for(it = request.files.begin(); it!=request.files.end(); it++){ string fileName = it->second.substr(it->second.find_last_of('/')+1); cout << "adding file: " << fileName << " path: " << it->second << endl; pocoForm.addPart(it->first,new FilePartSource(it->second)); } pocoForm.prepareSubmit(req); pocoForm.write(session.sendRequest(req)); } HTTPResponse res; istream& rs = session.receiveResponse(res); vector<HTTPCookie> pocoCookies; res.getCookies(pocoCookies); vector<pair<string,string> > cookies; // res.write(cout); for (vector<HTTPCookie>::iterator iter=pocoCookies.begin();iter!=pocoCookies.end();iter++) { cookies.push_back(make_pair(iter->getName(), iter->getValue())); } if(!request.saveTo){ return ofxHttpResponse(request,cookies,rs,res.getStatus(),res.getReason()); }else{ ofFile saveTo(request.name,ofFile::WriteOnly); char aux_buffer[1024]; rs.read(aux_buffer, 1024); std::streamsize n = rs.gcount(); while (n > 0){ // we resize to size+1 initialized to 0 to have a 0 at the end for strings saveTo.write(aux_buffer,n); if (rs){ rs.read(aux_buffer, 1024); n = rs.gcount(); } else n = 0; } return ofxHttpResponse(request,cookies,res.getStatus(),res.getReason()); } } catch (Exception& exc) { ofLog(OF_LOG_ERROR, "ofxURLFileLoader " + exc.displayText()); return ofxHttpResponse(request,-1,exc.displayText()); } }
void HTTPHandler::processQuery( Poco::Net::HTTPServerRequest & request, HTMLForm & params, Poco::Net::HTTPServerResponse & response, Output & used_output) { Context context = server.context(); context.setGlobalContext(server.context()); CurrentThread::QueryScope query_scope(context); LOG_TRACE(log, "Request URI: " << request.getURI()); std::istream & istr = request.stream(); /// Part of the query can be passed in the 'query' parameter and the rest in the request body /// (http method need not necessarily be POST). In this case the entire query consists of the /// contents of the 'query' parameter, a line break and the request body. std::string query_param = params.get("query", ""); if (!query_param.empty()) query_param += '\n'; /// The user and password can be passed by headers (similar to X-Auth-*), /// which is used by load balancers to pass authentication information. std::string user = request.get("X-ClickHouse-User", ""); std::string password = request.get("X-ClickHouse-Key", ""); std::string quota_key = request.get("X-ClickHouse-Quota", ""); if (user.empty() && password.empty() && quota_key.empty()) { /// User name and password can be passed using query parameters /// or using HTTP Basic auth (both methods are insecure). if (request.hasCredentials()) { Poco::Net::HTTPBasicCredentials credentials(request); user = credentials.getUsername(); password = credentials.getPassword(); } else { user = params.get("user", "default"); password = params.get("password", ""); } quota_key = params.get("quota_key", ""); } else { /// It is prohibited to mix different authorization schemes. if (request.hasCredentials() || params.has("user") || params.has("password") || params.has("quota_key")) { throw Exception("Invalid authentication: it is not allowed to use X-ClickHouse HTTP headers and other authentication methods simultaneously", ErrorCodes::REQUIRED_PASSWORD); } } std::string query_id = params.get("query_id", ""); context.setUser(user, password, request.clientAddress(), quota_key); context.setCurrentQueryId(query_id); /// The user could specify session identifier and session timeout. /// It allows to modify settings, create temporary tables and reuse them in subsequent requests. std::shared_ptr<Context> session; String session_id; std::chrono::steady_clock::duration session_timeout; bool session_is_set = params.has("session_id"); const auto & config = server.config(); if (session_is_set) { session_id = params.get("session_id"); session_timeout = parseSessionTimeout(config, params); std::string session_check = params.get("session_check", ""); session = context.acquireSession(session_id, session_timeout, session_check == "1"); context = *session; context.setSessionContext(*session); } SCOPE_EXIT({ if (session_is_set) session->releaseSession(session_id, session_timeout); });
// ---------------------------------------------------------------------- int ofxHttpUtils::doPostForm(ofxHttpForm & form){ int ret = -1; try{ URI uri( form.action.c_str() ); std::string path(uri.getPathAndQuery()); if (path.empty()) path = "/"; HTTPClientSession session(uri.getHost(), uri.getPort()); HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); if(auth.getUsername()!="") auth.authenticate(req); if(sendCookies){ for(unsigned i=0; i<cookies.size(); i++){ NameValueCollection reqCookies; reqCookies.add(cookies[i].getName(),cookies[i].getValue()); req.setCookies(reqCookies); } } HTMLForm pocoForm; // create the form data to send if(form.formFiles.size()>0) pocoForm.setEncoding(HTMLForm::ENCODING_MULTIPART); else pocoForm.setEncoding(HTMLForm::ENCODING_URL); // form values for(unsigned i=0; i<form.formIds.size(); i++){ const std::string name = form.formIds[i].c_str(); const std::string val = form.formValues[i].c_str(); pocoForm.set(name, val); } map<string,string>::iterator it; for(it = form.formFiles.begin(); it!=form.formFiles.end(); it++){ string fileName = it->second.substr(it->second.find_last_of('/')+1); cout << "adding file: " << fileName << " path: " << it->second << endl; pocoForm.addPart(it->first,new FilePartSource(it->second)); } pocoForm.prepareSubmit(req); pocoForm.write(session.sendRequest(req)); HTTPResponse res; istream& rs = session.receiveResponse(res); ofxHttpResponse response = ofxHttpResponse(res, rs, path); if(sendCookies){ cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end()); } ofNotifyEvent(newResponseEvent, response, this); ret = 0; }catch (Exception& exc){ printf("ofxHttpUtils error--\n"); //ofNotifyEvent(notifyNewError, "time out", this); // for now print error, need to broadcast a response std::cerr << exc.displayText() << std::endl; } return ret; }
/** * HTMLCollection item(long) method * * param - index - the index of the element to get * return - the HTMLElement at index */ JSBool jhtml_collection_item(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { int index; int32 dIndex = 0; WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx); WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0; if (!jsmgr) { return JS_FALSE; } HTMLDocument *pDoc = jsmgr->GetDocument(); if (!pDoc) { return JS_FALSE; } //if we have at least 1 argument and it is a number if (argc > 0 && JSVAL_IS_INT(argv[0])) { //convert the jsval to a number JS_ValueToInt32(cx, argv[0], &dIndex); index = (int)dIndex; HTMLElementType ele_type = HTML_ELEMENT_NONE; jhtml_collection *pColl = (jhtml_collection*)jhutil_GetPrivate(cx, obj); if (!pColl) { return JS_FALSE; } HTMLElement *pElem = 0; switch(pColl->finderType) { case DOCUMENT_IMAGES: ele_type = HTML_IMAGE_ELEMENT; break; case DOCUMENT_ANCHORS: ele_type = HTML_ANCHOR_ELEMENT; break; case TABLE_ROWS: ele_type = HTML_TABLE_ROW_ELEMENT; break; case TABLEROW_CELLS: ele_type = HTML_TABLE_CELL_ELEMENT; break; case MAP_AREAS: ele_type = HTML_AREA_ELEMENT; break; case SELECT_OPTIONS: ele_type = HTML_OPTION_ELEMENT; break; case WIN_FRAMES: { *rval = JSVAL_NULL; #if (WEBC_SUPPORT_FRAMES) HTMLNthOfTypeFinder finder(HTML_FRAME_ELEMENT, index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); if (pElem) { HTMLFrame *pFrame = (HTMLFrame *) pElem; if (pFrame->FrameDocument() && pFrame->FrameDocument()->GetJSMgr()) { *rval = OBJECT_TO_JSVAL(pFrame->FrameDocument()->GetJSMgr()->GetGlobalObject()); } } #endif // WEBC_SUPPORT_FRAMES return JS_TRUE; } case ELEMENT_NODES: { HTMLNthOfAnyTypeFinder finder(index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_NODES_DEFAULT); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case DOCUMENT_FORMS: { HTMLElementTypeFinder formFinder(HTML_FORM_ELEMENT); HTMLNthElementFinder nthFormFinder(&formFinder, index); pElem = pDoc->FindElement(&nthFormFinder); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case DOCUMENT_IDS: { HTMLNthOfAnyTypeFinder finder(index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case DOCUMENT_ALL: { HTMLNthOfAnyTypeFinder finder(index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case ALL_BY_NAME: { //get the nth item with name... HTMLNthByNameFinder finder(pColl->nameOfAll, index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case ALL_TAGS_BY_TAGNAME: { //get the nth item with the specified tag name... HTMLTagType hType = HTML_ParseTagType(pColl->nameOfAll, webc_strlen(pColl->nameOfAll)); HTMLElementType eType = TagToHTMLElementType[hType]; HTMLNthOfTypeFinder finder(eType, index); pElem = pColl->pTop->FindElement(&finder, 1, WEBC_FALSE); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } case FORM_INPUTS: { //for this type of collection, the top will always be of type form HTMLForm *form = (HTMLForm *)pColl->pTop; if (form) { pElem = jutils_GetNthOfObjectList(form->GetFieldVector(), index, _matchInput, 0); if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; } break; } case DOCUMENT_STYLESHEETS: { #if (WEBC_SUPPORT_STYLE_SHEETS) //GMP this needs to be revisited if CSS is changed to have more than 1 style sheet *rval = OBJECT_TO_JSVAL(pDoc->GetCSSContext()->GetJSObject()); #else *rval = JSVAL_NULL; #endif return JS_TRUE; } case SSHEET_RULES: { #if (WEBC_SUPPORT_STYLE_SHEETS) /*int i = 0; CSSDocumentContext *pCSSCx = pDoc->GetCSSContext(); if (pCSSCx) { vector_iterator pvi[1]; CSSPropertyDescriptor *pCSSPD = pCSSCx->EnumFirstProperty(pvi); while(pCSSPD) { if ( i == index) { *rval = OBJECT_TO_JSVAL(pCSSPD->GetJSObject()); return JS_TRUE; } i++; pCSSPD = pCSSCx->EnumNextProperty(pvi); } }*/ #endif // (WEBC_SUPPORT_STYLE_SHEETS) return JS_TRUE; } case RADIO_BUTTONS: { HTMLRadioButton *pRadio = (HTMLRadioButton*)pColl->pTop; while (index > 0) { index--; pRadio = (pRadio->mpGroupNext != pColl->pTop) ? pRadio->mpGroupNext : 0; } if (pRadio) { *rval = OBJECT_TO_JSVAL(pRadio->CreateJSObject()); return JS_TRUE; } } break; }//end switch if (ele_type != HTML_ELEMENT_NONE) { HTMLNthOfTypeFinder finder(ele_type, index); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); } if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } else { *rval = JSVAL_NULL; } return JS_TRUE; }//end if else if (argc > 0 && JSVAL_IS_STRING(argv[0])) { //MSIE allows for the item method to take a srting that corresponds to the name //therefore we call namedItem instead return jhtml_collection_namedItem(cx, obj, argc, argv, rval); } *rval = JSVAL_NULL; return JS_TRUE; }
/** * HTMLCollection namedItem(long) method * * param - name - the name of the element to get * return - the first htmlelement in the tree with the given name */ JSBool jhtml_collection_namedItem(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx); WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0; if (!jsmgr) { return JS_FALSE; } HTMLDocument *pDoc = jsmgr->GetDocument(); if (!pDoc) { return JS_FALSE; } HTMLElementType ele_type = HTML_ELEMENT_NONE; //if we have atleast one argument and it is a string if (argc > 0 && JSVAL_IS_STRINGABLE(argv[0])) { //conver the JSString to char * WEBC_CHAR *name = WEBC_JS_STRING_TO_WEBC_STRING(JS_ValueToString(cx, argv[0])); if (!name || !(*name)) { *rval = JSVAL_NULL; return JS_TRUE;; } if (webc_c_stricmp(name, "toString")==0) { return JS_TRUE; } jhtml_collection *pColl = (jhtml_collection*)jhutil_GetPrivate(cx, obj); if (!pColl) return JS_TRUE; HTMLElement *pElem = 0; switch(pColl->finderType) { case DOCUMENT_IMAGES: ele_type = HTML_IMAGE_ELEMENT; break; case DOCUMENT_ANCHORS: ele_type = HTML_ANCHOR_ELEMENT; break; case TABLE_ROWS: ele_type = HTML_TABLE_ROW_ELEMENT; break; case TABLEROW_CELLS: ele_type = HTML_TABLE_CELL_ELEMENT; break; case MAP_AREAS: ele_type = HTML_AREA_ELEMENT; break; case SELECT_OPTIONS: ele_type = HTML_OPTION_ELEMENT; break; case WIN_FRAMES: { #if (WEBC_SUPPORT_FRAMES) HTMLTypeAndNameOrIdFinder finder(name, HTML_FRAME_ELEMENT); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); if (pElem) { HTMLFrame *pFrame = (HTMLFrame *) pElem; if (pFrame->FrameDocument() && pFrame->FrameDocument()->GetJSMgr()) { *rval = OBJECT_TO_JSVAL(pFrame->FrameDocument()->GetJSMgr()->GetGlobalObject()); return JS_TRUE; } } *rval = JSVAL_NULL; #endif // WEBC_SUPPORT_FRAMES return JS_TRUE; } case DOCUMENT_FORMS: { WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx); WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0; if (jsmgr) { HTMLNameOrIdFinder nameFinder(name); HTMLElementTypeFinder formFinder(HTML_FORM_ELEMENT); HTMLElementAndFinder formNameFinder(&nameFinder, &formFinder); HTMLDocument *pDoc = jsmgr->GetDocument(); pElem = pDoc->FindElement(&formNameFinder); } break; } case DOCUMENT_ALL: { HTMLNameOrIdFinder finder(name); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); break; } case DOCUMENT_IDS: { HTMLNameOrIdFinder finder(name); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); break; } case ALL_BY_NAME: { HTMLElementByNameFinder finder(name); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); break; } case ALL_TAGS_BY_TAGNAME: { if(pColl && pColl->nameOfAll) { HTMLTagType hType = HTML_ParseTagType(pColl->nameOfAll, webc_strlen(pColl->nameOfAll)); HTMLElementType eType = TagToHTMLElementType[hType]; HTMLNameTypeFinder finder(name, eType); // TODO this should probably restrict to a specific tag name pElem = pColl->pTop->FindElement(&finder, 1, WEBC_FALSE); } break; } case ELEMENT_NODES: { HTMLNameOrIdFinder finder(name); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_NODES_DEFAULT); break; } case FORM_INPUTS: { //for this type of collection, the top will always be of type form HTMLForm *form = (HTMLForm *)pColl->pTop; if (form && name && *name) { pElem = jutils_CheckObjectList(form->GetFieldVector(), _matchInputByNameOrId, (WEBC_PFBYTE)name); }//end if break; } case DOCUMENT_STYLESHEETS: { #if (WEBC_SUPPORT_STYLE_SHEETS) //GMP this needs to be revisited if CSS is changed to have more than 1 style sheet #endif break; } case SSHEET_RULES: { #if (WEBC_SUPPORT_STYLE_SHEETS) CSSDocumentContext *pCSSCx= pDoc->GetCSSContext(); /* if (pCSSCx) { int i = 0; vector_iterator pvi[1]; CSSPropertyDescriptor * pCSSPD = pCSSCx->EnumFirstProperty(pvi); while (pCSSPD) { char *cName = pCSSPD->EnumFirstClass(); while (cName) { if (tc_stricmp(cName, name) == 0) { *rval = OBJECT_TO_JSVAL(pCSSPD->GetJSObject()); return JS_TRUE; } pCSSPD->EnumNextClass(); } pCSSPD = pCSSCx->EnumNextProperty(pvi); } }*/ #endif //(WEBC_SUPPORT_STYLE_SHEETS) return JS_TRUE; } case RADIO_BUTTONS: { HTMLRadioButton *pRadio = (HTMLRadioButton *) pColl->pTop; if (name) { while (pRadio && pRadio->Value() && webc_stricmp(name, pRadio->Value())) { pRadio = (pRadio->mpGroupNext != pColl->pTop)? pRadio->mpGroupNext : 0; } } if (pRadio) { *rval = OBJECT_TO_JSVAL(pRadio->CreateJSObject()); return JS_TRUE; } break; } default: break; }//end switch if (ele_type != HTML_ELEMENT_NONE) { HTMLTypeAndNameOrIdFinder finder(name, ele_type); pElem = pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); } if (pElem) { *rval = OBJECT_TO_JSVAL(pElem->CreateJSObject()); } return JS_TRUE; }//end if *rval = JSVAL_NULL; return JS_TRUE; }
/** * Call this method when getting a Property from HTMLCollection */ static JSBool jhtml_collection_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx); WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0; if (!jsmgr) { return JS_FALSE; } HTMLDocument *pDoc = jsmgr->GetDocument(); jhtml_collection *pColl = (jhtml_collection *)jhutil_GetPrivate(cx, obj); if (!pColl) return JS_TRUE; switch (JSVAL_TO_INT(id)) { //if we are looking for the element length case HTMLCOLLECTION_LENGTH: { if (pColl->finderType) { HTMLElementType ele_type = HTML_ELEMENT_NONE; //switch on the type of collection this is switch(pColl->finderType) { //these cases can use the HTMLCountByType Finder, and therefore //just set the ele_type and break case DOCUMENT_IMAGES: ele_type = HTML_IMAGE_ELEMENT; break; case DOCUMENT_ANCHORS: ele_type = HTML_ANCHOR_ELEMENT; break; case TABLE_ROWS: ele_type = HTML_TABLE_ROW_ELEMENT; break; case TABLEROW_CELLS: ele_type = HTML_TABLE_CELL_ELEMENT; break; case MAP_AREAS: ele_type = HTML_AREA_ELEMENT; break; case SELECT_OPTIONS: ele_type = HTML_OPTION_ELEMENT; break; case WIN_FRAMES: ele_type = HTML_FRAME_ELEMENT; break; case ELEMENT_NODES: { HTMLCountAllFinder finder; pColl->pTop->FindElement(&finder, 1, INCLUDE_SELF_NODES_DEFAULT); int count = finder.Length(); *vp = INT_TO_JSVAL(count); return JS_TRUE; } case DOCUMENT_FORMS: { WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx); WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0; //forms do not live in the document tree, therefore we must use //the form vector if (jsmgr) { HTMLElementTypeFinder f(HTML_FORM_ELEMENT); HTMLElementCounter fl(&f); jsmgr->GetDocument()->FindElement(&fl); int len = fl.Count(); *vp = INT_TO_JSVAL(len); return JS_TRUE; } return JS_FALSE; } case DOCUMENT_IDS: { HTMLCountAllFinder finder; pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); int count = finder.Length(); *vp = INT_TO_JSVAL(count); return JS_TRUE; } case DOCUMENT_ALL: { HTMLCountAllFinder finder; pColl->pTop->FindElement(&finder,1, INCLUDE_SELF_ELEMENT_DEFAULT); int count = finder.Length(); *vp = INT_TO_JSVAL(count); return JS_TRUE; } case ALL_BY_NAME: { if (!pColl->nameOfAll) { *vp = INT_TO_JSVAL(0); return JS_TRUE; } //this finder counts the total number of elements with the //name given by nameOfAll HTMLCountByNameFinder finder(pColl->nameOfAll); pColl->pTop->FindElement(&finder, 1, INCLUDE_SELF_ELEMENT_DEFAULT); int count = finder.Length(); *vp = INT_TO_JSVAL(count); return JS_TRUE; } case ALL_TAGS_BY_TAGNAME: { if (!pColl->nameOfAll) { *vp = INT_TO_JSVAL(0); return JS_TRUE; } // use this finder to count the total number of elements with the // type given by nameOfAll (misnomer) HTMLTagType hType = HTML_ParseTagType(pColl->nameOfAll, webc_strlen(pColl->nameOfAll)); HTMLElementType eType = TagToHTMLElementType[hType]; HTMLCountByTypeFinder finder(eType); pColl->pTop->FindElement(&finder, 1, WEBC_FALSE); // don't include myself in the search results int count = finder.Length(); *vp = INT_TO_JSVAL(count); return JS_TRUE; } case FORM_INPUTS: { //for this type of collection, the top will always be of type form HTMLForm *form = (HTMLForm *)pColl->pTop; int len = vector_get_size(form->GetFieldVector()); *vp = INT_TO_JSVAL(len); return JS_TRUE; } case DOCUMENT_STYLESHEETS: { //GMP this needs to be revisited if CSS is changed to have more than 1 style sheet *vp = INT_TO_JSVAL(1); return JS_TRUE; } case SSHEET_RULES: { #if (WEBC_SUPPORT_STYLE_SHEETS) CSSDocumentContext *pCSSCx= pDoc->GetCSSContext(); /* int i = 0; if (pCSSCx) { vector_iterator pvi[1]; CSSPropertyDescriptor * pCSSPD = pCSSCx->EnumFirstProperty(pvi); while (pCSSPD) { i++; pCSSPD = pCSSCx->EnumNextProperty(pvi); } } *vp = INT_TO_JSVAL(i);*/ #endif //(WEBC_SUPPORT_STYLE_SHEETS) return JS_TRUE; } case RADIO_BUTTONS: { int numRadioElems = 0; HTMLRadioButton *pRadio = (HTMLRadioButton*)pColl->pTop; while (pRadio) { numRadioElems++; pRadio = (pRadio->mpGroupNext != pColl->pTop) ? pRadio->mpGroupNext : 0; } *vp = INT_TO_JSVAL(numRadioElems); return JS_TRUE; } }//end inner switch if (ele_type != HTML_ELEMENT_NONE) { HTMLCountByTypeFinder finder(ele_type); pColl->pTop->FindElement(&finder, 1, INCLUDE_SELF_ELEMENT_DEFAULT); *vp = INT_TO_JSVAL(finder.Length()); } }//end if return JS_TRUE; }//end case length default: { //MSIE allows collections to be index like 'document.all.nameofelement' where //nameofelement is an element name in the document tree. It also allows //'document.all[4]' To account for that we call item on the element passed in. //which will call namedItem if the jsval passed is not an int. jhtml_collection_item(cx, obj, 1, &id, vp); break; } }//end switch return JS_TRUE; }