141 Commits
Author SHA1 Message Date
Florian Motteau 559fd37c1f Fixed: Wrong Less file path for some theme/locale combinations (OFBIZ-12660) (#521)
For some themes, we rely on toLowerCase method to build a Less file path.
toLowerCase("I") = "ı" for some locales (TR, AZ), which lead to incorrect
file paths and finally broken themes.
2022-08-10 10:40:35 +02:00
Jacques Le Roux 7493714769 Improved: Data of tenant specific component gets loaded in all instances (OFBIZ-6065)
Improves the information provided about importing and loadAll Gradle task
loadTenant Gradle task should be used when necessary
2022-07-28 09:40:58 +02:00
Jacques Le Roux be6270e583 Improved: Data of tenant specific component gets loaded in all instances (OFBIZ-6065)
The tenant relevant Gradle tasks are:

OFBiz Server tasks
------------------
createTenant - Create a new tenant in your environment
loadAdminUserLogin - Create admin user with temporary password equal to ofbiz.
You must provide userLoginId
loadAll - Load default data; meant for OFBiz development, testing, and demo
purposes
loadTenant - Load data using tenantId

loadAll is the new "ant load-data" and should clearly only used for
"OFBiz development, testing, and demo purposes".

Remains the import functionalities. We don't want to get to far with that,
a warning is enough.

Thanks: Pierre Smits for report
2022-07-27 16:22:20 +02:00
georg1312 5a326dfb9a Improved: Strip data to maximum column length for initialRequest and (#526)
initialReferrer (OFBIZ-12672)

Analogous to the existing limitation of the "initialUserAgent" to 250
characters, installation of a limitation of 2000 characters for
initialRequest and initialReferrer, so as not to exit with
"MysqlDataTruncation: Data truncation: Data too long for column
'INITIAL_REFERRER' at row 1" in the case of very long requests.
2022-07-25 09:20:45 +02:00
Jacques Le Roux a05c223a52 Improved: Update Groovy to 2.5.18 (OFBIZ-12673)
See https://lists.apache.org/thread/r3q4mh3nnxyl7p0gclzbshcgz574l3sp, notably:

    This release is a maintenance release of the GROOVY_2_5_X branch.
    It is strongly encouraged that all users using prior
    versions on this branch upgrade to this version.

    This release includes 15 bug fixes/improvements as outlined in the changelog:
    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12318123&version=12351798
2022-07-25 09:05:08 +02:00
Michael Brohl 0b36f12327 Improved: Make loading of data containing urls configurable
(OFBIZ-12670)

Introduces a SystemProperty security/security.datafile.loadurls.enable
which can be set to true to allow loading of urls in the XML import.
2022-07-21 15:15:39 +02:00
Nicolas Malin d9e974633b Fixed: Calendar in Work Effort does not work (OFBIZ-12665)
Fix a null pointer exception when a menu extend a menu with empty item.
In this case, we use a empty link for the extended menu.

Thanks to Jacques Leroux for the alert
2022-07-15 15:02:10 +02:00
Nicolas Malin c91ee80c2e Improved: Update documentation for official support of java 11 2022-07-15 11:14:35 +02:00
Jacques Le Roux 5a54afbb15 Improved: Runs GitHub Gradle build with Java 11 2022-07-15 11:10:18 +02:00
Nicolas Malin a130a05475 Improved: Convert SupplierProductServices.xml mini-lang to groovyDSL (OFBIZ-9350) (OFBIZ-12667)
Convert the service getSupplierProductFeatures from mini-lang to groovyDSL

Thanks to Tom Gibert for the help
2022-07-15 09:42:32 +02:00
Nicolas Malin f158685ceb Improved: Allow DynamicView use in standard performFind services (OFBIZ-12663)
Extend standard find services (prepareFind, executeFind and performFind) to use a built dynamicView instead of just an entityName.

With this, you can prepare a dedicated dynamicView and call the performFind with on result a database optimisation.

Thanks to Leila Mekika for this proposal and patch
2022-07-08 17:34:04 +02:00
Nicolas Malin 6e2b9bd088 Improved: Add missing parameter on xsd for widget-form:on-field-event-update-area (OFBIZ-12586)
On the widget-form.xsd definition, the element on-field-event-update-area haven't possibility to define some parameters.

But on java code, the on-field-event-update-area is read like on-event-update-area.

If you put some parameters on your code, your editor raise a syntax error but OFBiz analyse and execute it well.

            <wf:field name="reload" >
                <wf:submit/>
                <wf:on-field-event-update-area event-type="click"
                                               area-target="ReloadIt">
                    <wf:auto-parameters-service service-name="computeForReload" send-if-empty="false"/>
                </wf:on-field-event-update-area>
            </wf:field>

By the way we can synchronize the on-field-event-update-area xsd on on-event-update-area.
2022-07-01 18:30:27 +02:00
Nicolas Malin 8cccb4b586 Improved: Convert a display-entity to hyperlink if subhyperlink this empty (OFBIZ-12547)
When you define a display-entity you have the possibility to add a sub-hyperlink related to the element displayed.

             <field name="partyIdFrom">
                <display-entity entity-name="PartyNameView" key-field-name="partyId" description="${groupName}${firstName} ${lastName}">
                    <sub-hyperlink target="viewprofile" description="view">...</sub-hyperlink>
                </display-entity>
            <field>

This display the party name with a link "view" connected.

When you use the name as link without a dedicate sub link, you need to change all the form to resolve the information to display for creating an hyperlink

            <row-actions>
                <entity-one entity-name="PartyNameView" value-field="partyName">
                        <field-map field-name="partyId" from-field="partyIdFrom"/>
                </entity-one>
                <set field="partyNameValue" value=" ${partyName.groupName}${partyName.firstName} ${partyName.lastName}"/>
            </row-actions>
            <field name="partyIdFrom">
                <hyperlink target="viewprofile" description="${partyNameValue}">..</hyperlink>
            </field>

We lost the advantage of the display-entity. With this case, we improve display-entity with the following rule :

If the display-entity has a subhyperlink and the subhyperlink haven't description, the description of the link is the display-entity description.
In the code, if a sub-hyperlink has an empty description, we convert the display entity as a hyperlink
2022-07-01 18:21:17 +02:00
Nicolas Malin 4c0773e531 Improved: Refactoring service resenquence (OFBIZ-12624)
The service "resequence" compute for a content all sequenceNum for linked content assoc.

The code is very old (before apache) so apply a slim refactor and migrate the service name resequence to resequenceContentAssocChildren.

By the way I kept the service definition resequence to move it as deprecated.
2022-07-01 17:53:38 +02:00
Nicolas Malin d95c23cbd3 Fixed: MenuItem doesn't follow correctly extended informations (OFBIZ-12628)
Fix a null pointer exception when the extended menu have an entry without link.

Thanks to Jacques Leroux for the alert
2022-07-01 17:39:53 +02:00
Jacques Le Roux 29bdb0ed86 Improved: Unable to upload a file through ecommerce (OFBIZ-12636)
Allows to check for only CSV files. This is not used OOTB in OFBiz.

Thanks: Sachin for report and confirmation it's OK
2022-06-30 11:27:59 +02:00
Jacques Le Roux 4847919874 Improved: Helveticus App-Bar Css Issue - Height change on hover (OFBIZ-12661)
When hovering an app-navigation item, the height of the app bar changes.
Doesn't look good. Attached the correction.

Thanks: Ingo Wolfmayr
2022-06-29 10:54:00 +02:00
Jacques Le Roux 803a8cadc1 Fixed: [SECURITY] Upgrade Tika to 1.28.4 (OFBIZ-12657)
Mentionned at https://tika.apache.org/
Apache Tika 1.28.4 has been released! This release includes security related
fixes and dependency upgrades
Note: The Apache Tika PMC has set September 30, 2022 as the End Of Life for the
Tika 1.x branch.
2022-06-22 13:54:17 +02:00
Jacques Le Roux 5983f647a2 Improved: Regular expression denial of service in jquery-validation (OFBIZ-12634)
Uses "gradlew npm_audit_fix" because backporting only this change was complicated
2022-06-17 17:47:44 +02:00
Jacques Le Roux 1ce8a93edc Improved: Backport, Use gradlew npm_outdated gradle-node-plugin tasks to check outdated scripts (OFBIZ-12480)
Forgot to put back _form in OfbizUtil.js. THis is necessary for query-ui (1.13.0)
cf. OFBIZ-12480

Coincidentally removes trailing blanks
2022-06-17 16:50:54 +02:00
Jacques Le Roux 8f08e1ee09 To send Dependabot to securityML.
Syntax error in previous commit
2022-06-17 16:13:32 +02:00
Jacques Le Roux a3e20ffdf1 To send Dependabot to securityML.
Also try jira_options: link label, see
https://cwiki.apache.org/confluence/display/INFRA/Git+-+.asf.yaml+features#Git.asf.yamlfeatures-Jiranotificationoptions
2022-06-17 16:13:32 +02:00
Jacques Le Roux 7aa7aa2b5c Improved: no functional change, adds GitHub Actions build status emails.
As the name suggests, these are emails that notify of either a failed build
using GitHub Actions, or a change from failure in previous builds to a
successful build. Continuously successful builds will not trigger emails, as
that could be rather spammy.

Please see the documentation on this at: https://s.apache.org/asfyaml-gha
2022-06-17 16:13:32 +02:00
Jacques Le Roux cd624e8144 Improved: no functional change, adds GitHub Actions build status emails.
As the name suggests, these are emails that notify of either a failed build
using GitHub Actions, or a change from failure in previous builds to a
successful build. Continuously successful builds will not trigger emails, as
that could be rather spammy.

Please see the documentation on this at: https://s.apache.org/asfyaml-gha
2022-06-17 16:13:32 +02:00
Nicolas Malin 71e0a2cbb4 Fixed: Service getNextOrderId failed if a customMethod is present (OFBIZ-12651)
When you generate an order on a party who have a PartyAcctgPreference with a customMethod orderSequence_enforced, the service failed due to the missing parameter partyAcctgPreference.

Like quote and invoice it's preferable to forward the partyAcctgPreference information.
2022-06-17 14:01:08 +02:00
Nicolas Malin bb57531901 Fixed: MenuItem doesn't follow correctly extended informations (OFBIZ-12628)
When you use two menus where the second extend the first, menu items and menu links aren't correctly propagated.

The menu items and menu links presents on the second menu already have the first menu on their model.

    ****
    <menu name="FirstMenu" extends="CommonInlineBarMenu" extends-resource="component://common/widget/CommonMenus.xml">
        <menu-item name="MyItem">
            <link target="GoAction"/>
        </menu-item>
    </menu>
    <menu name="SecondMenu" extends="FirstMenu"/>
    ****

The result, if during the rendering some information are generated from the menu, in the previous case, it's always the "FirstMenu" that would be use.

Like when your menu generate a hidden-form, the SecondMenu link the bad form

    ****
    <form method="post" action="GoAction" onsubmit="javascript:submitFormDisableSubmits(this)" name="SecondMenu">...</form>
    <a href="javascript:ajaxSubmitFormUpdateAreas('FirstMenu', 'xxx')">MyItem</a>
    ****

To solve it and don't break the thread safe pattern, I introduce two new constructor for ModelItem and MenuLink for duplicate the ModelMenuItem and MenuLink in memory with the new parent. With this, the SecondMenu iw now completely duplicated on memory and now share any reference with the extended menu.

Thanks to Marco Rodrigues that detect this problem
2022-06-17 11:20:52 +02:00
Nicolas Malin 7bbabc140b Fixed: Backport ProductWorker getBoolean logic update (OFBIZ-12609) (OFBIZ-12649)
If chargeShipping is null (default) the method ProductWorker.shippingApplies
fails.
GenericEntity::getBoolean has changed. If the passed value equals null, false is
returned. ProductWorker expects "null".

jleroux: GenericEntity::getBoolean has been changed for OFBIZ-12386 "Fix some
bugs SpotBugs reports". I checked at least that
"CommunicationEventServices::sendEmailToContactList handles correctly
tmpResult != null". After this fix I have to check other possible similar cases
I neglected. Fortunately, only trunk is concerned.

Thanks: Ingo Wolfmayr
2022-06-17 10:22:15 +02:00
Jacques Le Roux 66d8609665 Fixed: Wrong location for service updateContentSEOCategory (OFBIZ-12642)
Service has been moved to groovy but definition still links to minilang.

Thanks: Ingo Wolfmayr
2022-06-14 17:13:55 +02:00
Jacques Le Roux 360f8e8d17 Improved: Secure the uploads (OFBIZ-12080)
Few more debug log texts changes for clarity

I backport to ease future merging while backporting
2022-06-11 14:45:42 +02:00
Jacques Le Roux e9da7c0e4e Fixed: Secure the uploads (OFBIZ-12080)
Several changes in SecuredUpload class:
Mostly checks that uploaded CSV files are valid text files
Also few debug log texts changes for clarity
2022-06-11 12:01:22 +02:00
Jacques Le Roux 4f469fdfb7 Fixed: Unable to upload a file through ecommerce (OFBIZ-12636)
We need to upload a CSV format file as part of project requirement
We were able upload CSV format file under eCommerce in Version 16.11.07.
We are trying to implement the same in version 18.12.05 - there the same upload
module does not work.

jleroux: I missed to check and allow CSV files when all files are allowed.
That now uses:
https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html

The default CSV format used to check upload of CSV files is set in the property
csvformat=CSVFormat.DEFAULT in security.properties

Thanks: Sachin for report
2022-06-11 09:06:04 +02:00
Deepak Dixit 221530683d Fixed: Added missing notification tag entry in services.xsd file (OFBIZ-12635) 2022-06-09 15:32:03 +05:30
Michael Brohl c3de53667e Improved: German Translation - Category (OFBIZ-12632)
Updates a few german translations for consistency.

Thanks Ingo Wolfmayr for reporting and providing the patch.
2022-06-07 21:41:55 +02:00
Jacques Le Roux 067fa97b04 Improved: Update Groovy to 2.5.17 (OFBIZ-12631)
This release includes 23 bug fixes/improvements as outlined in the changelog:
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12318123&version=12351416
2022-06-03 12:03:35 +02:00
Jacques Le Roux 858a669ccb Fixed: [SECURITY] Upgrade Tika to 1.28.3 (OFBIZ-12626)
Apache Tika 1.28.3 contains security-related fixes and dependency upgrades.
Details can be found in the changes file:
https://www.apache.org/dist/tika/1.28.3/CHANGES-1.28.3.txt
2022-05-28 10:05:11 +02:00
Jacques Le Roux 2cf8d185f0 Improved: Json response failed when element not serializable (OFBIZ-12621)
No functional changes, just removing a compilation warning

While compiling with Java 11 I got this message:
> Task :compileJava
UtilHttp.java:502: warning: [unchecked] unchecked call to
<R>map(Function<? super T,? extends R>) as a member of the raw type Stream
[...]

This fixes it with the help of Eclipse
2022-05-26 12:25:22 +02:00
Jacques Le Roux 8cd5da2e4d Fixed: Webtools Service Logs ‘Service Name’ column always empty (OFBIZ-12625)
rs.getModelService().getName() should be used
instead of
rs.getModelService().name

The rest of changes is only non functional formatting and such

Thanks: Emad Radwan for reporting
2022-05-26 12:08:48 +02:00
Nicolas Malin 5f19f02349 Improved: Redirect unauthenticated user to login on AJAX calls (OFBIZ-12620)
At this time when you aren't logged and you need to be authenticated for access to a page, OFBiz return the login page with a http code 200

This set a problem for ajax call to understand why the page returned isn't the attendee/

This improvement does 3 things :
   * return a HTTP status code 401 (Unauthorized) in LoginWorker::checkLogin if user is not authenticated (no more 200),
   * in common-theme, OfbizUtil.js, on AJAX calls handler, if the request fails with a 401 status code, reload current page (so we land on login form instead of being stuck in a blank modal) with a new search param `clickOn` containing the id of the link that triggered the AJAX call,
   * on page load, if `clickOn` search parameter exists, trigger a click event on the link, so the initial modal pops in after a successful login

Thanks to Florian Motteau for this improvement
2022-05-25 15:37:45 +02:00
Nicolas Malin 4e30052c8a Fixed: Json response failed when element not serializable (OFBIZ-12621)
When you forward a request-map on json response after a service call like this :

     <request-map uri="updateMyEntity">
        <security https="true" auth="true"/>
        <event type="service" invoke="serviceWithUnserializableElement"/>
        <response name="success" type="request" value="json"/>
        <response name="error" type="request" value="json"/>
    </request-map>

The request json works fine if the serviceWithUnserializableElement have an element unserializable on out put at the first level

     <service name="serviceWithUnserializableElement"...>
        <attribute name="outputStream" type="java.io.OutputStream" mode="OUT"/>
     </service>

If the definition is like this

     <service name="serviceWithUnserializableElement"...>
        <attribute name="outputStreamMap" type="Map" mode="OUT"/>
     </service>

The json failed to generate if the outputStream is a map. despite the function UtilHttp.getJSONAttributeMap that safe only the first map level and don't work in deep.

By the way, we improved the getJSONAttributeMap to work in deep by a recursive treatment on Map and List.
2022-05-25 14:37:10 +02:00
Nicolas Malin 0af153a750 Implemented: Configure invoice, quote and order templates for an organizational party (OFBIZ-10215) (OFBIZ-10216) (OFBIZ-10217)
Add the possibility to print invoice, quote and order as pdf from the organizational party configuration.

With this you can define your own xslfo template connected to a custom screen and configure it for each organization through PartyPrefDocTypeTpl

Thanks to Ingo Wolfmayr for patch submission
2022-05-25 14:00:14 +02:00
Jacques Le Roux e8750ec581 Improved: Required field not working on upload type form (OFBIZ-12619)
Fixes a checkstyle issue
2022-05-21 10:42:01 +02:00
Jacques Le Roux 9f55205b65 Fixed: Required field not working on upload type form (OFBIZ-12619)
When trying to submit an upload form with empty required fields, the validation
is not blocked and the submit is made.

Thanks: Leila Mekika
2022-05-21 10:42:01 +02:00
Jacques Le Roux 4f71f851db Improved: Secure the uploads (OFBIZ-12080)
Attachments to order can be also documents. Accepting only images did not prevent
it, you can always bypass that, but it clarifies things.

Also improves the ContentUploadFileTypeNotMatch English label
2022-05-21 10:42:01 +02:00
Nicolas Malin 970857b420 Improved: Helveticus, improve keyboard navigation on login page (OFBIZ-12622)
A few improvement to put directly the focus on username field when we arrive on login page for helveticus theme

Thanks to Marine Desmarchelier for this
2022-05-20 17:14:11 +02:00
Nicolas Malin 94e818c211 Improved: Convert BlogServices.xml mini lang to groovy DSL (OFBIZ-12623)
Convert service createBlogEntry, updateBlogEntry, getBlogEntry and getOwnedOrPublishedBlogEntries from mini lang to
2022-05-19 20:54:29 +02:00
Jacques Le Roux 5cb12eece0 Fixed: German Translation - Inv. Nr. (OFBIZ-12618)
Correct abbreviation of invoice number - german.

Thanks: Ingo Wolfmayr
2022-05-17 19:15:21 +02:00
Jacques Le Roux e8fde502d2 Fixed: cssImgSmall css class definition missing in Helveticus Theme (OFBIZ-12617)
https://localhost:8443/catalog/control/EditCategory?productCategoryId=FOOD-001
Just upload an image - it will be displayed in full size. cssImageSmall css class
is defined in template but no definition is defined the theme.

Thanks: Ingo Wolfmayr
2022-05-17 19:11:03 +02:00
Jacques Le Roux 7471139af1 Improved: ProductAssocs Screen confused (Helveticus Theme) (OFBIZ-12615)
Improve the location and look of the label about date/time entries

Thanks: Ingo Wolfmayr
2022-05-17 09:36:57 +02:00
Jacques Le Roux 3d13c039f4 Fixed: ProductAssocs Screen confused (Helveticus Theme) (OFBIZ-12615)
The ProductAssocs screen does not display as expected.
https://localhost:8443/catalog/control/EditProductAssoc?productId=WG-9943
This is caused by the tooltip syle (flex) defined for an info text that is used
on that screen.

Solution suggested : keep the text by just removing "style=tooltip".

Thanks: Ingo Wolfmayr
2022-05-16 18:31:10 +02:00
Jacques Le Roux e936240b89 Improved: Update sshd dependency and implementation (OFBIZ-12612)
Adds missing ASL2 license header
2022-05-10 10:42:26 +02:00
Gil Portenseigne f5d7bd9b9e Improved: Update sshd dependency and implementation (OFBIZ-12612)
This commit fix an issue that, under high usage, redondant thread are
created.
Update sshd-core to 2.8.0, adding sshd-ftp since it has been separated in its own library.
Add SshClientHelper to hold the unique instance of SshClient.
Update SshFtpClient class to use the unique SshClient, manage the password/identity into the session and clean close the session.
2022-05-06 16:39:15 +02:00
Jacques Le Roux f2894c65d7 Improved: Secure the uploads (OFBIZ-12080)
I did not have these ones, found there
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
and there https://github.com/tennc/webshell
2022-04-25 10:56:57 +02:00
Jacques Le Roux 40c3973a60 Fixed: no functional changes, fixes chekstyle issues
Also adds javadoc task to GH actions, let's see if it works there.

 Conflicts handled by hand in github/workflows/gradle.yaml
2022-04-22 18:38:14 +02:00
Nicolas Malin 59fdc4081b Fixed: RequestMap.event with type service multi doesn't work with dynamic url (OFBIZ-12604)
When you define a controller request-map with an event of type 'service-multi', if your uri contains multiple allocation like 'MyWay/MyAction' the class ServiceMultiEventHandler failed to execute with an EventHandlerException

 *****
    <request-map uri="Payment/QuickSend">
        ...
        <event type="service-multi" invoke="quickSendPayment"/>
        ...
 *****

The reason comes from the necessary to resolve the attribute global-transaction on event definition, and to do that a call to ConfigXMLReader is realized.

But unnecessary because we already have the event element on the context.
Use it directly, simplify the code and fix this issue
2022-04-22 16:09:00 +02:00
Nicolas Malin 44324fc243 Fixed: In place editor wrong enable on display field (OFBIZ-12603)
When, on a form, you set a widget-style on a display field, you activate the inline editor without reason.
The issue comes from HtmlFormMacroLibrary.ftl that initialize some value in a span without control if it's necessary.
2022-04-22 15:33:18 +02:00
Jacques Le Roux cec382dda5 Improved: no functional change, fixes a Javadoc issue
SecurityUtil.java:91: error: unknown tag: String
     * @return List<String>
2022-04-22 12:34:21 +02:00
Jacques Le Roux 3074f476e1 Tested: GH Actions and Buildbot Builders are not consistent (OFBIZ-23076)
This is just a try Infra asked about. I have also asked montastic if we can
have 3 different badges. For now I simply backport this one in order to test
all the Buildbot flows.
2022-04-22 11:09:48 +02:00
Jacques Le Roux 957a088f57 Improved: Prevent possible DOS attack done using Java deserialisation (OFBIZ-12592)
The previous commit was twice wrong:
1. System properties in gradle.properties are not defined using -D but using
systemProp.
2. Anyway systemProp. is defining system properties only available in JVM where
Gradle is running, not the application you run. For that you need to use
applicationDefaultJvmArgs in application in the main build.gradle.

Here is the system property for jdk.serialFilter
2022-04-21 06:00:47 +02:00
Jacques Le Roux aead955798 Fixed: XML Import fails due to security check (OFBIZ-12602)
When importing an entity with "${" in for at least an element it's rejected
because of the security check done to protect from Freemarker unauth attacks
(see OFBIZ-12594).

As suggested by Ingo, allowing users with appropriate permissions seems an
usable solution. We still need to define the "appropriate permissions".
We can start with OFBTOOLS and WEBTOOLS, as it's reported by Ingo, and add
others later if they ever come.

Thanks: Ingo Wolfmayr for report and suggestion
2022-04-20 14:03:51 +02:00
Jacques Le Roux 93557f9788 Improved: GH Actions and Buildbot Builders are not consistent (INFRA-23076)
Reverts previous commit,
see https://lists.apache.org/thread/80wzf4kclfk5nh2fss56jd6otf7y4n2f
2022-04-18 09:32:01 +02:00
Jacques Le Roux f616bb1fd2 Improved: GH Actions and Buildbot Builders are not consistent (INFRA-23076)
It's now 2 weeks that INFRA-23076 is open, so like 3 weeks that BuildBot is not
working for OFBiz at all.

So far I did not run the integration tests on GH because
* we have it on BuildBot
* it's complicated to show the results

Hopefully BuildBot will soon run the OFBiz builds again. But it does not hurt
to run the integration tests on GH, even w/o the results, because at least it's
easier than running them for each commit locally (takes time) and we can run
them locally once we know there is a problem demonstrated with GH actions.
2022-04-18 09:04:48 +02:00
Giulio Speri ed5e12dda6 Fixed: ecomm. listing ProductFacility out of stock issue (OFBIZ-12359)
In method filterOutOfStockProducts added case for "virtual" products.
In case a product isVirtual (= Y), then the available inventory count
(lastInventoryCount) is summed up on all its product variants, across
all the ProductFacility records, and then used to determine if the
(parent/virtual) product is in stock or out of stock.

This fix does not check if the facilityId of the ProductFacility
records retrieved is associated and enabled to the ProductStore.

Thanks Nicola Mazzoni for helping in anlyzing this issue.
2022-04-17 12:32:06 +02:00
Jacopo Cappellato 18b7b0a8d9 Improved: In UtilHttp, for regex processing of urls, replace Java regex with Google RE2J. (#514)
The Main advantage of RE2J is that it guarantees linear time execution.
2022-04-14 07:29:04 +02:00
Jacques Le Roux 2e81ebe705 Fixed: Test run was unsuccessful because of failing solr tests (OFBIZ-12595)
The previous commit for OFBIZ-12594 was only working on Windows. On *nix OSs
there is no way to reliably get "--test" String from java.class.path property.

Also the previous fix was brittle because relying only on 1 space separating
words.

This fix puts in the SolrDispatchFilter system property at the beginning of the
4 Solr tests and removes it at end of them. That presence can reliably be tested
in ControlFilter that is called before SolrDispatchFilter. It allows to bypass
SecurityUtil::containsFreemarkerInterpolation that would else change the
parameters content type that must be application/x-www-form-urlencoded.
content

Thanks: Tom Pietsch for report and Mart Naum for confirmation
2022-04-13 14:40:25 +02:00
Giulio Speri b10e74b030 Fixed: inv. reservation places order if not enough qty (OFBIZ-12455)
If quantity not reserved is not 0, requireInventory is set to Y, system
let an order to be placed anyway.

The usage of the service around the project let make an important
assertion: we can consider that also reserveInventory flag of the
ProductStore is Y, since right now is always the caller context that
checks for the reserveInventory flag.

This fix simply returns a specific error to the caller, avoiding the
system to place the order.

Thanks Nicola Mazzoni for helping in debug this issue and Jacopo
Cappellato for the patch review.
2022-04-07 23:33:54 +02:00
Jacques Le Roux 4fafd9733b Tested: INFRA-23076
Just a fake change to test INFRA-23076
2022-04-06 15:15:35 +02:00
Jacques Le Roux 80b0d9c33f Fixed: Prevent Freemarker interpolation in fields (OFBIZ-12594)
I did not catch an issue put in by this feature because BuildBot is not running
for few days (see INFRA-23076) and i don't always run tests locally (relying on
BuildBot and GH actions don't run tests).

This is the error Solr tests throw else:
<<Unfortunately, the stream was empty / not available. This may be caused by
another servlet filter calling ServletRequest.getParameter*() before
SolrDispatchFilter>>

Conflicts handled by hand
2022-04-06 12:12:51 +02:00
Jacques Le Roux 174ad12179 Fixed: Prevent Freemarker interpolation in fields (OFBIZ-12594)
I did not catch an issue put in by this feature because BuildBot is not running
for few days (see INFRA-23076) and i don't always run tests locally (relying on
BuildBot and GH actions don't run tests).

This is the error Solr tests throw else:
<<Unfortunately, the stream was empty / not available. This may be caused by
another servlet filter calling ServletRequest.getParameter*() before
SolrDispatchFilter>>
2022-04-06 11:00:18 +02:00
Jacques Le Roux 4a5b0f829b Fixed: testInvoicePerShipmentSetFalse work with runtime configuration data (OFBIZ-12453)
UtilProperties::setPropertyValueInMemory was only based on files. Thinking by
analogy, as Pierre pushed SystemProperties with OFBIZ-6189, I thought that by
adding an UtilProperties::setPropertyValueInMemory based on
EntityUtilProperties::getProperties it would resolve the issue. But it did not.

Looking closer at the code, I wondered why UtilProperties::setPropertyValueInMemory
was used at all.

This fixes the issue by simply removing setPropertyValueInMemory and setting "Y"
or "N" when calling testInvoicePerShipment.

It though keeps the new UtilProperties::setPropertyValueInMemory variant
2022-04-06 09:25:15 +02:00
Jacques Le Roux 3284ad3994 Improved: Prevent Freemarker interpolation in fields (OFBIZ-12594)
OFBIZ_12587 is a definitive solution to prevent any kind of Freemarker exploits.
But it's hard to realise because OFBiz exposes objects, like attributes from the
Servlet scopes. So in the meantime preventing Freemarker interpolation in fields
is a pragmatic solution.

This is an improvement but needs to be backported because it kinda affects
security
2022-04-04 08:54:04 +02:00
Giulio Speri ae37f446d7 Fixed: multiple facility inventory reservation issue (OFBIZ-12264)
The ProductStore is set up to reserve inventory from more than one
facility, so the flag oneInventoryFacility is set to N.
Flags requireInventory and reserveInventory are both to Y.
Flag allocateInventory is N.

A product can be anyway reserved in a ProductStoreFacility with its
thru date set and past, so is disabled, and if is not present enough
inventory quantity on other facilities.

Added filtering by date on multiple facility code in
reserveStoreInventoryMethod() and on isStoreInventoryAvailable().
This is the first part of the problem resolution; the second part is
accomplished by path to OFBIZ-12455 Jira.

Thanks: Jacques Le Roux and Pierre SMith for Jira feedbacks, Nicola
Mazzoni for helping in bug analaysis and Jacopo Cappellato for path
review.
2022-04-03 12:44:44 +02:00
Jacques Le Roux e7af1f77f4 Fixed: NullPointerException in plugin 'projectMgr' when listing TimeSheets (OFBIZ-12593)
The empty string causes a NullPointerException, because in the WidgetWorker
returns only an anchorElement  if the description of the hyperlink is not empty.

Solution:  If the anchorElement is null, the line is simply not executed:

Thanks: Tom Pietsch
2022-04-02 11:38:33 +02:00
kabutz a959be75e9 Removed direct call to Class.newInstance() (#510) 2022-04-01 10:46:42 +02:00
Jacques Le Roux a150e7c7a4 Implemented: Restart the ofbiz-vm3 demos server (OFBIZ-22722)
For the next demo to work we need to set the host-headers-allowed to
demo-next.ofbiz.apache.org instead of demo-old.ofbiz.apache.org

Thanks to Drew Foulks for handling the Infra part for us
2022-03-28 18:48:01 +02:00
Jacques Le Roux 4bb226df77 Improved: Prevent possible DOS attack done using Java deserialisation (OFBIZ-12592)
Qing Xu, a security reporter, alerted us that, despite no current vulnerability,
it could be maybe possible to do DOS attacks using Java deserialisation.

That has been fixed with https://openjdk.java.net/jeps/290 and even implemented
in Java 8, but it needs a little effort on our side, here it is.

There is no real bug, to this is an improvement but a security improvement so it
will be backported

Thanks: Qing Xu for report
2022-03-28 12:32:40 +02:00
Jacques Le Roux 2d524f10c5 Documented: Date picker not initialised in ajax-called form (OFBIZ-12097)
Just adds the missing Jira issue number
2022-03-20 12:00:35 +01:00
Jacques Le Roux 90a291d939 Fixed: Date picker not initialised in ajax-called form (OFBIZ-)
Initially wanting to make an useful commit to test changes I did to allow/fix
the stable RAT report rendering, I randomly picked ofbiz-12111. While working on
it I stumbled upon a wrong result when using example/control/ExampleReportXls.

That's due to isXMLHttpRequest="" missing in the renderDateTimeField macro
signature in XlsFormMacroLibrary.ftl. I added it there, and while at
it at other such signatures.

I initially made the renderDateTimeField macro signatures same then in
HtmlFormMacroLibrary.ftl, but finally decided to only add isXMLHttpRequest=""

Unfortunately this can be backported to 18.12 :D
2022-03-19 12:27:19 +01:00
Jacques Le Roux dda10648a4 Fixed: Secure the uploads (OFBIZ-12080)
Changes name="upload_file_type_bogus" in EditCategory.ftl and
EditProductContent.ftl to name="up_load_file_type_bogus"

The last line of deniedWebShellTokens in SecuredUpload and similarly in
SecurityUtilTest classes should no have a comma and anti-slash as previous lines.

Also logs when an image contains one of the token in deniedWebShellTokens
2022-03-17 18:11:01 +01:00
Jacques Le Roux 1363973508 Revert "Fixed: PartyScreen include-form to include-grid (OFBIZ-12591)"
This reverts commit 8913567ec4.
2022-03-17 12:28:33 +01:00
Jacques Le Roux 8913567ec4 Fixed: PartyScreen include-form to include-grid (OFBIZ-12591)
In OFBIZ-11345 the include-form in SecurityForm.xml has been changed to grid.
There is a reference to a form in PartyScreen that has been changed to grid.

Thanks: Ingo Wolfmayr
2022-03-17 12:25:29 +01:00
Michael Brohl 6203b5881c Improved: Update to log4j 2.17.2 (OFBIZ-12590)
Contains bugfixes and improvements, see
https://logging.apache.org/log4j/2.x/changes-report.html#a2.17.2
2022-03-15 17:06:01 +01:00
Michael Brohl f8fd3ebcc7 Improved: Update Tomcat to Version 9.0.60 (OFBIZ-12589)
For changes see https://tomcat.apache.org/tomcat-9.0-doc/changelog.html
2022-03-15 12:21:18 +01:00
Jacques Le Roux f4932aa12d Fixed: Stored XSS in webappPath parameter from content/control/EditWebSite (OFBIZ-12584)
Adds "webappPath" token in deniedWebShellTokens to definitely fix this issue

Also adds "assign" token  for possible future Freemarker exploits
2022-03-13 21:10:53 +01:00
Jacques Le Roux e70deb4cae Fixed: Secure the uploads (OFBIZ-12080)
Removes non satisfying last line (because images may contain those strings) in
security.properties and SecurityUtilTest.java

In SecuredUpload, renames deniedFileExtensions and deniedWebShellTokens to
respectively getDeniedFileExtensions and getDeniedWebShellTokens
2022-03-06 09:42:06 +01:00
Jacques Le Roux edfd4de38d Fixed: Remove _PREVIOUS_REQUEST_ Session Attribute on non-authentication pages (OFBIZ-12047)
Demo content website cmssite/cms could not be accessed because in this case
requestUri is null. Like login request it does not need auth, I did not dig
further, here is a simple fix.
2022-03-06 09:18:42 +01:00
Jacques Le Roux 06893c762f Fixed: Secure the uploads (OFBIZ-12080)
Removes <svg, replaces by onload,build according to
https://portswigger.net/web-security/cross-site-scripting/cheat-sheet
2022-02-27 21:58:02 +01:00
Jacques Le Roux cc468b125f Fixed: Stored XSS in webappPath parameter from content/control/EditWebSite (OFBIZ-12584)
Adds <<",","+",',','+'>> to deniedWebShellTokens as an obviously non satisfying
(because images may contain those strings, I checked) temporary solution before
looking at Freemarker::WhitelistMemberAccessPolicy as suggested by Matei

Thanks to Matei "Mal" Badanoiu for reporting this post-auth vulnerabily
2022-02-27 18:27:21 +01:00
Jacques Le Roux b06585c9bd Fixed: Secure the uploads (OFBIZ-12080)
Just occurred to my mind that I forgot to lower case the tokens in
DENIEDWEBSHELLTOKENS when checking with SecuredUpload::isValidText
2022-02-27 15:42:56 +01:00
Jacques Le Roux 5f92549b9e Improved: Reflected XSS in content component (OFBIZ-11840)
This was already fixed but we can do better by using SecuredUpload::isValidText

Also grabs some tokens to security.properties::deniedWebShellTokens from
DataEvents.java, and adds "alert" even it's harmless as is, as it's often used
by attackers to demonstrate issues, so will earn time.

Though an improvement, I backport as it's related to security
2022-02-27 13:39:29 +01:00
Jacques Le Roux 169e370a60 Fixed: Stored XSS in webappPath parameter from content/control/EditWebSite (OFBIZ-12584)
A user with rights to modify and/or create websites may insert malicious HTML
elements in the “webappPath” parameter from content/control/EditWebSite
resulting in XSS.

In order to trigger the XSS a victim needs to navigate to main page of the
modified website (eg webpos or ecommerce) and interact with the malicious
HTML elements (eg trigger the “onmouseover” event by navigating with the mouse
over the “form” and/or “a” tags).

Thanks to Matei "Mal" Badanoiu for reporting this post-auth vulnerabily
2022-02-27 13:36:28 +01:00
Jacques Le Roux 2ad16f3e8a Fixed: Secure the uploads (OFBIZ-12080)
Checks that the content of SecuredUpload::isValidText is not null,
else returns false

Suspenders and belt type of fix.
2022-02-25 12:08:21 +01:00
Jacques Le Roux 16c8afe5d0 Fixed: Prevent post-Auth vulnerability: FreeMarker Bypass (OFBIZ-12582)
By inserting malicious content in the “Text” field from
“/content/control/updateLayoutSubContent” -> “Templates”, an attacker may
perform SSTI (Server-Side Template Injection) attacks, which can leverage
FreeMarker exposed objects to bypass restrictions and obtain RCE (Remote Code
Execution).

This fixes it by calling SecuredUpload::isValidText on the “Text” field content.
I'll check that there are no other attack opportunities...

Thanks: Mal Aware <awaremal@gmail.com> for reporting this post-auth vulnerabily
2022-02-23 11:51:02 +01:00
Jacques Le Roux 7157cf3681 Fixed: Secure the uploads (OFBIZ-12080)
Adds some tokens in security.properties::deniedWebShellTokens
Updates SecurityUtilTest::webShellTokensTesting accordingly
2022-02-23 11:51:01 +01:00
Jacques Le Roux f1b967160f Fixed: Trivial change in ProgramExport.groovy, uses the SecuredUpload import
No Functional change

Conflicts handled by hand in ProgramExport.groovy
2022-02-23 11:51:01 +01:00
Jacques Le Roux 6e54f7d000 Fixed: Secure the uploads (OFBIZ-12080)
Fixes deniedWebShellTokens tests
2022-02-22 09:48:56 +01:00
Jacques Le Roux c82fb190a5 Fixed: Secure the uploads (OFBIZ-12080)
Trivial change in DataServices.java: uses the SecuredUpload import in 2 places
it was missing.

Adds some tokens in security.properties::deniedWebShellTokens
Removes a duplicated htaccess in security.properties::deniedFileExtensions
2022-02-21 17:15:26 +01:00
Jacques Le Roux 4d70280cb8 Fixed: Secure the uploads (OFBIZ-12080)
Last commits put in an issue in DataServices.java and GroovyBaseScript.groovy.
I should have used SecuredUpload::isValidFileName with dataResourceName and
SecuredUpload::isValidFile  with objectInfo. This fixes that.

Also fixes formatting checkstyle issues in SecuredUpload class.

Also fixes formatting checkstyle issues in SecuredUpload class and move allow
all and check line length in right places (it's about content)
2022-02-20 15:44:16 +01:00
Jacques Le Roux b885423107 Improved: no functional change, just removes a line
This is because I pushed all from 22.01 branch instead of trunk and there are
checkstyle issues in trunk, in SecuredUpload.java
2022-02-20 09:27:58 +01:00
Jacques Le Roux 3b29cd3a78 Improved: Secure the uploads (OFBIZ-12080)
In security.properties, adds some deniedFileExtensions and improves few comments
(easier to merge later)

In  DataServices::createFileNoPerm filters file upload to verify the filename
before the content is checked if necessary

Manually merges SecuredUpload.java based on trunk

Conflicts merged by hand in SecuredUpload.java
2022-02-19 11:40:30 +01:00
Jacques Le Roux e25470ce13 Fixed: Secure the uploads (OFBIZ-12080)
Prevents special bytes in filename
Adds some deniedFileExtensions
2022-02-18 18:36:10 +01:00
Jacques Le Roux b476d67bef Fixed: Secure the uploads (OFBIZ-12080)
Prevents billions laugh attacks
2022-02-18 15:45:26 +01:00
Jacques Le Roux e6443c1369 Fixed: Secure the uploads (OFBIZ-12080)
In previous comment, to prevent linked images inside SVG I used xlink:href
That's no good, it must be followed by <<="http">>, this does it. Else a lot
of SVP images would not be loadable. Because xlink:href can be used in other
cases.
2022-02-18 15:33:44 +01:00
Jacques Le Roux 97740e0c7a Improved: Create a deny list to reject webshell tokens (OFBIZ-12324)
Prevents CSV injection (MS Excel or Open Office)
2022-02-18 13:51:18 +01:00
Jacques Le Roux 70c799dc63 Fixed: Secure the uploads (OFBIZ-12080)
Prevents
* too long lines (10 000) by default
* linked images inside SVG

Adds a comment about double extensions not allowed

Conflicts handled by hand
 SecuredUpload.java
2022-02-17 19:02:52 +01:00
Jacques Le Roux 52ae393138 Fixed: Secure the uploads (OFBIZ-12080)
Prevents
* too long lines (10 000) by default
* linked images inside SVG

Adds a comment about double extensions not allowed
2022-02-17 18:55:26 +01:00
Jacques Le Roux 124eb38abb Improved: Error in uploading very large files, ie >2GB (OFBIZ-11534)
I reopened, forgot that you need to set -PjvmArgs, as I commented before:
<<For a 2GB+ file you need to set Xmx to more than the double of the file size,
eg: gradlew ofbiz -PjvmArgs="-Xms1024M -Xmx5048M">>

This also adds information in security.properties:
<<By default (OOTB) OFBiz is protected against Large File Denial of Service>>
2022-02-16 17:28:11 +01:00
Jacques Le Roux d9467463c5 Improved: Create a deny list to reject webshell tokens (OFBIZ-12324)
After reviewing https://github.com/nsacyber/Mitigating-Web-Shells this mostly
adds as tokens the "Linux applications commonly used by attackers and rarely
launched by benign Apache applications"
2022-02-15 08:03:00 +01:00
Jacques Le Roux 183b507041 Improved: Create a deny list to reject webshell tokens (OFBIZ-12324)
After reviewing https://docs.oracle.com/cd/B14099_19/web.1012/b14014/jspxml.htm,
since we use "<jsp:" this removes "scriptlet>", "declaration>" and "expression>".
They are redundant with "<jsp:"; "<jsp:" covers those already.

Also adds eval( for js and shrinks base64_decode to decode, and processbuilder
to process because of OFBIZ 12571

I always test the denied tokens against a lib of  images with 33 600 elements (
3.99 GB). If an image contains the token it can't be in the denied list.
2022-02-14 13:17:24 +01:00
Jacques Le Roux b1eade9270 Fixed: CLONE - [SECURITY] Upgrade Tika to 1.28.1 (OFBIZ-12573)
Simpler for now, later OFBIZ 12573 needs to be done
Also formatting improvement in DataResourceWorker.java: removes a blank lines

Thanks: Tim Allison <tallison@apache.org> for the nice exchanges :)
2022-02-12 11:45:34 +01:00
Jacques Le Roux c75c37d1ec Fixed: Groovy denied list bypass causes post-auth RCE from webtools/control/ProgramExport (OFBIZ-12571)
The 1st issue was due to use of processbuilder token. It has been added to
deniedWebShellTokens in security.properties by f2cf262 commit for OFBIZ 11948
The tokens function (for js) and class have been added since while browsing
https://github.com/tennc/webshell

As mention the related deniedWebShellTokens TODO comment: "TODO.... to be continued
with known webshell contents... a complete allow list is impossible anyway...

So, later a deeper review of Groovy sandbox possibilities will be done..

Thanks: Y4er for report
2022-02-11 11:01:28 +01:00
Jacques Le Roux 9fcc4d7806 Improved: no functional changes, removes trailing spaces just to pass checkstyle
Check passed locally but not on GH nor BuildBot
2022-02-10 18:27:41 +01:00
Jacques Le Roux 8691b1a7e1 Fixed: Remote Code Execution (File Upload) Vulnerability (OFBIZ-11948)
This fixes and improves file upload.

Refactor a bit SecuredUpload class and fixes:
Prevent double extensions
Check extensions
Improves getMimeTypeFromFileName() by checking is file exists
In isValidImageFile() finally use isValidText() bypassing encoding

Completely refactor deniedWebShellTokens in security.properties by re-adding
removed tokens in last commit and adding several new ones. I have still to check
encoded, encrypted and obfuscated webshells)
Modifies SecurityUtilTest::webShellTokensTesting accordingly
While at it better format commonsImagingSupportedFormats, deniedFileExtensions
and imagejSupportedFormats properties for legibility.

Check if createAnonFile service is used in GroovyBaseScript.groovy and if a
complete file name is used (file exist) check, using SecuredUpload, extensions
and prevent double extensions, actually check all the file and stop there.

Adds some "Check if a webshell is not uploaded" comments in
ContentManagementServices.java
DataServices.java
ScaleImage.java
FrameImage.java
ImageManagementServices.java
ProductServices.java
HttpRequestFileUpload.java
ProgramExport.groovy

Trivial comments fixes in catalog.properties

Also fixes OFBIZ 12571 (I use here a space because of pending INFRA 22843)
by simply adding processbuilder to deniedWebShellTokens
2022-02-10 14:02:08 +01:00
Jacques Le Roux 4bb37d7950 Improved: Possible authenticated attack related to Tomcat CVE-2020-1938 (OFBIZ-12558)
As reported by Michael, secretRequired value must be false because secret value
is empty. Else a notifying message appears in log saying that AJP is not available.

This uncomment out secretRequired, so its value is now false, and document more
notably about that. I'll later add more information in the
https://cwiki.apache.org/confluence/display/OFBIZ/Keeping+OFBiz+secure wiki page

Thanks: Michael for report
2022-02-10 14:02:08 +01:00
Jacques Le Roux af6286e304 Improved: no functional trivial cleaning changes
Removes useless menu-name="secondary" for common-theme webapp
Removes now useless runtime/patches directory. It was only used with Ant
2022-02-10 14:02:08 +01:00
Jacques Le Roux 9ea39d4eff Documented: Possible authenticated attack related to Tomcat CVE-2020-1938 (OFBIZ-12558)
Explains that the current AJP config works only for localhost
2022-02-10 14:02:08 +01:00
Jacques Le Roux b447f4dd3f Fixed: Remote Code Execution (File Upload) Vulnerability (OFBIZ-11948)
In SecuredUpload::isValidImageFile I initially used isValidText() and thought
that decoding would be better so finally used isValidTextFile() instead. But
then valid images files are not passing. So this replaces isValidTextFile by
isValidText there.

Also while at it removes few other PHP tokens, now useless (hopefully, I have
still to check encoded and encrypted PHP webshells), from
security::deniedWebShellTokens. The less tokens we have the better the whole is
legible.
Improves related comments.

Modifies SecurityUtilTest::webShellTokensTesting accordingly
2022-02-05 10:14:17 +01:00
Jacques Le Roux b2b6250fac Fixed: Remote Code Execution (File Upload) Vulnerability (OFBIZ-11948)
I forgot about SecurityUtilTest::webShellTokensTesting. This fixes it.

Note that I expect to simplify and remove more tokens for PHP, but I have 1st
other things to do...
2022-02-04 15:04:08 +01:00
Jacques Le Roux b2c0a4a644 Fixed: Possible authenticated attack related to Tomcat CVE-2020-1938 (OFBIZ-12558)
Despite OFBIZ-11407, the 2 values secretRequired and especially
allowedRequestAttributesPattern are commented out because of OFBIZ-12558

The Tomcat default values will be used as recommended by
https://tomcat.apache.org/tomcat-9.0-doc/config/ajp.html#Introduction
This is in relation with
https://tomcat.apache.org/security-9.html#Fixed_in_Apache_Tomcat_9.0.31
and
https://tomcat.apache.org/tomcat-9.0-doc/security-howto.html#Connectors

Thanks: Lion Tree for report
2022-02-04 12:29:09 +01:00
Jacques Le Roux 8c2d759847 Fixed: Remote Code Execution (File Upload) Vulnerability (OFBIZ-11948)
Lion Tree <liontree0110@gmail.com> has reported us that
"CVE-2020-1938 is not fully fixed".

Though it was fixed by OFBIZ-11407, it still possible for an authenticated user
to upload a webshell included in an image using one of the upload possibilities
in OFBiz. That is not new and covered by OFBIZ-12080 "Secure the uploads", but
was still incomplete.

This enforces the secured uploads by
* checking in SecuredUpload::isValidImageFile that a webshell is not embedded in
an image.
* Keeping only "<%" as a denied token for JSP webshells, instead of currently
"<%@ page"
* Adds "application/text/x-ruby" to SecuredUpload::isExecutable

Also
* Adds "<jsp", and "<?" for PHP. Even if OFBiz does not use PHP at all,
it's often installed on servers.
* Removes "import=\"java" and "runtime.getruntime().exec(". They are no
longer useful since "<%" and "<jsp" block them.
* Remove php token since I'll put "<?" in.
* Adds "#!", rather than adding other shebangs like perl,python and ruby

This will make deniedWebShellTokens more understandable.

But I'm conscious that despite SecuredUpload::isExecutableI I still need to
better handle encoded webshells. I'll do that soon in a second approach.

I'll also certainly more prune PHP related tokens.

Thanks: Lion Tree for report
2022-02-04 12:13:44 +01:00
Jacques Le Roux ef60c32669 Improved: no functional change, adds a BuildBot badge (INFRA-22807)
It works locally (once you have installed Ruby, asciidoctor and
asciidoctor-diagram), I see it's currently running, fine
2022-02-03 11:35:11 +01:00
Nicolas Malin bc91eedebe Fixed: Attribute default-field-type hidden doesn't work for auto-fields-service element (OFBIZ-12555)
Fix the compilation error on build bot that not support java11, downgrade the code to java8
2022-02-03 10:28:33 +01:00
Nicolas Malin 4caa15b26a Fixed: Attribute default-field-type hidden doesn't work for auto-fields-service element (OFBIZ-12555)
When you define a widget form and wish populate hidden fields with the element auto-fields-service, OFBiz rendering each as edit field type.

    <form name="ListPartyQuals" ...>
        <auto-fields-service service-name="updatePartyQual" default-field-type="hidden"/>
    </form>

The problem came from the function ModelFormFieldBuilder.induceFieldInfoFromServiceParam didn't manage the case "hidden"

By the way, this function is "if" forest, and simplify reading.
2022-02-02 18:09:00 +01:00
Jacques Le Roux a1de8f0351 Fixed: View for ViewBinaryDataResource missing (OFBIZ-12552)
The view definition for ViewBinaryDataResource is missing.
Goto: /content/control/EditDataResource?dataResourceId=GZ-DIG
Click the "Download"-Button.

Thanks: Ingo Wolfmayr for the patch
2022-02-01 13:23:40 +01:00
Jacques Le Roux 395ef47762 Fixed: Manufacturing Jobshop find screen by default does not show all production runs (OFBIZ-12550)
The manufacturing jobshop find screen has the seach date initialized to nowdate.
if one wants to see all production runs, one has to clear the date which should
be empty initially

The same problem exists on the MRP log find where the date is filled by default.

Thanks: Hans for report and patches
2022-02-01 08:58:36 +01:00
Jacques Le Roux 13f5f3eb6e Fixed: [SECURITY] CVE-2022-23437: Infinite loop within Apache XercesJ xml parser (OFBIZ-12549)
Severity: high

Description:

There's a vulnerability within the Apache Xerces Java (XercesJ) XML
parser when handling specially crafted XML document payloads. This
causes, the XercesJ XML parser to wait in an infinite loop, which may
sometimes consume system resources for prolonged duration. This
vulnerability is present within XercesJ version 2.12.1 and the
previous versions.

Mitigation:

Apache XercesJ users, should migrate to version 2.12.2

Credit:

This issue was discovered by Sergey Temnikov and Ziyi Luo, from Amazon
Corretto/JDK Team

References:

https://markmail.org/message/vcmhwbuorfgcdr6l
2022-01-31 17:44:21 +01:00
Nicolas Malin c12e727df2 Fixed: Element condition-[expr/list/object] doesn't work with compound (OFBIZ-12546)
When you create an entity-condition in a form or grid under a compound element, to write a valid xml you write it with the namespace like this :

    <wf:actions>
        <wf:entity-condition entity-name="PartyRelationship"...>
            <wf:condition-list>
                <wf:condition-expr field-name="partyIdFrom" from-field="parameters.partyIdFrom"/>
                <wf:condition-expr field-name="partyIdTo" from-field="parameters.partyIdTo"/>
            </wf:condition-list>
        </wf:entity-condition>
    </wf:actions>

This failed when OFBiz execute the search with error Invalid element with name '[wf:condition-expr]' found under a condition-list element.

The error came from the class EntityFinderUtil.ConditionList who analyze the condition-list's children with the namespace + node name instead take only the node name.

    if ("condition-expr".equals(subElement.getNodeName()))

To solve this issue we only check the local node name regardless from the namespace used.
2022-01-31 14:45:33 +01:00
Jacques Le Roux 51930641c5 Fixed: Wrong Field Name Definition in RequirementForms (OFBIZ-12505)
The issue exists also in the older version.

The field "requirementByDate" form "FindApprovedProductRequirements" in
RequirementForms.xml has been set wrongly and it should be "requiredByDate".

This causes the result could not be queried out properly as indicated as below:

The result is governed by the service "getRequirementsForSupplier",
where reads the list from the view "RequirementAndRole".
In the view entity definition, the field is defined as
<alias entity-alias="RQ" name="requiredByDate"/>,
but it is not the case in the form "FindApprovedProductRequirements" above.

After changing it to the correct name, the bug is solved.

jleroux: Same exists in OrderEntryForms::FindRequirements

Thanks: Schumann Ye for report Pierre Smits for creating the initial PR494
2022-01-31 12:25:04 +01:00
Jacques Le Roux d324f6abee Fixed: Attribute 'placeholder' is not allowed to appear in element 'text'
Completes the previous fix by Wei Zhang. This was committed at a wrong place
for OFBIZ-5341. Only text was concerned, not date-time
2022-01-29 10:57:31 +01:00
Jacques Le Roux bbc5757782 Fixed: Upgrade Tomcat from 9.0.54 to 9.0.58 (OFBIZ-12539)
The fix for bug CVE-2020-9484 introduced a time of check, time of use
    vulnerability that allowed a local attacker to perform actions with the
    privileges of the user that the Tomcat process is using. This issue is only
    exploitable when Tomcat is configured to persist sessions using the FileStore.

Also reverts node from 13.14.0 back to 16.13.1. It accidentally slipped in with
OFBIZ-11960
2022-01-26 12:40:29 +01:00
Nicolas Malin 4936f6f145 Improved: Use flexible expander to resolve the area target on call back (OFBIZ-12509)
When you use a callback, at this time we haven't to possibility to resolve the area target from the context like this

                <wm:link target="WorkEffortAgreement/delete">
                    ....
                    <wm:set-callback area-target="${useThisTarget}">
                       ...
                    </wm-setcallback>
                </wm:link>
2022-01-24 07:16:36 +01:00
Jacques Le Roux 8b3e8b5a22 Improved: no functional change, removes tests in GH actions
Adding testIntegration in the GH Gradle process does not work.

For a reason I'll not dig in, it ALWAYS fails at:
Cannot find service [indexProductsFromContent] location class
(org.apache.ofbiz.content.search.SearchServices)
2022-01-15 12:23:35 +01:00
Jacques Le Roux 1a022418d0 Improved: no functional change, add tests to GH actions
Buildbot is stale at the moment and it's better to not rely only on it.
This adds testIntegration to the GH Gradle process
2022-01-15 10:00:36 +01:00
Jacques Le Roux 8a0bdbaf3b Fixed: no functional change, changes VERSION file to test BB 22 config
Since bb_worker4_ubuntu is stale
temporary trying with bb_worker5_ubuntu
2022-01-14 15:16:22 +01:00
Jacques Le Roux f6e5b85a05 Fixed: no functional change, removes a space in VERSION file to test BB 22 config
The common BB config was broken by Apache Commons (actually a converter issue).
Though the BB syntax checker does not report it's OK, it should be after Sebb's
fix
2022-01-13 14:04:42 +01:00
Jacques Le Roux 937ecd5098 Fixed: no functional change, just adds a space in Version to test BB config
IRC ofbiz-bot is planned by Infra to be available this month
2022-01-13 13:23:50 +01:00
Jacques Le Roux 2d7ceaa6b5 Fixed: no functional change, right version (22.01) in gradle.yaml (fix a typo)
This will also allow to test the just updated BB config, thanks to Pierre's
report on dev ML
2022-01-13 10:57:22 +01:00
Jacques Le Roux a114a20ba8 Fixed: no functional change, right version (22.01) in gradle.yaml
This will also allow to test the just updated BB config, nothing happened last
time no ideas why yet...
2022-01-13 10:14:05 +01:00
Jacques Le Roux 1c8e598ece Fixed: no functional change, right version (22.01) in README.adoc
This will also allow to test the just updated BB config
2022-01-13 09:32:06 +01:00
Jacques Le Roux 958ef1185e Fixed: Updates README.adoc file from trunk to next 2022-01-10 19:17:35 +01:00
Jacques Le Roux 02a13d9f3c Fixed: Updates codeql-analysis.yml file from trunk to release22.01 2022-01-10 18:34:35 +01:00
Jacques Le Roux e13d335618 Fixed: Updates VERSION file from trunk to release22.01 2022-01-10 18:32:18 +01:00
107 changed files with 1806 additions and 872 deletions
+6
View File
@@ -16,6 +16,8 @@
github:
description: "Apache OFBiz is an open source product for the automation of enterprise processes. It includes framework components and business applications for ERP, CRM, E-Business/E-Commerce, Supply Chain Management and Manufacturing Resource Planning. OFBiz provides a foundation and starting point for reliable, secure and scalable enterprise solutions."
homepage: https://ofbiz.apache.org/
dependabot_alerts: true
dependabot_updates: false
labels:
- ofbiz
- plugins
@@ -29,3 +31,7 @@ github:
- https
- content
- geospatial
notifications:
jobs: notifications@ofbiz.apache.org
jira_options: link label
+1 -1
View File
@@ -28,7 +28,7 @@ on:
branches: [ trunk, release* ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ trunk ]
branches: [ release22.01 ]
schedule:
- cron: '27 15 * * 1'
+8 -5
View File
@@ -21,9 +21,9 @@ name: Java CI with Gradle
on:
push:
branches: [ trunk ]
branches: [ release22.01 ]
pull_request:
branches: [ trunk ]
branches: [ release22.01 ]
jobs:
build:
@@ -32,11 +32,14 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 1.8
java-version: 11
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build with Gradle
run: ./gradlew pullAllPluginsSource check
run: ./gradlew pullAllPluginsSource check javadoc
# Below does not work, see see https://lists.apache.org/thread/80wzf4kclfk5nh2fss56jd6otf7y4n2f
# - name: Builds with Gradle, checks style and run integration tests (just to know if they pass)
# run: ./gradlew pullAllPluginsSource check javadoc loadAll testIntegration
+1 -1
View File
@@ -6,7 +6,7 @@ your business.
System requirements
The only requirement to run OFBiz is to have the Java Development Kit (JDK)
version 8 installed on your system (not just the JRE, but the full JDK) which
version 11 installed on your system (not just the JRE, but the full JDK) which
you can download from the below link. Make sure of setting the $JAVA_HOME
environment variable.
+10 -7
View File
@@ -21,14 +21,16 @@ under the License.
The Apache OFBiz Project
image:https://img.shields.io/badge/License-Apache%202.0-blue.svg[link=http://www.apache.org/licenses/LICENSE-2.0]
image:https://img.shields.io/badge/Version-trunk-blue.svg[link=https://github.com/apache/ofbiz-framework]
image:https://github.com/apache/ofbiz-framework/actions/workflows/gradle.yaml/badge.svg?branch=trunk[link=https://github.com/apache/ofbiz-framework/actions/workflows/gradle.yaml]
image:https://img.shields.io/badge/Version-release22.01-blue.svg[link=https://github.com/apache/ofbiz-framework]
image:https://ci2.apache.org/badges/ofbizBranch22Framework.svg[link=https://ci2.apache.org/badges/ofbizBranch22Framework.svg]
image:https://github.com/apache/ofbiz-framework/actions/workflows/gradle.yaml/badge.svg?branch=release22.01[link=https://github.com/apache/ofbiz-framework/actions/workflows/gradle.yaml]
image:https://sonarcloud.io/api/project_badges/measure?project=apache_ofbiz-framework&metric=alert_status[link=https://sonarcloud.io/dashboard?id=apache_ofbiz-framework]
image:https://github.com/apache/ofbiz-framework/actions/workflows/codeql-analysis.yml/badge.svg[link=https://github.com/apache/ofbiz-framework/actions/workflows/codeql-analysis.yml]
image:https://qpkb254zxeu.montastic.io/badge[link=https://qpkb254zxeu.montastic.io]
If you are reading this file in AsciiDoc format you may want to see it at
https://nightlies.apache.org/ofbiz/trunk/readme/html5/[HTML]
or https://ci.apache.org/projects/ofbiz/site/trunk/readme/pdf/README.pdf[PDF] format
https://nightlies.apache.org/ofbiz/next/readme/html5/[HTML]
or https://ci.apache.org/projects/ofbiz/site/next/readme/pdf/README.pdf[PDF] format
---
@@ -68,7 +70,7 @@ ________________________________________________________________________________
The only requirements to run OFBiz is
* to have the Java Development Kit (JDK) version 8 installed on your system
* to have the Java Development Kit (JDK) version 11 installed on your system
(not just the JRE, but the full JDK) that you can download from the below link.
Make sure of setting the $JAVA_HOME environment variable. +
https://adoptopenjdk.net/[JDK download].
@@ -95,7 +97,7 @@ the command line at the OFBiz top level directory (folder).
MS Windows: `init-gradle-wrapper`
[IMPORTANT]
====
* If you cross the error
* If you cross the error
[quote]
____
"Powershell is not recognized as an internal or external command, operable program or batch file"
@@ -166,7 +168,8 @@ Once proper mitigations to the security issues are complete the OFBiz team will
disclose this information to the public mailing list.
* If you find a post-auth security issue, please https://s.apache.org/dsj2p[create a bug in our issue tracker (Jira)] .
* If you want to use AJP on a non localhost OFBiz instance, you need to set the value of allowedRequestAttributesPattern
in framework/catalina/ofbiz-component.xml
You can find more information about security in OFBiz at
https://cwiki.apache.org/confluence/display/OFBIZ/Keeping+OFBiz+secure[Keeping OFBiz secure]
+1 -1
View File
@@ -1 +1 @@
Trunk
Release22.01
@@ -7312,7 +7312,7 @@
<property key="AccountingInvNr">
<value xml:lang="ar">رقم الفاتورة</value>
<value xml:lang="cs">Číslo faktury</value>
<value xml:lang="de">Inv.Nr</value>
<value xml:lang="de">Rg.Nr</value>
<value xml:lang="en">Inv.Nr</value>
<value xml:lang="es">Nr.Fact</value>
<value xml:lang="es-CL">Factura N°</value>
@@ -18,7 +18,7 @@ specific language governing permissions and limitations
under the License.
-->
<entity-engine-xml>
<!--
<!--
# what should the default of the payment to invoice processing be?
# paymentProcessing by invoice or paymentprocessing by invoiceitem?
# there is still a box on the menu to change this option by the user.
@@ -27,27 +27,27 @@ under the License.
#value YY: do not show the option box to the user and do only invoice processing
#value NN: do not show the option box to the user and do only invoiceitem processing
-->
<SystemProperty systemResourceId="accounting" systemPropertyId="invoiceProcessing"
<SystemProperty systemResourceId="accounting" systemPropertyId="invoiceProcessing"
systemPropertyValue="YY"
description="Options are: Y, N, YY, NN"
/>
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.fixedasset.autocreate"
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.fixedasset.autocreate"
systemPropertyValue="Y"
description="Create a fixed asset when an 'asset usage' type product is created. Options: Y, N"/>
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.application.autocreate"
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.application.autocreate"
systemPropertyValue="Y"
description="Create a payment application when a payment is received/sent or invoice is approved (take the oldest not closed one). Options: Y, N"/>
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.purchaseorder.autocreate"
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.purchaseorder.autocreate"
systemPropertyValue="Y"
description="Create a 'not-paid' payment record if the purchase order is approved. Options: Y, N"/>
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.salesorder.autocreate"
<SystemProperty systemResourceId="accounting" systemPropertyId="accounting.payment.salesorder.autocreate"
systemPropertyValue="Y"
description="Create a 'not-paid' payment record if the sales order is completed and no payment exist yet. Options:: Y, N"/>
<!-- <SystemProperty systemResourceId="accounting" systemPropertyId="create.invoice.per.shipment" systemPropertyValue="Y"
description="create invoice per shipment. Options: = Y (Invoice per shipment), N (Invoice per order)"/> -->
<SystemProperty systemResourceId="accounting" systemPropertyId="create.invoice.per.shipment" systemPropertyValue="Y"
description="create invoice per shipment. Options: = Y (Invoice per shipment), N (Invoice per order)"/>
</entity-engine-xml>
@@ -19,7 +19,7 @@
package org.apache.ofbiz.accounting
import javax.servlet.http.HttpSession
import org.apache.ofbiz.base.util.UtilProperties
import org.apache.ofbiz.base.util.UtilValidate
import org.apache.ofbiz.entity.GenericValue
import org.apache.ofbiz.order.shoppingcart.CheckOutEvents
@@ -142,49 +142,43 @@ public class InvoicePerShipmentTests extends OFBizTestCase {
}
void testInvoicePerShipmentSetFalse() {
/* Test Invoice Per Shipment
Step 1) Set create.invoice.per.shipment=N in accounting.properties file.
Step 2) Create order and approve order.
Step 3) Pack Shipment For Ship Group.
Step 4) Check invoice should not created.
*/
UtilProperties.setPropertyValueInMemory("accounting", "create.invoice.per.shipment", "N")
logInfo("===== >>> Set Accounting.properties / create.invoice.per.shipment = N")
List invoices = testInvoicePerShipment("GZ-1000", null)
Step 1) Set create.invoice.per.shipment=N in accounting.properties file.
Step 2) Create order and approve order.
Step 3) Pack Shipment For Ship Group.
Step 4) Check invoice should not created.
*/
List invoices = testInvoicePerShipment("GZ-1000", "N")
assert UtilValidate.isEmpty(invoices)
}
void testInvoicePerShipmentSetTrue() {
/* Test Invoice Per Shipment
Step 1) Set create.invoice.per.shipment=Y in accounting.properties file.
Step 2) Create order and approve order.
Step 3) Pack Shipment For Ship Group.
Step 4) Check invoice should be created.
Step 1) Set create.invoice.per.shipment=Y in accounting.properties file.
Step 2) Create order and approve order.
Step 3) Pack Shipment For Ship Group.
Step 4) Check invoice should be created.
*/
UtilProperties.setPropertyValueInMemory("accounting", "create.invoice.per.shipment", "Y")
logInfo("===== >>> Set Accounting.properties / create.invoice.per.shipment = Y")
List invoices = testInvoicePerShipment("GZ-1000", null)
List invoices = testInvoicePerShipment("GZ-1000", "Y")
assert UtilValidate.isNotEmpty(invoices)
}
void testInvoicePerShipmentSetOrderFalse() {
/* Test Invoice Per Shipment
Step 1) Create order and set invoicePerShipment=N.
Step 2) Pack Shipment For Ship Group.
Step 3) Check invoice should not be created.
*/
Step 1) Create order and set invoicePerShipment=N.
Step 2) Pack Shipment For Ship Group.
Step 3) Check invoice should not be created.
*/
List invoices = testInvoicePerShipment("GZ-2644", "N")
assert UtilValidate.isEmpty(invoices)
}
void testInvoicePerShipmentSetOrderTrue() {
/* Test Invoice Per Shipment
Step 1) Create order and set invoicePerShipment=Y
Step 2) Pack Shipment For Ship Group.
Step 3) Check invoice should be created.
*/
Step 1) Create order and set invoicePerShipment=Y
Step 2) Pack Shipment For Ship Group.
Step 3) Check invoice should be created.
*/
List invoices = testInvoicePerShipment("GZ-2644", "Y")
assert UtilValidate.isNotEmpty(invoices)
}
}
}
@@ -25,6 +25,19 @@ under the License.
<!-- generate a PDF for the invoice. Sharing the same script file as the HTML page for viewing invoice -->
<screen name="InvoicePDF">
<section>
<actions>
<set field="defaultTemplateLocation" value="component://accounting/widget/AccountingPrintScreens.xml"/>
<set field="defaultTemplateName" value="DefaultInvoicePDF"/>
<script location="component://commonext/groovyScripts/template/DocTypeTemplate.groovy"/>
</actions>
<widgets>
<include-screen name="${templateName}" location="${templateLocation}"/>
</widgets>
</section>
</screen>
<screen name="DefaultInvoicePDF">
<section>
<actions>
<property-map resource="AccountingUiLabels" map-name="uiLabelMap" global="true"/>
@@ -0,0 +1,70 @@
package org.apache.ofbiz.common.template
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.ofbiz.entity.GenericValue
import org.apache.ofbiz.entity.model.ModelUtil
def getFieldTypeName(String entityName) {
return ModelUtil.lowerFirstChar(entityName) + 'Id'
}
/**
* For a entityTypeName and a value return the matching templating document screen
* If no value found, do a recursive search on parentType
*/
def getCustomScreenTemplate(String entityTypeName, String fieldTypeValue) {
if (! fieldTypeValue) {
return null
}
GenericValue tplCustScreen = from("PartyPrefDocTypeTplAndCustomScreen")
.where(getFieldTypeName(entityTypeName), fieldTypeValue)
.cache()
.queryFirst()
if (tplCustScreen) {
return tplCustScreen
}
// No template found for this type, try if the parent had
String parentTypeValue = from(entityTypeName).where().cache().queryFirst().parentTypeId
return getCustomScreenTemplate(entityTypeName, parentTypeValue)
}
// first resolve the document reference passed on the context
String entityName = ""
String entityTypeName = ""
if (parameters.orderId) {
entityName = "OrderHeader"
entityTypeName = "OrderType"
} else if (parameters.invoiceId) {
entityName ="Invoice"
} else if (parameters.quoteId) {
entityName = "Quote"
}
// second ask for this entity the custom screen to use
GenericValue tplCustScreen
if (entityName) {
entityTypeName = entityTypeName ?: entityName + 'Type'
GenericValue entityValue = from(entityName).where(parameters).queryOne()
if (entityValue) {
tplCustScreen = getCustomScreenTemplate(entityTypeName, entityValue[getFieldTypeName(entityTypeName)])
}
}
context.templateLocation = tplCustScreen ? tplCustScreen.customScreenLocation : context.defaultTemplateLocation
context.templateName = tplCustScreen ? tplCustScreen.customScreenName : context.defaultTemplateName
@@ -3141,7 +3141,7 @@
<value xml:lang="zh-TW">你沒有檢視本頁面的權限.(需要具備"CONTENTMGR_UPDATE"或"CONTENTMGR_ADMIN")</value>
</property>
<property key="ContentUploadFileTypeNotMatch">
<value xml:lang="en">Upload file type not match your selected.</value>
<value xml:lang="en">Upload file type not match your selection.</value>
<value xml:lang="fr">Le type de fichier chargé ne correspond pas avec votre selection.</value>
<value xml:lang="it">Tipo file da caricare non corrisponde alla tua selezione.</value>
<value xml:lang="ja">選択したアップロードファイルの種類が一致しません。</value>
@@ -7147,4 +7147,4 @@
<value xml:lang="zh">生成缺失的搜索引擎优化的网址</value>
<value xml:lang="zh-TW">產生缺失的搜尋引擎優化的網址</value>
</property>
</resource>
</resource>
@@ -1,325 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<simple-methods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ofbiz.apache.org/Simple-Method" xsi:schemaLocation="http://ofbiz.apache.org/Simple-Method http://ofbiz.apache.org/dtds/simple-methods.xsd">
<simple-method method-name="createBlogEntry" short-description="Create a new Blog Entry">
<set field="contentAssocTypeId" value="PUBLISH_LINK"/>
<set field="ownerContentId" from-field="parameters.blogContentId"/>
<set field="contentIdFrom" from-field="parameters.blogContentId"/>
<if-empty field="parameters.statusId">
<set field="parameters.statusId" value="CTNT_INITIAL_DRAFT"/>
</if-empty>
<if-empty field="parameters.templateDataResourceId">
<set field="parameters.templateDataResourceId" value="BLOG_TPL_TOPLEFT"/>
</if-empty>
<!-- determine of we need to create complex template structure or simple content structure -->
<if-empty field="parameters.contentName">
<add-error>
<fail-property resource="ContentUiLabels" property="ContentArticleNameIsMissing"/>
</add-error>
</if-empty>
<check-errors/>
<!-- complex template structure (image & text) -->
<set field="createMain.dataResourceId" from-field="parameters.templateDataResourceId"/>
<set field="createMain.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createMain.contentName" from-field="parameters.contentName"/>
<set field="createMain.description" from-field="parameters.description"/>
<set field="createMain.statusId" from-field="parameters.statusId"/>
<set field="createMain.contentIdFrom" from-field="contentIdFrom"/>
<set field="createMain.partyId" from-field="userLogin.partyId"/>
<set field="createMain.ownerContentId" from-field="ownerContentId"/>
<set field="createMain.dataTemplateTypeId" value="SCREEN_COMBINED"/>
<set field="createMain.mapKey" value="MAIN"/>
<call-service service-name="createContent" in-map-name="createMain">
<result-to-field result-name="contentId" field="contentId"/>
</call-service>
<!-- reset contentIdFrom to new contentId -->
<set field="contentAssocTypeId" value="SUB_CONTENT"/>
<set field="contentIdFrom" from-field="contentId"/>
<if-not-empty field="parameters._uploadedFile_fileName">
<!-- upload a picture -->
<set field="createImage.dataResourceTypeId" value="LOCAL_FILE"/>
<set field="createImage.dataTemplateTypeId" value="NONE"/>
<set field="createImage.mapKey" value="IMAGE"/>
<set field="createImage.ownerContentId" from-field="ownerContentId"/>
<set field="createImage.contentName" from-field="parameters.contentName"/>
<set field="createImage.description" from-field="parameters.description"/>
<set field="createImage.statusId" from-field="parameters.statusId"/>
<set field="createImage.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createImage.contentIdFrom" from-field="contentIdFrom"/>
<set field="createImage.partyId" from-field="userLogin.partyId"/>
<set field="createImage.isPublic" value="Y"/>
<set field="createImage.uploadedFile" from-field="parameters.uploadedFile"/>
<set field="createImage._uploadedFile_fileName" from-field="parameters._uploadedFile_fileName"/>
<set field="createImage._uploadedFile_contentType" from-field="parameters._uploadedFile_contentType"/>
<call-service service-name="createContentFromUploadedFile" in-map-name="createImage">
<result-to-field result-name="contentId" field="imageContentId"/>
</call-service>
</if-not-empty>
<if-not-empty field="parameters.articleData">
<!-- create text data -->
<set field="createText.dataResourceTypeId" value="ELECTRONIC_TEXT"/>
<set field="createText.contentPurposeTypeId" value="ARTICLE"/>
<set field="createText.dataTemplateTypeId" value="NONE"/>
<set field="createText.mapKey" value="MAIN"/>
<set field="createText.ownerContentId" from-field="ownerContentId"/>
<set field="createText.contentName" from-field="parameters.contentName"/>
<set field="createText.description" from-field="parameters.description"/>
<set field="createText.statusId" from-field="parameters.statusId"/>
<set field="createText.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createText.textData" from-field="parameters.articleData"/>
<set field="createText.contentIdFrom" from-field="contentIdFrom"/>
<set field="createText.partyId" from-field="userLogin.partyId"/>
<set field="createText.mapKey" value="ARTICLE"/>
<log level="info" message="calling createTextContent with map: ${createText}"/>
<call-service service-name="createTextContent" in-map-name="createText">
<result-to-field result-name="contentId" field="textContentId"/>
</call-service>
</if-not-empty>
<if-not-empty field="contentId">
<if-not-empty field="parameters.summaryData">
<!-- create the summary data -->
<set field="createSummary.dataResourceTypeId" value="ELECTRONIC_TEXT"/>
<set field="createSummary.dataTemplateTypeId" value="NONE"/>
<set field="createSummary.mapKey" value="SUMMARY"/>
<set field="createSummary.ownerContentId" from-field="ownerContentId"/>
<set field="createSummary.contentName" from-field="parameters.contentName"/>
<set field="createSummary.description" from-field="parameters.description"/>
<set field="createSummary.statusId" from-field="parameters.statusId"/>
<set field="createSummary.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createSummary.textData" from-field="parameters.summaryData"/>
<set field="createSummary.contentIdFrom" from-field="contentIdFrom"/>
<set field="createSummary.partyId" from-field="userLogin.partyId"/>
<call-service service-name="createTextContent" in-map-name="createSummary"/>
</if-not-empty>
</if-not-empty>
<field-to-result field="contentIdFrom" result-name="contentId"/>
<field-to-result field="parameters.blogContentId" result-name="blogContentId"/>
</simple-method>
<simple-method method-name="updateBlogEntry" short-description="Update a existing Blog Entry">
<set field="showNoResult" value="Y"/>
<call-simple-method method-name="getBlogEntry"/>
<if>
<condition>
<or>
<if-compare-field field="parameters.contentName" operator="not-equals" to-field="contentName"/>
<if-compare-field field="parameters.description" operator="not-equals" to-field="description"/>
<if-compare-field field="parameters.summaryData" operator="not-equals" to-field="summaryData"/>
<if-compare-field field="parameters.templateDataResourceId" operator="not-equals" to-field="templateDataResourceId"/>
<if-compare-field field="parameters.statusId" operator="not-equals" to-field="statusId"/>
</or>
</condition>
<then>
<set-service-fields service-name="updateContent" map="parameters" to-map="updContent"/>
<set field="updContent.dataResourceId" from-field="parameters.templateDataResourceId"/>
<call-service service-name="updateContent" in-map-name="updContent"/>
<if-compare-field field="parameters.statusId" operator="not-equals" to-field="statusId">
<if-not-empty field="imageContent">
<set field="imageContent.status.Id" from-field="parameters.statusId"/>
<store-value value-field="imageContent"/>
</if-not-empty>
</if-compare-field>
</then>
</if>
<!-- new article text -->
<if-empty field="articleText">
<if-not-empty field="parameters.articleData">
<set field="ownerContentId" from-field="parameters.blogContentId"/>
<set field="contentAssocTypeId" value="SUB_CONTENT"/>
<set field="contentIdFrom" from-field="contentId"/>
<set field="createText.dataResourceTypeId" value="ELECTRONIC_TEXT"/>
<set field="createText.contentPurposeTypeId" value="ARTICLE"/>
<set field="createText.dataTemplateTypeId" value="NONE"/>
<set field="createText.mapKey" value="ARTICLE"/>
<set field="createText.ownerContentId" from-field="ownerContentId"/>
<set field="createText.contentName" from-field="parameters.contentName"/>
<set field="createText.description" from-field="parameters.description"/>
<set field="createText.statusId" from-field="parameters.statusId"/>
<set field="createText.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createText.textData" from-field="parameters.articleData"/>
<set field="createText.contentIdFrom" from-field="contentIdFrom"/>
<set field="createText.partyId" from-field="userLogin.partyId"/>
<call-service service-name="createTextContent" in-map-name="createText"/>
</if-not-empty>
</if-empty>
<!-- update article text -->
<if-not-empty field="articleText">
<if-compare-field field="parameters.articleData" operator="not-equals" to-field="articleData">
<set field="articleText.textData" from-field="parameters.articleData"/>
<store-value value-field="articleText"/>
</if-compare-field>
</if-not-empty>
<!-- create summary text -->
<if-empty field="summaryData">
<if-not-empty field="parameters.summaryData">
<!-- create the summary data -->
<set field="ownerContentId" from-field="parameters.blogContentId"/>
<set field="contentAssocTypeId" value="SUB_CONTENT"/>
<set field="contentIdFrom" from-field="contentId"/>
<set field="createSummary.dataResourceTypeId" value="ELECTRONIC_TEXT"/>
<set field="createSummary.contentPurposeTypeId" value="ARTICLE"/>
<set field="createSummary.dataTemplateTypeId" value="NONE"/>
<set field="createSummary.mapKey" value="SUMMARY"/>
<set field="createSummary.ownerContentId" from-field="ownerContentId"/>
<set field="createSummary.contentName" from-field="parameters.contentName"/>
<set field="createSummary.description" from-field="parameters.description"/>
<set field="createSummary.statusId" from-field="parameters.statusId"/>
<set field="createSummary.contentAssocTypeId" from-field="contentAssocTypeId"/>
<set field="createSummary.textData" from-field="parameters.summaryData"/>
<set field="createSummary.contentIdFrom" from-field="contentIdFrom"/>
<set field="createSummary.partyId" from-field="userLogin.partyId"/>
<call-service service-name="createTextContent" in-map-name="createSummary"/>
</if-not-empty>
</if-empty>
<!-- update summary text -->
<if-not-empty field="summaryData">
<if-compare-field field="parameters.summaryData" operator="not-equals" to-field="summaryData">
<set field="summaryText.textData" from-field="parameters.summaryData"/>
<store-value value-field="summaryText"/>
</if-compare-field>
</if-not-empty>
<if-not-empty field="parameters._uploadedFile_fileName">
<if-not-empty field="imageContent">
<entity-and entity-name="ContentAssoc" list="oldAssocs" filter-by-date="true">
<field-map field-name="contentId" from-field="contentId"/>
<field-map field-name="contentIdTo" from-field="imageContent.contentId"/>
<field-map field-name="mapKey" value="IMAGE"/>
</entity-and>
<first-from-list list="oldAssocs" entry="oldAssoc"/>
<now-timestamp field="oldAssoc.thruDate"/>
<store-value value-field="oldAssoc"/>
</if-not-empty>
<!-- upload a picture -->
<set field="createImage.dataResourceTypeId" value="LOCAL_FILE"/>
<set field="createImage.dataTemplateTypeId" value="NONE"/>
<set field="createImage.mapKey" value="IMAGE"/>
<set field="createImage.ownerContentId" from-field="parameters.contentId"/>
<set field="createImage.contentName" from-field="parameters.contentName" default-value="${contentName}"/>
<set field="createImage.description" from-field="parameters.description" default-value="${description}"/>
<set field="createImage.statusId" from-field="parameters.statusId" default-value="${statusId}"/>
<set field="createImage.contentAssocTypeId" value="SUB_CONTENT"/>
<set field="createImage.contentIdFrom" from-field="parameters.contentId"/>
<set field="createImage.partyId" from-field="userLogin.partyId"/>
<set field="createImage.isPublic" value="Y"/>
<set field="createImage.uploadedFile" from-field="parameters.uploadedFile"/>
<set field="createImage._uploadedFile_fileName" from-field="parameters._uploadedFile_fileName"/>
<set field="createImage._uploadedFile_contentType" from-field="parameters._uploadedFile_contentType"/>
<call-service service-name="createContentFromUploadedFile" in-map-name="createImage"/>
</if-not-empty>
<field-to-result field="parameters.contentId" result-name="contentId"/>
<field-to-result field="parameters.blogContentId" result-name="blogContentId"/>
</simple-method>
<simple-method method-name="getOwnedOrPublishedBlogEntries" short-description="Get blog entries that the user owns or are published">
<entity-condition entity-name="ContentAssocViewTo" use-cache="false" list="unfilteredList">
<condition-list combine="and">
<condition-expr field-name="contentIdStart" operator="equals" from-field="parameters.contentId"/>
<condition-expr field-name="caContentAssocTypeId" operator="equals" value="PUBLISH_LINK"/>
</condition-list>
<order-by field-name="caFromDate DESC"/>
</entity-condition>
<filter-list-by-date list="unfilteredList" to-list="blogItems"/>
<set field="blogList[]"/>
<iterate list="blogItems" entry="blogItem">
<set-service-fields service-name="genericContentPermission" map="blogItem" to-map="mapIn"/>
<set field="mapIn.ownerContentId" from-field="parameters.contentId"/>
<set field="mapIn.mainAction" value="VIEW"/>
<call-service service-name="genericContentPermission" in-map-name="mapIn">
<result-to-field result-name="hasPermission" field="hasPermission"/>
</call-service>
<if-compare field="hasPermission" operator="equals" value="true" type="Boolean">
<set field="blogList[]" from-field="blogItem"/>
<else>
<set field="mapIn.mainAction" value="UPDATE"/>
<call-service service-name="genericContentPermission" in-map-name="mapIn">
<result-to-field result-name="hasPermission" field="hasPermission"/>
</call-service>
<if-compare field="hasPermission" operator="equals" value="true" type="Boolean">
<set field="blogList[]" from-field="blogItem"/>
</if-compare>
</else>
</if-compare>
</iterate>
<field-to-result field="blogList" result-name="blogList"/>
<field-to-result field="parameters.blogContentId" result-name="blogContentId"/>
</simple-method>
<simple-method method-name="getBlogEntry" short-description="Get all the info for a blog article">
<if-empty field="parameters.contentId">
<field-to-result field="parameters.blogContentId" result-name="blogContentId"/>
<return/>
</if-empty>
<entity-one entity-name="Content" value-field="content"/>
<get-related value-field="content" relation-name="FromContentAssoc" list="rawAssocs"/>
<filter-list-by-date list="rawAssocs" to-list="assocs"/>
<iterate list="assocs" entry="assoc">
<if-compare field="assoc.mapKey" value="ARTICLE" operator="equals">
<get-related-one value-field="assoc" relation-name="ToContent" to-value-field="mainContent"/>
<get-related-one value-field="mainContent" relation-name="DataResource" to-value-field="dataResource"/>
<get-related-one value-field="dataResource" relation-name="ElectronicText" to-value-field="articleText"/>
</if-compare>
<if-compare field="assoc.mapKey" value="SUMMARY" operator="equals">
<get-related-one value-field="assoc" relation-name="ToContent" to-value-field="summaryContent"/>
<get-related-one value-field="summaryContent" relation-name="DataResource" to-value-field="dataResource"/>
<get-related-one value-field="dataResource" relation-name="ElectronicText" to-value-field="summaryText"/>
</if-compare>
<if-compare field="assoc.mapKey" value="IMAGE" operator="equals">
<get-related-one value-field="assoc" relation-name="ToContent" to-value-field="imageContent"/>
</if-compare>
</iterate>
<if-empty field="showNoResult">
<field-to-result field="content.contentId" result-name="contentId"/>
<field-to-result field="content.contentName" result-name="contentName"/>
<field-to-result field="content.description" result-name="description"/>
<field-to-result field="content.statusId" result-name="statusId"/>
<if-not-empty field="imageContent">
<field-to-result field="content.dataResourceId" result-name="templateDataResourceId"/>
</if-not-empty>
<field-to-result field="articleText.textData" result-name="articleData"/>
<field-to-result field="summaryText.textData" result-name="summaryData"/>
<field-to-result field="imageContent.contentId" result-name="imageContentId"/>
<field-to-result field="mainContent.contentId" result-name="articleContentId"/>
<field-to-result field="summaryContent.contentId" result-name="summaryContentId"/>
<field-to-result field="parameters.blogContentId" result-name="blogContentId"/>
<else>
<set from-field="content.contentId" field="contentId"/>
<set from-field="content.contentName" field="contentName"/>
<set from-field="content.description" field="description"/>
<set from-field="content.statusId" field="statusId"/>
<set from-field="content.dataResourceId" field="templateDataResourceId"/>
<set from-field="articleText.textData" field="articleData"/>
<set from-field="summaryText.textData" field="summaryData"/>
<set from-field="imageContent.dataResourceId" field="imageDataResourceId"/>
</else>
</if-empty>
</simple-method>
</simple-methods>
+29 -23
View File
@@ -559,20 +559,27 @@
<attribute name="fieldValue0" type="String" mode="IN" optional="true"/>
</service>
<service name="resequence" auth="true" engine="java" validate="true" transaction-timeout="7200"
location="org.apache.ofbiz.content.ContentManagementServices" invoke="resequence">
<service name="resequence" auth="true" engine="group">
<deprecated use-instead="resequenceContentAssocChildren" since="release22.01"/>
<group>
<invoke name="resequenceContentAssocChildren"/>
</group>
</service>
<service name="resequenceContentAssocChildren" auth="true" engine="java" transaction-timeout="7200"
location="org.apache.ofbiz.content.ContentManagementServices" invoke="resequence">
<description>Reorder sequence numbers in ContentAssoc entities for a given parent id</description>
<attribute mode="IN" name="contentIdTo" optional="false" type="String">
<attribute mode="IN" name="contentId" optional="false" type="String">
<type-validate>
<fail-property resource="ContentErrorUiLabels" property="ContentRequiredFieldMissingContentIdTo"/>
<fail-property resource="ContentErrorUiLabels" property="ContentRequiredFieldMissingContentId"/>
</type-validate>
</attribute>
<attribute mode="IN" name="seqInc" optional="true" type="Integer"/>
<attribute mode="IN" name="seqInc" optional="true" type="Integer" default-value="10"/>
<attribute mode="IN" name="typeList" optional="true" type="List"/>
<attribute mode="IN" name="contentId" optional="true" type="String"/>
<attribute mode="IN" name="contentIdTo" optional="true" type="String"/>
<attribute mode="IN" name="contentAssocTypeId" optional="true" type="String"/>
<attribute mode="IN" name="dir" optional="true" type="String"/>
</service>
<service name="changeLeafToNode" validate="true" auth="true" engine="java" transaction-timeout="7200"
location="org.apache.ofbiz.content.ContentManagementServices" invoke="changeLeafToNode">
<description>Moves dataResource to separate content associated with current content so that node can have only children, no content of its own</description>
@@ -818,8 +825,8 @@
</service>
<!-- blog services -->
<service name="createBlogEntry" engine="simple" auth="true"
location="component://content/minilang/blog/BlogServices.xml" invoke="createBlogEntry">
<service name="createBlogEntry" engine="groovy" auth="true"
location="component://content/src/main/groovy/org/apache/ofbiz/content/BlogServices.groovy" invoke="createBlogEntry">
<description>Creates content records for a blog entry</description>
<required-permissions join-type="AND">
<check-permission permission="CONTENTMGR" action="_CREATE"/>
@@ -838,8 +845,8 @@
<attribute name="articleData" type="String" mode="IN" optional="true" allow-html="safe"/>
<attribute name="summaryData" type="String" mode="IN" optional="true" allow-html="safe"/>
</service>
<service name="updateBlogEntry" engine="simple" auth="true"
location="component://content/minilang/blog/BlogServices.xml" invoke="updateBlogEntry">
<service name="updateBlogEntry" engine="groovy" auth="true"
location="component://content/src/main/groovy/org/apache/ofbiz/content/BlogServices.groovy" invoke="updateBlogEntry">
<description>Updates content records for a blog entry</description>
<required-permissions join-type="AND">
<check-permission permission="CONTENTMGR" action="_UPDATE"/>
@@ -862,8 +869,8 @@
<attribute name="articleData" type="String" mode="IN" optional="true" allow-html="safe"/>
<attribute name="summaryData" type="String" mode="IN" optional="true" allow-html="safe"/>
</service>
<service name="getBlogEntry" engine="simple" auth="true"
location="component://content/minilang/blog/BlogServices.xml" invoke="getBlogEntry">
<service name="getBlogEntry" engine="groovy" auth="true"
location="component://content/src/main/groovy/org/apache/ofbiz/content/BlogServices.groovy" invoke="getBlogEntry">
<description>Retrieves content records for a blog entry</description>
<attribute name="blogContentId" type="String" mode="INOUT" optional="false">
<type-validate>
@@ -875,25 +882,24 @@
<attribute name="statusId" type="String" mode="OUT" optional="true"/>
<attribute name="description" type="String" mode="OUT" optional="true"/>
<attribute name="templateDataResourceId" type="String" mode="OUT" optional="true"/>
<attribute name="summaryData" type="String" mode="OUT" optional="true"/>
<attribute name="articleData" type="String" mode="OUT" optional="true"/>
<attribute name="imageContentId" type="String" mode="OUT" optional="true"/>
<attribute name="imageDataResourceId" type="String" mode="IN" optional="true"/>
<attribute name="articleData" type="String" mode="OUT" optional="true"/>
<attribute name="articleContentId" type="String" mode="OUT" optional="true"/>
<attribute name="articleDataResourceId" type="String" mode="OUT" optional="true"/>
<attribute name="summaryData" type="String" mode="OUT" optional="true"/>
<attribute name="summaryContentId" type="String" mode="OUT" optional="true"/>
<attribute name="summaryDataResourceId" type="String" mode="OUT" optional="true"/>
</service>
<service name="getOwnedOrPublishedBlogEntries" engine="simple" location="component://content/minilang/blog/BlogServices.xml" invoke="getOwnedOrPublishedBlogEntries"
auth="true" transaction-timeout="7200">
<attribute type="String" mode="IN" name="contentId" optional="false">
<service name="getOwnedOrPublishedBlogEntries" engine="groovy" auth="true" transaction-timeout="7200"
location="component://content/src/main/groovy/org/apache/ofbiz/content/BlogServices.groovy" invoke="getOwnedOrPublishedBlogEntries">
<attribute name="contentId" type="String" mode="IN" >
<type-validate>
<fail-property resource="ContentErrorUiLabels" property="ContentRequiredFieldMissingContentId"/>
</type-validate>
</attribute>
<attribute mode="IN" name="userLogin" optional="false" type="org.apache.ofbiz.entity.GenericValue">
<type-validate>
<fail-property resource="ContentErrorUiLabels" property="ContentRequiredFieldMissingUserLogin"/>
</type-validate>
</attribute>
<attribute mode="OUT" name="blogList" optional="true" type="List"/>
<attribute name="blogContentId" type="String" mode="OUT" optional="true"/>
<attribute name="blogList" type="List" mode="OUT" optional="true"/>
</service>
<!-- blog RSS services -->
@@ -0,0 +1,273 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.content
import org.apache.ofbiz.base.util.UtilDateTime
import org.apache.ofbiz.entity.GenericValue
import org.apache.ofbiz.entity.condition.EntityCondition
import org.apache.ofbiz.entity.condition.EntityConditionBuilder
def createBlogEntry() {
String ownerContentId = parameters.blogContentId
String contentIdFrom = parameters.blogContentId
parameters.statusId = parameters.statusId ?: "CTNT_INITIAL_DRAFT"
parameters.templateDataResourceId = parameters.templateDataResourceId ?: "BLOG_TPL_TOPLEFT"
if (!parameters.contentName) {
return error(label("ContentUiLabels", "ContentArticleNameIsMissing"))
}
Map serviceResult = run service: "createContent",
with: [dataResourceId : parameters.templateDataResourceId,
contentAssocTypeId: "PUBLISH_LINK",
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentIdFrom : contentIdFrom,
partyId : userLogin.partyId,
ownerContentId : ownerContentId,
dataTemplateTypeId: "SCREEN_COMBINED",
mapKey : "MAIN"]
contentIdFrom = serviceResult.contentId
if (parameters._uploadedFile_fileName) {
run service: "createContentFromUploadedFile",
with: [
dataResourceTypeId : "LOCAL_FILE",
dataTemplateTypeId : "NONE",
mapKey : "IMAGE",
ownerContentId : ownerContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentAssocTypeId : "SUB_CONTENT",
contentIdFrom : contentIdFrom,
partyId : userLogin.partyId,
isPublic : "Y",
uploadedFile : parameters.uploadedFile,
_uploadedFile_fileName : parameters._uploadedFile_fileName,
_uploadedFile_contentType: parameters._uploadedFile_contentType]
}
if (parameters.articleData) {
run service: "createTextContent",
with: [
dataResourceTypeId : "ELECTRONIC_TEXT",
contentPurposeTypeId: "ARTICLE",
dataTemplateTypeId : "NONE",
mapKey : "MAIN",
ownerContentId : ownerContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentAssocTypeId : "SUB_CONTENT",
textData : parameters.articleData,
contentIdFrom : contentIdFrom,
partyId : userLogin.partyId,
mapKey : "ARTICLE"]
}
if (parameters.summaryData) {
run service: "createTextContent",
with: [
dataResourceTypeId: "ELECTRONIC_TEXT",
dataTemplateTypeId: "NONE",
mapKey : "SUMMARY",
ownerContentId : ownerContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentAssocTypeId: "SUB_CONTENT",
textData : parameters.summaryData,
contentIdFrom : contentIdFrom,
partyId : userLogin.partyId]
}
return success([blogContentId: ownerContentId, contentId: contentIdFrom])
}
/**
* Get all the info for a blog article
*/
def getBlogEntry() {
if (!parameters.contentId) {
return success([blogContentId: parameters.blogContentId])
}
GenericValue content = from("Content").where(parameters).cache().queryOne()
GenericValue mainContent, articleText, dataResource, summaryContent, summaryText, imageContent
from("ContentAssoc")
.where(contentId: content.contentId)
.filterByDate()
.cache()
.queryList()
.each {
switch (it.mapKey) {
case "ARTICLE":
mainContent = it.getRelatedOne("ToContent", true)
dataResource = mainContent.getRelatedOne("DataResource", true)
articleText = dataResource.getRelatedOne("ElectronicText", true)
break
case "SUMMARY":
summaryContent = it.getRelatedOne("ToContent", true)
dataResource = summaryContent.getRelatedOne("DataResource", true)
summaryText = dataResource.getRelatedOne("ElectronicText", true)
break
case "IMAGE":
imageContent = it.getRelatedOne("ToContent", true)
break
}
}
Map resultMap = [blogContentId: parameters.blogContentId,
contentId : content.contentId,
contentName : content.contentName,
description : content.description,
statusId : content.statusId]
if (imageContent) {
resultMap.templateDataResourceId = content.dataResourceId
resultMap.imageContentId = imageContent.contentId
resultMap.imageDataResourceId = imageContent.dataResourceId
}
if (mainContent) {
resultMap.articleData = articleText.textData
resultMap.articleContentId = mainContent.contentId
resultMap.articleDataResourceId = mainContent.dataResourceId
}
if (summaryContent) {
resultMap.summaryData = summaryText.textData
resultMap.summaryContentId = summaryContent.contentId
resultMap.summaryDataResourceId = summaryContent.dataResourceId
}
return success(resultMap)
}
/**
* Update a existing Blog Entry
*/
def updateBlogEntry() {
Map blog = run service: "getBlogEntry", with: parameters
if (['contentName', 'description', 'summaryData', 'templateDataResourceId', 'statusId']
.stream().anyMatch { blog[it] != parameters[it] }) {
run service: "updateContent", with: [* : parameters,
dataResourceId: parameters.templateDataResourceId]
if (parameters.statusId != blog.statusId
&& blog.imageContentId) {
delegator.storeByCondition("Content", [statusId: parameters.statusId],
EntityCondition.makeCondition("contentId", blog.imageContentId))
}
}
if (!blog.articleText && parameters.articleData) {
run service: "createTextContent",
with: [
dataResourceTypeId : "ELECTRONIC_TEXT",
contentPurposeTypeId: "ARTICLE",
dataTemplateTypeId : "NONE",
mapKey : "MAIN",
ownerContentId : parameters.blogContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentAssocTypeId : "SUB_CONTENT",
textData : parameters.articleData,
contentIdFrom : blog.contentId,
partyId : userLogin.partyId,
mapKey : "ARTICLE"]
}
if (blog.articleData && parameters.articleData != blog.articleData) {
run service: 'updateElectronicText', with: [dataResourceId: blog.articleDataResourceId,
textData : parameters.articleData]
}
if (!blog.summaryData && parameters.summaryData) {
run service: "createTextContent",
with: [
dataResourceTypeId: "ELECTRONIC_TEXT",
dataTemplateTypeId: "NONE",
mapKey : "SUMMARY",
ownerContentId : parameters.blogContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentAssocTypeId: "SUB_CONTENT",
textData : parameters.summaryData,
contentIdFrom : blog.contentId,
partyId : userLogin.partyId]
}
if (blog.summaryData && parameters.summaryData != blog.summaryData) {
run service: 'updateElectronicText', with: [dataResourceId: blog.summaryDataResourceId,
textData : parameters.summaryData]
}
if (parameters._uploadedFile_fileName) {
if (blog.imageContentId) {
EntityCondition condition = new EntityConditionBuilder().AND() {
EQUALS(contentId: blog.contentId)
EQUALS(contentIdTo: blog.imageContentId)
EQUALS(mapKey: "IMAGE")
EQUALS(thruDate: null)
}
delegator.storeByCondition("ContentAssoc", [thruDate: UtilDateTime.nowTimestamp()], condition)
}
run service: "createContentFromUploadedFile",
with: [
isPublic : "Y",
dataTemplateTypeId : "NONE",
mapKey : "IMAGE",
dataResourceTypeId : "LOCAL_FILE",
contentAssocTypeId : "SUB_CONTENT",
ownerContentId : parameters.blogContentId,
contentName : parameters.contentName,
description : parameters.description,
statusId : parameters.statusId,
contentIdFrom : blog.contentId,
partyId : userLogin.partyId,
uploadedFile : parameters.uploadedFile,
_uploadedFile_fileName : parameters._uploadedFile_fileName,
_uploadedFile_contentType: parameters._uploadedFile_contentType]
}
return success([blogContentId: parameters.blogContentId, contentId: blog.contentId])
}
/**
* Get blog entries that the user owns or are published
* @return
*/
def getOwnedOrPublishedBlogEntries() {
List blogList = []
from("ContentAssocViewTo")
.where(contentIdStart: parameters.contentId,
caContentAssocTypeId: "PUBLISH_LINK")
.orderBy("-caFromDate")
.filterByDate()
.cache()
.queryList()
.each {
Map serviceResult = run service: "genericContentPermission",
with: [* : it.getAllFields(),
ownerContentId: parameters.contentId,
mainAction : "VIEW"]
if (!serviceResult.hasPermission) {
serviceResult = run service: "genericContentPermission",
with: [* : it.getAllFields(),
ownerContentId: parameters.contentId,
mainAction : "UPDATE"]
}
if (serviceResult.hasPermission) {
blogList << it
}
}
return success([blogList : blogList,
blogContentId: parameters.blogContentId])
}
@@ -23,6 +23,7 @@ import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
@@ -50,6 +51,7 @@ import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.ModelUtil;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.security.SecuredUpload;
import org.apache.ofbiz.security.Security;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
@@ -146,6 +148,20 @@ public class ContentManagementServices {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Locale locale = (Locale) context.get("locale");
// Check if a webshell is not uploaded
String textData = (String) context.get("textData");
if (UtilValidate.isNotEmpty(textData)) {
try {
if (!SecuredUpload.isValidText(textData, Collections.emptyList())) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return ServiceUtil.returnError("================== Not saved for security reason ==================");
}
} catch (IOException e) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return ServiceUtil.returnError("================== Not saved for security reason ==================");
}
}
// Knowing why a request fails permission check is one of the more difficult
// aspects of content management. Setting "displayFailCond" to true will
// put an html table in result.errorMessage that will show what tests were performed
@@ -176,7 +192,7 @@ public class ContentManagementServices {
if (Debug.infoOn()) {
Debug.logInfo("in persist... contentPurposeList(0):" + contentPurposeList, MODULE);
Debug.logInfo("in persist... textData(0):" + context.get("textData"), MODULE);
Debug.logInfo("in persist... textData(0):" + textData, MODULE);
}
GenericValue content = delegator.makeValue("Content");
@@ -835,15 +851,23 @@ public class ContentManagementServices {
return results;
}
/**
* Reorder sequence numbers in ContentAssoc entities for a given parent id
* if variable dir contains the string up or down, realize for the given contentIdTo switch
* with the previous or the next
* @param dctx
* @param context
* @return
* @throws GenericServiceException
*/
public static Map<String, Object> resequence(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
String contentIdTo = (String) context.get("contentIdTo");
Integer seqInc = (Integer) context.get("seqInc");
if (seqInc == null) {
seqInc = 100;
}
int seqIncrement = seqInc;
String contentId = (String) context.get("contentId");
int seqStep = (Integer) context.get("seqInc");
// Resolve the association type to use for resolve content's child
List<String> typeList = UtilGenerics.cast(context.get("typeList"));
if (typeList == null) {
typeList = new LinkedList<>();
@@ -855,60 +879,45 @@ public class ContentManagementServices {
if (UtilValidate.isEmpty(typeList)) {
typeList = UtilMisc.toList("PUBLISH_LINK", "SUB_CONTENT");
}
EntityCondition conditionType = EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList);
EntityCondition conditionMain = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("contentIdTo",
EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND);
// Resolve all content assoc to resequence from the content
try {
List<GenericValue> listAll = EntityQuery.use(delegator).from("ContentAssoc")
.where(conditionMain)
List<GenericValue> contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
.where(List.of(
EntityCondition.makeCondition("contentId", contentId),
EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList)))
.orderBy("sequenceNum", "fromDate", "createdDate")
.filterByDate().queryList();
String contentId = (String) context.get("contentId");
.filterByDate()
.queryList();
String contentIdTo = (String) context.get("contentIdTo");
String dir = (String) context.get("dir");
int seqNum = seqIncrement;
String thisContentId = null;
for (int i = 0; i < listAll.size(); i++) {
GenericValue contentAssoc = listAll.get(i);
if (UtilValidate.isNotEmpty(contentId) && UtilValidate.isNotEmpty(dir)) {
// move targeted entry up or down
thisContentId = contentAssoc.getString("contentId");
if (contentId.equals(thisContentId)) {
if (dir.startsWith("up")) {
if (i > 0) {
// Swap with previous entry
try {
GenericValue prevValue = listAll.get(i - 1);
Long prevSeqNum = (Long) prevValue.get("sequenceNum");
prevValue.put("sequenceNum", (long) seqNum);
prevValue.store();
contentAssoc.put("sequenceNum", prevSeqNum);
contentAssoc.store();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
}
}
} else {
if (i < listAll.size()) {
// Swap with next entry
GenericValue nextValue = listAll.get(i + 1);
nextValue.put("sequenceNum", (long) seqNum);
nextValue.store();
seqNum += seqIncrement;
contentAssoc.put("sequenceNum", (long) seqNum);
contentAssoc.store();
i++; // skip next one
}
}
} else {
contentAssoc.put("sequenceNum", (long) seqNum);
contentAssoc.store();
}
} else {
contentAssoc.put("sequenceNum", (long) seqNum);
contentAssoc.store();
int seqNum = seqStep;
boolean switchSequence = UtilValidate.isNotEmpty(contentIdTo) && UtilValidate.isNotEmpty(dir);
boolean switchModeUp = switchSequence && dir.startsWith("up");
int changePosition = -1;
// update the sequence for all element and check if we need switch two element
for (int i = 0; i < contentAssocs.size(); i++) {
boolean stopLimit = ((i <= 0 && switchModeUp) || (i + 1 >= contentAssocs.size() && !switchModeUp));
GenericValue contentAssoc = contentAssocs.get(i);
contentAssoc.put("sequenceNum", (long) seqNum);
seqNum += seqStep;
if (switchSequence
&& contentIdTo.equals(contentAssoc.getString("contentIdTo"))
&& !stopLimit) {
changePosition = i;
}
seqNum += seqIncrement;
}
// We need to switch, do it
if (changePosition >= 0) {
GenericValue currentContent = contentAssocs.get(changePosition);
GenericValue destinationContent = contentAssocs.get(changePosition + (switchModeUp ? -1 : +1));
long switchSeqNum = currentContent.getLong("sequenceNum");
currentContent.put("sequenceNum", destinationContent.getLong("sequenceNum"));
destinationContent.put("sequenceNum", switchSeqNum);
}
delegator.storeAll(contentAssocs);
} catch (GenericEntityException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(e.toString());
@@ -1594,6 +1603,9 @@ public class ContentManagementServices {
File file = new File(objectInfo);
if (file.isFile()) {
try {
// Check if a webshell is not uploaded
// This should now be useless after the add of SecuredUpload::isValidFile in GroovyBaseScript for createAnonFile service.
// But I prefer to keep it anyway, it's hard to test all cases, better safe than sorry
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(objectInfo, "All", delegator)) {
errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
}
@@ -21,6 +21,7 @@ package org.apache.ofbiz.content.data;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
@@ -41,6 +42,7 @@ import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.apache.ofbiz.security.SecuredUpload;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
@@ -83,22 +85,16 @@ public class DataEvents {
String permissionService = EntityUtilProperties.getPropertyValue("content", "stream.permission.service",
"genericContentPermission", delegator);
// @formatter:off (prevent unwanted formatting in Eclipse)
// For OFBIZ-11840. It's counterintuitive to return success but it makes sense if you thing about it. It simply returns a blank screen.
// To illustrate, only few payloads, onLoad related, are handled because it works everytime.
// It could be improved by checking for all payloads.
// As listed at https://portswigger.net/web-security/cross-site-scripting/cheat-sheet, at 2020-11-11 there are 8979 of them.
// So a way could be to read all of them and test...
// @formatter:on
if (contentId.toLowerCase().contains("<svg")
|| contentId.toLowerCase().contains("<body")
|| contentId.toLowerCase().contains("<iframe")
|| contentId.toLowerCase().contains("<object")
|| contentId.toLowerCase().contains("<embed")
|| contentId.toLowerCase().contains("<a href='javas")
|| contentId.toLowerCase().contains("<a href=\"javas")
|| contentId.toLowerCase().contains("<script")) {
// For OFBIZ-11840, checks if a webshell is not uploaded
// It's counterintuitive to return success but it makes sense if you thing about it.
// It simply returns a blank screen.
try {
if (!SecuredUpload.isValidText(contentId, Collections.emptyList())) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return "success";
}
} catch (IOException e) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return "success";
}
@@ -49,6 +49,7 @@ import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.security.SecuredUpload;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.ModelService;
@@ -195,7 +196,30 @@ public class DataServices {
return createFileMethod(dctx, context);
}
public static Map<String, Object> createFileNoPerm(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
public static Map<String, Object> createFileNoPerm(DispatchContext dctx, Map<String, ? extends Object> rcontext) throws IOException,
ImageReadException {
String originalFileName = (String) rcontext.get("dataResourceName");
String fileNameAndPath = (String) rcontext.get("objectInfo");
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) rcontext.get("locale");
File file = new File(fileNameAndPath);
if (!originalFileName.isEmpty()) {
// Check the file name
if (!SecuredUpload.isValidFileName(originalFileName, delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
// TODO we could verify the file type (here "All") with dataResourceTypeId. Anyway it's done with isValidFile()
// We would just have a better error message
if (file.exists()) {
// Check if a webshell is not uploaded
if (!SecuredUpload.isValidFile(fileNameAndPath, "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
}
}
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
context.put("skipPermissionCheck", "true");
return createFileMethod(dctx, context);
@@ -254,7 +278,9 @@ public class DataServices {
if (UtilValidate.isNotEmpty(textData)) {
try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);) {
out.write(textData);
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedTextFileFormats", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -265,10 +291,11 @@ public class DataServices {
}
} else if (binData != null) {
try {
// Check if a webshell is not uploaded
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, binData.array(), StandardOpenOption.APPEND);
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "All", delegator)) {
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(tempFile.toString(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -460,7 +487,9 @@ public class DataServices {
if (UtilValidate.isNotEmpty(textData)) {
try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);) {
out.write(textData);
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedTextFileFormats", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -472,9 +501,10 @@ public class DataServices {
} else if (binData != null) {
try {
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, binData.array(), StandardOpenOption.APPEND);
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
if (!SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -647,7 +677,8 @@ public class DataServices {
try (FileOutputStream out = new FileOutputStream(file);) {
out.write(imageData);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -706,7 +737,8 @@ public class DataServices {
try (FileOutputStream out = new FileOutputStream(file);) {
out.write(imageData);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
@@ -0,0 +1,50 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.content.ftp;
import java.util.ArrayList;
import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.config.keys.ClientIdentityLoader;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.kex.BuiltinDHFactories;
import org.apache.sshd.common.signature.BuiltinSignatures;
public abstract class SshClientHelper {
private static SshClient client = null;
public static SshClient getSshClient() {
if (client == null) {
client = SshClient.setUpDefaultClient();
client.setClientIdentityLoader(ClientIdentityLoader.DEFAULT);
client.setKeyExchangeFactories(NamedFactory.setUpTransformedFactories(
false,
BuiltinDHFactories.VALUES,
ClientBuilder.DH2KEX));
client.setSignatureFactories(new ArrayList<>(BuiltinSignatures.VALUES));
}
if (!client.isStarted()) {
client.start();
}
return client;
}
}
@@ -28,7 +28,8 @@ import org.apache.commons.io.IOUtils;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.subsystem.sftp.SftpClient;
import org.apache.sshd.sftp.client.SftpClient;
import org.apache.sshd.sftp.client.SftpClientFactory;
/**
* Basic client to copy files to an ssh ftp server
@@ -37,12 +38,12 @@ public class SshFtpClient implements FtpClientInterface {
private static final String MODULE = SshFtpClient.class.getName();
private SshClient client;
private final SshClient client;
private SftpClient sftp;
private ClientSession session;
public SshFtpClient() {
client = SshClient.setUpDefaultClient();
client.start();
client = SshClientHelper.getSshClient();
}
@Override
@@ -50,11 +51,10 @@ public class SshFtpClient implements FtpClientInterface {
if (port == null) port = 22L;
if (timeout == null) timeout = 10000L;
if (sftp != null) return;
ClientSession session = client.connect(username, hostname, port.intValue()).verify(timeout.intValue()).getSession();
session = client.connect(username, hostname, port.intValue()).verify(timeout.intValue()).getSession();
session.addPasswordIdentity(password);
session.auth().verify(timeout.intValue());
sftp = session.createSftpClient();
session.auth().verify();
sftp = SftpClientFactory.instance().createSftpClient(session).singleSessionInstance();
}
@Override
@@ -83,10 +83,8 @@ public class SshFtpClient implements FtpClientInterface {
}
@Override
public void closeConnection() {
if (sftp != null) {
client.stop();
sftp = null;
}
public void closeConnection() throws IOException {
if (sftp != null) sftp.close();
if (session != null) session.close();
}
}
@@ -1937,7 +1937,7 @@ under the License.
<view-map name="EditAddContent" type="screen" page="component://content/widget/cms/CMSScreens.xml#EditAddContent"/>
<view-map name="EditAddSubContent" type="screen" page="component://content/widget/cms/CMSScreens.xml#EditAddSubContent"/>
<view-map name="ViewBinaryDataResource" page="" type="simplecontent"/>
<view-map name="ViewSimpleContent" page="" type="simplecontent"/>
<!-- lookup content component -->
@@ -1609,5 +1609,9 @@ under the License.
<InventoryItem facilityId="WebStoreWarehouse" locationSeqId="TLTLTLUL01" datetimeReceived="2008-08-01 08:00:00.000"
inventoryItemId="9030" inventoryItemTypeId="NON_SERIAL_INV_ITEM" productId="MAT_B_COST" ownerPartyId="Company" currencyUomId="USD" unitCost="7.0"/>
<InventoryItemDetail inventoryItemId="9030" inventoryItemDetailSeqId="0001" effectiveDate="2001-05-13 12:00:00.0" availableToPromiseDiff="20" quantityOnHandDiff="20" accountingQuantityDiff="20"/>
<!-- defaut template screen use for Company -->
<CustomScreen customScreenId="DEFAULT_INV_TPL" customScreenTypeId="CST_INVOICE_TPL" customScreenName="DefaultInvoicePDF" customScreenLocation="component://accounting/widget/AccountingPrintScreens.xml"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="InvTplInvoice" partyId="Company" fromDate="2001-05-13 00:00:00" invoiceTypeId="INVOICE" customScreenId="DEFAULT_INV_TPL"/>
</entity-engine-xml>
@@ -2600,5 +2600,15 @@ under the License.
<AgreementTerm agreementId="AGR_SALES" agreementItemSeqId="00001" agreementTermId="9000" description="Sales test agreement" termDays="30" termTypeId="FIN_PAYMENT_FIXDAY"/>
<!-- An AgreementProductAppls aris related to an AgreementItem. AgreementProductAppls are optional. If a product id and a price are specified the price will override the ProductPrice if the agreement is selected in the order -->
<AgreementProductAppl agreementId="AGR_SALES" agreementItemSeqId="00001" price="10.000" productId="GZ-1000"/>
<CustomScreen customScreenId="DEFAULT_ORD_TPL" customScreenTypeId="CST_ORDER_TPL" customScreenName="DefaultOrderPDF" customScreenLocation="component://order/widget/ordermgr/OrderPrintScreens.xml"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="OrdTplSales" partyId="Company" fromDate="2001-05-13 00:00:00" orderTypeId="SALES_ORDER" customScreenId="DEFAULT_ORD_TPL"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="OrdTplPurchase" partyId="Company" fromDate="2001-05-13 00:00:00" orderTypeId="PURCHASE_ORDER" customScreenId="DEFAULT_ORD_TPL"/>
<CustomScreen customScreenId="DEFAULT_QUOTE_TPL" customScreenTypeId="CST_QUOTE_TPL" customScreenName="DefaultQuotePDF" customScreenLocation="component://order/widget/ordermgr/QuoteScreens.xml"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="QuoTplOther" partyId="Company" fromDate="2001-05-13 00:00:00" quoteTypeId="OTHER_QUOTE" customScreenId="DEFAULT_QUOTE_TPL"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="QuoTplProposal" partyId="Company" fromDate="2001-05-13 00:00:00" quoteTypeId="PROPOSAL" customScreenId="DEFAULT_QUOTE_TPL"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="QuoTplProduct" partyId="Company" fromDate="2001-05-13 00:00:00" quoteTypeId="PRODUCT_QUOTE" customScreenId="DEFAULT_QUOTE_TPL"/>
<PartyPrefDocTypeTpl partyPrefDocTypeTplId="QuoTplPurchase" partyId="Company" fromDate="2001-05-13 00:00:00" quoteTypeId="PURCHASE_QUOTE" customScreenId="DEFAULT_QUOTE_TPL"/>
</entity-engine-xml>
@@ -70,7 +70,7 @@ function lookupInventory() {
<td width='20%' align='right' class="label">${uiLabelMap.CommonFromDate}</td>
<td width='5%'>&nbsp;</td>
<td>
<@htmlTemplate.renderDateTimeField name="eventDate" event="" action="" className="" alert="" title="Format: yyyy-MM-dd HH:mm:ss.SSS" value="${requestParameters.eventDate!nowTimestamp}" size="25" maxlength="30" id="fromDate_2" dateType="date" shortDateInput=false timeDropdownParamName="" defaultDateTimeString="" localizedIconTitle="" timeDropdown="" timeHourName="" classString="" hour1="" hour2="" timeMinutesName="" minutes="" isTwelveHour="" ampmName="" amSelected="" pmSelected="" compositeType="" formName=""/>
<@htmlTemplate.renderDateTimeField name="eventDate" event="" action="" className="" alert="" title="Format: yyyy-MM-dd HH:mm:ss.SSS" value="" size="25" maxlength="30" id="fromDate_2" dateType="date" shortDateInput=false timeDropdownParamName="" defaultDateTimeString="" localizedIconTitle="" timeDropdown="" timeHourName="" classString="" hour1="" hour2="" timeMinutesName="" minutes="" isTwelveHour="" ampmName="" amSelected="" pmSelected="" compositeType="" formName=""/>
</td>
</tr>
<tr>
@@ -80,7 +80,7 @@ under the License.
</field>
<field name="productId" title="${uiLabelMap.ProductProductId}"><lookup target-form-name="LookupProduct"/></field>
<field name="workEffortName" title="${uiLabelMap.ManufacturingProductionRunName}"><text-find/></field>
<field name="estimatedStartDate" title="${uiLabelMap.ManufacturingStartDate}"><date-find default-value="${nowTimestamp}"/></field>
<field name="estimatedStartDate" title="${uiLabelMap.ManufacturingStartDate}"><date-find/></field>
<field name="facilityId" title="${uiLabelMap.ProductFacilityId}">
<drop-down allow-empty="true">
<entity-options entity-name="Facility" key-field-name="facilityId" description="${facilityName} [${facilityId}]">
@@ -47,9 +47,10 @@ def getNextOrderId() {
customMethodName = 'orderSequence_enforced'
}
String orderIdTemp
if (customMethodName) {
Map customMethodMap = [*: parameters]
Map result = run service: customMethodName, with: customMethodMap
parameters.partyAcctgPreference = partyAcctgPreference
Map result = run service: customMethodName, with: parameters
orderIdTemp = result.orderId
} else {
logInfo 'In getNextOrderId sequence by Standard'
@@ -68,10 +69,7 @@ def getNextOrderId() {
if (partyAcctgPreference) orderId += partyAcctgPreference.orderIdPrefix ?: ""
orderId += orderIdTemp.toString()
Map result = success()
result.orderId = orderId
return result
return success([orderId: orderId])
}
/**
@@ -49,7 +49,7 @@ under the License.
</select>
</div>
<div>
<input type="file" name="uploadedFile" class="required" size="25" accept=".png,.gif,.jpg,.jpeg,.tiff,.tif"/>
<input type="file" name="uploadedFile" class="required" size="25"/>
</div>
<div>
<button type="submit">
@@ -24,7 +24,7 @@ under the License.
<field name="requirementId"><text-find/></field>
<field name="partyId" title="${uiLabelMap.PartySupplier}"><lookup target-form-name="LookupPartyName"/></field>
<field name="productId" title="${uiLabelMap.ProductProductId}"><lookup target-form-name="LookupProduct"/></field>
<field name="requirementByDate"><date-find type="date"/></field>
<field name="requiredByDate"><date-find type="date"/></field>
<field name="submitButton" title="${uiLabelMap.CommonFind}" widget-style="smallSubmit"><submit button-type="button"/></field>
</form>
<form name="RequirementsList" type="multi" use-row-submit="true" target="addRequirementsToCart" title="" list-name="requirementsForSupplier"
@@ -25,6 +25,19 @@ under the License.
<!-- generate a PDF for the order, sharing the same groovy file as the HTML page for viewing the order -->
<screen name="OrderPDF">
<section>
<actions>
<set field="defaultTemplateLocation" value="component://order/widget/ordermgr/OrderPrintScreens.xml"/>
<set field="defaultTemplateName" value="DefaultOrderPDF"/>
<script location="component://commonext/groovyScripts/template/DocTypeTemplate.groovy"/>
</actions>
<widgets>
<include-screen name="${templateName}" location="${templateLocation}"/>
</widgets>
</section>
</screen>
<screen name="DefaultOrderPDF">
<section>
<actions>
<set field="titleProperty" value="OrderOrder" />
@@ -160,8 +160,22 @@ under the License.
</widgets>
</section>
</screen>
<!-- generate a PDF for the quote -->
<screen name="QuoteReport">
<section>
<actions>
<set field="defaultTemplateLocation" value="component://order/widget/ordermgr/QuoteScreens.xml"/>
<set field="defaultTemplateName" value="DefaultQuotePDF"/>
<script location="component://commonext/groovyScripts/template/DocTypeTemplate.groovy"/>
</actions>
<widgets>
<include-screen name="${templateName}" location="${templateLocation}"/>
</widgets>
</section>
</screen>
<screen name="DefaultQuotePDF">
<section>
<actions>
<set field="titleProperty" value="OrderOrderQuoteReport"/>
@@ -282,7 +282,7 @@ under the License.
</drop-down>
</field>
<field name="productId" title="${uiLabelMap.ProductProductId}"><lookup target-form-name="LookupProduct"/></field>
<field name="requirementByDate"><date-find type="date"/></field>
<field name="requiredByDate"><date-find type="date"/></field>
<field name="submitButton" title="${uiLabelMap.CommonFind}" widget-style="smallSubmit"><submit button-type="button"/></field>
</form>
<form name="ApprovedProductRequirementsList" type="list" title="" list-name="requirementsForSupplier" paginate-target="RequirementsForSupplier"
+15 -10
View File
@@ -11331,6 +11331,7 @@
<value xml:lang="zh-TW">尋找庫存細項標籤</value>
</property>
<property key="PageTitleFindProduct">
<value xml:lang="de">Produkt suchen</value>
<value xml:lang="en">Find Product</value>
<value xml:lang="es">Buscar Producto</value>
<value xml:lang="fr">Recherche d'articles</value>
@@ -13101,7 +13102,7 @@
</property>
<property key="ProductAddProductsUsingDefaultQuantities">
<value xml:lang="cs">Přidat výrobky této skupiny do košíku v přednastaveném možství</value>
<value xml:lang="de">Produkte dieser Produktgruppe in der vorgegebenen Menge in den Warenkorb legen</value>
<value xml:lang="de">Produkte dieser Produktkategorie in der vorgegebenen Menge in den Warenkorb legen</value>
<value xml:lang="en">Add Products in this Category to the Cart using Default Quantities</value>
<value xml:lang="en-GB">Add Products in this Category to the basket using default quantities</value>
<value xml:lang="es">Agregue los productos en esta categoría al carro usando cantidades predeterminadas</value>
@@ -13298,7 +13299,7 @@
</property>
<property key="ProductAdvancedSearchInCategory">
<value xml:lang="cs">Rozšířené hledání ve skupině výrobků</value>
<value xml:lang="de">Erweiterte Suche in der Produktgruppe</value>
<value xml:lang="de">Erweiterte Suche in der Produktkategorie</value>
<value xml:lang="en">Advanced Search in Category</value>
<value xml:lang="es">Búsqueda Avanzada en las Categorías</value>
<value xml:lang="fr">Recherche avancée dans la catégorie</value>
@@ -14379,7 +14380,7 @@
</property>
<property key="ProductBrowseCategories">
<value xml:lang="cs">Výběr skupiny výrobků</value>
<value xml:lang="de">Produktgruppen durchsuchen</value>
<value xml:lang="de">Produktkategorien durchsuchen</value>
<value xml:lang="en">Browse Categories</value>
<value xml:lang="es">Hojear Categorías</value>
<value xml:lang="es-CL">Navegar Categorías</value>
@@ -14866,7 +14867,7 @@
</property>
<property key="ProductCategory">
<value xml:lang="cs">Skupina výrobků</value>
<value xml:lang="de">Produktgruppe</value>
<value xml:lang="de">Kategorie</value>
<value xml:lang="en">Category</value>
<value xml:lang="es">Categoría</value>
<value xml:lang="fr">Catégorie</value>
@@ -14983,7 +14984,7 @@
</property>
<property key="ProductCategoryNotFoundForCategoryID">
<value xml:lang="cs">Skupina výrobků nenalezena</value>
<value xml:lang="de">Produktgruppe wurde nicht gefunden mit ID</value>
<value xml:lang="de">Kategorie wurde nicht gefunden mit ID</value>
<value xml:lang="en">Category not found for Category ID</value>
<value xml:lang="es">Categoría no encontrada por ID</value>
<value xml:lang="fr">Aucune catégorie pour cet réf.</value>
@@ -15000,11 +15001,11 @@
<value xml:lang="zh-TW">沒有找到分類識別</value>
</property>
<property key="ProductCategoryAttrAlreadyExists">
<value xml:lang="de">Eine Attribut mit diesem Namen existiert bereits für die Produktgruppe mit dieser ID.</value>
<value xml:lang="de">Eine Attribut mit diesem Namen existiert bereits für die Kategorie mit dieser ID.</value>
<value xml:lang="en">There already is an attribute with this name for a group with this ID.</value>
</property>
<property key="ProductCategoryAlreadyExists">
<value xml:lang="de">Eine Produktgruppe mit dieser ID existiert bereits.</value>
<value xml:lang="de">Eine Kategorie mit dieser ID existiert bereits.</value>
<value xml:lang="en">There already is a Category with this ID.</value>
</property>
<property key="ProductCategoryNoVariants">
@@ -15367,7 +15368,7 @@
</property>
<property key="ProductChooseQuickAddCategory">
<value xml:lang="cs">Výběr zrychleným zadáním produktové skupiny</value>
<value xml:lang="de">Auswahl einer Produktgruppe für Schnelleingabe</value>
<value xml:lang="de">Auswahl einer Produktkategorie für Schnelleingabe</value>
<value xml:lang="en">Choose QuickAdd Category</value>
<value xml:lang="es">Elegir la categoría Añadir-Rápido</value>
<value xml:lang="fr">Choisir une catégorie d'ajout-rapide</value>
@@ -20866,6 +20867,10 @@
<value xml:lang="zh">这个明细缺货</value>
<value xml:lang="zh-TW">這個細項缺貨</value>
</property>
<property key="ProductCannotReserveInventoryNotEnoughStock">
<value xml:lang="it">Impossibile riservare l'articolo ${parameters.productId}: quantità in stock non sufficiente nel deposito ${parameters.facilityId}. Quantità non riservata è ${parameters.quantityNotReserved}</value>
<value xml:lang="en">Cannot reserve product ${parameters.productId}: not enough quantity left in stock for facility ${parameters.facilityId}. Quantity not reserved is ${parameters.quantityNotReserved}</value>
</property>
<property key="ProductItemPrc">
<value xml:lang="de">Position Preis</value>
<value xml:lang="en">Item Prc</value>
@@ -23268,7 +23273,7 @@
</property>
<property key="ProductNoProductsInThisCategory">
<value xml:lang="cs">V této skupině nejsou žádné výrobky</value>
<value xml:lang="de">Es gibt keine Produkte in dieser Produktgruppe</value>
<value xml:lang="de">Es gibt keine Produkte in dieser Produktkategorie</value>
<value xml:lang="en">There are no products in this category</value>
<value xml:lang="es">No hay productos en esta categoría</value>
<value xml:lang="fr">Aucun article dans cette catégorie</value>
@@ -29046,7 +29051,7 @@
</property>
<property key="ProductSearchInCategory">
<value xml:lang="cs">Hledání ve skupině výrobků</value>
<value xml:lang="de">Suche in Produktgruppe</value>
<value xml:lang="de">Suche in Produktkategorie</value>
<value xml:lang="en">Search in Category</value>
<value xml:lang="es">Buscar en la Categoría</value>
<value xml:lang="fr">Rechercher dans la catégorie</value>
@@ -21,7 +21,7 @@
# -- Image upload path on the server
#FIXME the image server path need to be move on runtime
#FIXME the image server path need to be moved on runtime
image.server.path=${sys:getProperty('ofbiz.home')}/themes/common/images/webapp/images/${tenantId}
# -- The prefix to put on auto-generated image urls (can be relative or absolute, whatever you want)
@@ -37,7 +37,7 @@ all.product.category=CATALOG1
reactivate.product.from.receipt=Y
# Image upload path on the image management
#FIXME the image management path need to be move on runtime
#FIXME the image management path need to be moved on runtime
image.management.path=${sys:getProperty('ofbiz.home')}/themes/common/webapp/images/products/management
image.management.url=/images/products/management
image.management.nameofthumbnail=-100
@@ -176,6 +176,7 @@ def reserveStoreInventory() {
List productStoreFacilities = from("ProductStoreFacility")
.where(productStoreId: productStore.productStoreId)
.orderBy("sequenceNum")
.filterByDate()
.cache()
.queryList()
for (GenericValue productStoreFacility : productStoreFacilities) {
@@ -184,29 +185,28 @@ def reserveStoreInventory() {
// TODO: must entire quantity be available in one location?
// Right now the answer is yes, it only succeeds if one facility has sufficient inventory for the order.
Map callServiceMapIABF = [productId: parameters.productId, facilityId: productStoreFacility.facilityId]
logInfo("ProductStoreService:In productStoreFacilities loop: [" + parameters.facilityId + "]")
Map serviceResultIABF = run service: "getInventoryAvailableByFacility", with: callServiceMapIABF
BigDecimal availableToPromiseTotal = serviceResultIABF.availableToPromiseTotal
if (availableToPromiseTotal >= parameters.quantity) {
storeFound = productStoreFacility
}
}
}
// didn't find anything? Take the first facility from list
GenericValue defaultStoreFound
if (!storeFound) {
storeFound = productStoreFacilities.get(0)
defaultStoreFound = productStore.getRelatedOne("Facility", true)
}
facilityId = storeFound.facilityId ?: ""
facilityId = storeFound ? storeFound.facilityId : defaultStoreFound.facilityId
Map serviceResult = run service: "reserveProductInventoryByFacility", with: [*: parameters,
facilityId: facilityId,
requireInventory: requireInventory,
reserveOrderEnumId: productStore.reserveOrderEnumId]
quantityNotReserved = serviceResult.quantityNotReserved
logInfo("Inventory IS reserved in facility with id [${storeFound.facilityId}] for product id [${parameters.productId}]; desired quantity was ${parameters.quantity}")
logInfo("Inventory IS reserved in facility with id [${facilityId}] for product id [${parameters.productId}]; desired quantity was ${parameters.quantity}")
}
} else {
List productStoreFacilities = from("ProductStoreFacility").where(productStoreId: productStore.productStoreId, facilityId: facilityId).cache().orderBy("sequenceNum").queryList()
List productStoreFacilities = from("ProductStoreFacility").where(productStoreId: productStore.productStoreId, facilityId: facilityId).cache().orderBy("sequenceNum").filterByDate().queryList()
GenericValue facilityFound
for (GenericValue productStoreFacility : productStoreFacilities) {
// Search Product Store Facilities to insure the facility passed in is associated to the Product Store passed in
@@ -314,6 +314,7 @@ def isStoreInventoryAvailable() {
List productStoreFacilities = from("ProductStoreFacility")
.where(productStoreId: productStore.productStoreId)
.orderBy("sequenceNum")
.filterByDate()
.cache()
.queryList()
available = "N"
@@ -0,0 +1,31 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package product.supplier
/**
* Get all supplier information for a product feature
*/
def getSupplierProductFeatures() {
return success([supplierProductFeatures: from('SupplierProductFeature')
.where(partyId: parameters.partyId,
productFeatureId: parameters.productFeatureId)
.cache()
.queryList()])
}
@@ -163,7 +163,14 @@ under the License.
-->
<if-compare field="parameters.quantityNotReserved" operator="not-equals" value="0" type="BigDecimal">
<if-compare field="parameters.requireInventory" operator="equals" value="Y">
<!-- use this else pattern to accomplish the anything but Y logic, ie if not specified default to inventory NOT required -->
<!-- if there is still quantity not reserved but ProductStore is configured to require inventory, we can
assume here that also reserveInventory is set to Y (reserveInventory is checked by caller services).
In such a scenario we return an error and avoid order creation.
-->
<add-error>
<fail-property resource="ProductUiLabels" property="ProductCannotReserveInventoryNotEnoughStock"/>
</add-error>
<check-errors/>
<else>
<if-not-empty field="lastNonSerInventoryItem">
<!-- subtract from quantityNotReserved from the availableToPromise of existing inventory item -->
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<simple-methods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Simple-Method" xsi:schemaLocation="http://ofbiz.apache.org/Simple-Method http://ofbiz.apache.org/dtds/simple-methods.xsd">
<simple-method method-name="getSupplierProductFeatures" short-description="Get all supplier information for a product feature" login-required="false">
<entity-and entity-name="SupplierProductFeature" list="supplierProductFeatures">
<field-map field-name="partyId" from-field="parameters.partyId"/>
<field-map field-name="productFeatureId" from-field="parameters.productFeatureId"/>
</entity-and>
<field-to-result field="supplierProductFeatures"/>
</simple-method>
</simple-methods>
+6 -6
View File
@@ -528,13 +528,13 @@ under the License.
</required-permissions>
<auto-attributes mode="IN" include="pk" optional="false"/>
</service>
<service name="getSupplierProductFeatures" engine="simple"
location="component://product/minilang/product/supplier/SupplierProductServices.xml" invoke="getSupplierProductFeatures">
<service name="getSupplierProductFeatures" engine="groovy" invoke="getSupplierProductFeatures"
location="component://product/groovyScripts/product/supplier/SupplierProductServices.groovy">
<description>Finds a list of SupplierProductFeature entities based on the productFeatureId.
If a partyId is given, only product feature information for that supplier party is returned.</description>
<attribute name="productFeatureId" type="String" mode="IN" optional="false"/>
<attribute name="productFeatureId" type="String" mode="IN"/>
<attribute name="partyId" type="String" mode="IN" optional="true"/>
<attribute name="supplierProductFeatures" type="java.util.List" mode="OUT" optional="false"/>
<attribute name="supplierProductFeatures" type="java.util.List" mode="OUT"/>
</service>
<service name="createProductMaint" default-entity-name="ProductMaint" engine="entity-auto" invoke="create" auth="true">
@@ -944,8 +944,8 @@ under the License.
</group>
</service>
<service name="updateContentSEOForCategory" engine="simple"
location="component://product/minilang/product/category/CategoryContentServices.xml" invoke="updateContentSEOForCategory" auth="true">
<service name="updateContentSEOForCategory" engine="groovy"
location="component://product/groovyScripts/product/category/CategoryContentServices.groovy" invoke="updateContentSEOForCategory" auth="true">
<description>Update SEO Content For Product Category</description>
<attribute name="productCategoryId" mode="IN" type="String" optional="false"/>
<attribute name="title" mode="IN" type="String" optional="true"/>
@@ -48,11 +48,12 @@ import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.security.SecurityUtil;
import org.apache.ofbiz.webapp.SeoConfigUtil;
import org.apache.ofbiz.webapp.control.ConfigXMLReader;
import org.apache.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig;
import org.apache.ofbiz.webapp.control.ControlFilter;
import org.apache.ofbiz.webapp.control.WebAppConfigurationException;
import org.apache.ofbiz.webapp.SeoConfigUtil;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Matcher;
@@ -115,6 +116,10 @@ public final class SeoContextFilter implements Filter {
uri = uri + "?" + queryString;
}
if (SecurityUtil.containsFreemarkerInterpolation(httpRequest, httpResponse, uri)) {
return;
}
boolean forwarded = forwardUri(httpResponse, uri);
if (forwarded) {
return;
@@ -224,6 +224,7 @@ public class ScaleImage {
try {
String fileToCheck = imageServerPath + "/" + newFileLocation + "." + imgExtension;
ImageIO.write(bufNewImg, imgExtension, new File(fileToCheck));
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(fileToCheck, "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -402,6 +403,7 @@ public class ScaleImage {
try {
String fileToCheck = imageServerPath + "/" + newFileLocation + "." + imgExtension;
ImageIO.write(bufNewImg, imgExtension, new File(fileToCheck));
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(fileToCheck, "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -290,7 +290,7 @@ public class FrameImage {
if (UtilValidate.isEmpty(imageName) || UtilValidate.isEmpty(imageData)) {
session.setAttribute("frameContentId", request.getParameter("frameExistContentId"));
session.setAttribute("frameDataResourceId", request.getParameter("frameExistDataResourceId"));
request.setAttribute("_ERROR_MESSAGE_", "There is no frame image, please select the image type *.PNG uploading.");
request.setAttribute("_ERROR_MESSAGE_", "There is no frame image, please select the image type *.PNG to upload.");
return "error";
}
if (!"image/png".equals(mimType)) {
@@ -320,6 +320,7 @@ public class FrameImage {
}
Path tmpFile = Files.createTempFile(null, null);
Files.write(tmpFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tmpFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
@@ -157,10 +157,10 @@ public class ImageManagementServices {
}
if (UtilValidate.isEmpty(imageResize)) {
// check file content
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -189,6 +189,7 @@ public class ImageManagementServices {
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -579,6 +580,7 @@ public class ImageManagementServices {
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -1079,6 +1079,7 @@ public class ProductServices {
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -1386,6 +1387,7 @@ public class ProductServices {
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, imageData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedImageFormats", locale);
return ServiceUtil.returnError(errorMessage);
@@ -34,6 +34,7 @@ import java.util.Set;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.GeneralException;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.common.geo.GeoWorker;
@@ -50,6 +51,7 @@ import org.apache.ofbiz.product.config.ProductConfigWrapper.ConfigOption;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
/**
* Product Worker class to reduce code in JSPs.
@@ -65,17 +67,13 @@ public final class ProductWorker {
String errMsg = "";
if (product != null) {
String productTypeId = product.getString("productTypeId");
if ("SERVICE".equals(productTypeId) || "SERVICE_PRODUCT".equals(productTypeId) || (ProductWorker.isDigital(product)
&& !ProductWorker.isPhysical(product))) {
if ("SERVICE".equals(productTypeId) || "SERVICE_PRODUCT".equals(productTypeId)
|| (ProductWorker.isDigital(product) && !ProductWorker.isPhysical(product))) {
// don't charge shipping on services or digital goods
return false;
}
Boolean chargeShipping = product.getBoolean("chargeShipping");
if (chargeShipping == null) {
return true;
}
return chargeShipping;
return product.get("chargeShipping") == null
|| product.getBoolean("chargeShipping");
}
throw new IllegalArgumentException(errMsg);
}
@@ -1317,17 +1315,51 @@ public final class ProductWorker {
productsInStock.add(genericRecord);
}
} else {
List<GenericValue> facilities = EntityQuery.use(delegator).from("ProductFacility").where("productId", productId).queryList();
BigDecimal availableInventory = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(facilities)) {
for (GenericValue facility : facilities) {
BigDecimal lastInventoryCount = facility.getBigDecimal("lastInventoryCount");
if (lastInventoryCount != null) {
availableInventory = lastInventoryCount.add(availableInventory);
if ("Y".equals(product.getString("isVirtual"))) {
BigDecimal availableInventory = BigDecimal.ZERO;
try {
Map<String, Object> variantResultOutput = dispatcher.runSync("getAllProductVariants",
UtilMisc.toMap("productId", productId));
if (ServiceUtil.isError(variantResultOutput)) {
Debug.logError("Error in retrieving all product variants for productId " + productId
+ " Skip this product. Error is : " + ServiceUtil.getErrorMessage(variantResultOutput), MODULE);
continue;
}
List<GenericValue> productVariants = UtilGenerics.cast(variantResultOutput.get("assocProducts"));
for (GenericValue productVariant : productVariants) {
List<GenericValue> facilities = EntityQuery.use(delegator)
.from("ProductFacility")
.where("productId", productVariant.getString("productIdTo"))
.queryList();
if (UtilValidate.isNotEmpty(facilities)) {
for (GenericValue facility : facilities) {
BigDecimal lastInventoryCount = facility.getBigDecimal("lastInventoryCount");
if (lastInventoryCount != null) {
availableInventory = lastInventoryCount.add(availableInventory);
}
}
}
}
if (availableInventory.compareTo(BigDecimal.ZERO) > 0) {
productsInStock.add(genericRecord);
}
} catch (GenericServiceException e) {
Debug.logError(e, "Error getting all product variants for productId " + productId
+ ", while filtering out of stock products.", MODULE);
}
if (availableInventory.compareTo(BigDecimal.ZERO) > 0) {
productsInStock.add(genericRecord);
} else {
List<GenericValue> facilities = EntityQuery.use(delegator).from("ProductFacility").where("productId", productId).queryList();
BigDecimal availableInventory = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(facilities)) {
for (GenericValue facility : facilities) {
BigDecimal lastInventoryCount = facility.getBigDecimal("lastInventoryCount");
if (lastInventoryCount != null) {
availableInventory = lastInventoryCount.add(availableInventory);
}
}
if (availableInventory.compareTo(BigDecimal.ZERO) > 0) {
productsInStock.add(genericRecord);
}
}
}
}
@@ -219,9 +219,9 @@ function insertImageName(type,nameValue) {
<input type="file" size="50" name="fname" accept=".png,.gif,.jpg,.jpeg,.tiff,.tif"/>
<br />
<span>
<label><input type="radio" name="upload_file_type_bogus" value="category" checked="checked" onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=category</@ofbizUrl>");'/>${uiLabelMap.ProductCategoryImageUrl}</label>
<label><input type="radio" name="upload_file_type_bogus" value="linkOne" onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=linkOne</@ofbizUrl>");'/>${uiLabelMap.ProductLinkOneImageUrl}</label>
<label><input type="radio" name="upload_file_type_bogus" value="linkTwo"onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=linkTwo</@ofbizUrl>");'/>${uiLabelMap.ProductLinkTwoImageUrl}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="category" checked="checked" onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=category</@ofbizUrl>");'/>${uiLabelMap.ProductCategoryImageUrl}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="linkOne" onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=linkOne</@ofbizUrl>");'/>${uiLabelMap.ProductLinkOneImageUrl}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="linkTwo"onclick='setUploadUrl("<@ofbizUrl>UploadCategoryImage?productCategoryId=${productCategoryId}&amp;upload_file_type=linkTwo</@ofbizUrl>");'/>${uiLabelMap.ProductLinkTwoImageUrl}</label>
</span>
<input type="submit" class="smallSubmit" value="${uiLabelMap.ProductUploadImage}"/>
</td></tr>
@@ -192,11 +192,11 @@ under the License.
</td>
<td>&nbsp;</td>
<td width="80%" colspan="4" valign="top">
<label><input type="radio" name="upload_file_type_bogus" value="small" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=small</@ofbizUrl>");'/>${uiLabelMap.CommonSmall}</label>
<label><input type="radio" name="upload_file_type_bogus" value="medium" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=medium</@ofbizUrl>");'/>${uiLabelMap.CommonMedium}</label>
<label><input type="radio" name="upload_file_type_bogus" value="large"onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=large</@ofbizUrl>");'/>${uiLabelMap.CommonLarge}</label>
<label><input type="radio" name="upload_file_type_bogus" value="detail" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=detail</@ofbizUrl>");'/>${uiLabelMap.CommonDetail}</label>
<label><input type="radio" name="upload_file_type_bogus" value="original" checked="checked" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=original</@ofbizUrl>");'/>${uiLabelMap.ProductOriginal}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="small" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=small</@ofbizUrl>");'/>${uiLabelMap.CommonSmall}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="medium" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=medium</@ofbizUrl>");'/>${uiLabelMap.CommonMedium}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="large"onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=large</@ofbizUrl>");'/>${uiLabelMap.CommonLarge}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="detail" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=detail</@ofbizUrl>");'/>${uiLabelMap.CommonDetail}</label>
<label><input type="radio" name="up_load_file_type_bogus" value="original" checked="checked" onclick='setUploadUrl("<@ofbizUrl>UploadProductImage?productId=${productId}&amp;upload_file_type=original</@ofbizUrl>");'/>${uiLabelMap.ProductOriginal}</label>
<input type="submit" class="smallSubmit" value="${uiLabelMap.ProductUploadImage}"/>
</td>
</tr>
@@ -89,7 +89,7 @@ under the License.
</widgets>
</section>
</screen>
<screen name="FindProduct">
<section>
<actions>
@@ -1033,11 +1033,11 @@ under the License.
<widgets>
<screenlet title="${assocSection.sectionTitle}">
<include-grid name="ListProductAssocs" location="component://product/widget/catalog/ProductForms.xml"/>
<label style="help-note">${uiLabelMap.CommonNote} : ${uiLabelMap.ProductHighlightedExplanation}</label>
</screenlet>
<label style="tooltip">${uiLabelMap.CommonNote} : ${uiLabelMap.ProductHighlightedExplanation}</label>
</widgets>
</section>
</iterate-section>
</iterate-section>
</decorator-section>
</decorator-screen>
</widgets>
@@ -1245,7 +1245,7 @@ under the License.
<screenlet title="${uiLabelMap.PageTitleEditProductParties}">
<include-grid name="UpdateProductRole" location="component://product/widget/catalog/ProductForms.xml"/>
</screenlet>
<screenlet title="${uiLabelMap.ProductAssociatePartyToProduct}">
<include-form name="AddProductRole" location="component://product/widget/catalog/ProductForms.xml"/>
</screenlet>
@@ -1373,7 +1373,7 @@ under the License.
</widgets>
</section>
</screen>
<screen name="ProductPriceHistory">
<section>
<actions>
+24 -20
View File
@@ -80,9 +80,10 @@ ext.pluginsDir = "${rootDir}/plugins"
application {
mainClassName = 'org.apache.ofbiz.base.start.Start'
// jdk.serialFilter is to "Prevent possible DOS attack done using Java deserialisation" (OFBIZ-12592)
applicationDefaultJvmArgs = project.hasProperty('jvmArgs')
? jvmArgs.tokenize()
: ['-Xms128M', '-Xmx1024M']
: ['-Xms128M','-Xmx1024M','-Djdk.serialFilter=maxarray=100000;maxdepth=20;maxrefs=500;maxbytes=500000']
}
distributions.main.contents.from(rootDir) {
@@ -101,7 +102,7 @@ javadoc {
links(
'https://docs.oracle.com/javase/8/docs/api',
'https://tomcat.apache.org/tomcat-9.0-doc/servletapi/',
'http://docs.groovy-lang.org/docs/groovy-2.5.11/html/api',
'http://docs.groovy-lang.org/docs/groovy-2.5.18/html/api',
'https://commons.apache.org/proper/commons-cli/apidocs'
)
}
@@ -109,13 +110,13 @@ javadoc {
node {
download = true
version = "13.14.0"
version = "16.13.1"
// npmVersion will be the one that comes default with node
// https://github.com/node-gradle/gradle-node-plugin/blob/2.2.4/README.md
// Set the work directory where node_modules should be located
nodeModulesDir = file("${project.projectDir}/themes/common-theme/webapp/common/js")
// If you set a "CI" env var then ci only will be used:
// If you set a "CI" env var then ci only will be used:
// https://github.com/node-gradle/gradle-node-plugin/blob/master/docs/faq.md#how-do-i-use-npm-ci-instead-of-npm-install
npmInstallCommand = System.getenv("CI") ? 'ci' : 'install'
}
@@ -192,7 +193,7 @@ configurations {
}
dependencies {
implementation 'xerces:xercesImpl:2.12.1'
implementation 'xerces:xercesImpl:2.12.2'
implementation 'com.google.zxing:core:3.4.1'
implementation 'com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.11.2'
@@ -217,23 +218,26 @@ dependencies {
implementation 'org.apache.geronimo.components:geronimo-transaction:3.1.4'
implementation 'org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.1.1'
implementation 'org.apache.httpcomponents:httpclient-cache:4.5.13'
implementation 'org.apache.logging.log4j:log4j-api:2.17.1' // the API of log4j 2
implementation 'org.apache.logging.log4j:log4j-core:2.17.1' // Somehow needed by Buildbot to compile OFBizDynamicThresholdFilter.java
implementation 'org.apache.logging.log4j:log4j-api:2.17.2' // the API of log4j 2
implementation 'org.apache.logging.log4j:log4j-core:2.17.2' // Somehow needed by Buildbot to compile OFBizDynamicThresholdFilter.java
implementation 'org.apache.poi:poi:4.1.2' // poi-ooxml-schemas-5.0.0.pom'. Received status code 401 from server
implementation 'org.apache.pdfbox:pdfbox:2.0.24'
implementation 'org.apache.shiro:shiro-core:1.8.0'
implementation 'org.apache.sshd:sshd-core:1.7.0' // So far we did not update from 1.7.0 because of a compile issue. You may try w/ a newer version than 2.4.0
implementation 'org.apache.tika:tika-core:1.28' // 2.1.0 does not work
implementation 'org.apache.tika:tika-parsers:1.28' // 2.1.0 does not work
implementation 'org.apache.tomcat:tomcat-catalina-ha:9.0.54' // Remember to change the version number (9 now) in javadoc block if needed.
implementation 'org.apache.tomcat:tomcat-jasper:9.0.54'
implementation 'org.apache.sshd:sshd-core:2.8.0'
implementation 'org.apache.sshd:sshd-sftp:2.8.0'
// Note: The Apache Tika PMC has set September 30, 2022 as the End Of Life for the Tika 1.x branch.
// The PMC will make security fixes for the 1.x branch until that date.
implementation 'org.apache.tika:tika-core:1.28.4' // version 2 needs more work, see OFBIZ-12572
implementation 'org.apache.tika:tika-parsers:1.28.4' // 2.1.0 does not work,
implementation 'org.apache.tomcat:tomcat-catalina-ha:9.0.60' // Remember to change the version number (9 now) in javadoc block if needed.
implementation 'org.apache.tomcat:tomcat-jasper:9.0.60'
implementation 'org.apache.axis2:axis2-kernel:1.7.9' // Above: SOAPEventHandler.java:42: error: package org.apache.axiom.om.impl.builder does not exist
implementation 'batik:batik-svg-dom:1.6-1'
implementation 'org.apache.xmlgraphics:fop:2.3' // NOTE: since 2.4 dependencies are messed up. See https://github.com/moqui/moqui-fop/blob/master/build.gradle
implementation 'org.apache.xmlrpc:xmlrpc-client:3.1.3'
implementation 'org.apache.xmlrpc:xmlrpc-server:3.1.3'
implementation 'org.clojure:clojure:1.10.2'
implementation 'org.codehaus.groovy:groovy-all:2.5.11' // Compile issue with commons-cli and Groovy 3. Remember to change the version number in javadoc block.
implementation 'org.codehaus.groovy:groovy-all:2.5.18' // Compile issue with commons-cli and Groovy 3. Remember to change the version number in javadoc block.
implementation 'org.freemarker:freemarker:2.3.31' // Remember to change the version number in FreeMarkerWorker class when upgrading. See OFBIZ-10019 if >= 2.4
implementation 'org.owasp.esapi:esapi:2.2.2.0'
implementation 'org.springframework:spring-test:5.3.9'
@@ -242,6 +246,7 @@ dependencies {
implementation 'wsdl4j:wsdl4j:1.6.3'
implementation 'com.auth0:java-jwt:3.18.1'
implementation 'org.jdom:jdom:1.1.3' // don't upgrade above 1.1.3, makes a lot of not obvious and useless complications, see last commits of OFBIZ-12092 for more
implementation 'com.google.re2j:re2j:1.6'
testImplementation 'org.hamcrest:hamcrest-library:2.2' // Enable junit4 to not depend on hamcrest-1.3
testImplementation 'org.mockito:mockito-core:3.12.4'
@@ -256,11 +261,11 @@ dependencies {
runtimeOnly 'org.apache.axis2:axis2-transport-local:1.7.9' // Above: SOAPEventHandler.java:42: error: package org.apache.axiom.om.impl.builder does not exist
runtimeOnly 'org.apache.derby:derby:10.14.2.0' // So far we did not update from 10.14.2.0 because of a compile issue. You may try w/ a newer version than 10.15.1.3
runtimeOnly 'org.apache.geronimo.specs:geronimo-jaxrpc_1.1_spec:2.1'
runtimeOnly 'org.apache.logging.log4j:log4j-1.2-api:2.17.1' // for external jars using the old log4j1.2: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-jul:2.17.1' // for external jars using the java.util.logging: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-slf4j-impl:2.17.1' // for external jars using slf4j: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-web:2.17.1' //???
runtimeOnly 'org.apache.logging.log4j:log4j-jcl:2.17.1' // need to constrain to version to avoid classpath conflict (ReflectionUtil)
runtimeOnly 'org.apache.logging.log4j:log4j-1.2-api:2.17.2' // for external jars using the old log4j1.2: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-jul:2.17.2' // for external jars using the java.util.logging: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-slf4j-impl:2.17.2' // for external jars using slf4j: routes logging to log4j 2
runtimeOnly 'org.apache.logging.log4j:log4j-web:2.17.2' //???
runtimeOnly 'org.apache.logging.log4j:log4j-jcl:2.17.2' // need to constrain to version to avoid classpath conflict (ReflectionUtil)
runtimeOnly 'org.codeartisans.thirdparties.swing:batik-all:1.8pre-r1084380'
// Dependencies defined by the plugins
@@ -1147,7 +1152,6 @@ tasks.startScripts {
unixScript.text.replace('CLASSPATH=$APP_HOME/lib','CLASSPATH=$APP_HOME/config/:$APP_HOME/lib-extra/*:$APP_HOME/lib')
// Alter the start script for Windows systems.
windowsScript.text =
windowsScript.text.replace('CLASSPATH=%APP_HOME%\\lib',
'CLASSPATH=%APP_HOME%\\conf\\;%APP_HOME%\\lib-extra\\*;%APP_HOME%\\lib')
windowsScript.text.replace('CLASSPATH=%APP_HOME%\\lib','CLASSPATH=%APP_HOME%\\conf\\;%APP_HOME%\\lib-extra\\*;%APP_HOME%\\lib')
}
}
@@ -270,6 +270,7 @@ public class HttpRequestFileUpload {
}
fos.flush();
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(fileTocheck, fileType, delegator)) {
return false;
}
@@ -61,8 +61,6 @@ import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -91,6 +89,9 @@ import org.apache.ofbiz.webapp.control.SameSiteFilter;
import org.apache.ofbiz.webapp.event.FileUploadProgressListener;
import org.apache.ofbiz.widget.renderer.VisualTheme;
import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
/**
* HttpUtil - Misc HTTP Utility Functions
*/
@@ -460,25 +461,49 @@ public final class UtilHttp {
* @return The resulting Map
*/
public static Map<String, Object> getJSONAttributeMap(HttpServletRequest request) {
return parseJSONAttributeMap(getAttributeMap(request));
}
/**
* For a map analyse each object to prepare a Json response
* @param attrMap
* @return
*/
private static Map<String, Object> parseJSONAttributeMap(Map<String, Object> attrMap) {
Map<String, Object> returnMap = new HashMap<>();
Map<String, Object> attrMap = getAttributeMap(request);
for (Map.Entry<String, Object> entry : attrMap.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (val instanceof java.sql.Timestamp) {
val = val.toString();
}
if (val instanceof String || val instanceof Number || val instanceof Map<?, ?> || val instanceof List<?> || val instanceof Boolean) {
if (Debug.verboseOn()) {
Debug.logVerbose("Adding attribute to JSON output: " + key, MODULE);
}
returnMap.put(key, val);
Object val = parseJSONAttributeValue(entry.getValue());
if (val != null) {
returnMap.put(entry.getKey(), val);
}
}
return returnMap;
}
/**
* For a value analyse the object type to prepare a Json response
* @param val
* @return
*/
private static Object parseJSONAttributeValue(Object val) {
if (val == null) {
return null;
}
if (val instanceof java.sql.Timestamp) {
val = val.toString();
}
if (val instanceof String
|| val instanceof Number
|| val instanceof Boolean) {
return val;
} else if (val instanceof Map<?, ?>) {
return parseJSONAttributeMap(UtilGenerics.cast(val));
} else if (val instanceof List<?>) {
return ((List<?>) val).stream().map(UtilHttp::parseJSONAttributeValue).collect(Collectors.toList());
}
return null;
}
/**
* Create a map from a HttpRequest (attributes) object
* @return The resulting Map
@@ -46,6 +46,8 @@ import org.apache.ofbiz.base.location.FlexibleLocation;
import org.apache.ofbiz.base.util.cache.UtilCache;
import org.apache.ofbiz.base.util.collections.ResourceBundleMapWrapper;
import org.apache.ofbiz.base.util.string.FlexibleStringExpander;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -501,7 +503,29 @@ public final class UtilProperties implements Serializable {
return;
}
Properties properties = getProperties(resource);
Properties properties = UtilProperties.getProperties(resource);
if (properties == null) {
return;
}
properties.setProperty(name, value);
}
/**
* Sets the specified value of the specified property name to the specified resource/properties in memory, does not persist it
* @param delegator Default delegator, mostly used in tests
* @param resource The name of the resource
* @param name The name of the property in the resource
* @param value The value of the property to set in memory
*/
public static void setPropertyValueInMemory(Delegator delegator, String resource, String name, String value) {
if (UtilValidate.isEmpty(resource)) {
return;
}
if (UtilValidate.isEmpty(name)) {
return;
}
Properties properties = EntityUtilProperties.getProperties(delegator, resource);
if (properties == null) {
return;
}
+15 -2
View File
@@ -74,9 +74,22 @@ under the License.
<property name="secure" value="false"/>
<property name="URIEncoding" value="UTF-8"/>
<property name="xpoweredBy" value="false"/>
<property name="secretRequired" value="false"/>
<property name="allowedRequestAttributesPattern" value=".*"/>
<!-- AJP/13 connector attributes -->
<!-- Despite OFBIZ-11407, allowedRequestAttributesPattern is commented out because of OFBIZ-12558
OOTB the Tomcat default values should be used as recommended by
https://tomcat.apache.org/tomcat-9.0-doc/config/ajp.html#Introduction
This is in relation with
https://tomcat.apache.org/security-9.html#Fixed_in_Apache_Tomcat_9.0.31
and
https://tomcat.apache.org/tomcat-9.0-doc/security-howto.html#Connectors
But secretRequired value must be false because secret value is empty
Else a notifying message appears in log saying that AJP is not available.
Long story short, with this configuration only localhost works.
So if you use it you need to use value/s
-->
<property name="secretRequired" value="false"/>
<!-- <property name="allowedRequestAttributesPattern" value=".*"/> -->
<!-- commented out because the values match the Tomcat defaults:
<property name="tomcatAuthentication" value="true"/>
<property name="allowTrace" value="false"/>
+3
View File
@@ -209,6 +209,7 @@ under the License.
<description>Generic service to return a entity conditions</description>
<attribute name="entityName" type="String" mode="IN" optional="false"/>
<attribute name="inputFields" type="java.util.Map" mode="IN" optional="false"/>
<attribute name="dynamicViewEntity" type="org.apache.ofbiz.entity.model.DynamicViewEntity" mode="IN" optional="true"/>
<attribute name="orderBy" type="String" mode="IN" optional="true"/>
<attribute name="noConditionFind" type="String" mode="IN" optional="true"><!-- find with no condition (empty entityConditionList) only done when this is Y --></attribute>
<attribute name="filterByDate" type="String" mode="IN" optional="true"/>
@@ -223,6 +224,7 @@ under the License.
<service name="executeFind" auth="false" engine="java" invoke="executeFind" location="org.apache.ofbiz.common.FindServices">
<description>Generic service to return an entity iterator</description>
<attribute name="entityName" type="String" mode="IN" optional="false"/>
<attribute name="dynamicViewEntity" type="org.apache.ofbiz.entity.model.DynamicViewEntity" mode="IN" optional="true"/>
<attribute name="fieldList" type="java.util.List" mode="IN" optional="true"/>
<attribute name="orderByList" type="java.util.List" mode="IN" optional="true"/>
<attribute name="maxRows" mode="IN" type="Integer" optional="true"/>
@@ -237,6 +239,7 @@ under the License.
<description>Generic service to return an entity iterator. set filterByDate to Y to exclude expired records.
set noConditionFind to Y to find without conditions. </description>
<attribute name="entityName" type="String" mode="IN" optional="false"/>
<attribute name="dynamicViewEntity" type="org.apache.ofbiz.entity.model.DynamicViewEntity" mode="IN" optional="true"/>
<attribute name="inputFields" type="java.util.Map" mode="IN" optional="false"/>
<attribute name="fieldList" type="java.util.List" mode="IN" optional="true"/>
<attribute name="orderBy" type="String" mode="IN" optional="true"/>
@@ -51,8 +51,11 @@ import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityConditionList;
import org.apache.ofbiz.entity.condition.EntityFunction;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.DynamicViewEntity;
import org.apache.ofbiz.entity.model.ModelEntity;
import org.apache.ofbiz.entity.model.ModelField;
import org.apache.ofbiz.entity.model.ModelReader;
import org.apache.ofbiz.entity.model.ModelViewEntity;
import org.apache.ofbiz.entity.util.EntityListIterator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
@@ -500,6 +503,7 @@ public class FindServices {
*/
public static Map<String, Object> performFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
DynamicViewEntity dynamicViewEntity = (DynamicViewEntity) context.get("dynamicViewEntity");
String orderBy = (String) context.get("orderBy");
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
String noConditionFind = (String) context.get("noConditionFind");
@@ -545,6 +549,7 @@ public class FindServices {
Map<String, Object> prepareResult = null;
try {
prepareResult = dispatcher.runSync("prepareFind", UtilMisc.toMap("entityName", entityName, "orderBy", orderBy,
"dynamicViewEntity", dynamicViewEntity,
"inputFields", inputFields, "filterByDate", filterByDate, "noConditionFind", noConditionFind,
"filterByDateValue", filterByDateValue, "userLogin", userLogin, "fromDateName", fromDateName,
"thruDateName", thruDateName,
@@ -559,6 +564,7 @@ public class FindServices {
Map<String, Object> executeResult = null;
try {
executeResult = dispatcher.runSync("executeFind", UtilMisc.toMap("entityName", entityName, "orderByList", orderByList,
"dynamicViewEntity", dynamicViewEntity,
"fieldList", fieldList, "entityConditionList", exprList,
"noConditionFind", noConditionFind, "distinct", distinct,
"locale", context.get("locale"), "timeZone", context.get("timeZone"),
@@ -589,6 +595,7 @@ public class FindServices {
*/
public static Map<String, Object> prepareFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
DynamicViewEntity dynamicViewEntity = (DynamicViewEntity) context.get("dynamicViewEntity");
Delegator delegator = dctx.getDelegator();
String orderBy = (String) context.get("orderBy");
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
@@ -611,7 +618,16 @@ public class FindServices {
String thruDateName = (String) context.get("thruDateName");
Map<String, Object> queryStringMap = new LinkedHashMap<>();
ModelEntity modelEntity = delegator.getModelEntity(entityName);
ModelEntity modelEntity;
if (dynamicViewEntity != null) {
try {
modelEntity = new ModelViewEntity(dynamicViewEntity, ModelReader.getModelReader(delegator.getDelegatorName()));
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
}
} else {
modelEntity = delegator.getModelEntity(entityName);
}
List<EntityCondition> tmpList = createConditionList(inputFields, modelEntity.getFieldsUnmodifiable(), queryStringMap, delegator, context);
/* the filter by date condition should only be added when there are other conditions or when
@@ -668,6 +684,7 @@ public class FindServices {
*/
public static Map<String, Object> executeFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
DynamicViewEntity dynamicViewEntity = (DynamicViewEntity) context.get("dynamicViewEntity");
EntityConditionList<EntityCondition> entityConditionList = UtilGenerics.cast(context.get("entityConditionList"));
List<String> orderByList = checkCollection(context.get("orderByList"), String.class);
boolean noConditionFind = "Y".equals(context.get("noConditionFind"));
@@ -686,20 +703,25 @@ public class FindServices {
int listSize = 0;
try {
if (noConditionFind || (entityConditionList != null && entityConditionList.getConditionListSize() > 0)) {
listIt = EntityQuery.use(delegator)
.select(fieldSet)
.from(entityName)
.where(entityConditionList)
.orderBy(orderByList)
.cursorScrollInsensitive()
.maxRows(maxRows)
.distinct(distinct)
.queryIterator();
EntityQuery query = EntityQuery.use(delegator);
if (dynamicViewEntity != null) {
query.from(dynamicViewEntity);
} else {
query.from(entityName);
}
listIt = query.select(fieldSet)
.where(entityConditionList)
.orderBy(orderByList)
.cursorScrollInsensitive()
.maxRows(maxRows)
.distinct(distinct)
.queryIterator();
listSize = listIt.getResultsSizeAfterPartialList();
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonFindErrorRunning",
UtilMisc.toMap("entityName", entityName, "errorString", e.getMessage()), locale));
UtilMisc.toMap("entityName", (dynamicViewEntity != null ? dynamicViewEntity.getEntityName() : entityName),
"errorString", e.getMessage()), locale));
}
Map<String, Object> results = ServiceUtil.returnSuccess();
@@ -282,13 +282,17 @@ public final class EntityFinderUtil {
} else {
List<Condition> conditionList = new ArrayList<>(subElements.size());
for (Element subElement : subElements) {
if ("condition-expr".equals(subElement.getNodeName())) {
switch (subElement.getLocalName()) {
case "condition-expr":
conditionList.add(new ConditionExpr(subElement));
} else if ("condition-list".equals(subElement.getNodeName())) {
break;
case "condition-list":
conditionList.add(new ConditionList(subElement));
} else if ("condition-object".equals(subElement.getNodeName())) {
break;
case "condition-object":
conditionList.add(new ConditionObject(subElement));
} else {
break;
default:
throw new IllegalArgumentException("Invalid element with name [" + subElement.getNodeName()
+ "] found under a condition-list element.");
}
+46 -9
View File
@@ -155,7 +155,7 @@ security.token.key=security.token.key
# -- List of domains or IP addresses to be checked to prevent Host Header Injection,
# -- no spaces after commas,no wildcard, can be extended of course...
host-headers-allowed=localhost,127.0.0.1,demo-trunk.ofbiz.apache.org,demo-stable.ofbiz.apache.org,demo-old.ofbiz.apache.org
host-headers-allowed=localhost,127.0.0.1,demo-trunk.ofbiz.apache.org,demo-stable.ofbiz.apache.org,demo-next.ofbiz.apache.org
# -- By default the SameSite value in SameSiteFilter is 'strict'.
# -- This property allows to change to 'lax' if needed.
@@ -212,12 +212,22 @@ templateClassResolver=
#-- For supported formats see https://commons.apache.org/proper/commons-imaging/formatsupport.html
#-- Notably https://commons.apache.org/proper/commons-imaging/formatsupport.html#Metadata_Format_Support
#-- OOTB OFBiz only supports PNG, GIF, TIFF and JPEG, it's a breeze to extend using more:
#-- commonsImagingSupportedFormats=BMP,GIF,JPEG/JFIF,ICNS,ICO/CUR,PCX/DCX,PNM/PGM/PBM/PPM/PAMPortablePixmap,PNG,PSD/Photoshop,RGBE/RadianceHDR,TIFF,WBMP,XBM,XPM
#-- commonsImagingSupportedFormats=BMP,GIF,JPEG/JFIF,ICNS,ICO/CUR,PCX/DCX,PNM/PGM/PBM/PPM/PAMPortablePixmap,PNG,PSD/Photoshop,RGBE/RadianceHDR,\
TIFF,WBMP,XBM,XPM
#-- You should then modify SupportedImageFormats label.
#--
#-- If you want to get more image formats then use imageJ:
#-- For imagejSupportedFormats see https://imagejdocu.tudor.lu/faq/general/which_file_formats_are_supported_by_imagej. NOTE: plugins support is important here
#-- imagejSupportedFormats=TIFF(.tiff,.tif),JPEG(.jpeg,.jpg),BMP(.bmp),FITS(.fits),PGM(.pgm),PPM(.ppm),PBM(.pbm),GIF(.gif),AnimatedGIF(.gif),PNG(.png),DICOM(.dic,.dcm,.dicom),PICT(.pict,.pic,.pct),PSD(.psd),TGA(.tga),ICO(.ico),CUR(.cur),Sunraster(.sun),XBM(.xbm),XPM(.xpm),PCX(.pcx),ANALYZE,NIfTi,AHF(.ahf),SPE(.spe),PIC(.pic),LeicaTIFF(.tiff,.lei),Quicktime(.pic,.mov),AVI(.avi),PDS(.pds),LSM(.lsm),RAW,ISAC,FluoViewTIFF(.tiff),FluoviewFV1000OIB(.oib),FluoviewFV1000OIF(.oif,.tif,-ro.pty,.lut,.bmp),IPLAB(.ipl),BrukerNMR(.fid,.ser,.2dseq,.2rr,.2ii,.3rrr,.3iii),FDF(.fdf),VFF(.vff),SIF(.sif),AxioVisionZVI(.zvi),DM3(.dm3),Deltavision(.dv,.r3d),MI,NII,NIII,IMG(.img),UNC,PerkinElmer(.tif,.tim,.zpo,.csv,.htm,.ano,.rec,.cfg,.2,.3,.4,.5,.6,.7,.8,\u2026),EPS(.eps,.epsi),SEQ(.seq),IPW(.ipw),OpenLabLIFF(.liff),OpenLabRAW(.raw),Metamorph(.stk),ICS(.ics,.ids),LeicaLif(.lif),Imaris(.ims),OME-XML(.ome),OME-TIFF(.tiff),ABD-TIFF(.tiff),GEL(.gel),Nikon(.nef,.tiff),Slidebook(.sld),SPCImage(.sdt),AL3D(.al3d),ND2(.nd2),μManager(.tif,.txt),MRC(.mrc),JPEG2000(.jp2),MNG(.mng),Flex(.flex),NRRD(.nrrd,.nhdr),VIFFbitmapimage(.xv),ROI(.roi),ERS(.ers),RS(.rs),HPGL
#-- imagejSupportedFormats=TIFF(.tiff,.tif),JPEG(.jpeg,.jpg),BMP(.bmp),FITS(.fits),PGM(.pgm),PPM(.ppm),PBM(.pbm),GIF(.gif),AnimatedGIF(.gif),\
PNG(.png),DICOM(.dic,.dcm,.dicom),PICT(.pict,.pic,.pct),PSD(.psd),TGA(.tga),ICO(.ico),CUR(.cur),Sunraster(.sun),\
XBM(.xbm),XPM(.xpm),PCX(.pcx),ANALYZE,NIfTi,AHF(.ahf),SPE(.spe),PIC(.pic),LeicaTIFF(.tiff,.lei),Quicktime(.pic,.mov),\
AVI(.avi),PDS(.pds),LSM(.lsm),RAW,ISAC,FluoViewTIFF(.tiff),FluoviewFV1000OIB(.oib),\
FluoviewFV1000OIF(.oif,.tif,-ro.pty,.lut,.bmp),IPLAB(.ipl),BrukerNMR(.fid,.ser,.2dseq,.2rr,.2ii,.3rrr,.3iii),FDF(.fdf),\
VFF(.vff),SIF(.sif),AxioVisionZVI(.zvi),DM3(.dm3),Deltavision(.dv,.r3d),MI,NII,NIII,IMG(.img),UNC,PerkinElmer(.tif,.tim,\
.zpo,.csv,.htm,.ano,.rec,.cfg,.2,.3,.4,.5,.6,.7,.8,\u2026),EPS(.eps,.epsi),SEQ(.seq),IPW(.ipw),OpenLabLIFF(.liff),\
OpenLabRAW(.raw),Metamorph(.stk),ICS(.ics,.ids),LeicaLif(.lif),Imaris(.ims),OME-XML(.ome),OME-TIFF(.tiff),\
ABD-TIFF(.tiff),GEL(.gel),Nikon(.nef,.tiff),Slidebook(.sld),SPCImage(.sdt),AL3D(.al3d),ND2(.nd2),μManager(.tif,.txt),\
MRC(.mrc),JPEG2000(.jp2),MNG(.mng),Flex(.flex),NRRD(.nrrd,.nhdr),VIFFbitmapimage(.xv),ROI(.roi),ERS(.ers),RS(.rs),HPGL
#--
#-- PDFBox and PDFReader are used for PDF files
#--
@@ -226,21 +236,39 @@ templateClassResolver=
#--
#-- List of denied files suffixes to be uploaded
#-- OFBiz of course also check contents...
deniedFileExtensions=html,htm,php,php2,hph3,php4,php5,asp,aspx,ascx,jsp,jspx,cfm,cfc,bat,exe,com,dll,vbs,js,reg,cgi,htaccess,asis,sh,phtm,shtm,inc,asp,cdx,asa,cer,py,pl,shtml,hta,ps1
deniedFileExtensions=html,htm,php,php1,php2,hph3,php4,php5,php6,php7,phps,asp,aspx,asa,asax,ascx,ashx,asmx,jsp,jspa,jspx,jsw,jsv,jspf,jtml,cfm,cfc,bat,exe,com,dll,\
vbs,js,reg,cgi,asis,sh,phtm,pht,phtml,shtm,inc,asp,cdx,asa,cer,py,pl,shtml,hta,ps1,tag,pgif,htaccess,phar,inc,cgi,wss,do,action
#--
#-- The upload vulnerability is only a post-auth (needs a credential with suitable permissions),
#-- people may like to allow more than what is allowed OOTB
#-- As it name says, allowAllUploads opens all possibilities
allowAllUploads=
#--
#-- List of denied tokens often part of webshells
#-- CSV format used to upload CSV files, cf. https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html
csvformat=CSVFormat.DEFAULT
#--
#-- List of denied tokens often part of webshells. Note that, for now at least, most are supposed to be used on a *nix system
#-- TODO.... to be continued with known webshell contents... a complete allow list is impossible anyway...
#-- eg: https://www.acunetix.com/blog/articles/detection-prevention-introduction-web-shells-part-5/
#--
#-- It could notably be improved by checking for all Javascripts payloads.
#-- As listed at https://portswigger.net/web-security/cross-site-scripting/cheat-sheet,
#-- at 2022-02-25 there are 8929 of them considering all tags, all events and all browsers...!
#--
#-- "freemarker" should be OK, should not be used in Freemarker templates, not part of the syntax.
#-- Else "template.utility.Execute" is a good replacement but not as much catching, who knows...
deniedWebShellTokens=freemarker,import=\"java,runtime.getruntime().exec(,<%@ page,<script,<body>,<form,php,\
javascript,%eval,@eval,import os,passthru,exec,shell_exec,assert,str_rot13,system,phpinfo,base64_decode,chmod,mkdir,\
fopen,fclose,new file,import,upload,getfilename,download,getoutputstring,readfile
#--
#-- If you are sure you are safe for a token you can remove it, etc.
deniedWebShellTokens=java.,beans,freemarker,<script,javascript,<body,body ,<form,<jsp:,<c:out,taglib,<prefix,<%@ page,<?php,exec(,alert(,\
%eval,@eval,eval(,runtime,import,passthru,shell_exec,assert,str_rot13,system,decode,include,page ,\
chmod,mkdir,fopen,fclose,new file,upload,getfilename,download,getoutputstring,readfile,iframe,object,embed,onload,build,\
python,perl ,/perl,ruby ,/ruby,process,function,class,InputStream,to_server,wget ,static,assign,webappPath,\
ifconfig,route,crontab,netstat,uname ,hostname,iptables,whoami,"cmd",*cmd|,+cmd|,=cmd|,localhost,thread,require,gzdeflate
#-- Max line length for uploaded files, by default 10000
maxLineLength=
#-- Popup last-visited time from database after user has logged in.
#-- So users can know of any unauthorised access to their accounts.
@@ -254,3 +282,12 @@ login.uris=login
#-- If you need to use localhost or 127.0.0.1 in textareas URLs then you can uncomment the allowedProtocols property, here given as an example
#-- You may also put other protocols you want to use, instead or with those
allowedProtocols=localhost,127.0.0.1
#-- By default (OOTB) OFBiz is protected against Large File Denial of Service because build.gradle defines -Xmx1024M
#-- So you can at most upload a file around 500MB (see OFBIZ-11534 for more info)
#-- If you need to upload larger files then follow https://nightlies.apache.org/ofbiz/trunk/readme/html5/#passing-jvm-runtime-options-to-ofbiz
#-- Prevent Freemarker exploits
#-- eg: allowedURIsForFreemarkerInterpolation=createTextContentCms,updateTextContentCms,...
allowedURIsForFreemarkerInterpolation=
@@ -24,7 +24,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MultivaluedHashMap;
@@ -68,9 +67,11 @@ public final class CsrfUtil {
try {
String className = UtilProperties.getPropertyValue("security", "csrf.defense.strategy",
NoCsrfDefenseStrategy.class.getCanonicalName());
Class<?> c = Class.forName(className);
Class<? extends ICsrfDefenseStrategy> c =
Class.forName(className).asSubclass(
ICsrfDefenseStrategy.class);
strategyCanonicalName = c.getCanonicalName();
setStrategy((ICsrfDefenseStrategy) c.newInstance());
setStrategy(c.getConstructor().newInstance());
} catch (Exception e) {
Debug.logError(e, MODULE);
setStrategy(new NoCsrfDefenseStrategy());
@@ -27,6 +27,8 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
@@ -49,6 +51,8 @@ import javax.imageio.stream.ImageInputStream;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.imaging.ImageFormat;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.ImageInfo;
@@ -62,6 +66,7 @@ import org.apache.commons.imaging.formats.png.PngImageParser;
import org.apache.commons.imaging.formats.tiff.TiffImageParser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.FileUtil;
import org.apache.ofbiz.base.util.StringUtil;
@@ -89,45 +94,62 @@ import com.lowagie.text.pdf.PdfReader;
public class SecuredUpload {
// To check if a webshell is not uploaded
// This can be helpful:
// https://en.wikipedia.org/wiki/File_format
// https://en.wikipedia.org/wiki/List_of_file_signatures
// See also information in security.properties:
// Line #-- UPLOAD: supported file formats are *safe* PNG, GIF, TIFF, JPEG, PDF, Audio and Video and ZIP
// Supported file formats are *safe* PNG, GIF, TIFF, JPEG, PDF, Audio, Video, Text, and ZIP
private static final String MODULE = SecuredUpload.class.getName();
private static final List<String> DENIEDFILEEXTENSIONS = deniedFileExtensions();
private static final List<String> DENIEDWEBSHELLTOKENS = deniedWebShellTokens();
private static final List<String> DENIEDFILEEXTENSIONS = getDeniedFileExtensions();
private static final List<String> DENIEDWEBSHELLTOKENS = getDeniedWebShellTokens();
private static final Integer MAXLINELENGTH = UtilProperties.getPropertyAsInteger("security", "maxLineLength", 10000);
/**
* @param fileToCheck
* @param fileType
* @return true if the file is valid
* @throws IOException
* @throws ImageReadException
*/
public static boolean isValidFile(String fileToCheck, String fileType, Delegator delegator) throws IOException, ImageReadException {
public static boolean isValidText(String content, List<String> allowed) throws IOException {
return content != null ? DENIEDWEBSHELLTOKENS.stream().allMatch(token -> isValid(content, token.toLowerCase(), allowed)) : false;
}
if (("true".equalsIgnoreCase(EntityUtilProperties.getPropertyValue("security", "allowAllUploads", delegator)))) {
return true;
public static boolean isValidFileName(String fileToCheck, Delegator delegator) throws IOException {
// Prevents double extensions
if (StringUtils.countMatches(fileToCheck, ".") > 1) {
Debug.logError("Double extensions are not allowed for security reason", MODULE);
return false;
}
String imageServerUrl = EntityUtilProperties.getPropertyValue("catalog", "image.management.url", delegator);
Path p = Paths.get(fileToCheck);
boolean wrongFile = true;
// Check extensions
if (p != null && p.getFileName() != null) {
String fileName = p.getFileName().toString(); // The file name is the farthest element from the root in the directory hierarchy.
if (DENIEDFILEEXTENSIONS.contains(FilenameUtils.getExtension(fileToCheck))) {
String extension = FilenameUtils.getExtension(fileToCheck).toLowerCase();
// Prevents null byte in filename
if (extension.contains("%00")
|| extension.contains("%0a")
|| extension.contains("%20")
|| extension.contains("%0d%0a")
|| extension.contains("/")
|| extension.contains("./")
|| extension.contains(".")) {
Debug.logError("Special bytes in extension are not allowed for security reason", MODULE);
return false;
}
if (DENIEDFILEEXTENSIONS.contains(extension)) {
Debug.logError("This file extension is not allowed for security reason", MODULE);
deleteBadFile(fileToCheck);
return false;
}
// Check the file and path names
if (org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS) {
// More about that: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
if (fileToCheck.length() > 259) {
Debug.logError("Uploaded file name too long", MODULE);
} else if (p.toString().contains(imageServerUrl.replaceAll("/", "\\\\"))) {
// TODO check this is still useful in at least 1 case
if (fileName.matches("[a-zA-Z0-9-_ ()]{1,249}.[a-zA-Z0-9-_ ]{1,10}")) { // "(" and ")" for duplicates files
wrongFile = false;
}
@@ -138,6 +160,7 @@ public class SecuredUpload {
if (fileToCheck.length() > 4096) {
Debug.logError("Uploaded file name too long", MODULE);
} else if (p.toString().contains(imageServerUrl)) {
// TODO check this is still useful in at least 1 case
if (fileName.matches("[a-zA-Z0-9-_ ()]{1,4086}.[a-zA-Z0-9-_ ]{1,10}")) { // "(" and ")" for duplicates files
wrongFile = false;
}
@@ -156,6 +179,34 @@ public class SecuredUpload {
deleteBadFile(fileToCheck);
return false;
}
return true;
}
/**
* @param fileToCheck
* @param fileType
* @return true if the file is valid
* @throws IOException
* @throws ImageReadException
*/
public static boolean isValidFile(String fileToCheck, String fileType, Delegator delegator) throws IOException, ImageReadException {
// Allow all
if (("true".equalsIgnoreCase(EntityUtilProperties.getPropertyValue("security", "allowAllUploads", delegator)))) {
return true;
}
// Check the file name
if (!isValidFileName(fileToCheck, delegator)) { // Useless when the file is internally generated, but not sure for all cases
return false;
}
// Check the file content
// Check max line length, default 10000
if (!checkMaxLinesLength(fileToCheck)) {
Debug.logError("For security reason lines over " + MAXLINELENGTH.toString() + " are not allowed", MODULE);
return false;
}
if (isExecutable(fileToCheck)) {
deleteBadFile(fileToCheck);
@@ -188,7 +239,7 @@ public class SecuredUpload {
break;
case "AllButCompressed":
if (isValidTextFile(fileToCheck)
if (isValidTextFile(fileToCheck, true)
|| isValidImageIncludingSvgFile(fileToCheck)
|| isValidPdfFile(fileToCheck)) {
return true;
@@ -199,7 +250,7 @@ public class SecuredUpload {
// The philosophy for isValidTextFile() is that
// we can't presume of all possible text contents used for attacks with payloads
// At least there is an easy way to prevent them in isValidTextFile
if (isValidTextFile(fileToCheck)) {
if (isValidTextFile(fileToCheck, true)) {
return true;
}
break;
@@ -214,13 +265,19 @@ public class SecuredUpload {
return true;
}
break;
case "CSV":
if (isValidCsvFile(fileToCheck)) {
return true;
}
break;
default: // All
if (isValidTextFile(fileToCheck)
if (isValidTextFile(fileToCheck, true)
|| isValidImageIncludingSvgFile(fileToCheck)
|| isValidCompressedFile(fileToCheck, delegator)
|| isValidAudioFile(fileToCheck)
|| isValidVideoFile(fileToCheck)
|| isValidCsvFile(fileToCheck)
|| isValidPdfFile(fileToCheck)) {
return true;
}
@@ -244,7 +301,8 @@ public class SecuredUpload {
|| imageFormat.equals(ImageFormats.GIF)
|| imageFormat.equals(ImageFormats.TIFF)
|| imageFormat.equals(ImageFormats.JPEG))
&& imageMadeSafe(fileName);
&& imageMadeSafe(fileName)
&& isValidTextFile(fileName, false);
}
/**
@@ -370,7 +428,7 @@ public class SecuredUpload {
} catch (IOException e) {
return false;
}
return isValidTextFile(fileName); // Validate content to prevent webshell
return isValidTextFile(fileName, true); // Validate content to prevent webshell
}
return false;
}
@@ -402,24 +460,62 @@ public class SecuredUpload {
}
} catch (Exception e) {
safeState = false;
Debug.logError(e, "for security reason the PDF file " + file.getAbsolutePath() + "can't be uploaded !", MODULE);
Debug.logInfo(e, "The file " + file.getAbsolutePath() + " is not a valid PDF file. For security reason it's not accepted as a such file",
MODULE);
}
return safeState;
}
/**
* Is it a CVS file?
* @param fileName
* @return true if it's a valid CVS file
* @throws IOException
*/
private static boolean isValidCsvFile(String fileName) throws IOException {
Path filePath = Paths.get(fileName);
String content = new String(Files.readAllBytes(filePath));
Reader in = new StringReader(content);
String cvsFormatString = UtilProperties.getPropertyValue("security", "csvformat");
CSVFormat cvsFormat = CSVFormat.DEFAULT;
switch (cvsFormatString) {
case "EXCEL":
cvsFormat = CSVFormat.EXCEL;
break;
case "MYSQL":
cvsFormat = CSVFormat.MYSQL;
break;
case "ORACLE":
cvsFormat = CSVFormat.ORACLE;
break;
case "POSTGRESQL_CSV":
cvsFormat = CSVFormat.POSTGRESQL_CSV;
break;
default:
cvsFormat = CSVFormat.DEFAULT;
}
// cf. https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html
try (CSVParser parser = new CSVParser(in, cvsFormat)) {
parser.getRecords();
}
return isValidTextFile(fileName, false); // Validate content to prevent webshell
}
private static boolean isExecutable(String fileName) throws IOException {
String mimeType = getMimeTypeFromFileName(fileName);
// Check for Windows executable. Neglect .bat and .ps1: https://s.apache.org/c8sim
if ("application/x-msdownload".equals(mimeType) || "application/x-ms-installer".equals(mimeType)) {
Debug.logError("The file" + fileName + " is a Windows executable, for security reason it's not accepted :", MODULE);
Debug.logError("The file " + fileName + " is a Windows executable, for security reason it's not accepted", MODULE);
return true;
}
// Check for ELF (Linux) and scripts
if ("application/x-elf".equals(mimeType)
|| "application/x-sh".equals(mimeType)
|| "application/text/x-perl".equals(mimeType)
|| "application/text/x-ruby".equals(mimeType)
|| "application/text/x-python".equals(mimeType)) {
Debug.logError("The file" + fileName + " is a Linux executable, for security reason it's not accepted :", MODULE);
Debug.logError("The file " + fileName + " is a Linux executable, for security reason it's not accepted", MODULE);
return true;
}
return false;
@@ -483,8 +579,11 @@ public class SecuredUpload {
*/
private static String getMimeTypeFromFileName(String fileName) throws IOException {
File file = new File(fileName);
Tika tika = new Tika();
return tika.detect(file);
if (file.exists()) {
Tika tika = new Tika();
return tika.detect(file);
}
return null;
}
private static boolean isValidDirectoryInCompressedFile(String folderName, Delegator delegator) throws IOException, ImageReadException {
@@ -568,7 +667,7 @@ public class SecuredUpload {
|| "audio/x-flac".equals(mimeType)) {
return true;
}
Debug.logError("The file" + fileName + " is not a valid audio file, for security reason it's not accepted :", MODULE);
Debug.logInfo("The file " + fileName + " is not a valid audio file. For security reason it's not accepted as a such file", MODULE);
return false;
}
@@ -593,52 +692,75 @@ public class SecuredUpload {
|| "video/x-ms-wmx".equals(mimeType)) {
return true;
}
Debug.logError("The file" + fileName + " is not a valid video file, for security reason it's not accepted :", MODULE);
Debug.logInfo("The file " + fileName + " is not a valid video file. For security reason it's not accepted as a such file", MODULE);
return false;
}
/**
* Does this text file contains a Freemarker Server-Side Template Injection (SSTI) using freemarker.template.utility.Execute? Etc.
* @param fileName must be an UTF-8 encoded text file
* @param encodedContent TODO
* @return true if the text file does not contains a Freemarker SSTI
* @throws IOException
*/
private static boolean isValidTextFile(String fileName) throws IOException {
private static boolean isValidTextFile(String fileName, Boolean encodedContent) throws IOException {
Path filePath = Paths.get(fileName);
byte[] bytesFromFile = Files.readAllBytes(filePath);
try {
Charset.availableCharsets().get("UTF-8").newDecoder().decode(ByteBuffer.wrap(bytesFromFile));
} catch (CharacterCodingException e) {
return false;
if (encodedContent) {
try {
Charset.availableCharsets().get("UTF-8").newDecoder().decode(ByteBuffer.wrap(bytesFromFile));
} catch (CharacterCodingException e) {
return false;
}
}
String content = new String(bytesFromFile);
if (content.toLowerCase().contains("xlink:href=\"http")
|| content.toLowerCase().contains("<!ENTITY ")) { // Billions laugh attack
Debug.logInfo("Linked images inside or Entity in SVG are not allowed for security reason", MODULE);
return false;
}
ArrayList<String> allowed = new ArrayList<>();
return isValidText(content, allowed);
}
public static boolean isValidText(String content, List<String> allowed) throws IOException {
return DENIEDWEBSHELLTOKENS.stream().allMatch(token -> isValid(content, token, allowed));
}
private static boolean isValid(String content, String string, List<String> allowed) {
return !content.toLowerCase().contains(string) || allowed.contains(string);
boolean isOK = !content.toLowerCase().contains(string) || allowed.contains(string);
if (!isOK) {
Debug.logInfo("The uploaded file contains the string '" + string + "'. It can't be uploaded for security reason", MODULE);
}
return isOK;
}
private static void deleteBadFile(String fileToCheck) {
Debug.logError("File :" + fileToCheck + ", can't be uploaded for security reason", MODULE);
Debug.logError("File : " + fileToCheck + ", can't be uploaded for security reason", MODULE);
File badFile = new File(fileToCheck);
if (!badFile.delete()) {
Debug.logError("File :" + fileToCheck + ", couldn't be deleted", MODULE);
if (badFile.exists() && !badFile.delete()) {
Debug.logError("File : " + fileToCheck + ", couldn't be deleted", MODULE);
}
}
private static List<String> deniedFileExtensions() {
private static List<String> getDeniedFileExtensions() {
String deniedExtensions = UtilProperties.getPropertyValue("security", "deniedFileExtensions");
return UtilValidate.isNotEmpty(deniedExtensions) ? StringUtil.split(deniedExtensions, ",") : new ArrayList<>();
}
private static List<String> deniedWebShellTokens() {
private static List<String> getDeniedWebShellTokens() {
String deniedTokens = UtilProperties.getPropertyValue("security", "deniedWebShellTokens");
return UtilValidate.isNotEmpty(deniedTokens) ? StringUtil.split(deniedTokens, ",") : new ArrayList<>();
}
private static boolean checkMaxLinesLength(String fileToCheck) {
try {
File file = new File(fileToCheck);
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
for (String line : lines) {
if (line.length() > MAXLINELENGTH) {
return false;
}
}
} catch (IOException e) {
return false;
}
return true;
}
}
@@ -19,13 +19,23 @@
package org.apache.ofbiz.security;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
@@ -55,7 +65,7 @@ public final class SecurityUtil {
* Return true if given userLogin possess at least one of the adminPermission
* @param delegator
* @param userLoginId
* @return
* @return boolean
*/
public static boolean hasUserLoginAdminPermission(Delegator delegator, String userLoginId) {
if (UtilValidate.isEmpty(userLoginId)) return false;
@@ -78,7 +88,7 @@ public final class SecurityUtil {
* @param delegator
* @param userLoginId
* @param toUserLoginId
* @return
* @return List
*/
public static List<String> hasUserLoginMorePermissionThan(Delegator delegator, String userLoginId, String toUserLoginId) {
ArrayList<String> returnList = new ArrayList<>();
@@ -161,4 +171,68 @@ public final class SecurityUtil {
}
return false;
}
/*
* Prevents Freemarker exploits
* @param req
* @param resp
* @param uri
* @throws IOException
*/
public static boolean containsFreemarkerInterpolation(HttpServletRequest req, HttpServletResponse resp, String uri)
throws IOException {
String urisOkForFreemarker = UtilProperties.getPropertyValue("security", "allowedURIsForFreemarkerInterpolation");
List<String> urisOK = UtilValidate.isNotEmpty(urisOkForFreemarker) ? StringUtil.split(urisOkForFreemarker, ",")
: new ArrayList<>();
String uriEnd = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
if (!urisOK.contains(uriEnd)) {
Map<String, String[]> parameterMap = req.getParameterMap();
if (uri.contains("ecomseo")) { // SeoContextFilter call
if (containsFreemarkerInterpolation(resp, uri)) {
return true;
}
} else if (!parameterMap.isEmpty()) { // ControlFilter call
List<BasicNameValuePair> params = new ArrayList<>();
parameterMap.forEach((name, values) -> {
for (String value : values) {
params.add(new BasicNameValuePair(name, value));
}
});
String queryString = URLEncodedUtils.format(params, Charset.forName("UTF-8"));
uri = uri + "?" + queryString;
if (SecurityUtil.containsFreemarkerInterpolation(resp, uri)) {
return true;
}
} else if (!UtilHttp.getAttributeMap(req).isEmpty()) { // Call with Content-Type modified by a MITM attack (rare case)
String attributeMap = UtilHttp.getAttributeMap(req).toString();
if (containsFreemarkerInterpolation(resp, attributeMap)) {
return true;
}
}
}
return false;
}
/**
* @param resp
* @param stringToCheck
* @throws IOException
*/
public static boolean containsFreemarkerInterpolation(HttpServletResponse resp, String stringToCheck) throws IOException {
if (stringToCheck.contains("%24%7B") || stringToCheck.contains("${")
|| stringToCheck.contains("%3C%23") || stringToCheck.contains("<#")
|| stringToCheck.contains("%23%7B") || stringToCheck.contains("#{")
|| stringToCheck.contains("%5B%3D") || stringToCheck.contains("[=")
|| stringToCheck.contains("%5B%23") || stringToCheck.contains("[#")) { // not used OOTB in OFBiz, but possible
Debug.logError("===== Not saved for security reason, strings '${', '<#', '#{', '[=' or '[#' not accepted in fields! =====",
MODULE);
resp.sendError(HttpServletResponse.SC_FORBIDDEN,
"Not saved for security reason, strings '${', '<#', '#{', '[=' or '[#' not accepted in fields!");
return true;
} else {
return false;
}
}
}
@@ -18,6 +18,10 @@
*/
package org.apache.ofbiz.security;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -25,10 +29,6 @@ import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
public class SecurityUtilTest {
@Test
public void basicAdminPermissionTesting() {
@@ -58,43 +58,95 @@ public class SecurityUtilTest {
@Test
public void webShellTokensTesting() {
// Currently used
// java.,beans,freemarker,<script,javascript,<body,body <form,<jsp:,<c:out,taglib,<prefix,<%@ page,<?php,exec(,alert(,\
// %eval,@eval,eval(,runtime,import,passthru,shell_exec,assert,str_rot13,system,decode,include,page ,\
// chmod,mkdir,fopen,fclose,new file,upload,getfilename,download,getoutputstring,readfile,iframe,object,embed,onload,build\
// python,perl ,/perl,ruby ,/ruby,process,function,class,InputStream,to_server,wget ,static,assign,webappPath,\
// ifconfig,route,crontab,netstat,uname ,hostname,iptables,whoami,"cmd",*cmd|,+cmd|,=cmd|,localhost,thread,require,gzdeflate
try {
List<String> allowed = new ArrayList<>();
allowed.add("getfilename");
assertTrue(SecuredUpload.isValidText("hack.getFileName", allowed));
allowed = new ArrayList<>();
assertFalse(SecuredUpload.isValidText("hack.getFileName", allowed));
assertFalse(SecuredUpload.isValidText("java.", allowed));
assertFalse(SecuredUpload.isValidText("beans", allowed));
assertFalse(SecuredUpload.isValidText("freemarker", allowed));
assertFalse(SecuredUpload.isValidText("import=\"java", allowed));
assertFalse(SecuredUpload.isValidText("runtime.getruntime().exec(", allowed));
assertFalse(SecuredUpload.isValidText("<%@ page", allowed));
assertFalse(SecuredUpload.isValidText("<script", allowed));
assertFalse(SecuredUpload.isValidText("<body>", allowed));
assertFalse(SecuredUpload.isValidText("<form", allowed));
assertFalse(SecuredUpload.isValidText("php", allowed));
assertFalse(SecuredUpload.isValidText("javascript", allowed));
assertFalse(SecuredUpload.isValidText("<body", allowed));
assertFalse(SecuredUpload.isValidText("body ", allowed));
assertFalse(SecuredUpload.isValidText("<form", allowed));
assertFalse(SecuredUpload.isValidText("<jsp:", allowed));
assertFalse(SecuredUpload.isValidText("<c:out", allowed));
assertFalse(SecuredUpload.isValidText("taglib", allowed));
assertFalse(SecuredUpload.isValidText("<prefix", allowed));
assertFalse(SecuredUpload.isValidText("<%@ page", allowed));
assertFalse(SecuredUpload.isValidText("<?php", allowed));
assertFalse(SecuredUpload.isValidText("exec(", allowed));
assertFalse(SecuredUpload.isValidText("%eval", allowed));
assertFalse(SecuredUpload.isValidText("@eval", allowed));
assertFalse(SecuredUpload.isValidText("import os", allowed));
assertFalse(SecuredUpload.isValidText("runtime", allowed));
assertFalse(SecuredUpload.isValidText("import", allowed));
assertFalse(SecuredUpload.isValidText("passthru", allowed));
assertFalse(SecuredUpload.isValidText("exec", allowed));
assertFalse(SecuredUpload.isValidText("shell_exec", allowed));
assertFalse(SecuredUpload.isValidText("assert", allowed));
assertFalse(SecuredUpload.isValidText("str_rot13", allowed));
assertFalse(SecuredUpload.isValidText("system", allowed));
assertFalse(SecuredUpload.isValidText("phpinfo", allowed));
assertFalse(SecuredUpload.isValidText("base64_decode", allowed));
assertFalse(SecuredUpload.isValidText("decode", allowed));
assertFalse(SecuredUpload.isValidText("include", allowed));
assertFalse(SecuredUpload.isValidText("chmod", allowed));
assertFalse(SecuredUpload.isValidText("mkdir", allowed));
assertFalse(SecuredUpload.isValidText("fopen", allowed));
assertFalse(SecuredUpload.isValidText("fclose", allowed));
assertFalse(SecuredUpload.isValidText("new file", allowed));
assertFalse(SecuredUpload.isValidText("import", allowed));
assertFalse(SecuredUpload.isValidText("upload", allowed));
assertFalse(SecuredUpload.isValidText("getfilename", allowed));
assertFalse(SecuredUpload.isValidText("download", allowed));
assertFalse(SecuredUpload.isValidText("getoutputstring", allowed));
assertFalse(SecuredUpload.isValidText("readfile", allowed));
assertFalse(SecuredUpload.isValidText("iframe", allowed));
assertFalse(SecuredUpload.isValidText("object", allowed));
assertFalse(SecuredUpload.isValidText("embed", allowed));
assertFalse(SecuredUpload.isValidText("onload", allowed));
assertFalse(SecuredUpload.isValidText("build", allowed));
assertFalse(SecuredUpload.isValidText("python", allowed));
assertFalse(SecuredUpload.isValidText("perl ", allowed));
assertFalse(SecuredUpload.isValidText("/perl", allowed));
assertFalse(SecuredUpload.isValidText("ruby ", allowed));
assertFalse(SecuredUpload.isValidText("/ruby", allowed));
assertFalse(SecuredUpload.isValidText("process", allowed));
assertFalse(SecuredUpload.isValidText("function", allowed));
assertFalse(SecuredUpload.isValidText("class", allowed));
assertFalse(SecuredUpload.isValidText("wget ", allowed));
assertFalse(SecuredUpload.isValidText("static", allowed));
assertFalse(SecuredUpload.isValidText("assign", allowed));
assertFalse(SecuredUpload.isValidText("webappPath", allowed));
assertFalse(SecuredUpload.isValidText("ifconfig", allowed));
assertFalse(SecuredUpload.isValidText("route", allowed));
assertFalse(SecuredUpload.isValidText("crontab", allowed));
assertFalse(SecuredUpload.isValidText("netstat", allowed));
assertFalse(SecuredUpload.isValidText("uname ", allowed));
assertFalse(SecuredUpload.isValidText("hostname", allowed));
assertFalse(SecuredUpload.isValidText("iptables", allowed));
assertFalse(SecuredUpload.isValidText("whoami", allowed));
// ip, ls, nc, ip, cat and pwd can't be used, too short
assertFalse(SecuredUpload.isValidText("\"cmd\"", allowed));
assertFalse(SecuredUpload.isValidText("*cmd|", allowed));
assertFalse(SecuredUpload.isValidText("+cmd|", allowed));
assertFalse(SecuredUpload.isValidText("=cmd|", allowed));
assertFalse(SecuredUpload.isValidText("localhost", allowed));
assertFalse(SecuredUpload.isValidText("thread", allowed));
assertFalse(SecuredUpload.isValidText("require", allowed));
assertFalse(SecuredUpload.isValidText("gzdeflate", allowed));
} catch (IOException e) {
fail(String.format("IOException occured : %s", e.getMessage()));
}
+1
View File
@@ -41,6 +41,7 @@ under the License.
<xs:element minOccurs="0" ref="description"/>
<xs:element minOccurs="0" ref="namespace"/>
<xs:element minOccurs="0" maxOccurs="1" ref="deprecated"/>
<xs:element minOccurs="0" ref="notification"/>
<xs:element minOccurs="0" maxOccurs="1" ref="permission-service"/>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="required-permissions"/>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="implements"/>
@@ -20,13 +20,13 @@ package org.apache.ofbiz.service.engine
import org.apache.ofbiz.base.util.Debug
import org.apache.ofbiz.base.util.UtilProperties
import org.apache.ofbiz.entity.GenericValue
import org.apache.ofbiz.entity.util.EntityQuery
import org.apache.ofbiz.service.DispatchContext
import org.apache.ofbiz.service.ExecutionServiceException
import org.apache.ofbiz.service.LocalDispatcher
import org.apache.ofbiz.service.ModelService
import org.apache.ofbiz.service.ServiceUtil
import org.apache.ofbiz.service.ExecutionServiceException
import org.apache.ofbiz.entity.GenericValue
abstract class GroovyBaseScript extends Script {
public static final String module = GroovyBaseScript.class.getName()
@@ -53,6 +53,27 @@ abstract class GroovyBaseScript extends Script {
? this.binding.getVariable('locale')
: this.binding.getVariable('parameters').locale
}
if (serviceName.equals("createAnonFile")) {
String fileName = inputMap.get("dataResourceName")
String fileNameAndPath = inputMap.get("objectInfo")
File file = new File(fileNameAndPath)
if (!fileName.isEmpty()) {
// Check the file name
if (!org.apache.ofbiz.security.SecuredUpload.isValidFileName(fileName, delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", inputMap.locale)
throw new ExecutionServiceException(errorMessage)
}
// TODO we could verify the file type (here "All") with dataResourceTypeId. Anyway it's done with isValidFile()
// We would just have a better error message
if (file.exists()) {
// Check if a webshell is not uploaded
if (!org.apache.ofbiz.security.SecuredUpload.isValidFile(fileNameAndPath, "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", inputMap.locale)
throw new ExecutionServiceException(errorMessage)
}
}
}
}
Map serviceContext = dctx.makeValidContext(serviceName, ModelService.IN_PARAM, inputMap)
Map result = dispatcher.runSync(serviceName, serviceContext)
if (ServiceUtil.isError(result)) {
@@ -18,6 +18,8 @@
*/
package org.apache.ofbiz.service.engine;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
@@ -37,6 +39,7 @@ import org.apache.ofbiz.entity.model.ModelEntity;
import org.apache.ofbiz.entity.model.ModelField;
import org.apache.ofbiz.entity.model.ModelUtil;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.security.SecuredUpload;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.ModelParam;
@@ -71,6 +74,9 @@ public final class EntityAutoEngine extends GenericAsyncEngine {
@Override
public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> parameters) throws GenericServiceException {
// static java service methods should be: public Map<String, Object> methodName(DispatchContext dctx, Map<String, Object> context)
if (!isValidText(parameters)) {
return ServiceUtil.returnError("Not saved for security reason!");
}
DispatchContext dctx = getDispatcher().getLocalContext(localName);
Locale locale = (Locale) parameters.get("locale");
Map<String, Object> result = ServiceUtil.returnSuccess();
@@ -614,4 +620,21 @@ public final class EntityAutoEngine extends GenericAsyncEngine {
UtilMisc.toMap("label", modelEntity.getTitle()), locale));
return result;
}
private static boolean isValidText(Map<String, Object> parameters) {
// TODO maybe more parameters will be needed in future...
String parameter = (String) parameters.get("webappPath");
if (parameter != null) {
try {
if (!SecuredUpload.isValidText(parameter, Collections.emptyList())) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return false;
}
} catch (IOException e) {
Debug.logError("================== Not saved for security reason ==================", MODULE);
return false;
}
}
return true;
}
}
@@ -36,6 +36,8 @@ import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.logging.log4j.ThreadContext;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.security.SecurityUtil;
/**
* A Filter used to specify an allowlist of allowed paths to the OFBiz application.
@@ -147,6 +149,16 @@ public class ControlFilter extends HttpFilter {
String uriWithContext = req.getRequestURI();
String uri = uriWithContext.substring(context.length());
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (!LoginWorker.hasBasePermission(userLogin, req)) { // Allows UEL and
if (!GenericValue.getStackTraceAsString().contains("ControlFilterTests")
&& null == System.getProperty("SolrDispatchFilter") // Allows Solr tests
&& SecurityUtil.containsFreemarkerInterpolation(req, resp, uri)) {
return;
}
}
// Check if the requested URI is allowed.
if (allowedPaths.stream().anyMatch(uri::startsWith)) {
try {
@@ -165,7 +177,7 @@ public class ControlFilter extends HttpFilter {
}
if (Debug.infoOn()) {
Debug.logInfo("[Filtered request]: " + uriWithContext + " --> "
+ (redirectPath == null ? errorCode : redirectPath), MODULE);
+ (redirectPath == null ? errorCode : redirectPath), MODULE);
}
}
}
@@ -45,6 +45,7 @@ import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import javax.transaction.Transaction;
import org.apache.http.HttpStatus;
import org.apache.ofbiz.base.component.ComponentConfig;
import org.apache.ofbiz.base.component.ComponentConfig.WebappInfo;
import org.apache.ofbiz.base.util.Debug;
@@ -362,6 +363,7 @@ public final class LoginWorker {
if (UtilValidate.isNotEmpty(formParams)) {
session.setAttribute("_PREVIOUS_PARAM_MAP_FORM_", formParams);
}
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
return "error";
}
}
@@ -629,7 +629,7 @@ public final class RequestHandler {
requestMap = ccfg.getRequestMapMap().get("ajaxCheckLogin");
}
}
} else {
} else if (requestUri != null) {
String[] loginUris = EntityUtilProperties.getPropertyValue("security", "login.uris", delegator).split(",");
boolean removePreviousRequest = true;
for (int i = 0; i < loginUris.length; i++) {
@@ -1,5 +1,5 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
@@ -47,11 +47,8 @@ import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceAuthException;
import org.apache.ofbiz.service.ServiceUtil;
import org.apache.ofbiz.service.ServiceValidationException;
import org.apache.ofbiz.webapp.control.ConfigXMLReader;
import org.apache.ofbiz.webapp.control.ConfigXMLReader.Event;
import org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap;
import org.apache.ofbiz.webapp.control.RequestHandler;
import org.apache.ofbiz.webapp.control.WebAppConfigurationException;
/**
* ServiceMultiEventHandler - Event handler for running a service multiple times; for bulk forms
@@ -63,6 +60,7 @@ public class ServiceMultiEventHandler implements EventHandler {
public static final String SYNC = "sync";
public static final String ASYNC = "async";
@SuppressWarnings("unused")
private ServletContext servletContext;
@Override
@@ -158,16 +156,7 @@ public class ServiceMultiEventHandler implements EventHandler {
List<Object> errorMessages = new LinkedList<>();
List<String> successMessages = new LinkedList<>();
// Check the global-transaction attribute of the event from the controller to see if the
// event should be wrapped in a transaction
String requestUri = RequestHandler.getRequestUri(request.getPathInfo());
ConfigXMLReader.ControllerConfig controllerConfig;
try {
controllerConfig = ConfigXMLReader.getControllerConfig(ConfigXMLReader.getControllerConfigURL(servletContext));
} catch (WebAppConfigurationException e) {
throw new EventHandlerException(e);
}
boolean eventGlobalTransaction = controllerConfig.getRequestMapMap().get(requestUri).getEvent().isGlobalTransaction();
boolean eventGlobalTransaction = event.isGlobalTransaction();
// big try/finally to make sure commit or rollback are run
boolean beganTrans = false;
@@ -150,8 +150,14 @@ public class VisitHandler {
visit.set("fromDate", new Timestamp(session.getCreationTime()));
visit.set("initialLocale", initialLocale);
visit.set("initialRequest", initialRequest);
visit.set("initialReferrer", initialReferrer);
if (initialRequest != null) {
visit.set("initialRequest", initialRequest.length() > 2000 ? initialRequest.substring(0, 1999)
: initialRequest);
}
if (initialReferrer != null) {
visit.set("initialReferrer", initialReferrer.length() > 2000 ? initialReferrer.substring(0, 1999)
: initialReferrer);
}
if (initialUserAgent != null) {
visit.set("initialUserAgent", initialUserAgent.length() > 250 ? initialUserAgent.substring(0, 250)
: initialUserAgent);
+13 -1
View File
@@ -1611,7 +1611,7 @@
<value xml:lang="vi">Tên Ủy quyền (delegator) Đích:</value>
<value xml:lang="zh">目标代表名称: </value>
<value xml:lang="zh-TW">目標代表名稱: </value>
</property>
</property>
<property key="WebtoolsDeleteFiles">
<value xml:lang="de">Dateien nachher löschen?</value>
<value xml:lang="en">Delete Files Afterwards?</value>
@@ -2125,6 +2125,10 @@
<value xml:lang="zh">错误:读取文件名 ${filename}:${errorString}</value>
<value xml:lang="zh-TW">錯誤:讀取檔案名 ${filename}:${errorString}</value>
</property>
<property key="WebtoolsErrorDatafileLoadUrlNotEnabled">
<value xml:lang="en">ERROR: For security reason HTTP URLs are not accepted, see OFBIZ-12304. Rather load your data from a file or set SystemProperty security.datafile.loadurls.enable = true</value>
<value xml:lang="de">FEHLER: Aus Sicherheitsgründen wird das Laden von HTTP Urls nicht erlaubt. Laden Sie die Daten über eine Datei oder setzen Sie die SystemProperty security.datafile.loadurls.enable = true.</value>
</property>
<property key="WebtoolsErrorReadingTemplateFile">
<value xml:lang="en">ERROR: reading template file ${filename}: ${errorString}</value>
<value xml:lang="fr">ERREUR : lors de la lecture du fichier modèle ${filename}, une exception c'est levée (${errorString})</value>
@@ -5977,6 +5981,14 @@
<value xml:lang="zh">本页面用于导入导出的实体引擎XML文档。这些文档都有一个根标签 "&lt;entity-engine-xml&gt;".</value>
<value xml:lang="zh-TW">本頁面用於匯入匯出的資料實體引擎XML檔.這些檔都有一個根標簽 "&lt;entity-engine-xml&gt;".&lt;/entity-engine-xml&gt;</value>
</property>
<property key="WebtoolsXMLImportInfoBewareTenant1">
<value xml:lang="en">Beware, you are using tenant, import acts as the "loadAll" Gradle task that says: "Load default data; meant for OFBiz development, testing, and demo purposes".</value>
<value xml:lang="fr">Attention, vous utilisez la fonctionnalité "tenant", l'import agit comme la tâche Gradle "loadAll" : "Charger les données par défaut ; destiné au développement, aux tests et à la démonstration OFBiz".</value>
</property>
<property key="WebtoolsXMLImportInfoBewareTenant2">
<value xml:lang="en">You should use the "loadTenant" Gradle task to load tenant specific data.</value>
<value xml:lang="fr">Vous devez utiliser la tâche Gradle "loadTenant" pour charger des données spécifiques à un tenant.</value>
</property>
<property key="WebtoolsYouMayCreateAnEntity">
<value xml:lang="de">You may create an Entity ${entityName} by entering the values you want, and clicking Create.</value>
<value xml:lang="en">You may create an Entity ${entityName} by entering the values you want, and clicking Create.</value>
@@ -16,19 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.ofbiz.entity.Delegator
import org.apache.ofbiz.entity.GenericValue
import org.apache.ofbiz.entity.condition.EntityCondition
import org.apache.ofbiz.entity.condition.EntityOperator
import org.apache.ofbiz.entity.model.ModelEntity
import org.apache.ofbiz.base.util.*
import org.w3c.dom.Document
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.apache.ofbiz.security.SecuredUpload
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.MultipleCompilationErrorsException
import org.codehaus.groovy.control.ErrorCollector
import org.codehaus.groovy.control.customizers.ImportCustomizer
String groovyProgram = null
recordValues = []
@@ -86,7 +78,9 @@ def shell = new GroovyShell(loader, binding, configuration)
if (groovyProgram) {
try {
if (!org.apache.ofbiz.security.SecuredUpload.isValidText(groovyProgram,["import"])) {
// Check if a webshell is not uploaded but allow "import"
if (!SecuredUpload.isValidText(groovyProgram, ["import"])) {
logError("================== Not executed for security reason ==================")
request.setAttribute("_ERROR_MESSAGE_", "Not executed for security reason")
return
}
@@ -17,18 +17,10 @@
* under the License.
*/
import java.util.ArrayList
import java.util.HashMap
import java.util.Iterator
import java.util.Map
import java.sql.Timestamp
import org.apache.ofbiz.base.util.UtilMisc
import org.apache.ofbiz.service.ServiceDispatcher
import org.apache.ofbiz.service.RunningService
import org.apache.ofbiz.service.engine.GenericEngine
import org.apache.ofbiz.base.util.UtilHttp
import org.apache.ofbiz.base.util.UtilProperties
import org.apache.ofbiz.service.ServiceDispatcher
import org.apache.ofbiz.service.engine.GenericEngine
uiLabelMap = UtilProperties.getResourceBundleMap("WebtoolsUiLabels", locale)
uiLabelMap.addBottomResourceBundle("CommonUiLabels")
@@ -37,7 +29,7 @@ log = ServiceDispatcher.getServiceLogMap()
serviceList = []
log.each { rs, value ->
service = [:]
service.serviceName = rs.getModelService().name
service.serviceName = rs.getModelService().getName()
service.localName = rs.getLocalName()
service.startTime = rs.getStartStamp()
service.endTime = rs.getEndStamp()
@@ -46,7 +38,7 @@ log.each { rs, value ->
serviceList.add(service)
}
sortField = parameters.sortField
if (sortField) {
if (sortField) {
context.services = UtilMisc.sortMaps(serviceList, UtilMisc.toList(sortField))
} else {
context.services = serviceList
@@ -84,6 +84,7 @@ import org.apache.ofbiz.entity.util.EntityDataLoader;
import org.apache.ofbiz.entity.util.EntityListIterator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntitySaxReader;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.apache.ofbiz.entityext.EntityGroupUtil;
import org.apache.ofbiz.security.Security;
import org.apache.ofbiz.service.DispatchContext;
@@ -108,6 +109,7 @@ public class WebToolsServices {
public static Map<String, Object> entityImport(DispatchContext dctx, Map<String, ? extends Object> context) {
GenericValue userLogin = (GenericValue) context.get("userLogin");
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
List<String> messages = new LinkedList<>();
@@ -145,10 +147,11 @@ public class WebToolsServices {
// #############################
// FM Template
// #############################
if (UtilValidate.urlInString(fulltext)) {
if (UtilValidate.urlInString(fulltext)
&& !"true".equals(EntityUtilProperties.getPropertyValue("security", "security.datafile.loadurls.enable", "false", delegator))) {
Debug.logError("For security reason HTTP URLs are not accepted, see OFBIZ-12304", MODULE);
Debug.logInfo("Rather load your data from a file", MODULE);
return null;
Debug.logInfo("Rather load your data from a file or set SystemProperty security.datafile.loadurls.enable = true", MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "WebtoolsErrorDatafileLoadUrlNotEnabled", locale));
}
if (UtilValidate.isNotEmpty(fmfilename) && (UtilValidate.isNotEmpty(fulltext) || url != null)) {
File fmFile = new File(fmfilename);
@@ -19,6 +19,11 @@ under the License.
<div class="page-title"><span>${uiLabelMap.WebtoolsImportToDataSource}</span></div>
<p>${uiLabelMap.WebtoolsXMLImportInfo}</p>
<#assign tenantUsed = Static["org.apache.ofbiz.entity.util.EntityUtilProperties"].getPropertyValue("general", "multitenant", "N", delegator)>
<#if tenantUsed=="Y">
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant1}</p>
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant2}</p>
</#if>
<hr />
<form class="basic-form" method="post" action="<@ofbizUrl>entityImport</@ofbizUrl>">
@@ -19,6 +19,11 @@ under the License.
<div class="page-title"><span>${uiLabelMap.WebtoolsImportToDataSource}</span></div>
<p>${uiLabelMap.WebtoolsXMLImportInfo}</p>
<#assign tenantUsed = Static["org.apache.ofbiz.entity.util.EntityUtilProperties"].getPropertyValue("general", "multitenant", "N", delegator)>
<#if tenantUsed=="Y">
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant1}</p>
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant2}</p>
</#if>
<hr />
<form class="basic-form" method="post" action="<@ofbizUrl>entityImportDir</@ofbizUrl>">
@@ -19,6 +19,11 @@ under the License.
<div class="page-title"><span>${uiLabelMap.WebtoolsImportToDataSource}</span></div>
<p>${uiLabelMap.WebtoolsXMLImportInfo}</p>
<#assign tenantUsed = Static["org.apache.ofbiz.entity.util.EntityUtilProperties"].getPropertyValue("general", "multitenant", "N", delegator)>
<#if tenantUsed=="Y">
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant1}</p>
<p>${uiLabelMap.WebtoolsXMLImportInfoBewareTenant2}</p>
</#if>
<hr />
<form class="basic-form" method="post" action="<@ofbizUrl>entityImportReaders</@ofbizUrl>">
<table class="basic-table" cellspacing="0">
+7 -7
View File
@@ -964,11 +964,6 @@ under the License.
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="placeholder" type="xs:string">
<xs:annotation>
<xs:documentation>Specifies a short hint that describes the expected value of an input field.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="display" substitutionGroup="AllFields">
@@ -1551,6 +1546,11 @@ under the License.
<xs:documentation>Area to be updated when a field event occurs.</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" ref="auto-parameters-service"/>
<xs:element minOccurs="0" ref="auto-parameters-entity"/>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="parameter" />
</xs:sequence>
<xs:attribute name="event-type" use="required">
<xs:simpleType>
<xs:restriction base="xs:token">
@@ -1559,8 +1559,8 @@ under the License.
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute type="xs:string" name="area-id" use="required" />
<xs:attribute type="xs:string" name="area-target" use="required" />
<xs:attribute type="xs:string" name="area-id" />
<xs:attribute type="xs:string" name="area-target" />
</xs:complexType>
</xs:element>
@@ -444,6 +444,32 @@ public final class CommonWidgetModels {
this.height = "";
}
// Empty link constructor
public Link() {
this.autoEntityParameters = null;
this.autoServiceParameters = null;
this.callback = null;
this.encode = false;
this.fullPath = false;
this.idExdr = FlexibleStringExpander.getInstance("");
this.image = null;
this.linkType = "";
this.nameExdr = FlexibleStringExpander.getInstance("");
this.parameterList = Collections.emptyList();
this.prefixExdr = FlexibleStringExpander.getInstance("");
this.secure = false;
this.styleExdr = FlexibleStringExpander.getInstance("");
this.targetExdr = FlexibleStringExpander.getInstance("");
this.targetWindowExdr = FlexibleStringExpander.getInstance("");
this.textExdr = FlexibleStringExpander.getInstance("");
this.urlMode = "intra-app";
this.size = null;
this.requestConfirmation = false;
this.confirmationMsgExdr = FlexibleStringExpander.getInstance("");
this.width = "";
this.height = "";
}
public AutoEntityParameters getAutoEntityParameters() {
return autoEntityParameters;
}
@@ -2476,7 +2476,7 @@ public abstract class ModelForm extends ModelWidget {
Map<String, String> claims = UtilMisc.toMap(
"areaId", WidgetWorker.getScreenStack(context).resolveScreenAreaId(getAreaId()),
"areaTarget", getAreaTarget());
"areaTarget", getAreaTarget(context));
// Propagate on the callback parameters use by pagination list
Map<String, Object> parameters = WidgetWorker.resolveParametersMapFromQueryString(context);
@@ -1568,6 +1568,30 @@ public final class ModelFormField {
public SubHyperlink getSubHyperlink() {
return this.subHyperlink;
}
/**
* Analyze if a sub hyperlink is associate to the display entity with an empty description
* @param context
* @return
*/
public boolean needConvertAsHyperlink(Map<String, Object> context) {
return getSubHyperlink() != null
&& getSubHyperlink().shouldUse(context)
&& getSubHyperlink().getDescription(context).isEmpty();
}
/**
* Convert the display entity as a Hyperlink for the rendering
* @param context
* @return
*/
public HyperlinkField asHyperlink(Map<String, Object> context) {
return new HyperlinkField(getModelFormField(),
getDescription(context),
getSubHyperlink().getLink(),
getAlsoHidden());
}
}
/**
@@ -2801,6 +2825,13 @@ public final class ModelFormField {
this.link = new Link(element);
}
public HyperlinkField(ModelFormField modelFormField, String description, Link link, boolean alsoHidden) {
super(FieldInfo.SOURCE_EXPLICIT, FieldInfo.HYPERLINK, modelFormField);
this.alsoHidden = alsoHidden;
this.description = FlexibleStringExpander.getInstance(description);
this.link = link;
}
private HyperlinkField(HyperlinkField original, ModelFormField modelFormField) {
super(original.getFieldSource(), original.getFieldType(), modelFormField);
this.alsoHidden = original.alsoHidden;
@@ -20,10 +20,12 @@ package org.apache.ofbiz.widget.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.UtilXml;
@@ -852,55 +854,68 @@ public class ModelFormFieldBuilder {
}
this.serviceName = modelService.getName();
this.attributeName = modelParam.getName();
if ("find".equals(defaultFieldType)) {
if (modelParam.getType().indexOf("Double") != -1 || modelParam.getType().indexOf("Float") != -1
|| modelParam.getType().indexOf("Long") != -1 || modelParam.getType().indexOf("Integer") != -1) {
ModelFormField.RangeFindField textField = new ModelFormField.RangeFindField(FieldInfo.SOURCE_AUTO_SERVICE, 6,
null);
this.setFieldInfo(textField);
} else if (modelParam.getType().indexOf("Timestamp") != -1) {
ModelFormField.DateFindField dateTimeField = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE,
"timestamp");
this.setFieldInfo(dateTimeField);
} else if (modelParam.getType().indexOf("Date") != -1) {
ModelFormField.DateFindField dateTimeField = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE,
"date");
this.setFieldInfo(dateTimeField);
} else if (modelParam.getType().indexOf("Time") != -1) {
ModelFormField.DateFindField dateTimeField = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE,
"time");
this.setFieldInfo(dateTimeField);
} else {
ModelFormField.TextFindField textField = new ModelFormField.TextFindField(FieldInfo.SOURCE_AUTO_SERVICE, null);
this.setFieldInfo(textField);
String modelParamFieldType = computeFieldTypeToUse(modelParam.getType());
FieldInfo fieldInfo = null;
switch (defaultFieldType) {
case "display":
fieldInfo = new ModelFormField.DisplayField(FieldInfo.SOURCE_AUTO_SERVICE, null);
break;
case "hidden":
fieldInfo = new ModelFormField.HiddenField(FieldInfo.SOURCE_AUTO_SERVICE, null);
break;
case "find":
if ("text".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.TextFindField(FieldInfo.SOURCE_AUTO_SERVICE, null);
} else if ("numeric".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.RangeFindField(FieldInfo.SOURCE_AUTO_SERVICE, 6, null);
} else if ("timestamp".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE, "timestamp");
} else if ("date".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE, "date");
} else if ("time".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateFindField(FieldInfo.SOURCE_AUTO_SERVICE, "time");
}
} else if ("display".equals(defaultFieldType)) {
ModelFormField.DisplayField displayField = new ModelFormField.DisplayField(FieldInfo.SOURCE_AUTO_SERVICE, null);
this.setFieldInfo(displayField);
} else {
// default to "edit"
if (modelParam.getType().indexOf("Double") != -1 || modelParam.getType().indexOf("Float") != -1
|| modelParam.getType().indexOf("Long") != -1 || modelParam.getType().indexOf("Integer") != -1) {
ModelFormField.TextField textField = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_SERVICE, 6, null, null);
this.setFieldInfo(textField);
} else if (modelParam.getType().indexOf("Timestamp") != -1) {
ModelFormField.DateTimeField dateTimeField = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE,
"timestamp");
this.setFieldInfo(dateTimeField);
} else if (modelParam.getType().indexOf("Date") != -1) {
ModelFormField.DateTimeField dateTimeField = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE,
"date");
this.setFieldInfo(dateTimeField);
} else if (modelParam.getType().indexOf("Time") != -1) {
ModelFormField.DateTimeField dateTimeField = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE,
"time");
this.setFieldInfo(dateTimeField);
} else {
ModelFormField.TextField textField = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_SERVICE, null);
this.setFieldInfo(textField);
break;
default: // default to "edit"
if ("text".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_SERVICE, null);
} else if ("numeric".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_SERVICE, 6, null, null);
} else if ("timestamp".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE, "timestamp");
} else if ("date".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE, "date");
} else if ("time".equals(modelParamFieldType)) {
fieldInfo = new ModelFormField.DateTimeField(FieldInfo.SOURCE_AUTO_SERVICE, "time");
}
}
return true;
this.setFieldInfo(fieldInfo);
return fieldInfo != null;
}
/**
* For a service model parameter type, return the logique field type to use
* If nothing found, return text
* @param modelParamType
* @return
*/
private String computeFieldTypeToUse(String modelParamType) {
final Map<String, String> switchType = UtilMisc.toMap("Double", "numeric",
"Float", "numeric",
"Long", "numeric",
"Integer", "numeric",
"BigDecimal", "numeric",
"Timestamp", "timestamp",
"Date", "date",
"Time", "time");
String typeToConvert = "";
if (modelParamType.contains(".")) {
LinkedList<String> splitString = new LinkedList<>(StringUtil.split(modelParamType, "."));
typeToConvert = splitString.getLast();
} else {
typeToConvert = modelParamType;
}
return switchType.containsKey(typeToConvert) ? switchType.get(typeToConvert) : "text";
}
private boolean induceFieldInfoFromServiceParam(String defaultFieldType, ModelReader entityModelReader,
@@ -170,8 +170,11 @@ public class ModelMenu extends ModelWidget {
defaultWidgetStyle = parent.defaultWidgetStyle;
defaultTooltipStyle = parent.defaultTooltipStyle;
defaultMenuItemName = parent.defaultMenuItemName;
menuItemList.addAll(parent.menuItemList);
menuItemMap.putAll(parent.menuItemMap);
for (ModelMenuItem originModelMenuItem: parent.menuItemList) {
ModelMenuItem modelMenuItem = new ModelMenuItem(originModelMenuItem, this, null);
menuItemList.add(modelMenuItem);
menuItemMap.put(modelMenuItem.getName(), modelMenuItem);
}
defaultPermissionOperation = parent.defaultPermissionOperation;
defaultPermissionEntityAction = parent.defaultPermissionEntityAction;
defaultAssociatedContentId = parent.defaultAssociatedContentId;
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -106,15 +107,9 @@ public class ModelMenuItem extends ModelWidget {
this.tooltipStyle = menuItemElement.getAttribute("tooltip-style");
this.selectedStyle = menuItemElement.getAttribute("selected-style");
String hideIfSelected = menuItemElement.getAttribute("hide-if-selected");
if (!hideIfSelected.isEmpty()) {
if ("true".equalsIgnoreCase(hideIfSelected)) {
this.hideIfSelected = Boolean.TRUE;
} else {
this.hideIfSelected = Boolean.FALSE;
}
} else {
this.hideIfSelected = null;
}
this.hideIfSelected = !hideIfSelected.isEmpty()
? "true".equalsIgnoreCase(hideIfSelected)
: null;
this.disableIfEmpty = menuItemElement.getAttribute("disable-if-empty");
this.align = menuItemElement.getAttribute("align");
this.alignStyle = menuItemElement.getAttribute("align-style");
@@ -171,6 +166,40 @@ public class ModelMenuItem extends ModelWidget {
this.overrideName = "";
}
public ModelMenuItem(ModelMenuItem originMenuItem, ModelMenu modelMenu, ModelMenuItem parentMenuItem) {
super(modelMenu.getName() + originMenuItem.getName());
this.modelMenu = modelMenu;
this.parentMenuItem = parentMenuItem;
this.entityName = originMenuItem.entityName;
this.title = originMenuItem.title;
this.tooltip = originMenuItem.tooltip;
this.parentPortalPageId = originMenuItem.parentPortalPageId;
this.titleStyle = originMenuItem.titleStyle;
this.disabledTitleStyle = originMenuItem.disabledTitleStyle;
this.widgetStyle = originMenuItem.widgetStyle;
this.tooltipStyle = originMenuItem.tooltipStyle;
this.selectedStyle = originMenuItem.selectedStyle;
this.hideIfSelected = originMenuItem.hideIfSelected;
this.disableIfEmpty = originMenuItem.disableIfEmpty;
this.align = originMenuItem.align;
this.alignStyle = originMenuItem.alignStyle;
this.position = originMenuItem.position;
this.associatedContentId = originMenuItem.associatedContentId;
this.cellWidth = originMenuItem.cellWidth;
this.subMenu = originMenuItem.subMenu;
this.link = new MenuLink(originMenuItem.link, this);
List<ModelMenuItem> menuItems = new LinkedList<>();
originMenuItem.menuItemList.forEach(item -> {
menuItems.add(new ModelMenuItem(item, modelMenu, this));
});
this.menuItemList = menuItems.isEmpty()
? Collections.emptyList()
: Collections.unmodifiableList(menuItems);
this.condition = originMenuItem.condition;
this.actions = originMenuItem.actions;
this.overrideName = originMenuItem.overrideName;
}
// Portal constructor
private ModelMenuItem(GenericValue portalPage, ModelMenuItem parentMenuItem, Locale locale) {
super(portalPage.getString("portalPageId"));
@@ -660,6 +689,13 @@ public class ModelMenuItem extends ModelWidget {
this.link = new Link(linkElement);
}
public MenuLink(MenuLink originLink, ModelMenuItem parentMenuItem) {
this.linkMenuItem = parentMenuItem;
this.link = originLink != null
? originLink.link
: new Link();
}
public MenuLink(GenericValue portalPage, ModelMenuItem parentMenuItem, Locale locale) {
this.linkMenuItem = parentMenuItem;
List<Parameter> parameterList = new ArrayList<>();
@@ -183,14 +183,21 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
@Override
public void renderDisplayField(Appendable writer, Map<String, Object> context, DisplayField displayField) {
writeFtlElement(writer,
renderableFtlFormElementsBuilder.displayField(context, displayField, this.javaScriptEnabled));
public void renderDisplayField(Appendable writer, Map<String, Object> context, DisplayField displayField)
throws IOException {
if (displayField instanceof DisplayEntityField
&& ((DisplayEntityField) displayField).needConvertAsHyperlink(context)) {
if (displayField instanceof DisplayEntityField) {
// When we have a subHyperlink on a display entity, display all as a hyperlink
renderHyperlinkField(writer, context, ((DisplayEntityField) displayField).asHyperlink(context));
} else {
writeFtlElement(writer,
renderableFtlFormElementsBuilder.makeHyperlinkString(((DisplayEntityField) displayField).getSubHyperlink(),
context));
renderableFtlFormElementsBuilder.displayField(context, displayField, this.javaScriptEnabled));
if (displayField instanceof DisplayEntityField) {
writeFtlElement(writer,
renderableFtlFormElementsBuilder.makeHyperlinkString(((DisplayEntityField) displayField).getSubHyperlink(),
context));
}
}
final ModelFormField modelFormField = displayField.getModelFormField();
@@ -198,7 +205,8 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
@Override
public void renderHyperlinkField(Appendable writer, Map<String, Object> context, HyperlinkField hyperlinkField) throws IOException {
public void renderHyperlinkField(Appendable writer, Map<String, Object> context, HyperlinkField hyperlinkField)
throws IOException {
this.request.setAttribute("image", hyperlinkField.getImageLocation(context));
ModelFormField modelFormField = hyperlinkField.getModelFormField();
String encodedAlternate = encode(hyperlinkField.getAlternate(context), modelFormField, context);
@@ -250,7 +258,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
}
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isEmpty(requiredStyle)) {
requiredStyle = "required";
@@ -322,6 +330,12 @@ public final class MacroFormRenderer implements FormStringRenderer {
this.appendTooltip(writer, context, modelFormField);
}
private boolean shouldApplyRequiredField(ModelFormField modelFormField) {
return ("single".equals(modelFormField.getModelForm().getType())
|| "upload".equals(modelFormField.getModelForm().getType()))
&& modelFormField.getRequiredField();
}
@Override
public void renderDateTimeField(Appendable writer, Map<String, Object> context, DateTimeField dateTimeField) throws IOException {
ModelFormField modelFormField = dateTimeField.getModelFormField();
@@ -486,7 +500,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
}
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isEmpty(requiredStyle)) {
requiredStyle = "required";
@@ -633,7 +647,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
}
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isEmpty(requiredStyle)) {
requiredStyle = "required";
@@ -1196,7 +1210,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
if (!sb.toString().isEmpty()) {
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isNotEmpty(requiredStyle)) {
style = requiredStyle;
@@ -2058,7 +2072,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
}
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isEmpty(requiredStyle)) {
requiredStyle = "required";
@@ -2559,7 +2573,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
}
//check for required field style on single forms
if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
if (shouldApplyRequiredField(modelFormField)) {
String requiredStyle = modelFormField.getRequiredFieldStyle();
if (UtilValidate.isEmpty(requiredStyle)) {
requiredStyle = "required";
@@ -2915,7 +2929,9 @@ public final class MacroFormRenderer implements FormStringRenderer {
writer.append(hiddenFormElement.outerHtml());
final Element anchorElement = WidgetWorker.makeHiddenFormLinkAnchorElement(linkStyle,
encodedDescription, confirmation, modelFormField, request, context);
writer.append(anchorElement.outerHtml());
if (anchorElement != null) {
writer.append(anchorElement.outerHtml());
}
}
} else {
if ("layered-modal".equals(realLinkType)) {
@@ -145,7 +145,7 @@ public class MacroFormRendererTest {
}
@Test
public void displayFieldRendersFieldWithTooltip(@Mocked ModelFormField.DisplayField displayField) {
public void displayFieldRendersFieldWithTooltip(@Mocked ModelFormField.DisplayField displayField) throws IOException {
new Expectations() {
{
renderableFtlFormElementsBuilder.displayField(withNotNull(), withNotNull(), anyBoolean);
@@ -163,7 +163,7 @@ public class MacroFormRendererTest {
@Test
public void displayEntityFieldRendersFieldWithLinkAndTooltip(
@Mocked ModelFormField.DisplayEntityField displayEntityField,
@Mocked ModelFormField.SubHyperlink subHyperlink) {
@Mocked ModelFormField.SubHyperlink subHyperlink) throws IOException {
new Expectations() {
{
renderableFtlFormElementsBuilder.displayField(withNotNull(), withNotNull(), anyBoolean);
+1 -1
View File
@@ -18,6 +18,6 @@
###############################################################################
org.gradle.console=plain
# If you experience heap memory problems during the Gradle build, for example
# If you experience heap memory problems during the Gradle build, for example
# building with integrated plugins, the following setting might help
#org.gradle.jvmargs=-Xms128m -Xmx1024m -XX:+CMSClassUnloadingEnabled
-1
View File
@@ -1 +0,0 @@
To put your patches, related with the build-dev ant target
-1
View File
@@ -31,7 +31,6 @@ under the License.
<!-- web applications -->
<webapp name="common-theme"
title="common theme"
menu-name="secondary"
server="default-server"
location="webapp/common"
mount-point="/common"
@@ -28,7 +28,7 @@ under the License.
<#macro renderTextareaField name className alert cols rows maxlength id readonly value visualEditorEnable buttons tabindex language="" disabled=""><@renderField value /></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled=""><@renderField value /></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled="" isXMLHttpRequest=""><@renderField value /></#macro>
<#macro renderDropDownField name className alert id multiple formName otherFieldName event action size firstInList currentValue explicitDescription allowEmpty options fieldName otherFieldName otherValue otherFieldSize dDFCurrent ajaxEnabled noCurrentSelectedKey ajaxOptions frequency minChars choices autoSelect partialSearch partialChars ignoreCase fullSearch conditionGroup tabindex disabled>
<#if currentValue?has_content && firstInList?has_content>
@@ -28,7 +28,7 @@ under the License.
<img src="${imageLocation}" alt=""><#lt/>
<#else>
<#if inPlaceEditorUrl?has_content || class?has_content || alert=="true" || title?has_content>
<span data-inplace-editor-url="${inPlaceEditorUrl}" data-inplace-editor-params="${inPlaceEditorParams}" <#if idName?has_content>id="cc_${idName}"</#if> <#if title?has_content>title="${title}"</#if> <@renderClass class alert />><#t/>
<span <#if inPlaceEditorUrl?has_content>data-inplace-editor-url="${inPlaceEditorUrl}" data-inplace-editor-params="${inPlaceEditorParams}"</#if> <#if idName?has_content>id="cc_${idName}"</#if> <#if title?has_content>title="${title}"</#if> <@renderClass class alert />><#t/>
</#if>
<#if description?has_content>
@@ -28,7 +28,7 @@ under the License.
<#macro renderTextareaField name className alert cols rows maxlength id readonly value visualEditorEnable buttons tabindex language="" disabled=""><@renderField value /></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled=""><@renderField value /></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled="" isXMLHttpRequest=""><@renderField value /></#macro>
<#macro renderDropDownField name className alert id multiple formName otherFieldName event action size firstInList currentValue explicitDescription allowEmpty options fieldName otherFieldName otherValue otherFieldSize dDFCurrent ajaxEnabled noCurrentSelectedKey ajaxOptions frequency minChars choices autoSelect partialSearch partialChars ignoreCase fullSearch conditionGroup tabindex disabled>
<#if currentValue?has_content && firstInList?has_content>
@@ -34,7 +34,7 @@ under the License.
<#macro renderTextareaField name className alert cols rows maxlength id readonly value visualEditorEnable buttons tabindex language="" disabled=""></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled="">
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled="" isXMLHttpRequest="">
<#if dateType=="time" ><@renderItemField value "tf" className/>
<#elseif dateType=="date"><@renderItemField value "dt" className/>
<#else><@renderItemField value "dtf" className/></#if>
@@ -44,7 +44,7 @@ under the License.
<#macro renderTextareaField name className alert cols rows maxlength id readonly value visualEditorEnable buttons tabindex language="" disabled=""><@renderField value/></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled=""><@renderField value/></#macro>
<#macro renderDateTimeField name className alert title value size maxlength id dateType shortDateInput timeDropdownParamName defaultDateTimeString localizedIconTitle timeDropdown timeHourName classString hour1 hour2 timeMinutesName minutes isTwelveHour ampmName amSelected pmSelected compositeType formName mask="" event="" action="" step="" timeValues="" tabindex="" disabled="" isXMLHttpRequest=""><@renderField value/></#macro>
<#macro renderDropDownField name className alert id multiple formName otherFieldName event action size firstInList currentValue explicitDescription allowEmpty options fieldName otherFieldName otherValue otherFieldSize dDFCurrent ajaxEnabled noCurrentSelectedKey ajaxOptions frequency minChars choices autoSelect partialSearch partialChars ignoreCase fullSearch conditionGroup tabindex disabled>
</#macro>
+3 -3
View File
@@ -32,9 +32,9 @@
}
},
"jquery-validation": {
"version": "1.19.3",
"resolved": "https://registry.npmjs.org/jquery-validation/-/jquery-validation-1.19.3.tgz",
"integrity": "sha512-iXxCS5W7STthSTMFX/NDZfWHBLbJ1behVK3eAgHXAV8/0vRa9M4tiqHvJMr39VGWHMGdlkhrtrkBuaL2UlE8yw=="
"version": "1.19.4",
"resolved": "https://registry.npmjs.org/jquery-validation/-/jquery-validation-1.19.4.tgz",
"integrity": "sha512-PcwKcATCR+JL77m9kkWd84NAHAunJP9iasF6IbMxUgl73xDAimxjt5oYFmYHDXBmTZM4rpkXxMNR/jGI5TlSjA=="
},
"jquery.browser": {
"version": "0.1.0",
@@ -4,13 +4,13 @@
"repository": "https://github.com/apache/ofbiz-framework.git",
"license": "Apache-2.0",
"dependencies": {
"dompurify": "^2.3.4",
"flot": "^4.2.2",
"jquery": "^3.6.0",
"jquery-migrate": "^3.3.2",
"jquery-validation": "^1.19.3",
"jquery.browser": "^0.1.0",
"dompurify": "^2.3.4",
"jquery-ui-dist": "^1.13.0",
"trumbowyg": "^2.25.1",
"flot": "^4.2.2"
"jquery-validation": "^1.19.4",
"jquery.browser": "^0.1.0",
"trumbowyg": "^2.25.1"
}
}
@@ -23,6 +23,9 @@ var LAST_AUTOCOMP_REF = null;
//default ajax request timeout in milliseconds
var AJAX_REQUEST_TIMEOUT = 5000;
// Search param : id of a link to be clicked right away
var SP_CLICK_ON = 'clickOn';
// Add observers on DOM ready.
$(document).ready(function() {
// add CSRF token to jQuery AJAX calls to the same domain
@@ -77,6 +80,14 @@ $(document).ready(function() {
jQuery(document).ajaxSuccess(function () {
initNamedBorders();
});
// if clickOn search parameter is present, click on a#SP_CLICK_ON
const currentUrl = new URL(window.location.href);
const openModal = currentUrl.searchParams.get(SP_CLICK_ON);
const modalLink = jQuery(`#${openModal}`);
if (openModal && modalLink.length) {
modalLink.first().click();
}
});
/* bindObservers function contains the code of adding observers and it can be called for specific section as well
@@ -205,6 +216,17 @@ function bindObservers(bind_element) {
success: function(data) {
dialogContainer.html(data);
bindObservers(dialogContainer);
},
error: (xhr) => {
// unauthorized user, reload page with the link id so we can reopen the modal
if (xhr.status === 401) {
const url = new URL(window.location.href);
url.searchParams.append(SP_CLICK_ON, element.attr('id'));
window.location.replace(url.toString());
} else {
// display some feedback in the modal body
dialogContainer.text(`An unexpected server error occurred (status : ${xhr.status}).`);
}
}
});
}
@@ -223,7 +245,7 @@ function bindObservers(bind_element) {
});
jQuery(bind_element).find("[data-lookup-presentation]").each(function(){
var element = jQuery(this);
var form = element.form();
var form = element._form();
var formName = form.attr("name");
if (!formName) {
console.log("Developer: For lookups to work you must provide a form name!");
@@ -651,7 +673,7 @@ function updateArea(areaId, data) {
*/
function ajaxUpdateAreas(areaCsvString) {
/*split all parameters separate by comma, the regExp manage areaId,target,param1=a&param2={b,c,d}&param3=e as three parameters*/
var regExpArea = /,(?=(?:[^{}]*{[^{}]*})*[^{}]*$)/g;
var regExpArea = /,(?=(?:[^{}]*{[^{}]*})*[^{}]*$)/g;
var areaArray = areaCsvString.split(regExpArea);
var numAreas = parseInt(areaArray.length / 3);
for (var i = 0; i < numAreas * 3; i = i + 3) {
@@ -1515,7 +1537,7 @@ function loadJWT() {
function sendJWT(targetUrl) {
var redirectUrl = targetUrl;
var jwtToken = loadJWT();
var jwtToken = loadJWT();
if (jwtToken != null && jwtToken != "") {
jQuery.ajax({
url: targetUrl,
+4 -4
View File
@@ -36,15 +36,15 @@ under the License.
<form method="post" action="<@ofbizUrl>login</@ofbizUrl>" name="loginform">
<label>
${uiLabelMap.CommonUsername}
<input type="text" name="USERNAME" value="${username}"/>
<input type="text" name="USERNAME" value="${username}" tabindex="0"/>
</label>
<label>
<span>
${uiLabelMap.CommonPassword}
<a href="<@ofbizUrl>forgotPassword</@ofbizUrl>">${uiLabelMap.CommonForgotYourPassword}</a>
</span>
<input type="password" name="PASSWORD" autocomplete="off" value=""/>
<input type="password" name="PASSWORD" autocomplete="off" value="" tabindex="0"/>
<a href="<@ofbizUrl>forgotPassword</@ofbizUrl>">${uiLabelMap.CommonForgotYourPassword}</a>
</label>
<#if ("Y" == useMultitenant) >
@@ -58,7 +58,7 @@ under the License.
</#if>
</#if>
<input type="submit" value="${uiLabelMap.CommonLogin}"/>
<input type="submit" value="${uiLabelMap.CommonLogin}" tabindex="0"/>
<input type="hidden" name="JavaScriptEnabled" value="N"/>
</form>
@@ -46,7 +46,7 @@ under the License.
<link rel="stylesheet/less" href="<@ofbizContentUrl>${StringUtil.wrapString(styleSheet)}</@ofbizContentUrl>" type="text/css"/>
</#list>
</#if>
<link rel="stylesheet/less" href="<@ofbizContentUrl>/helveticus/${visualTheme.visualThemeId?replace("_","-")?lower_case}.less</@ofbizContentUrl>" type="text/css"/>
<link rel="stylesheet/less" href="<@ofbizContentUrl>/helveticus/${visualTheme.visualThemeId}.less</@ofbizContentUrl>" type="text/css"/>
<#if layoutSettings.VT_HDR_JAVASCRIPT?has_content>
<#list layoutSettings.VT_HDR_JAVASCRIPT as javaScript>
<script src="<@ofbizContentUrl>${StringUtil.wrapString(javaScript)}</@ofbizContentUrl>" type="application/javascript"></script>

Some files were not shown because too many files have changed in this diff Show More