Some cleanup and refactoring of role_id update.
[timetracker.git] / dbinstall.php
index a800df2..1c95fc2 100644 (file)
@@ -31,6 +31,7 @@ require_once('WEB-INF/lib/common.lib.php');
 require_once('initialize.php');
 import('ttUserHelper');
 import('ttTaskHelper');
+import('ttRoleHelper');
 
 // setChange - executes an sql statement. TODO: rename this function to something better.
 // Better yet, redo the entire thing and make an installer.
@@ -764,6 +765,46 @@ if ($_POST) {
     setChange("UPDATE `tt_site_config` SET `param_value` = '1.17.44' where param_name = 'version_db'");
   }
 
+  // The update_role_id function assigns a role_id to users, who don't have it.
+  if ($_POST['update_role_id']) {
+    import('I18n');
+
+    $mdb2 = getConnection();
+
+    $sql = "select u.id, u.team_id, u.role, u.status, t.lang from tt_users u inner join `tt_site_config` sc on (sc.param_name = 'version_db' and sc.param_value = '1.17.44') left join tt_teams t on (u.team_id = t.id) where u.role_id is NULL and u.status is NOT NULL";
+    $res = $mdb2->query($sql);
+    if (is_a($res, 'PEAR_Error')) die($res->getMessage());
+
+    $users_updated = 0;
+    // Iterate through users.
+    while ($val = $res->fetchRow()) {
+
+      $user_id = $val['id'];
+      $team_id = $val['team_id'];
+      $lang = $val['lang'];
+      $legacy_role = $val['role'];
+  
+      $sql = "select count(*) as count from tt_roles where team_id = $team_id";
+      $result = $mdb2->query($sql);
+      if (is_a($result, 'PEAR_Error')) die($result->getMessage());
+      $row = $result->fetchRow();
+      if ($row['count'] == 0)
+        ttRoleHelper::createPredefinedRoles($team_id, $lang);
+
+      // Obtain new role id based on legacy role.
+      $role_id = ttRoleHelper::getRoleByRank($legacy_role, $team_id);
+      if (!$role_id) continue; // Role not found, nothing to do.
+
+      $sql = "update tt_users set role_id = $role_id where id = $user_id and team_id = $team_id";
+      $affected = $mdb2->exec($sql);
+      if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
+
+      $users_updated++;
+      // if ($users_updated >= 1000) break; // TODO: uncomment for large user sets to run multiple times.
+    }
+    print "Updated $users_updated users...<br>\n";
+  }
+
   if ($_POST["cleanup"]) {
 
     $mdb2 = getConnection();
@@ -844,7 +885,7 @@ if ($_POST) {
   </tr>
   <tr valign="top">
     <td>Update database structure (v1.14 to v1.17.44)</td>
-    <td><input type="submit" name="convert11400to11744" value="Update"><br></td>
+    <td><input type="submit" name="convert11400to11744" value="Update"><br><input type="submit" name="update_role_id" value="Update role_id"></td>
   </tr>
 </table>