3 * FusionForge form management
5 * Copyright 2005, GForge, LLC
6 * Copyright 2009, Roland Mas
7 * Copyright 2019, Franck Villaume - TrivialDev
9 * This file is part of FusionForge. FusionForge is free software;
10 * you can redistribute it and/or modify it under the terms of the
11 * GNU General Public License as published by the Free Software
12 * Foundation; either version 2 of the Licence, or (at your option)
15 * FusionForge is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * form_generate_key() - Returns a new key, and registers it in the db.
28 * @return int A new identifier.
31 function form_generate_key() {
34 // there's about 99.999999999% probability this loop will run only once :)
36 $key = md5(microtime().util_randbytes().$_SERVER['REMOTE_ADDR']);
37 $res = db_query_params('SELECT * FROM form_keys WHERE key=$1', array ($key));
38 if (!db_numrows($res)) {
42 $res = db_query_params('INSERT INTO form_keys (key, is_used, creation_date) VALUES ($1, 0, $2)', array($key, time()));
52 * form_key_is_valid() - Checks the db to see if the given key is already used. In case it's not already used
55 * @param int $key The key.
56 * @return bool True if the given key is already used. False if not.
59 function form_key_is_valid($key) {
60 // Fail if key is empty
65 $res = db_query_params ('SELECT * FROM form_keys WHERE key=$1 and is_used=0 AND creation_date > $2 FOR UPDATE',
68 if (!$res || !db_numrows($res)) {
72 $res = db_query_params ('UPDATE form_keys SET is_used=1 WHERE key=$1', array ($key));
82 * form_release_key() - Releases the given key if it is already used. If the given key it's not in the db, it returns false.
84 * @param int $key The key.
85 * @return bool True if the given key is successfully released. False if not.
88 function form_release_key($key) {
90 $res = db_query_params ('SELECT * FROM form_keys WHERE key=$1 FOR UPDATE', array ($key));
91 if (!$res || !db_numrows($res)) {
95 $res = db_query_params ('UPDATE form_keys SET is_used=0 WHERE key=$1', array ($key));
106 // c-file-style: "bsd"