+
+define('DB_ORD_MAX', 2000000000);
+
+function db_reposition_respace($table, $field, $where = '') {
+ if($where) {
+ $andand = " && ($where) ";
+ }
+ $ids = db_get_column($table, 'id', "where $field != 0 $andand order by $field");
+ $c = count($ids);
+ if(!$c) {
+ # should never happen
+ return;
+ }
+ $inc = floor(DB_ORD_MAX / ($c + 1));
+ $cur = $inc;
+ foreach($ids as $id) {
+ db_update($table, $field, $cur, 'where id=%i', $id);
+ $cur += $inc;
+ }
+}
+
+# this function facilitates letting the user manually sort records (with (int) $field != 0)
+#
+# When editing a particular row, give the user a pulldown, with 0 -> first, 1 -> second, etc, and pass this integer to db_reposition (3rd parameter). The value "ignored" can be passed, and the row will be given a sort value of 0 and ignored for all sorting.
+#
+# $pretty is used in error messages to refer to the row, it defaults to whatever you pass for $table.
+#
+# return value is the "ord" value you should set/insert into your database
+
+function db_reposition($table, $row_id, $new_pos, $field = 'ord', $pretty = 'same as $table', $where = '', $renumbered_already = false) {
+ if($pretty == 'same as $table') {
+ $pretty = $table;
+ }
+ if($where) {
+ $andand = " && ($where) ";
+ }
+
+ if($new_pos === 'ignored') {
+ # not sorted
+ return '0';
+ }
+
+ # strategy: calculate $prev_ord and $next_ord. If there's no space between, renumber and recurse
+ if($new_pos == '0') {
+ $row = db_get_row($table, "id,$field", "where $field != 0 $andand order by $field limit 1");
+ if($row) {
+ list($first_row_id, $first_row_ord) = $row;
+ if($first_row_id == $row_id) {
+ # already first
+ return $first_row_ord;
+ }
+ $next_ord = $first_row_ord;
+ } else {
+ # this is the only row, put it in the middle
+ return '' + floor(DB_ORD_MAX / 2);
+ }
+
+ $prev_ord = 0;
+ } else {
+ $new_pos = format_int_0($new_pos);
+ $rows = db_get_rows($table, "id,$field", "where $field != 0 $andand order by $field limit %i,2", $new_pos - 1);
+ if(!$rows) {
+ message("Sorry, couldn't find the $pretty you asked to put this $pretty after. Putting it first instead.");
+ return db_reposition($table, $row_id, '0', $field, $pretty, $where);
+ } else {
+ list($prev_id, $prev_ord) = $rows[0];
+ if($prev_id == $row_id) {
+ # after self? this shouldn't happen
+ return $prev_ord;
+ }
+ if(count($rows) == 1) {
+ # we should be last
+ $next_ord = DB_ORD_MAX;
+ } else {
+ list($next_id, $next_ord) = $rows[1];
+ if($next_id == $row_id) {
+ # after prev (already there)
+ return $next_ord;
+ }
+ }
+ }
+ }
+ if($prev_ord + 1 == $next_ord || $prev_ord == $next_ord) { # the latter should never happen
+ if($renumbered_already) {
+ message("Programmer error in $pretty ordering code. Please tell your website administrator.");
+ return '' . rand(2, DB_ORD_MAX - 2); # reasonably unlikely to be the same as some other ord
+ }
+ db_reposition_respace($table, $field, $where);
+ return db_reposition($table, $row_id, $new_pos, $field, $pretty, $where, $renumbered_already = true);
+ } else {
+ return $prev_ord + round(($next_ord - $prev_ord) / 2);
+ }
+}
+
+# Call this to upgrade your database (using upgrade functions you define.)
+#
+# You can call this from config.php right after db_connect() to make sure the
+# database is up to date.
+#
+# When you want to update your schema, define a new function named
+# db_upgrade_to_X() where X is the next integer (start at 1).
+#
+# If there are any page views while your upgrade function is running, they will
+# stall until the upgrade function completes. This is often better than running
+# while the databse is in a transitional state, and is way way better than
+# running the upgrade function multiple times concurrently.
+#
+# Efficiency: this function is designed to be lean enough that you'd run it on
+# every page load, so you never forget to upgrade your schema after uploading
+# code changes. If your schema is up to date, this will only execute one
+# database query, and that query loads the persistent data store (used by
+# persistent_get()), so if you use that, you'll need that query to happen
+# anyway (giving this function a zero-query overhead).
+
+function db_upgrade() {
+ if (isset($GLOBALS['wfpl_persistent'])) {
+ $version = persistent_get('wfpl_db_version');
+ } else {
+ # custom version of persistent_init() that creates the table if needed
+ # instead of dying
+ $GLOBALS['wfpl_persistent'] = array();
+ _db_connection_needed();
+ $result = mysqli_query($GLOBALS['wfpl_db_handle'], 'select k,v from wfpl_persistent');
+ if ($result) {
+ while($row = mysqli_fetch_assoc($result)) {
+ $GLOBALS['wfpl_persistent'][$row['k']] = json_decode($row['v'], true);
+ } unset($row);
+ if (isset($GLOBALS['wfpl_persistent']['wfpl_db_version'])) {
+ $version = $GLOBALS['wfpl_persistent']['wfpl_db_version'];
+ } else {
+ $version = -1;
+ }
+ } else {
+ db_send_query('create table if not exists wfpl_persistent (k varchar(30) binary not null default "", v mediumblob, primary key (k)) CHARSET=utf8;');
+ $version = -1;
+ }
+ }
+
+ if ($version === -1) {
+ db_send_query('create table if not exists wfpl_mutexes (id int unique auto_increment, name varchar(30) binary, expires int(11)) CHARSET=utf8;');
+ $version = 0;
+ # don't save version now in case another thread is doing this too
+ }
+ $next = $version + 1;
+ if (function_exists("db_upgrade_to_$next")) {
+ require_once(__DIR__.'/'.'persistent.php');
+ require_once(__DIR__.'/'.'mutex.php');
+ mutex_lock('wfpl_db_upgrade', 20);
+ # check version again, in case another thread upgraded the database
+ # while we waited for a lock just now
+ persistent_invalidate_cache();
+ $version = persistent_get('wfpl_db_version');
+ if ($version === null) {
+ $version = 0;
+ }
+
+ for ($next = $version + 1; function_exists("db_upgrade_to_$next"); ++$next) {
+ call_user_func("db_upgrade_to_$next");
+ persistent_set('wfpl_db_version', $next);
+ }
+ mutex_unlock('wfpl_db_upgrade');
+ }
+}