diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/BulkAPISampleFiles/delete.csv b/BulkAPISampleFiles/delete.csv new file mode 100644 index 0000000..9535358 --- /dev/null +++ b/BulkAPISampleFiles/delete.csv @@ -0,0 +1,5 @@ +Id +003E000001DJOfxIAH +003E000001DJOfyIAH +003E000001DJOV4IAP +003E000001DJOV5IAP \ No newline at end of file diff --git a/BulkAPISampleFiles/delete.xml b/BulkAPISampleFiles/delete.xml new file mode 100644 index 0000000..e644728 --- /dev/null +++ b/BulkAPISampleFiles/delete.xml @@ -0,0 +1,16 @@ + + + + + 003E000001DJOfxIAH + + + 003E000001DJOfyIAH + + + 003E000001DJOV4IAP + + + 003E000001DJOV5IAP + + \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.csv b/BulkAPISampleFiles/insert.csv new file mode 100644 index 0000000..31cb26a --- /dev/null +++ b/BulkAPISampleFiles/insert.csv @@ -0,0 +1,3 @@ +FirstName,LastName,Department,Birthdate,Description +Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast" +Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases." \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.xml b/BulkAPISampleFiles/insert.xml new file mode 100644 index 0000000..686ed5a --- /dev/null +++ b/BulkAPISampleFiles/insert.xml @@ -0,0 +1,17 @@ + + + + + Tom + Jones + Marketing + 1940-06-07Z + Self-described as "the top" branding guru on the West Coast + + + Ian + Dury + R&D + World-renowned expert in fuzzy logic design. Influential in technology purchases. + + \ No newline at end of file diff --git a/BulkAPISampleFiles/update.csv b/BulkAPISampleFiles/update.csv new file mode 100644 index 0000000..230ef1a --- /dev/null +++ b/BulkAPISampleFiles/update.csv @@ -0,0 +1,2 @@ +Id,Title +003E000001CbzBi,Ninja \ No newline at end of file diff --git a/BulkAPISampleFiles/update.xml b/BulkAPISampleFiles/update.xml new file mode 100644 index 0000000..8574c72 --- /dev/null +++ b/BulkAPISampleFiles/update.xml @@ -0,0 +1,8 @@ + + + + + 003E000001CbzBi + Pirate + + \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.csv b/BulkAPISampleFiles/upsert.csv new file mode 100644 index 0000000..5841c32 --- /dev/null +++ b/BulkAPISampleFiles/upsert.csv @@ -0,0 +1,2 @@ +Twitter_Handle__c,Title +pattest7,Guru \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.xml b/BulkAPISampleFiles/upsert.xml new file mode 100644 index 0000000..b942d57 --- /dev/null +++ b/BulkAPISampleFiles/upsert.xml @@ -0,0 +1,8 @@ + + + + + pattest7 + Pirate + + \ No newline at end of file diff --git a/BulkTK.md b/BulkTK.md new file mode 100644 index 0000000..a5eb38f --- /dev/null +++ b/BulkTK.md @@ -0,0 +1,137 @@ +BulkTK: Force.com Bulk API JavaScript Toolkit +============================================= + +This minimal toolkit extends ForceTK to allow JavaScript in web pages to call the [Force.com Bulk API](https://www.salesforce.com/us/developer/docs/api_asynch/). + +Background +========== + +The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK with methods to create Bulk API jobs, add batches to them, monitor job status and retrieve job results. Control plane XML is parsed to JavaScript objects for ease of use, while data is returned verbatim. + +You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. + +[bulk.page](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/bulk.page) is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. + +Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. + +Dependencies +============ + + * [jquery](http://jquery.com/) + * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) + * [jxon](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js) (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) project; this version preserves case in element and attribute names) + +Example Usage +============= + +This example focuses on Visualforce. See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +First, include BulkTK and its dependencies: + + + + + + +Now create a ForceTK client: + + var client = new forcetk.Client(); + client.setSessionToken('{!$Api.Session_ID}'); + +See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +Create a job +------------ + + // See https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_reference_jobinfo.htm + // for details of the JobInfo structure + + // Insert Contact records in CSV format + var job = { + operation : 'insert', + object : 'Contact', + contentType : 'CSV' + }; + + client.createJob(job, function(response) { + jobId = response.jobInfo.id; + console.log('Job created with id '+jobId+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error creating job', jqXHR.responseText); + }); + +Add a batch of records to the job +--------------------------------- + +You can add multiple batches to the job; each batch can contain up to 10,000 records. See [batch size and limits](https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_concepts_limits.htm#batch_size_title) for more details. + + var csvData = "FirstName,LastName,Department,Birthdate,Description\n"+ + "Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast\n"+ + "Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases."\n"; + + client.addBatch(jobId, "text/csv; charset=UTF-8", csvData, + function(response){ + console.log('Added batch '+response.batchInfo.id+'. State: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error adding batch', jqXHR.responseText); + }); + +See BulkAPISampleFiles for sample CSV and XML data for different operations. + +Close the job +------------- + +You must close the job to inform Salesforce that no more batches will be submitted for the job. + + client.closeJob(jobId, function(response){ + console.log('Job closed. State: '+response.jobInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error closing job', jqXHR.responseText); + }); + +Check batch status +------------------ + + client.getBatchDetails(jobId, batchId, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch details', jqXHR.responseText); + }); + +Get batch results +----------------- + +Pass `true` as the `parseXML` parameter to get batch results for a query, false otherwise. + + client.getBatchResult(jobId, batchId, false, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Bulk query +---------- + +When adding a batch to a bulk query job, the `contentType` for the request must be either `text/csv` or `application/xml`, depending on the content type specified when the job was created. The actual SOQL statement supplied for the batch will be in plain text format. + + var soql = 'SELECT Id, FirstName, LastName, Email FROM Contact'; + + client.addBatch(jobId, 'text/csv', soql, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Getting bulk query results is a two step process. Call `getBatchResult()` with `parseXML` set to `true` to get a set of result IDs, then call `getBulkQueryResult()` to get the actual records for each result + + client.getBatchResult(jobId, batchId, true, function(response){ + response['result-list'].result.forEach(function(resultId){ + client.getBulkQueryResult(jobId, batchId, resultId, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting bulk query results', jqXHR.responseText); + }); + }); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..522fa4a --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +# Comment line immediately above ownership line is reserved for related gus information. Please be careful while editing. +#ECCN:Open Source diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b4612a7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,105 @@ +# Salesforce Open Source Community Code of Conduct + +## About the Code of Conduct + +Equality is a core value at Salesforce. We believe a diverse and inclusive +community fosters innovation and creativity, and are committed to building a +culture where everyone feels included. + +Salesforce open-source projects are committed to providing a friendly, safe, and +welcoming environment for all, regardless of gender identity and expression, +sexual orientation, disability, physical appearance, body size, ethnicity, nationality, +race, age, religion, level of experience, education, socioeconomic status, or +other similar personal characteristics. + +The goal of this code of conduct is to specify a baseline standard of behavior so +that people with different social values and communication styles can work +together effectively, productively, and respectfully in our open source community. +It also establishes a mechanism for reporting issues and resolving conflicts. + +All questions and reports of abusive, harassing, or otherwise unacceptable behavior +in a Salesforce open-source project may be reported by contacting the Salesforce +Open Source Conduct Committee at ossconduct@salesforce.com. + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of gender +identity and expression, sexual orientation, disability, physical appearance, +body size, ethnicity, nationality, race, age, religion, level of experience, education, +socioeconomic status, or other similar personal characteristics. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy toward other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Personal attacks, insulting/derogatory comments, or trolling +* Public or private harassment +* Publishing, or threatening to publish, others' private information—such as +a physical or electronic address—without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* Advocating for or encouraging any of the above behaviors + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned with this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project email +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the Salesforce Open Source Conduct Committee +at ossconduct@salesforce.com. All complaints will be reviewed and investigated +and will result in a response that is deemed necessary and appropriate to the +circumstances. The committee is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement +policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership and the Salesforce Open Source Conduct +Committee. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][contributor-covenant-home], +version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html. +It includes adaptions and additions from [Go Community Code of Conduct][golang-coc], +[CNCF Code of Conduct][cncf-coc], and [Microsoft Open Source Code of Conduct][microsoft-coc]. + +This Code of Conduct is licensed under the [Creative Commons Attribution 3.0 License][cc-by-3-us]. + +[contributor-covenant-home]: https://www.contributor-covenant.org (https://www.contributor-covenant.org/) +[golang-coc]: https://golang.org/conduct +[cncf-coc]: https://github.com/cncf/foundation/blob/master/code-of-conduct.md +[microsoft-coc]: https://opensource.microsoft.com/codeofconduct/ +[cc-by-3-us]: https://creativecommons.org/licenses/by/3.0/us/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..9ba9791 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,14 @@ +BSD 3-Clause License + +Copyright (c) 2022 Salesforce, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.markdown b/README.markdown index 4812c6c..b72c733 100644 --- a/README.markdown +++ b/README.markdown @@ -1,19 +1,60 @@ +> [!WARNING] +> This project is deprecated, use [JSforce](https://jsforce.github.io/) instead. + + Force.com JavaScript REST Toolkit ================================= -This minimal toolkit allows JavaScript in Visualforce pages to call the Force.com REST API either via the Ajax Proxy (in the case of web apps) or directly (from a PhoneGap app), providing an easy-to-use JavaScript wrapper. +This minimal toolkit allows JavaScript in web pages to call the Force.com REST API in a number of different ways. Background ---------- -Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. +ForceTK provides a convenient, thin JavaScript abstraction of the [Force.com REST API](https://developer.salesforce.com/page/REST_API), making the API more accessible to JavaScript code running in Visualforce, in hybrid mobile apps, and elsewhere. + +Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running outside the Force.com Platform may not use [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, so a minimal PHP proxy is provided. + +Recent Updates +-------------- + +* [Visualforce Remote Objects](https://www.salesforce.com/us/developer/docs/pages/index_Left.htm#CSHID=pages_remote_objects.htm|StartTopic=Content%2Fpages_remote_objects.htm|SkinName=webhelp) are proxy objects that enable basic DML operations on sObjects directly from JavaScript. Behind the scenes, the Remote Objects controller handles sharing rules, field level security, and other data accessibility concerns. Pages that use Remote Objects are subject to all the standard Visualforce limits, but like JavaScript remoting, Remote Objects calls don’t count toward API request limits. -We can work around this restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy). Since the AJAX proxy is present on all -Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. + + Since Remote Objects are more secure than RemoteTK (which does not respect sharing rules, FLS etc since system-level access is proxied via the RemoteTK controller), and similarly do not consume API calls (the main motivation for RemoteTK), RemoteTK has been removed from the toolkit. -Alternatively, to host JavaScript outside the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. +* Since the Summer '13 release, the `/services/data` endpoint has been exposed on Visualforce hosts, so no proxy is now required for REST API calls in JavaScript served via Visualforce (although the proxy **is** still required for calls to `/services/apexrest`). `forcetk.js` has been updated to reflect this. -[PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. +* Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: + + +

+ Select a file to upload as a new Chatter File. +

+ +

+ + + +
+ + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ @@ -23,10 +64,10 @@ The toolkit uses [jQuery](http://jquery.com/). It has been tested on jQuery 1.4. Configuration ------------- -You must add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. +ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. -Using the Toolkit in a Visualforce page ---------------------------------------- +Using ForceTK in a Visualforce page +----------------------------------- Create a zip file containing app.js, forcetk.js, jquery.js, and any other static resources your project may need. Upload the zip via *Your Name > App Setup > Develop > Static Resources*. @@ -36,15 +77,12 @@ Your Visualforce page will need to include jQuery and the toolkit, then create a

The first account I see is .

@@ -99,14 +137,14 @@ Your HTML page will need to include jQuery and the toolkit, then create a client function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - $('#message').html('Error - unauthorized!'); + $('#message').text('Error - unauthorized!'); } else { client.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); }); } @@ -117,39 +155,50 @@ Your HTML page will need to include jQuery and the toolkit, then create a client More fully featured samples are provided in [example.html](Force.com-JavaScript-REST-Toolkit/blob/master/example.html) and [mobile.html](Force.com-JavaScript-REST-Toolkit/blob/master/mobile.html). -Using the Toolkit in a PhoneGap app ------------------------------------ +Using the Toolkit in a Cordova app +---------------------------------- -Your HTML page will need to include jQuery, the toolkit, PhoneGap and the ChildBrowser plugin, then create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in ChildBrowser. +Your HTML page will need to include jQuery, the toolkit and Cordova. You will also need to install the [InAppBrowser](http://plugins.cordova.io/#/package/org.apache.cordova.inappbrowser) plugin to be able to pop up a browser window for authentication. Create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in InAppBrowser. An absolutely minimal sample using OAuth to obtain a session ID is: + - - - - - + + + -

Click here.

+ + + +

+ -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [phonegap.html](Force.com-JavaScript-REST-Toolkit/blob/master/phonegap.html). +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) for iOS is provided in [cordova-ios.html](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with + cordova plugin add org.apache.cordova.inappbrowser + cordova plugin add com.shazron.cordova.plugin.keychainutil diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e31774d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +## Security + +Please report any security issue to [security@salesforce.com](mailto:security@salesforce.com) +as soon as it is discovered. This library limits its runtime dependencies in +order to reduce the total cost of ownership as much as can be, but all consumers +should remain vigilant and have their security stakeholders review all third-party +products (3PP) like this one and their dependencies. \ No newline at end of file diff --git a/app.js b/app.js index 10b7064..7ce5297 100644 --- a/app.js +++ b/app.js @@ -51,18 +51,18 @@ function metadataCallback(response){ // Using TrimPath Template for now - may switch to jQuery Template at some // point - $j('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" + $('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" , response)); // Set up autocomplete - $j( "#value" ).autocomplete({ + $( "#value" ).autocomplete({ source: function( request, response ) { var query = "SELECT Id, Name FROM Account "+ - "WHERE "+$j("#field").val()+" LIKE '%"+request.term+"%' "+ + "WHERE "+$("#field").val()+" LIKE '%"+request.term+"%' "+ "ORDER BY Name LIMIT 20"; client.query(query, function( data ) { - response( $j.map( data.records, function( record ) { + response( $.map( data.records, function( record ) { return { label: record.Name, value: record.Id @@ -76,22 +76,22 @@ if ( ui.item != null ) { showAccountDetail(ui.item.value); } else { - filterAccounts($j("#field").val(),this.value); + filterAccounts($("#field").val(),this.value); } return false; }, }); - $j('#go').click(function(e) { - var field = $j("#field").val(); - var value = $j("#value").val(); + $('#go').click(function(e) { + var field = $("#field").val(); + var value = $("#value").val(); e.preventDefault(); filterAccounts(field,value); }); - $j('#new').click(function(e) { + $('#new').click(function(e) { e.preventDefault(); // Just make Trimpath happy @@ -101,19 +101,19 @@ dummy[response.fields[i].name] = ''; } $dialog.html(TrimPath.processDOMTemplate("edit_jst", dummy)); - $dialog.find('#action').html('Create').click(function(e) { + $dialog.find('#action').text('Create').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 ) { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" creating account..."); + $('#list').html(ajaxgif+" creating account..."); client.create('Account', fields, createCallback, errorCallback); }); @@ -125,21 +125,21 @@ } function queryCallback(response) { - $j('#list').html(TrimPath.processDOMTemplate("accounts_jst" + $('#list').html(TrimPath.processDOMTemplate("accounts_jst" , response)); - $j('#version').html($j.fn.jquery); - $j('#uiversion').html($j.ui.version); + $('#version').text($.fn.jquery); + $('#uiversion').text($.ui.version); - $j("#list tr:nth-child(odd)").addClass("odd"); + $("#list tr:nth-child(odd)").addClass("odd"); - $j('#logout').click(logout); + $('#logout').click(logout); - $j('#accounts').find('.id') + $('#accounts').find('.id') .hover(function() { - $j(this).addClass("highlighted"); + $(this).addClass("highlighted"); },function(){ - $j(this).removeClass("highlighted"); + $(this).removeClass("highlighted"); }) .click(function(){ showAccountDetail(this.id); @@ -156,36 +156,36 @@ && !response.Website.startsWith('http://')) { response.Website = 'http://'+response.Website; } - $dialog.html(TrimPath.processDOMTemplate("detail_jst" + $dialog.TrimPath.processDOMTemplate("detail_jst" ,response)); $dialog.find('#industry').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - filterIndustry($j(this).html()); + filterIndustry($(this).text()); }); $dialog.find('#delete').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - $j('#list').html(ajaxgif+" deleting account..."); + $('#list').html(ajaxgif+" deleting account..."); client.del('Account', $dialog.find('#id').val(), deleteCallback, errorCallback); }); $dialog.find('#edit').click(function(e) { e.preventDefault(); $dialog.html(TrimPath.processDOMTemplate("edit_jst" ,response)); - $dialog.find('#action').html('Update').click(function(e) { + $dialog.find('#action').text('Update').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 && child.attr("name") != 'id') { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" updating account..."); + $('#list').html(ajaxgif+" updating account..."); client.update('Account', $dialog.find('#id').val(), fields, updateCallback, errorCallback); }); @@ -193,19 +193,19 @@ } function createCallback(response) { - $j('#list').html('Created '+response.id); + $('#list').text('Created '+response.id); setTimeout("filterAccounts()",1000); } function updateCallback(response) { - $j('#list').html('Updated'); + $('#list').text('Updated'); setTimeout("filterAccounts()",1000); } function deleteCallback(response) { - $j('#list').html('Deleted'); + $('#list').text('Deleted'); setTimeout("filterAccounts()",1000); } @@ -222,7 +222,7 @@ } function filterIndustry(industry) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = "SELECT Id, Name FROM Account WHERE Industry = '"+industry +"' ORDER BY Name LIMIT 20"; @@ -231,7 +231,7 @@ } function filterAccounts(field, value) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = ( typeof value !== 'undefined' && value.length > 0 ) ? "SELECT Id, Name FROM Account WHERE "+field+" LIKE '%"+value diff --git a/bulk.page b/bulk.page new file mode 100644 index 0000000..e9e7504 --- /dev/null +++ b/bulk.page @@ -0,0 +1,255 @@ + + + + +
+

1. Create a Bulk API job


+ + +
+ + +
+ + + +
+
+

+    
+ + + + + + + + +
\ No newline at end of file diff --git a/bulktk.js b/bulktk.js new file mode 100644 index 0000000..4540aea --- /dev/null +++ b/bulktk.js @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2015, salesforce.com, inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or + * promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * BulkTK: JavaScript library to wrap Force.com Bulk API. Extends ForceTK. + * Dependencies: + * jquery - http://jquery.com/ + * ForceTK - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/forcetk.js + * jxon - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js + * (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) + * project; this version preserves case in element and attribute names) + */ + +forcetk.Client.prototype.xmlHeader = "\n"; + +/* + * Low level utility function to call the Bulk API. + * @param path resource path + * @param parseXML set to true to parse XML response + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [contentType=null] Content type of payload - e.g. 'application/xml; charset=UTF-8' + * @param [payload=null] payload for POST + * @param [parseXML=false] set to true to parse XML response + */ +forcetk.Client.prototype.bulkAjax = function(path, parseXML, callback, error, method, contentType, payload, retry) { + var that = this; + var url = this.instanceUrl + path; + + if (this.debug) { + console.log('bulkAjax sending: ', payload); + } + + return $.ajax({ + type: method || "GET", + async: this.asyncAjax, + url: (this.proxyUrl !== null) ? this.proxyUrl: url, + contentType: method == "DELETE" ? null : contentType, + cache: false, + processData: false, + data: payload, + success: function(data, textStatus, jqXHR) { + var respContentType = jqXHR.getResponseHeader('Content-Type'); + // Naughty Bulk API doesn't always set Content-Type! + if (parseXML && + ((respContentType && respContentType.indexOf('application/xml') === 0) || + data.indexOf(' + + + + + Accounts + + + + + + + + + + + + +
+
+

Login

+
+
+ Connecting to Force.com +
+
+

Force.com

+
+
+
+
+

Account List

+
+
+
+ +
+
    +
+
+ +
+
+
+

Force.com

+
+
+
+
+

Account Detail

+
+
+ + + + +
Account Name:
Industry:
Ticker Symbol:
+
+ + + +
+
+
+

Force.com

+
+
+
+
+

New Account

+
+
+
+ + + + + + + + + + + + + + +
Account Name:
Industry:
Ticker Symbol:
+ +
+
+
+

Force.com

+
+
+ + diff --git a/example.html b/example.html index 1af86b9..f5439d4 100644 --- a/example.html +++ b/example.html @@ -76,13 +76,8 @@ var $dialog = null; - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; - } - - $j(document).ready(function() { - $j('#login').popupWindow({ + $(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -90,7 +85,7 @@ width:675 }); - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 @@ -104,13 +99,12 @@ } function hideButton(){ - $j('#connect').html(ajaxgif+" connecting..."); + $('#connect').text(ajaxgif+" connecting..."); } function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -121,7 +115,7 @@ oauthResponse.instance_url); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').text(ajaxgif+" loading metadata..."); client.describe('Account',metadataCallback, errorCallback); } } diff --git a/example.page b/example.page index e18b827..7ce51a7 100644 --- a/example.page +++ b/example.page @@ -48,9 +48,6 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit * It must go in the VF page so that merge variables are processed. */ - // Get a reference to jQuery that we can work with - $j = jQuery.noConflict(); - // Get an instance of the REST API client and set the session ID var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); @@ -59,16 +56,16 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit var $dialog = null; - $j(document).ready(function() { + $(document).ready(function() { // Set up the dialog - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 }); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').html(ajaxgif+" loading metadata..."); client.describe('Account', metadataCallback); }); diff --git a/forcetk.js b/forcetk.js index f58de58..7fd2918 100644 --- a/forcetk.js +++ b/forcetk.js @@ -32,6 +32,9 @@ * console, go to Your Name | Setup | Security Controls | Remote Site Settings */ +/*jslint browser: true*/ +/*global alert, Blob, $, jQuery*/ + var forcetk = window.forcetk; if (forcetk === undefined) { @@ -40,11 +43,6 @@ if (forcetk === undefined) { if (forcetk.Client === undefined) { - // We use $j rather than $ for jQuery so it works in Visualforce - if (window.$j === undefined) { - $j = $; - } - /** * The Client provides a convenient wrapper for the Force.com REST API, * allowing JavaScript in Visualforce pages to use the API via the Ajax @@ -55,15 +53,16 @@ if (forcetk.Client === undefined) { * PhoneGap etc * @constructor */ - forcetk.Client = function(clientId, loginUrl, proxyUrl) { + forcetk.Client = function (clientId, loginUrl, proxyUrl) { + 'use strict'; this.clientId = clientId; this.loginUrl = loginUrl || 'https://login.salesforce.com/'; - if (typeof proxyUrl === 'undefined' || proxyUrl === null) { - if (location.protocol === 'file:') { + if (proxyUrl === undefined || proxyUrl === null) { + if (location.protocol === 'file:' || location.protocol === 'ms-appx:') { // In PhoneGap this.proxyUrl = null; } else { - // In Visualforce + // In Visualforce - still need proxyUrl for Apex REST methods this.proxyUrl = location.protocol + "//" + location.hostname + "/services/proxy"; } @@ -76,66 +75,80 @@ if (forcetk.Client === undefined) { this.refreshToken = null; this.sessionId = null; this.apiVersion = null; + this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; - } + }; /** * Set a refresh token in the client. * @param refreshToken an OAuth refresh token */ - forcetk.Client.prototype.setRefreshToken = function(refreshToken) { + forcetk.Client.prototype.setRefreshToken = function (refreshToken) { + 'use strict'; this.refreshToken = refreshToken; - } + }; /** * Refresh the access token. * @param callback function to call on success * @param error function to call on failure */ - forcetk.Client.prototype.refreshAccessToken = function(callback, error) { - var that = this; - var url = this.loginUrl + '/services/oauth2/token'; - $j.ajax({ + forcetk.Client.prototype.refreshAccessToken = function (callback, error) { + 'use strict'; + var that = this, + url = this.loginUrl + '/services/oauth2/token'; + return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, success: callback, error: error, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } }); - } + }; /** * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="v29.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ - forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { + forcetk.Client.prototype.setSessionToken = function (sessionId, apiVersion, instanceUrl) { + 'use strict'; this.sessionId = sessionId; - this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v21.0': apiVersion; - if (typeof instanceUrl === 'undefined' || instanceUrl == null) { - // location.hostname can be of the form 'abc.na1.visual.force.com' or - // 'na1.salesforce.com'. Split on '.', and take the [1] or [0] element - // as appropriate - var elements = location.hostname.split("."); - var instance = (elements.length == 3) ? elements[0] : elements[1]; + this.apiVersion = (apiVersion === undefined || apiVersion === null) + ? 'v29.0' : apiVersion; + if (instanceUrl === undefined || instanceUrl === null) { + this.visualforce = true; + + // location.hostname can be of the form 'abc.na1.visual.force.com', + // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). + // Split on '.', and take the [1] or [0] element as appropriate + var elements = location.hostname.split("."), + instance = null; + if (elements.length === 4 && elements[1] === 'my') { + instance = elements[0] + '.' + elements[1]; + } else if (elements.length === 3) { + instance = elements[0]; + } else { + instance = elements[1]; + } + this.instanceUrl = "https://" + instance + ".salesforce.com"; } else { this.instanceUrl = instanceUrl; } - } + }; /* * Low level utility function to call the Salesforce endpoint. @@ -145,41 +158,295 @@ if (forcetk.Client === undefined) { * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc */ - forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { - var that = this; - var url = this.instanceUrl + '/services/data' + path; + forcetk.Client.prototype.ajax = function (path, callback, error, method, payload, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, - contentType: 'application/json', + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, + contentType: method === "DELETE" ? null : 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.ajax(path, callback, error, method, payload, true); }, - error); + error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !that.visualforce) { + xhr.setRequestHeader('SalesforceProxy-Endpoint', url); + } + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); + xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); + } + }); + }; + + /** + * Utility function to query the Chatter API and download a file + * Note, raw XMLHttpRequest because JQuery mangles the arraybuffer + * This should work on any browser that supports XMLHttpRequest 2 because arraybuffer is required. + * For mobile, that means iOS >= 5 and Android >= Honeycomb + * @author Tom Gersic + * @param path resource path relative to /services/data + * @param mimetype of the file + * @param callback function to which response will be passed + * @param [error=null] function to which request will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.getChatterFile = function (path, mimeType, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + path, + request = new XMLHttpRequest(); + + request.open("GET", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, true); + request.responseType = "arraybuffer"; + + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && !this.visualforce) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } + + request.onreadystatechange = function () { + // continue if the process is completed + if (request.readyState === 4) { + // continue only if HTTP status is "OK" + if (request.status === 200) { + try { + // retrieve the response + callback(request.response); + } catch (e) { + // display error message + alert("Error reading the response: " + e.toString()); + } + } else if (request.status === 401 && !retry) { + //refresh token in 401 + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); + that.getChatterFile(path, mimeType, callback, error, true); + }, error); + } else { + // display status message + error(request, request.statusText, request.response); + } + } + }; + + request.send(); + + }; + + // Local utility to create a random string for multipart boundary + var randomString = function () { + 'use strict'; + var str = '', + i; + for (i = 0; i < 4; i += 1) { + str += (Math.random().toString(16) + "000000000").substr(2, 8); + } + return str; + }; + + /* Low level function to create/update records with blob data + * @param path resource path relative to /services/data + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.blob = function (path, fields, filename, payloadField, payload, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path, + boundary = randomString(), + blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}), + request = new XMLHttpRequest(); + + request.open("POST", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, this.asyncAjax); + + request.setRequestHeader('Accept', 'application/json'); + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + request.setRequestHeader('Content-Type', 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'); + if (this.proxyUrl !== null && !this.visualforce) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } + + if (this.asyncAjax) { + request.onreadystatechange = function () { + // continue if the process is completed + if (request.readyState === 4) { + // continue only if HTTP status is good + if (request.status >= 200 && request.status < 300) { + // retrieve the response + callback(request.response ? JSON.parse(request.response) : null); + } else if (request.status === 401 && !retry) { + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); + that.blob(path, fields, filename, payloadField, payload, callback, error, true); + }, error); + } else { + // return status message + error(request, request.statusText, request.response); + } + } + }; + } + + request.send(blob); + + return this.asyncAjax ? null : JSON.parse(request.response); + }; + + /* + * Create a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.createBlob = function (objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error, retry); + }; + + /* + * Update a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param id the record's object ID + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.updateBlob = function (objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error, retry); + }; + + /* + * Low level utility function to call the Salesforce endpoint specific for Apex REST API. + * @param path resource path relative to /services/apexrest + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [payload=null] string or object with payload for POST/PATCH etc or params for GET + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error + */ + forcetk.Client.prototype.apexrest = function (path, callback, error, method, payload, paramMap, retry) { + 'use strict'; + var that = this, + url = this.instanceUrl + '/services/apexrest' + path; + + method = method || "GET"; + + if (method === "GET") { + // Handle proxied query params correctly + if (this.proxyUrl && payload) { + if (typeof payload !== 'string') { + payload = $.param(payload); + } + url += "?" + payload; + payload = null; + } + } else { + // Allow object payload for POST etc + if (payload && typeof payload !== 'string') { + payload = JSON.stringify(payload); + } + } + + return $.ajax({ + type: method, + async: this.asyncAjax, + url: this.proxyUrl || url, + contentType: 'application/json', + cache: false, + processData: false, + data: payload, + success: callback, + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { + if (jqXHR.status === 401) { + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, + oauthResponse.instance_url); + that.apexrest(path, callback, error, method, payload, paramMap, true); + }, error); + } else { + error(jqXHR, textStatus, errorThrown); + } + }, + dataType: "json", + beforeSend: function (xhr) { + var paramName; if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + //Add any custom headers + if (paramMap === null) { + paramMap = {}; + } + for (paramName in paramMap) { + if (paramMap.hasOwnProperty(paramName)) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } + } + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /* * Lists summary information about each Salesforce.com version currently @@ -188,9 +455,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.versions = function(callback, error) { - this.ajax('/', callback, error); - } + forcetk.Client.prototype.versions = function (callback, error) { + 'use strict'; + return this.ajax('/', callback, error); + }; /* * Lists available resources for the client's API version, including @@ -198,9 +466,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.resources = function(callback, error) { - this.ajax('/' + this.apiVersion + '/', callback, error); - } + forcetk.Client.prototype.resources = function (callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/', callback, error); + }; /* * Lists the available objects and their metadata for your organization's @@ -208,9 +477,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describeGlobal = function(callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); - } + forcetk.Client.prototype.describeGlobal = function (callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); + }; /* * Describes the individual metadata for the specified object. @@ -218,10 +488,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.metadata = function(objtype, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error); - } + forcetk.Client.prototype.metadata = function (objtype, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error); + }; /* * Completely describes the individual metadata at all levels for the @@ -230,10 +501,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describe = function(objtype, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype - + '/describe/', callback, error); - } + forcetk.Client.prototype.describe = function (objtype, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + + '/describe/', callback, error); + }; /* * Creates a new record of the given type. @@ -244,10 +516,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.create = function(objtype, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.create = function (objtype, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error, "POST", JSON.stringify(fields)); + }; /* * Retrieves field values for a record of the given type. @@ -258,16 +531,17 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - if (!arguments[4]) { + forcetk.Client.prototype.retrieve = function (objtype, id, fieldlist, callback, error) { + 'use strict'; + if (arguments.length === 4) { error = callback; callback = fieldlist; fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + fields, callback, error); - } + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + fields, callback, error); + }; /* * Upsert - creates or updates record of the given type, based on the @@ -281,10 +555,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.upsert = function (objtype, externalIdField, externalId, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Updates field values on a record of the given type. @@ -296,10 +571,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.update = function (objtype, id, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Deletes a record of the given type. Unfortunately, 'delete' is a @@ -309,10 +585,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.del = function(objtype, id, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - , callback, error, "DELETE"); - } + forcetk.Client.prototype.del = function (objtype, id, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id, + callback, error, "DELETE"); + }; /* * Executes the specified SOQL query. @@ -321,10 +598,34 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.query = function(soql, callback, error) { - this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) - , callback, error); - } + forcetk.Client.prototype.query = function (soql, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql), + callback, error); + }; + + /* + * Queries the next set of records based on pagination. + *

This should be used if performing a query that retrieves more than can be returned + * in accordance with http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query.htm

+ *

Ex: forcetkClient.queryMore( successResponse.nextRecordsUrl, successHandler, failureHandler )

+ * + * @param url - the url retrieved from nextRecordsUrl or prevRecordsUrl + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + */ + forcetk.Client.prototype.queryMore = function (url, callback, error) { + 'use strict'; + //-- ajax call adds on services/data to the url call, so only send the url after + var serviceData = "services/data", + index = url.indexOf(serviceData); + + if (index > -1) { + url = url.substr(index + serviceData.length); + } + + return this.ajax(url, callback, error); + }; /* * Executes the specified SOSL search. @@ -333,8 +634,9 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.search = function(sosl, callback, error) { - this.ajax('/' + this.apiVersion + '/search?s=' + escape(sosl) - , callback, error); - } -} \ No newline at end of file + forcetk.Client.prototype.search = function (sosl, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl), + callback, error); + }; +} diff --git a/jxon.js b/jxon.js new file mode 100644 index 0000000..192694d --- /dev/null +++ b/jxon.js @@ -0,0 +1,140 @@ +/* + * JXON.js + * Ratatosk + * + * Created by Alexander Ljungberg on March 15th, 2012. + * + * Public domain JXON implementation from algorithm #3 of: + * https://developer.mozilla.org/en/Parsing_and_serializing_XML + * + * Any copyright is dedicated to the Public Domain. + * + * Modified by Andrew (Pat) Patterson, 2015 from original at + * https://github.com/wireload/Ratatosk/blob/master/jxon.js + * to preserve case of element and attribute names + */ + +JXON = function() +{ + +}; + +JXON.buildValue = function(sValue) +{ + if (/^\s*$/.test(sValue)) + return null; + if (/^(true|false)$/i.test(sValue)) + return sValue.toLowerCase() === "true"; + if (isFinite(sValue)) + return parseFloat(sValue); + // Don't do this - it'll parse anything that looks like a date and get the timezone wrong. + // https://bugzilla.mozilla.org/show_bug.cgi?id=693077 + //if (isFinite(Date.parse(sValue))) + // return new Date(sValue); + return sValue; +}; + +JXON.fromXML = function(xmlString) +{ + return JXON.getJXONData((new DOMParser()).parseFromString(xmlString, "text/xml")); +}; + +JXON.getJXONData = function(oXMLParent) +{ + var vResult = /* put here the default value for empty nodes! */ null, + nLength = 0, + sCollectedTxt = ""; + if (oXMLParent.hasAttributes && oXMLParent.hasAttributes()) + { + vResult = {}; + for (nLength; nLength < oXMLParent.attributes.length; nLength++) + { + oItAttr = oXMLParent.attributes.item(nLength); + vResult["@" + oItAttr.nodeName] = JXON.buildValue(oItAttr.value.replace(/^\s+|\s+$/g, "")); + } + } + if (oXMLParent.hasChildNodes()) + { + for (var oItChild, sItKey, sItVal, nChildId = 0; nChildId < oXMLParent.childNodes.length; nChildId++) + { + oItChild = oXMLParent.childNodes.item(nChildId); + if (oItChild.nodeType === 4) + { + sCollectedTxt += oItChild.nodeValue; + } /* nodeType is "CDATASection" (4) */ + else if (oItChild.nodeType === 3) + { + sCollectedTxt += oItChild.nodeValue.replace(/^\s+|\s+$/g, ""); + } /* nodeType is "Text" (3) */ + else if (oItChild.nodeType === 1 && !oItChild.prefix) + { /* nodeType is "Element" (1) */ + if (nLength === 0) + vResult = {}; + sItKey = oItChild.nodeName; + sItVal = JXON.getJXONData(oItChild); + if (vResult.hasOwnProperty(sItKey)) + { + if (vResult[sItKey].constructor !== Array) + vResult[sItKey] = [vResult[sItKey]]; + vResult[sItKey].push(sItVal); + } + else + { + vResult[sItKey] = sItVal; + nLength++; + } + } + } + } + if (sCollectedTxt) + nLength > 0 ? vResult.keyValue = JXON.buildValue(sCollectedTxt) : vResult = JXON.buildValue(sCollectedTxt); + /* if (nLength > 0) { Object.freeze(vResult); } */ + return vResult; +}; + +JXON.loadObj = function(oParentObj, oParentEl, oNewDoc) +{ + var nSameIdx, + vValue, + oChild; + for (var sName in oParentObj) + { + vValue = oParentObj[sName]; + if (sName === "keyValue") + { + if (vValue !== null && vValue !== true) + oParentEl.appendChild(oNewDoc.createTextNode(String(vValue))); + } + else if (sName.charAt(0) === "@") + oParentEl.setAttribute(sName.slice(1), vValue); + else + { + oChild = oNewDoc.createElement(sName); + if (vValue && vValue.constructor === Date) + oChild.appendChild(oNewDoc.createTextNode(vValue.toGMTString())); + else if (vValue && vValue.constructor === Array) + { + for (nSameIdx = 0; nSameIdx < vValue.length; nSameIdx++) + JXON.loadObj(vValue[nSameIdx], oChild); + } + else if (vValue && vValue instanceof Object) + { + JXON.loadObj(vValue, oChild, oNewDoc); + } + else if (vValue !== null && vValue !== true) + oChild.appendChild(oNewDoc.createTextNode(vValue.toString())); + + oParentEl.appendChild(oChild); + // CPLog.error("Document: " + (new XMLSerializer()).serializeToString(oNewDoc)); + } + } +}; + +JXON.toXML = function(oJXONObj, rootName) +{ + var oNewDoc = document.implementation.createDocument("", "", null), + rootNode = oNewDoc.createElement(rootName || 'xml'); + oNewDoc.appendChild(rootNode); + JXON.loadObj(oJXONObj, rootNode, oNewDoc); + return (new XMLSerializer()).serializeToString(oNewDoc); +}; diff --git a/mobile.html b/mobile.html index c1a14eb..9c07cad 100644 --- a/mobile.html +++ b/mobile.html @@ -55,13 +55,8 @@ // OAuth var client = new forcetk.Client(clientId, loginUrl, proxyUrl);; -// We use $j rather than $ for jQuery -if (window.$j === undefined) { - $j = $; -} - -$j(document).ready(function() { - $j('#login').popupWindow({ +$(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -79,7 +74,6 @@ function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -91,10 +85,10 @@ addClickListeners(); - $j.mobile.changePage('#mainpage',"slide",false,true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage',"slide",false,true); + $.mobile.pageLoading(); getAccounts(function(){ - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } } diff --git a/mobile.page b/mobile.page index 40105bf..c3f54e8 100644 --- a/mobile.page +++ b/mobile.page @@ -50,20 +50,17 @@ an HTML5 mobile app using jQuery Mobile diff --git a/mobileapp.js b/mobileapp.js index 8d7d1b6..eeb9242 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -35,85 +35,85 @@ function errorCallback(jqXHR){ } function addClickListeners() { - $j('#newbtn').click(function(e) { + $('#newbtn').click(function(e) { // Show the 'New Account' form e.preventDefault(); - $j('#accountform')[0].reset(); - $j('#accformheader').html('New Account'); + $('#accountform')[0].reset(); + $('#accformheader').text('New Account'); setButtonText('#actionbtn', 'Create'); - $j('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); - $j.mobile.changePage('#editpage', "slide", false, true); + $('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); + $.mobile.changePage('#editpage', "slide", false, true); }); - $j('#deletebtn').click(function(e) { + $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $j.mobile.pageLoading(); - client.del('Account', $j('#accountdetail').find('#Id').val() + $.mobile.loading('show'); + client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); }); - $j('#editbtn').click(function(e) { + $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $j.mobile.pageLoading(); - client.retrieve("Account", $j('#accountdetail').find('#Id').val() + $.mobile.loading('show'); + client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { - $j('#accountform').find('input').each(function() { - $j(this).val(response[$j(this).attr("name")]); + $('#accountform').find('input').each(function() { + $(this).val(response[$(this).attr("name")]); }); - $j('#accformheader').html('Edit Account'); + $('#accformheader').text('Edit Account'); setButtonText('#actionbtn', 'Update'); - $j('#actionbtn') + $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#editpage', "slide", false, true); + $.mobile.loading('hide'); + $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); } // Populate the account list and set up click handling function getAccounts(callback) { - $j('#accountlist').empty(); + $('#accountlist').empty(); client.query("SELECT Id, Name FROM Account ORDER BY Name LIMIT 20" , function(response) { - $j.each(response.records, + $.each(response.records, function() { var id = this.Id; - $j('
  • ') + $('
  • ') .hide() .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $j.mobile.pageLoading(); + $.mobile.loading('show'); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... client.retrieve("Account", id, "Name,Id,Industry,TickerSymbol" , function(response) { - $j('#Name').html(response.Name); - $j('#Industry').html(response.Industry); - $j('#TickerSymbol').html(response.TickerSymbol); - $j('#Id').val(response.Id); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#detailpage', "slide", false, true); + $('#Name').text(response.Name); + $('#Industry').text(response.Industry); + $('#TickerSymbol').text(response.TickerSymbol); + $('#Id').val(response.Id); + $.mobile.loading('hide'); + $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) .appendTo('#accountlist') .show(); }); - $j('#accountlist').listview('refresh'); + $('#accountlist').listview('refresh'); if (typeof callback != 'undefined' && callback != null) { callback(); @@ -124,20 +124,20 @@ function getAccounts(callback) { // Gather fields from the account form and create a record function createHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.loading('show'); client.create('Account', fields, function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -145,21 +145,21 @@ function createHandler(e) { // Gather fields from the account form and update a record function updateHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.loading('show'); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -167,5 +167,5 @@ function updateHandler(e) { // Ugh - this is required to change text on a jQuery Mobile button // due to the way it futzes with things at runtime function setButtonText(id, str) { - $j(id).html(str).parent().find('.ui-btn-text').text(str); + $(id).text(str).parent().find('.ui-btn-text').text(str); } diff --git a/phonegap.html b/phonegap.html deleted file mode 100644 index 1e80547..0000000 --- a/phonegap.html +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - Accounts - - - - - - - - - - - - - - -
    -
    -

    Login

    -
    -
    - Connecting to Force.com -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    Account List

    -
    -
    -
    - -
    -
      -
    -
    - -
    -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    Account Detail

    -
    -
    - - - - -
    Account Name:
    Industry:
    Ticker Symbol:
    -
    - - - -
    -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    New Account

    -
    -
    -
    - - - - - - - - - - - - - - -
    Account Name:
    Industry:
    Ticker Symbol:
    - -
    -
    -
    -

    Force.com

    -
    -
    - - diff --git a/proxy.php b/proxy.php index cca675e..b9f91ec 100644 --- a/proxy.php +++ b/proxy.php @@ -169,7 +169,8 @@ // Change these configuration options if needed, see above descriptions for info. $enable_jsonp = false; $enable_native = true; -$valid_url_regex = '/https:\/\/.*salesforce.com/'; +$valid_forcecom_url_regex = '/https:\/\/.*\.(salesforce|database|cloudforce)\.com/'; + $url_query_param = null; // 'url' $url_header = 'HTTP_SALESFORCEPROXY_ENDPOINT'; @@ -201,7 +202,7 @@ $status['http_code'] = 400; $status['status_text'] = 'Bad Request'; -} else if ( !preg_match( $valid_url_regex, $url ) ) { +} else if ( !preg_match( $valid_forcecom_url_regex, $url )) { // Passed url doesn't match $valid_url_regex. $contents = 'ERROR: invalid url'; @@ -232,7 +233,8 @@ isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' ); // Pass on content, regardless of request method - if ( isset($_SERVER['CONTENT_LENGTH'] ) && $_SERVER['CONTENT_LENGTH'] > 0 ) { + if ( (isset($_SERVER['CONTENT_LENGTH'] ) && $_SERVER['CONTENT_LENGTH'] > 0) || + (isset($_SERVER['HTTP_CONTENT_LENGTH'] ) && $_SERVER['HTTP_CONTENT_LENGTH'] > 0) ) { curl_setopt( $ch, CURLOPT_POSTFIELDS, file_get_contents("php://input") ); } @@ -257,7 +259,14 @@ if ( isset($_SERVER['CONTENT_TYPE']) ) { // Pass through the Content-Type header array_push($headers, "Content-Type: ".$_SERVER['CONTENT_TYPE'] ); - } + } elseif ( isset($_SERVER['HTTP_CONTENT_TYPE']) ) { + // Pass through the Content-Type header + array_push($headers, "Content-Type: ".$_SERVER['HTTP_CONTENT_TYPE'] ); + } + if ( isset($_SERVER['HTTP_SOAPACTION']) ) { + // Pass through the SOAPAction header + array_push($headers, "SOAPAction: ".$_SERVER['HTTP_SOAPACTION'] ); + } if ( isset($_SERVER['HTTP_X_USER_AGENT']) ) { // Pass through the X-User-Agent header array_push($headers, "X-User-Agent: ".$_SERVER['HTTP_X_USER_AGENT'] );