Passed
Push — master ( d9bccd...639079 )
by Nils
11:04
created

execInBackground()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Teampass - a collaborative passwords manager.
7
 * ---
8
 * This library is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 * ---
12
 *
13
 * @project   Teampass
14
 *
15
 * @file      users.background.php
16
 * ---
17
 *
18
 * @author    Nils Laumaillé ([email protected])
19
 *
20
 * @copyright 2009-2022 Teampass.net
21
 *
22
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
23
 * ---
24
 *
25
 * @see       https://www.teampass.net
26
 */
27
28
require_once 'SecureHandler.php';
29
session_name('teampass_session');
30
session_start();
31
if (! isset($_SESSION['CPM']) || $_SESSION['CPM'] === false || ! isset($_SESSION['key']) || empty($_SESSION['key'])) {
32
    die('Hacking attempt...');
33
}
34
35
// Load config
36
if (file_exists('../includes/config/tp.config.php')) {
37
    include_once '../includes/config/tp.config.php';
38
} elseif (file_exists('./includes/config/tp.config.php')) {
39
    include_once './includes/config/tp.config.php';
40
} else {
41
    throw new Exception("Error file '/includes/config/tp.config.php' not exists", 1);
42
}
43
44
// Do checks
45
require_once $SETTINGS['cpassman_dir'].'/includes/config/include.php';
46
require_once $SETTINGS['cpassman_dir'].'/sources/checks.php';
47
if (checkUser($_SESSION['user_id'], $_SESSION['key'], 'folders', $SETTINGS) === false) {
48
    // Not allowed page
49
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
50
    include $SETTINGS['cpassman_dir'].'/error.php';
51
    exit;
52
}
53
54
require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
55
require_once $SETTINGS['cpassman_dir'].'/includes/config/settings.php';
56
header('Content-type: text/html; charset=utf-8');
57
header('Cache-Control: no-cache, must-revalidate');
58
require_once 'main.functions.php';
59
// Connect to mysql server
60
require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
61
if (defined('DB_PASSWD_CLEAR') === false) {
62
    define('DB_PASSWD_CLEAR', defuseReturnDecrypted(DB_PASSWD, $SETTINGS));
63
}
64
DB::$host = DB_HOST;
65
DB::$user = DB_USER;
66
DB::$password = DB_PASSWD_CLEAR;
67
DB::$dbName = DB_NAME;
68
DB::$port = DB_PORT;
69
DB::$encoding = DB_ENCODING;
70
DB::$ssl = DB_SSL;
71
DB::$connect_options = DB_CONNECT_OPTIONS;
72
73
$post_key = filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING);
74
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
75
76
// Check KEY
77
if ($post_key !== $_SESSION['key']) {
78
    echo prepareExchangedData(
79
        $SETTINGS['cpassman_dir'],
80
        array(
81
            'error' => true,
82
            'message' => langHdl('key_is_not_correct'),
83
        ),
84
        'encode'
85
    );
86
} elseif ($_SESSION['user_read_only'] === true) {
87
    echo prepareExchangedData(
88
        $SETTINGS['cpassman_dir'],
89
        array(
90
            'error' => true,
91
            'message' => langHdl('error_not_allowed_to'),
92
        ),
93
        'encode'
94
    );
95
}
96
97
// decrypt and retrieve data in JSON format
98
$dataReceived = prepareExchangedData(
99
    $SETTINGS['cpassman_dir'],
100
    $post_data,
101
    'decode'
102
);
103
104
// Prepare variables
105
$type = filter_var($dataReceived['type'], FILTER_SANITIZE_STRING);
106
$user_id = filter_var($dataReceived['user_id'], FILTER_SANITIZE_NUMBER_INT);
107
$creator_id = filter_var($dataReceived['creator_id'], FILTER_SANITIZE_NUMBER_INT);
108
$creator_pwd = filter_var($dataReceived['creator_pwd'], FILTER_SANITIZE_STRING);
109
110
// Store process
111
DB::insert(
112
    prefixTable('processes'),
113
    array(
114
        'created_at' => time(),
115
        'owner_id' => (int) $creator_id,
116
        'process_type' => (string) $type,
117
        'arguments' => json_encode([
118
            'user_id' => $user_id ,
119
            'creator_pwd' => $creator_pwd,
120
        ]),
121
    )
122
);
123
124
// Now let the cron manage the action
125
/*
126
$queue_id = DB::insertId();
127
128
require_once $SETTINGS['cpassman_dir'].'/includes/libraries/BackgroundProcesser/BackgroundProcess.php';
129
$random = rand(5, 15);
130
$process = new Cocur\BackgroundProcess\BackgroundProcess('php -f '.$SETTINGS['cpassman_dir'].'/scripts/process_new_user.php '.$queue_id);
131
$process->run('/tmp/out_' . $random, true);
132
133
//echo sprintf('%s %s %s 2>&1 & echo $!', 'php '.$SETTINGS['cpassman_dir'].'/scripts/process_new_user.php '.$queue_id, '>', '/tmp/out_' . $random);
134
135
echo "PROCESS ID:".$process->getPid()."<br>";
136
137
DB::update(
138
    prefixTable('processes'),
139
    array(
140
        'process_id' => (int) $process->getPid(),
141
    ),
142
    'increment_id = %i',
143
    $queue_id
144
);
145
*/
146
147
148
149
150
// Class loader
151
/*require_once $SETTINGS['cpassman_dir'].'/includes/libraries/BackgroundProcesser/BackgroundProcess.php';
152
$proc = new BackgroundProcess('exec php '.$SETTINGS['cpassman_dir'].'/scripts/process_new_user.php '.$queue_id, true);
153
$pid = $proc->getProcessId();
154
*/
155
156
//require_once $SETTINGS['cpassman_dir'].'/includes/libraries/BackgroundProcesser/background_process.php';
157
158
159
160
161
162
function execInBackground($cmd) {
163
    if (substr(php_uname(), 0, 7) == "Windows"){
164
        pclose(popen("start /B ". $cmd, "r"));
165
    }
166
    else {
167
        exec($cmd . " > /dev/null &"); 
168
    }
169
}
170
171
function run_process($cmd, $outputFile = '/dev/null', $append = false){
172
    $pid=0;
173
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
174
        $cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
175
        $handle = popen("start /B ". $cmd, "r");
176
        $read = fread($handle, 200); //Read the output 
177
        $pid=substr($read,strpos($read,'=')+1);
178
        $pid=substr($pid,0,strpos($pid,';') );
179
        $pid = (int)$pid;
180
        pclose($handle); //Close
181
}else{
182
    $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
183
}
184
return $pid;
185
}
186
187
/*
188
$cmd='';
189
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
190
    $cmd=  $php_path.'\php.exe '.$path.'\long_process.php' ;	
191
}else{
192
    $cmd = 'php -f '.$SETTINGS['cpassman_dir'].'/scripts/process_new_user.php '.$queue_id;
193
}
194
$pid=run_process($cmd);
195
if(is_process_running($pid)){
196
    echo 'Process running';
197
    //stop_process($pid);
198
}else{
199
    echo 'Process not running';
200
}
201
*/
202
203
204
205
/*
206
$random = rand(5, 15);
207
$outPath = ' 1> /tmp/out_' . $random . ' 2> /tmp/error_out_' . $random;
208
exec('php '.$SETTINGS['cpassman_dir'].'/scripts/process_new_user.php '.$queue_id .' > /dev/null 2>&1 '.$outPath.' & echo $!', $process, $retval);
209
$pid = $process[0];
210
print_r($process);
211
echo "  ; ; ".$retval;
212
*/
213
214
215