Skip to content

Commit

Permalink
Added further documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Jérémie Fréreault committed Nov 8, 2024
1 parent 64b3053 commit a020abe
Show file tree
Hide file tree
Showing 12 changed files with 835 additions and 9 deletions.
88 changes: 88 additions & 0 deletions common/dataphyre/modules/caspow/documentation/Dataphyre_CASPOW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
### CASPOW Module

The **CASPOW** (Cryptographic Anti-Spam Proof of Work) module in Dataphyre generates and verifies cryptographic challenges to reduce spam and ensure message integrity. It implements a proof-of-work mechanism using hash-based challenges, where clients must solve a hash challenge before their payloads are accepted, which can help mitigate automated spamming.

---

#### Purpose and Use Cases

The CASPOW module is designed to:
- **Mitigate spam** by requiring clients to perform computational work before submitting requests.
- **Verify the integrity** of payloads to prevent tampering.
- **Optimize workload** based on the client device, with lighter challenges for mobile users.

---

#### Key Components

##### Configuration Properties

- **`$algorithm`**: Specifies the hashing algorithm used for challenges. Supported algorithms include:
- `SHA-256`
- `SHA-384`
- `SHA-512`

- **`$range_min`**: The minimum number range for generating the challenge number, influencing the difficulty level.
- **`$range_max`**: The maximum number range for generating the challenge number.

---

#### Methods

##### `create_challenge(?string $salt=null, ?int $number=null)`

- **Parameters**:
- **`$salt`** (optional): A random or user-provided string used to create a unique challenge.
- **`$number`** (optional): A specific integer to be used in the challenge. If not provided, a random number is chosen based on device type.

- **Functionality**:
- Generates a cryptographic challenge by hashing the salt and number with the specified algorithm.
- If `$salt` is not provided, a random 12-byte salt is generated.
- If `$number` is not provided, the range for random number generation is adjusted for mobile devices (one-fifth of the usual range for mobile).
- Calculates a `signature` for the challenge using HMAC, ensuring authenticity.

- **Returns**:
- An associative array with the following fields:
- **`algorithm`**: The hashing algorithm used (e.g., `SHA-256`).
- **`challenge`**: The generated hash-based challenge string.
- **`salt`**: The salt value used to generate the challenge.
- **`signature`**: The HMAC signature of the challenge, providing integrity verification.

- **Example Usage**:
```php
$challenge = caspow::create_challenge();
```

##### `verify_payload(mixed $payload): bool`

- **Parameters**:
- **`$payload`**: The payload to verify, typically a base64-encoded JSON string containing the salt, number, algorithm, challenge, and signature.

- **Functionality**:
- Decodes and parses the payload.
- Recreates the challenge using the salt and number from the payload.
- Verifies the integrity and correctness of the payload by checking that the algorithm, challenge, and signature match the recreated challenge.

- **Returns**:
- **`true`** if the payload is verified successfully.
- **`false`** if verification fails, indicating possible tampering or incorrect challenge response.

- **Example Usage**:
```php
$is_valid = caspow::verify_payload($received_payload);
```

---

#### Example Workflow

1. **Challenge Creation**: A server generates a challenge for a client using `create_challenge()`, which provides a salt, challenge, and signature.
2. **Challenge Solution**: The client attempts to solve the challenge by guessing the correct number that hashes to the challenge result.
3. **Payload Submission**: Once solved, the client submits a payload containing the salt, number, algorithm, challenge, and signature.
4. **Verification**: The server verifies the payload using `verify_payload()` to ensure it matches the original challenge and hasn't been tampered with.

---

#### Summary

The **CASPOW** module provides an efficient mechanism for enforcing computational work as an anti-spam measure in Dataphyre-based applications, adding a layer of security against automated requests.
4 changes: 0 additions & 4 deletions common/dataphyre/modules/currency/currency.main.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
* This software is provided "as is", without any warranty of any kind.
*/


namespace dataphyre;

use simplexml;
Expand All @@ -28,9 +27,6 @@
if(file_exists($filepath=$rootpath['dataphyre']."config/currency.php")){
require_once($filepath);
}
if(!isset($configurations['dataphyre']['currency'])){
//core::unavailable("MOD_CURRENCY_NO_CONFIG", "safemode");
}

