Passed
Push — master ( c5717d...c49ce8 )
by Nils
10:07
created

handleTask2()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 26
rs 9.9
1
<?php
2
/**
3
 * Teampass - a collaborative passwords manager.
4
 * ---
5
 * This file is part of the TeamPass project.
6
 * 
7
 * TeamPass is free software: you can redistribute it and/or modify it
8
 * under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation, version 3 of the License.
10
 * 
11
 * TeamPass is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 * 
19
 * Certain components of this file may be under different licenses. For
20
 * details, see the `licenses` directory or individual file headers.
21
 * ---
22
 * @file      background_tasks___items_handler.php
23
 * @author    Nils Laumaillé ([email protected])
24
 * @copyright 2009-2024 Teampass.net
25
 * @license   GPL-3.0
26
 * @see       https://www.teampass.net
27
 */
28
29
use TeampassClasses\NestedTree\NestedTree;
30
use TeampassClasses\SessionManager\SessionManager;
31
use Symfony\Component\HttpFoundation\Request;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Request. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
32
use Symfony\Component\Process\Process;
33
use TeampassClasses\Language\Language;
34
35
// Load functions
36
require_once __DIR__.'/../sources/main.functions.php';
37
38
// init
39
loadClasses('DB');
40
$session = SessionManager::getSession();
41
$request = Request::createFromGlobals();
42
$lang = new Language();
43
44
// Load config if $SETTINGS not defined
45
try {
46
    include_once __DIR__.'/../includes/config/tp.config.php';
47
} catch (Exception $e) {
48
    throw new Exception("Error file '/includes/config/tp.config.php' not exists", 1);
49
}
50
51
// Define Timezone
52
date_default_timezone_set(isset($SETTINGS['timezone']) === true ? $SETTINGS['timezone'] : 'UTC');
53
54
// Set header properties
55
header('Content-type: text/html; charset=utf-8');
56
header('Cache-Control: no-cache, no-store, must-revalidate');
57
error_reporting(E_ERROR);
58
// increase the maximum amount of time a script is allowed to run
59
set_time_limit($SETTINGS['task_maximum_run_time']);
60
61
// --------------------------------- //
62
63
require_once __DIR__.'/background_tasks___functions.php';
64
65
$tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
66
67
// Get PHP binary
68
$phpBinaryPath = getPHPBinary();
69
70
$processToPerform = DB::queryfirstrow(
71
    'SELECT *
72
    FROM ' . prefixTable('background_tasks') . '
73
    WHERE is_in_progress = %i AND process_type IN ("item_copy", "new_item", "update_item", "item_update_create_keys")
74
    ORDER BY increment_id ASC',
75
    1
76
);
77
78
// Vérifie s'il y a une tâche à exécuter
79
if (DB::count() > 0) {
80
    // Exécute ou continue la tâche
81
    handleTask2($processToPerform['increment_id']);
82
}
83
84
function handleTask2($task) {
85
    // Récupérer les sous-tâches de la tâche
86
    $subTasks = getSubTasks($task['increment_id']);
87
88
    foreach ($subTasks as $subTask) {
89
        // Continue tant que la sous-tâche n'est pas terminée
90
        while ($subTask['finished_at'] === null) {
91
            // Paramètres de la sous-tâche
92
            $taskParams = json_decode($subTask['task'], true);
93
            
94
            // Lance la sous-tâche avec les paramètres actuels
95
            $process = new Process(['php', __DIR__.'background_tasks___items_handler_subtask.php', $subTask['increment_id']]);
96
            $process->start();
97
            $process->wait();
98
99
            // Mise à jour pour la prochaine itération
100
            $taskParams['index'] += $taskParams['nb'];
101
            updateSubTask($subTask['id'], $taskParams);
0 ignored issues
show
Bug introduced by
The function updateSubTask was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

101
            /** @scrutinizer ignore-call */ 
102
            updateSubTask($subTask['id'], $taskParams);
Loading history...
102
103
            // Recharger les informations de la sous-tâche pour vérifier si elle est terminée
104
            $subTask = reloadSubTask($subTask['id']);
0 ignored issues
show
Bug introduced by
The function reloadSubTask was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

104
            $subTask = /** @scrutinizer ignore-call */ reloadSubTask($subTask['id']);
Loading history...
105
        }
106
    }
107
108
    // Marquer la tâche principale comme terminée
109
    markTaskAsFinished($task['increment_id']);
110
}
111
112
/**
113
 * Fonction pour obtenir les sous-tâches d'une tâche
114
 */
115
function getSubTasks($taskId) {
116
    $task_to_perform = DB::query(
117
        'SELECT *
118
        FROM ' . prefixTable('processes_tasks') . '
119
        WHERE process_id = %i AND finished_at IS NULL
120
        ORDER BY increment_id ASC',
121
        $taskId
122
    );
123
    return $task_to_perform;
124
}
125
126
/**
127
 * Fonction pour marquer une sous-tâche comme terminée
128
 */
129
function markSubTaskAsFinished($subTaskId) {
0 ignored issues
show
Unused Code introduced by
The parameter $subTaskId is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

129
function markSubTaskAsFinished(/** @scrutinizer ignore-unused */ $subTaskId) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
130
    // ... Code pour mettre à jour l'état de la sous-tâche dans la base de données ...
131
}
132
133
/**
134
 * Fonction pour marquer une tâche comme terminée
135
 */
136
function markTaskAsFinished($taskId) {
0 ignored issues
show
Unused Code introduced by
The parameter $taskId is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

136
function markTaskAsFinished(/** @scrutinizer ignore-unused */ $taskId) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
137
    // ... Code pour mettre à jour l'état de la tâche dans la base de données ...
138
}