<?php
/*+*******************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *
 ********************************************************************************/
error_reporting(E_ALL & ~E_NOTICE);

include_once 'config.php';
include_once 'include/database/PearDatabase.php';
include_once 'include/utils/utils.php';
require_once('modules/Users/CreateUserPrivilegeFile.php');

class RecalculateSharingAccessCmdCls {

	function __construct() {
		global $adb;

		// Initialize table to store the recalculation state
		$dieOnErrorState = $adb->dieOnError;
		$adb->dieOnError = false;
		$adb->query("CREATE TABLE vtiger_recalculate_privilege_state(lastuserid INT);");
		$adb->dieOnError = $dieOnErrorState;
	}
	
	function processFromLastState() {
		global $adb;
		
		$lastuserid = 0;
		$lastuserstate = $adb->query("SELECT lastuserid FROM vtiger_recalculate_privilege_state");
		if($lastuserstate && $adb->num_rows($lastuserstate)) $lastuserid = $adb->query_result($lastuserstate, 0, 'lastuserid');
		else $adb->query("INSERT INTO vtiger_recalculate_privilege_state (lastuserid) VALUES(0)");

		if ($lastuserid !== 0) {
			echo "NOTE: Restarting the calculation, lastuserid [$lastuserid]\n";
		}

		$users = $adb->query("SELECT id FROM vtiger_users WHERE deleted = 0 and id > $lastuserid ORDER BY id ASC");
		if($users && $adb->num_rows($users)) {
			while($resultrow = $adb->fetch_array($users)) {
				echo sprintf("Calculating for userid [%s]: ", $resultrow['id']);
		
				echo "UserPrivilege... ";
				createUserPrivilegesfile($resultrow['id']);
				echo "SharingPrivilege... ";
				createUserSharingPrivilegesfile($resultrow['id']);
				echo "DONE\n";
		
				$adb->pquery("UPDATE vtiger_recalculate_privilege_state SET lastuserid=?", array($resultrow['id']));
			}
			// Reset the state on successful completion
			$adb->query("UPDATE vtiger_recalculate_privilege_state SET lastuserid=0");
		}
		echo "\nSuccessfully computed privileges for all users.\n";
	}
}

$recalculator = new RecalculateSharingAccessCmdCls();
$recalculator->processFromLastState();