currency::get_exchange_rates();

Expand Down
114 changes: 114 additions & 0 deletions common/dataphyre/modules/currency/documentation/Dataphyre_Currency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
### Currency Module

The Currency module in Dataphyre is designed to handle currency conversion and formatting within applications, making it easier to display prices and amounts in different currencies, regions, and languages. This module interacts with exchange rate sources and caches exchange rates for efficient access, ensuring users see accurate, real-time prices in their local currency.

#### Key Properties

- **`$base_currency`**: The primary currency used by the application, defaulted to `USD`.
- **`$display_currency`**: The currency currently displayed to the user, defaulted to `USD`.
- **`$display_language`**: The language in which currency values are displayed, e.g., `en-CA` for English (Canada).
- **`$display_country`**: The country code used for display purposes, defaulted to `CA`.
- **`$available_currencies`**: An array of available currencies with their symbols, e.g., `["USD" => "$"]`.
- **`$special_formatting`**: Defines currency formatting options by region, including decimal and thousand separators and decimal precision. This property allows custom currency formatting based on regional conventions.

#### Public Methods

1. **`get_exchange_rates()`**

Loads the latest exchange rates into the session. If cached rates are unavailable, invalid, or expired, this method retrieves rates from an external source specified in the configuration.

- **Returns**: The exchange rate data stored in the session.
- **Example Usage**:
```php
$rates = currency::get_exchange_rates();
```

2. **`get_rates_data(string $source)`**

Fetches exchange rates from a specified source. Currently supported sources include `exchangerate.host` and `europa.eu`. Each source requires different processing for parsing and storing the exchange rates.

- **Parameters**:
- `$source`: The exchange rate source to use (e.g., `exchangerate.host` or `europa.eu`).
- **Returns**: `true` if rates were successfully retrieved and cached, `false` otherwise.
- **Example Usage**:
```php
$success = currency::get_rates_data('exchangerate.host');
```

3. **`formatter(float|null $amount, bool|null $show_free = false, string|null $currency = null): string`**

Formats a given amount into the specified or default currency format. Regional formatting rules are applied based on the `display_language` and `display_country` properties.

- **Parameters**:
- `$amount`: The amount to format.
- `$show_free`: If `true`, returns "Free" for a zero amount.
- `$currency`: The currency code to format the amount in. Defaults to the `display_currency`.
- **Returns**: A string representing the formatted currency amount.
- **Example Usage**:
```php
echo currency::formatter(100, true, 'USD');
```

4. **`convert(float|null $amount, string $source_currency, string $target_currency, bool|null $formatted = false, bool|null $show_free = true): string|float`**

Converts an amount from one currency to another using cached exchange rates.

- **Parameters**:
- `$amount`: The amount to convert.
- `$source_currency`: The currency code of the source currency.
- `$target_currency`: The currency code of the target currency.
- `$formatted`: If `true`, formats the result using `formatter`.
- `$show_free`: If `true`, shows "Free" for zero amounts.
- **Returns**: The converted amount, either formatted as a string or as a float.
- **Example Usage**:
```php
$convertedAmount = currency::convert(100, 'USD', 'EUR', true);
```

5. **`convert_to_user_currency(float|null $amount, bool|null $formatted = false, bool|null $show_free = true, string|null $currency = null): string|float`**

Converts an amount from the base currency to the user’s display currency, applying regional formatting if specified.

- **Parameters**:
- `$amount`: The amount to convert.
- `$formatted`: If `true`, formats the result using `formatter`.
- `$show_free`: If `true`, shows "Free" for zero amounts.
- `$currency`: The target currency code. Defaults to the user’s `display_currency`.
- **Returns**: The converted amount in the user’s currency, either formatted or as a float.
- **Example Usage**:
```php
$userCurrencyAmount = currency::convert_to_user_currency(100);
```

6. **`convert_to_website_currency(float|null $amount, string $original_currency, bool|null $formatted = false, bool|null $show_free = true): string|float`**

Converts an amount from a specified currency to the base currency used on the website.

