Skip to content

Commit

Permalink
RemoveTags, Increment, Decrement Upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredrick Peter committed May 8, 2023
1 parent 4dc17dc commit bc67744
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 55 deletions.
56 changes: 18 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ Having been introduced to learning Laravel Framework; Over the past yr(s), Comin
was pretty tough. So i decided to create a much more easier way of communicating with Database, using native `PHP PDO:: Driver`.



* [Requirements](#requirements)
* [Installation](#installation)
* [Instantiate](#instantiate)
Expand Down Expand Up @@ -104,7 +103,7 @@ Prior to installing `php-orm-database` get the [Composer](https://getcomposer.or
**Step 1** — update your `composer.json`:
```composer.json
"require": {
"peterson/php-orm-database": "^3.1.4"
"peterson/php-orm-database": "^3.1.5"
}
```

Expand Down Expand Up @@ -183,8 +182,6 @@ $db->table('users')
</details>

## More Database Connection Keys
<details><summary>Read more...</summary>

- All available connection keys
- The DRIVER_NAME uses only `mysql`
- No other connection type is supported for now.
Expand All @@ -201,7 +198,6 @@ $db->table('users')
| DB_PORT | int | `3306` |
| DB_CHARSET | string | `utf8mb4_unicode_ci` |
| DB_COLLATION | string | `utf8mb4` |
</details>

## Usage
- All Methods of usage
Expand Down Expand Up @@ -279,7 +275,6 @@ $db->table('users')
```

### Increment
<details><summary>Read more...</summary>

- Takes three parameter
- Only the first param is required
Expand All @@ -301,25 +296,20 @@ $db->table('users')
$db->table('users')
->where('user_id', 10000001)
->increment('wallet_bal', 10);
-- Query
UPDATE `users`
SET wallet_bal=wallet_bal+:10
WHERE user_id=:user_id
```

- You can also pass in a second or third parameter to update additional columns
```
$db->table('users')
->where('user_id', 10000001)
->increment('wallet_bal', 10, [
->increment('wallet_bal', 100.23, [
'first_name' => 'F. Peterson',
'status' => 1,
]);
-- Query
UPDATE `users`
SET wallet_bal=wallet_bal+:10, first_name=:first_name, status=:status
SET wallet_bal=wallet_bal + :wallet_bal, first_name=:first_name, status=:status
WHERE user_id=:user_id
```

Expand All @@ -332,7 +322,6 @@ $db->table('users')
'status' => 1,
]);
```
</details>

### Decrement
- Same as Increment
Expand Down Expand Up @@ -368,26 +357,23 @@ SELECT count(*) FROM users WHERE status=:status
</details>

### Remove Tags
<details><summary>Read more...</summary>

- Helps against `XSS attacks`
- By default we remove-prevention of `XSS attacks` as this should already been handled by Forms Validation before sending into the Database
-> Applies to `insert` `update` `increment` `decrement` methods.
- Takes one param as `bool` Default is `false`
- Helps against `XSS attacks`
- By default we did not handle `XSS attacks`. As we assume this should be done by `Forms Validation` before sending to Database
-> Applies to `insert` `update` `increment` `decrement` methods.

- 1 usage
```
$db->table('post')
->removeTags()
->removeTags(true)
->insert([
'description' => '<script> alert(2); console.log('Blossom');</script>',
'description' => "<script> alert(2); console.log('Blossom');</script>",
'user_id' =>
])
-- Query
The value should be 'empty' if found as an attack
Now the method automatically apply strict method of cleaning each values
- If param set to true, then this will allow all possible tags
- If false, it will allow few supported HTML5 tags
```
</details>

## Fetching Data

Expand Down Expand Up @@ -454,8 +440,6 @@ SELECT * FROM `users`
```

### Exists
<details><summary>Read more...</summary>

```
$db->table('users')
->where('email', '[email protected]')
Expand All @@ -465,7 +449,6 @@ $db->table('users')
-- Query
SELECT EXISTS(SELECT 1 FROM `users` WHERE email=:email OR name=:name) as `exists`
```
</details>

### Table Exist
- Takes param as `string` `$table_name`
Expand All @@ -476,11 +459,11 @@ $db->tableExist('users');
## Collections
- You can directly use `methods` of `Collections Instance` on any of the below
- All the below `methods` are received by Collection `class`
1. get()
2. first()
3. firstOrFail()
4. insert()
5. insertOrIgnore()
1. get()
2. first()
3. firstOrFail()
4. insert()
5. insertOrIgnore()



Expand Down Expand Up @@ -660,7 +643,6 @@ $users->showing([
- Multiple clause

### Raw
<details><summary>Read more...</summary>
- Allows you to use direct raw `SQL query syntax`

```
Expand All @@ -670,7 +652,7 @@ $date = strtotime('next week');
$db->table("tb_wallet")
->raw("date >= $date")
->raw("NOW() > created_at")
->raw("YEAR(created_at) = '2022'")
->raw("YEAR(created_at) = 2022")
->where('email', '[email protected]')
->limit(10)
->random()
Expand All @@ -681,12 +663,10 @@ $db->table("tb_wallet")
SELECT * FROM `tb_wallet`
WHERE date >= 1681178855
AND NOW() > created_at
AND YEAR(created_at) = '2022'
AND YEAR(created_at) = 2022
AND email=:email
ORDER BY RAND() LIMIT 10
```
</details>


### Select
- Used to select needed columns from database
Expand Down
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"php": ">=7.2",
"vlucas/phpdotenv": "^5.3",
"yidas/pagination": "^1.0",
"symfony/var-dumper": "^6.2.8"
"symfony/var-dumper": "^6.2.8",
"ezyang/htmlpurifier": "^4.16.0"
},
"autoload": {
"files": [
Expand All @@ -37,7 +38,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "3.1.4-dev"
"dev-main": "3.1.5-dev"
}
},
"minimum-stability": "stable",
Expand Down
2 changes: 1 addition & 1 deletion src/Capsule/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ static public function saveTempIncrementQuery($data = [], $type = true)
$sign = '-'; //decrement
}

$tempIncrementQuery = "{$data['column']}={$data['column']}{$sign}:{$data['count']}";
$tempIncrementQuery = "{$data['column']}={$data['column']} {$sign} :{$data['column']}";
if(count($data['param']) > self::COUNT){
$tempIncrementQuery .= ",";
}
Expand Down
31 changes: 21 additions & 10 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

namespace builder\Database\Query;

use Config;
use Exception;
use HTMLPurifier;

class Builder extends MySqlExec{

/**
Expand Down Expand Up @@ -661,18 +665,25 @@ public function whitelistInput(mixed $input)
}

// Convert input to string
$filteredInput = (string) $input;

// Remove any script or style tags and their contents
$filteredInput = preg_replace('/<(script|style)[^>]*?>.*?<\/\\1>/si', '', $filteredInput);

// Allow only letters, digits, spaces, and common punctuation marks
$filteredInput = preg_replace('/[^\w\s.,!?():;\'"`-]/u', '', $filteredInput);
$html = (string) $input;

$allowedTags = null;
if ($this->allowAllTags) {
// Allow all HTML tags except those seen as attacks
$allowedTags = null;
} else {
// Allow only basic tags
$allowedTags = '<a><abbr><address><area><article><aside><audio><b><base><bdi><bdo><blockquote><body><br><button><canvas><caption><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><div><dl><dt><em><embed><fieldset><figcaption><figure><footer><form><h1><h2><h3><h4><h5><h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><u><ul><var><video><wbr>';
}

// Remove any extra whitespace
$filteredInput = trim(preg_replace('/\s+/u', ' ', $filteredInput));
// Use HTMLPurifier to remove any other potential XSS attacks
$config = \HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', $allowedTags);

return $filteredInput;
// purify html
$purifier = new HTMLPurifier($config);
$cleanHtml = $purifier->purify($html);
return $cleanHtml;
}

return $input;
Expand Down
13 changes: 10 additions & 3 deletions src/Query/MySqlExec.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,13 +367,19 @@ protected function allowCount()

/**
* Remove Tags Found as an XSS-Attack
* @param bool $tag\Default true
* - If set to true, then this will allow all possible tags
* - If false, it will allow few supported HTML5 tags
* Apart from tags seen as an attack
*
* @return object\builder\Database\removeTags
*/
public function removeTags()
public function removeTags(?bool $tag = true)
{
$this->removeTags = true;

if(!$tag){
$this->allowAllTags = false;
}
return $this;
}

Expand Down Expand Up @@ -567,6 +573,7 @@ protected function closeQuery()
$this->countQuery = false;
$this->modelQuery = false;
$this->removeTags = false;
$this->allowAllTags = true;
$this->runtime = 0.00;
$this->timer = [
'start' => 0.00,
Expand All @@ -575,7 +582,7 @@ protected function closeQuery()
];
}

/**
/**
* Get last insert ID
* @param bool $type true or false
* If true then it return an OBJECT data
Expand Down
5 changes: 5 additions & 0 deletions src/Query/MySqlProperties.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ trait MySqlProperties{
*/
protected $removeTags = false;

/**
* @var bool
*/
protected $allowAllTags = true;

/**
* @var array
*/
Expand Down
2 changes: 1 addition & 1 deletion src/Traits/InsertionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ protected function incrementInsertionQuery(?array $temp = [])
$this->query($this->query);

// bind increment data
$this->bind(":{$temp['count']}", $temp['count']);
$this->bind(":{$temp['column']}", $temp['count']);

// bind query for param
foreach($temp['param'] as $key => $value){
Expand Down

0 comments on commit bc67744

Please sign in to comment.