- **Parameters**:
- `$amount`: The amount to convert.
- `$original_currency`: The source currency code.
- `$formatted`: If `true`, formats the result using `formatter`.
- `$show_free`: If `true`, shows "Free" for zero amounts.
- **Returns**: The converted amount in the base currency, either formatted or as a float.
- **Example Usage**:
```php
$websiteCurrencyAmount = currency::convert_to_website_currency(100, 'EUR');
```

---

### Workflow

1. **Initialization**: The class is instantiated with default currency, language, and country settings. The framework sets up base currency properties according to configuration.

2. **Exchange Rate Fetching**:
- **Cached rates**: Cached rates are used if available and within the time limit (60 minutes).
- **External rates**: If cached rates are unavailable or expired, the module fetches data from configured external sources, such as `exchangerate.host` or `europa.eu`.

3. **Conversion and Formatting**:
- **Conversion**: Converts amounts between currencies using the cached exchange rates.
- **Formatting**: Formats the converted amounts according to regional display settings.

---

This Currency module provides flexible support for multiple currencies and regions, allowing Dataphyre applications to handle complex currency requirements seamlessly.
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
### Date Translation Module

The **Date Translation** module in Dataphyre enables localization of date strings based on the specified language and format. This module translates date components (like month names, day names, and ordinal suffixes) into the target language while preserving the intended date format.

#### Key Functionalities

1. **Language-Specific Date Translation**: Transforms date strings from English to the target language (e.g., French) based on language-specific configurations.
2. **Configurable Format Support**: Maintains the specified date format structure even after translation.
3. **Handling of Ordinal Suffixes**: Adjusts ordinal suffixes based on language rules (e.g., "1st" to "1er" in French).
4. **Localized Caching**: Loads and caches language configurations to ensure efficient translation operations.

---

#### Core Properties and Methods

1. **`$date_locales` (Private Static Property)**
- **Description**: Stores the cached date translation configurations for each language to avoid reloading during multiple translation requests.
- **Type**: `array`

2. **`translate_date(string $string, string $lang, string $format) : string|null`**
- **Purpose**: Translates a date string into the specified language and formats it according to the provided structure.
- **Parameters**:
- `$string`: The date string to translate (e.g., "January 1st").
- `$lang`: The target language code (e.g., "fr" for French).
- `$format`: The desired date format to maintain during translation (e.g., "d M Y").
- **Returns**: Translated date string or `null` if translation is not possible.

**Translation Process**:
- **Step 1**: Check if the target language is English. If so, return the input date string as no translation is required.
- **Step 2**: Break the date string into individual components (e.g., "January 1st" becomes `["January", "1st"]`).
- **Step 3**: Load the language-specific configuration file for the target language if it hasn't been loaded yet.
- **Step 4**: Translate each component of the date string using the loaded configuration:
- **Month Translation**: Converts full and abbreviated month names.
- **Weekday Translation**: Translates weekdays based on the target language.
- **Ordinal Suffix Handling**: Adjusts ordinal suffixes for days, such as "1st" to "1er" for French or removing them as needed.
- **Step 5**: Reassemble the components to form the translated date string, modifying the format if required for certain languages (e.g., reversing day and month in French).
- **Step 6**: Return the translated and formatted date string.

---

#### Example Usage

1. **Translate a Date to French**:
```php
$translated_date = date_translation::translate_date("January 1st", "fr", "d M Y");
// Output: "le 1 janvier"
```

2. **Translate with Format Reversal**:
```php
$translated_date = date_translation::translate_date("March 15th", "fr", "F jS");
// Output: "15 mars"
```

3. **Translate a Weekday with Ordinal Handling**:
```php
$translated_date = date_translation::translate_date("Monday, January 2nd", "fr", "l, F jS");
// Output: "lundi, 2 janvier"
```

---

#### Workflow and Usage

1. **Localization Configuration**: The module references pre-configured language files (PHP or JSON format) containing translations for months, weekdays, and ordinal suffix rules.
2. **Date Transformation**: Applies transformations on the date string based on the specified language and target format, preserving the intended structure.
3. **Caching for Efficiency**: Caches language configurations upon the first load to optimize performance for repeated translation requests.

---

The **Date Translation** module is essential for Dataphyre's support for internationalization, allowing dates to be displayed naturally across different languages and formats while adhering to language-specific conventions.
Loading

0 comments on commit a020abe

Please sign in to comment.