Example #1
0
function getStatEntriesByCountriesQuery($ORIS = false, $Athletes = false)
{
    $Sql = "";
    if ($ORIS) {
        $Sql = "SELECT SUM(IF((DivAthlete AND ClAthlete AND EnSex=0), 1,0)) as M, SUM(IF((DivAthlete AND ClAthlete AND EnSex=1), 1,0)) as W, SUM(IF((DivAthlete AND ClAthlete), 0,1)) as Of, ";
        $Sql .= "CoCode as NationCode, CoName as NationName ";
        $Sql .= "FROM Entries ";
        $Sql .= "INNER JOIN Countries ON EnCountry = CoId ";
        $Sql .= "LEFT JOIN Divisions ON EnDivision=DivId AND DivTournament=" . StrSafe_DB($_SESSION['TourId']) . " ";
        $Sql .= "LEFT JOIN Classes ON EnClass=ClId AND ClTournament=" . StrSafe_DB($_SESSION['TourId']) . " ";
        $Sql .= "WHERE EnTournament = " . StrSafe_DB($_SESSION['TourId']) . " ";
        $Sql .= "GROUP BY CoCode ";
        $Sql .= "ORDER BY CoCode ";
    } else {
        $Sql = "SELECT DISTINCT CONCAT(TRIM(EnDivision),'|',TRIM(EnClass)) as Id, (DivAthlete AND ClAthlete) as isAthlete " . "FROM Entries " . "LEFT JOIN Divisions ON EnDivision=DivId AND DivTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . "LEFT JOIN Classes ON EnClass=ClId AND ClTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . "WHERE EnTournament = " . StrSafe_DB($_SESSION['TourId']) . " " . ($Athletes ? 'AND DivAthlete=1 AND ClAthlete=1 ' : '') . "ORDER BY LENGTH(EnDivision) DESC, DivViewOrder, EnDivision, LENGTH(EnClass) DESC, ClViewOrder, EnClass";
        $Rs = safe_r_sql($Sql);
        $Sql = "SELECT ";
        if (safe_num_rows($Rs) > 0) {
            while ($MyRow = safe_fetch($Rs)) {
                $Sql .= "SUM(IF(CONCAT(TRIM(EnDivision),'|',TRIM(EnClass))='" . $MyRow->Id . "',1,0)) as `" . $MyRow->Id . "`, ";
            }
            safe_free_result($Rs);
        }
        $Sql .= "CoCode as NationCode, CoName as NationName ";
        $Sql .= "FROM Entries ";
        $Sql .= "INNER JOIN Countries ON EnCountry = CoId ";
        $Sql .= "WHERE EnTournament = " . StrSafe_DB($_SESSION['TourId']) . " ";
        $Sql .= "GROUP BY CoCode ";
        $Sql .= "ORDER BY CoCode ";
    }
    return $Sql;
}
Example #2
0
function getPhasesId($startPhase = 64)
{
    $myPhases = array();
    $where = "";
    if ($startPhase == -1) {
        $where = " 1=1 ";
    } else {
        $where = " PhId<=" . StrSafe_DB($startPhase) . " ";
    }
    $MyQuery = "SELECT PhId FROM Phases WHERE {$where} ORDER BY PhId DESC";
    $Rs = safe_r_sql($MyQuery);
    if (safe_num_rows($Rs) > 0) {
        while ($MyRow = safe_fetch($Rs)) {
            if ($startPhase == -1) {
                $myPhases[] = $MyRow->PhId;
            } else {
                if (!($MyRow->PhId == 32 && $startPhase == 48 || $MyRow->PhId == 24 && $startPhase == 32 || $MyRow->PhId == 48 && $startPhase == 64 || $MyRow->PhId == 24 && $startPhase == 64)) {
                    $myPhases[] = $MyRow->PhId;
                }
            }
        }
        safe_free_result($Rs);
    }
    return $myPhases;
}
Example #3
0
            $TotalPrice = 0;
            $ShowStatusLegend = false;
        }
        $pdf->SetFont($pdf->FontStd, '', 7);
        $pdf->Cell(10, 4, '', 0, 0, 'C', 0);
        $pdf->Cell(10, 4, $MyRow->Session, 1, 0, 'R', 0);
        $pdf->Cell(15, 4, $MyRow->TargetNo, 1, 0, 'R', 0);
        $pdf->Cell(10, 4, $MyRow->Bib, 1, 0, 'R', 0);
        $pdf->Cell(45, 4, $MyRow->FirstName . ' ' . $MyRow->Name, 1, 0, 'L', 0);
        $pdf->Cell(15, 4, $MyRow->AgeClass, 1, 0, 'C', 0);
        $pdf->Cell(10, 4, $MyRow->SubClass, 1, 0, 'C', 0);
        $pdf->Cell(15, 4, $MyRow->DivCode, 1, 0, 'C', 0);
        $pdf->Cell(15, 4, $MyRow->ClassCode, 1, 0, 'C', 0);
        //Disegna i Pallini per la partecipazione
        $pdf->DrawParticipantDetails($MyRow->IC, $MyRow->IF, $MyRow->TC, $MyRow->TF, $MyRow->TM);
        $pdf->SetDefaultColor();
        $pdf->SetFont($pdf->FontStd, '', 7);
        $ShowStatusLegend = $ShowStatusLegend || $MyRow->Status != 0;
        $pdf->Cell(10, 4, $MyRow->Status == 0 ? '' : $MyRow->Status, 1, 0, 'C', 0);
        $pdf->Cell(20, 4, ($MyRow->EnPays == 1 ? NumFormat($MyRow->APPrice, 2) : NumFormat(0, 2)) . " " . $pdf->writeCurrency(), 1, 1, 'R', 0);
        $TotalPrice += $MyRow->EnPays == 1 ? $MyRow->APPrice : 0;
    }
    $pdf->SetFont($pdf->FontStd, '', 8);
    $pdf->Cell(165, 15, get_text('Cash', 'Tournament') . ":", 0, 0, 'R', 0);
    $pdf->SetFont($pdf->FontStd, 'B', 12);
    $pdf->Cell(25, 15, NumFormat($TotalPrice, 2) . " " . $pdf->writeCurrency(), 0, 1, 'R', 0);
    safe_free_result($Rs);
}
if (!isset($isCompleteResultBook)) {
    $pdf->Output();
}
Example #4
0
require_once dirname(dirname(__FILE__)) . '/config.php';
require_once 'Common/pdf/BackNoPDF.php';
require_once 'Common/Fun_FormatText.inc.php';
$BisTarget = 0;
$NumEnd = 0;
/*$Select
	= "SELECT (TtElabTeam!=0) as BisTarget, TtNumEnds "
	. "FROM Tournament INNER JOIN Tournament*Type ON ToType=TtId "
	. "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " ";*/
$Select = "SELECT (ToElabTeam!=0) as BisTarget, ToNumEnds AS TtNumEnds " . "FROM Tournament " . "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " ";
$RsTour = safe_r_sql($Select);
if (safe_num_rows($RsTour) == 1) {
    $r = safe_fetch($RsTour);
    $BisTarget = $r->BisTarget;
    $NumEnd = $r->TtNumEnds;
    safe_free_result($RsTour);
}
$pdf = new BackNoPDF(0);
$max4Page = $pdf->AthletesPerPage();
if (isset($_REQUEST["BackNoDraw"]) && $_REQUEST['BackNoDraw'] == "Test") {
    $tmp = new stdClass();
    $tmp->EnFirstName = get_text('Athlete');
    $tmp->EnFirstNameUpper = mb_convert_case(get_text('Athlete'), MB_CASE_UPPER, "UTF-8");
    $tmp->EnName = get_text('Athlete');
    $tmp->CoCode = 'ABC';
    $tmp->CoName = get_text('Country');
    $pdf->DrawElements("1a", $tmp, 0);
    $pdf->DrawElements("99z", $tmp, 1);
} else {
    $From = str_pad(intval($_REQUEST['x_From']), 3, '0', STR_PAD_LEFT);
    $To = str_pad(intval($_REQUEST['x_To']), 3, '0', STR_PAD_LEFT);
function recalculateIndividuals_20101211($TournamentID)
{
    // Popolo la tabella degli Individuals
    $events = array();
    MakeIndividuals($events, $TournamentID);
    // Ottengo il numero di Distanze
    $MySql = "SELECT ToNumDist FROM Tournament WHERE ToId=" . StrSafe_DB($TournamentID);
    $rs = safe_r_SQL($MySql);
    $MyRow = safe_fetch($rs);
    safe_free_result($rs);
    // Calcolo la tabella Individuals per ogni distanza + il finale
    for ($i = 0; $i <= $MyRow->ToNumDist; $i++) {
        $rank = Obj_RankFactory::create('Abs', array('tournament' => $TournamentID, 'dist' => $i, 'skipExisting' => 1));
        if ($rank) {
            $rank->calculate();
        }
    }
    //Prendo le posizione dei Coin toss dalla tabella delle finali - SE senza eliminatorie
    $MySql = "UPDATE Individuals\n\t\tINNER JOIN Finals ON IndId=FinAthlete AND IndEvent=FinEvent AND IndTournament=FinTournament\n\t\tINNER JOIN Events ON EvCode=FinEvent AND EvTeamEvent=0 AND EvTournament=FinTournament\n\t\tINNER JOIN Grids ON GrMatchNo=FinMatchNo AND GrPhase=IF(EvFinalFirstPhase=24,32,EvFinalFirstPhase)\n\t\tSET IndRank=GrPosition\n\t\tWHERE FinTournament='{$TournamentID}' AND FinAthlete!=0 AND (EvElim1=0 AND EvElim2=0)";
    safe_w_SQL($MySql);
    // Gestisco le posizioni a seguito dello shootoff di entrata - SE le IndRank sono a 0
    $MySql = "SELECT IndId, IndEvent, QuScore, QuGold, QuXnine, IndRank\n\t\tFROM Individuals\n\t\tINNER JOIN Qualifications ON IndId=QuId\n\t\tINNER JOIN Events ON EvCode=IndEvent AND EvTeamEvent=0 AND EvTournament=IndTournament\n\t\tLEFT JOIN Finals ON IndTournament=FinTournament AND IndEvent=FinEvent AND IndId=FinAthlete\n\t\tLEFT JOIN Eliminations AS e1 ON e1.ElElimPhase=0 AND IndTournament=e1.ElTournament AND IndEvent=e1.ElEventCode AND IndId=e1.ElId\n\t\tLEFT JOIN Eliminations AS e2 ON e2.ElElimPhase=1 AND IndTournament=e2.ElTournament AND IndEvent=e2.ElEventCode AND IndId=e2.ElId\n\t\tWHERE IndTournament='{$TournamentID}' AND IndSO=1 AND IndRank=0 AND ((EvElim2=0 AND FinAthlete IS NULL) OR (EvElim2>0 AND EvElim1=0 AND e2.ElId IS NULL) OR (EvElim2>0 AND EvElim1>0 AND e1.ElId IS NULL))\n\t\tORDER BY IndEvent, QuScore DESC, QuGold DESC, QuXnine DESC, IndId\n\t\t";
    $rs = safe_r_SQL($MySql);
    $curGroup = "-----";
    $myPos = -1;
    $myRank = -1;
    $oldScore = -1;
    $oldGold = -1;
    $oldXnine = -1;
    while ($MyRow = safe_fetch($rs)) {
        if ($curGroup != $MyRow->IndEvent) {
            $curGroup = $MyRow->IndEvent;
            $myPos = $MyRow->IndRank;
        }
        $myPos++;
        if ($MyRow->QuScore != $oldScore || $MyRow->QuGold != $oldGold || $MyRow->QuXnine != $oldXnine) {
            $myRank = $myPos;
        }
        $MySql = "UPDATE Individuals\n\t\t\tSET IndRank = {$myRank}\n\t\t\tWHERE IndId='{$MyRow->IndId}' AND IndEvent='{$MyRow->IndEvent}' AND IndTournament='{$TournamentID}'";
        safe_w_SQL($MySql);
        $oldScore = $MyRow->QuScore;
        $oldGold = $MyRow->QuGold;
        $oldXnine = $MyRow->QuXnine;
    }
    //Sistemo le Rank di quelli che NON hanno passato i gironi ELiminatori (se c'erano i gironi) e i flag di SO/CT
    $MySql = "SELECT EvCode, EvFinalFirstPhase, EvElim1, EvElim2 FROM Events WHERE (EvElim1!=0 OR EvElim2!=0) AND EvTournament=" . StrSafe_DB($TournamentID) . " AND EvTeamEvent=0";
    $rs = safe_r_SQL($MySql);
    $eventsC = array();
    while ($MyRow = safe_fetch($rs)) {
        if ($MyRow->EvElim1 > 0) {
            $eventsC[] = $MyRow->EvCode . "@1";
        }
        if ($MyRow->EvElim2 > 0) {
            $eventsC[] = $MyRow->EvCode . "@2";
        }
    }
    Obj_RankFactory::create('ElimInd', array('tournament' => $TournamentID, 'eventsC' => $eventsC, 'skipExisting' => 1))->calculate();
    /*
    	$MySql = "SELECT ElId, ElElimPhase, ElEventCode, ElQualRank, ElScore, ElGold, ElXnine, ElRank
    		FROM Eliminations
    		INNER JOIN Events ON EvCode=ElEventCode AND EvTeamEvent=0 AND EvTournament=ElTournament
    		WHERE ElTournament='{$TournamentID}' AND  ((EvElim1>0 AND EvE1ShootOff!=0 AND ElElimPhase=0) OR (EvElim2>0 AND EvE2ShootOff!=0 AND ElElimPhase=1))
    		ORDER BY ElEventCode, ElElimPhase, ElScore DESC, ElRank ASC, ElGold DESC, ElXnine DESC, ElId
    		";
    	$rs = safe_r_SQL($MySql);
    	$curGroup = "-----";
    	$myPos = -1;
    	$myRank = -1;
    	$oldScore = -1;
    	$oldGold = -1;
    	$oldXnine = -1;
    	while($MyRow = safe_fetch($rs))
    	{
    		if($curGroup != $MyRow->ElElimPhase . "|". $MyRow->ElEventCode)
    		{
    			$curGroup = $MyRow->ElElimPhase . "|". $MyRow->ElEventCode;
    			$myPos = 0;
    		}
    		$myPos++;
    		if($MyRow->ElScore != $oldScore || $MyRow->ElGold != $oldGold || $MyRow->ElXnine != $oldXnine)
    			$myRank=$myPos;
    
    		if($MyRow->ElRank == 0)
    		{
    			$MySql = "UPDATE Eliminations
    				SET ElRank = {$myRank}
    				WHERE ElElimPhase='{$MyRow->ElElimPhase}' AND ElEventCode='{$MyRow->ElEventCode}' AND ElTournament='{$TournamentID}' AND ElQualRank='{$MyRow->ElQualRank}'";
    			safe_w_SQL($MySql);
    		}
    		$oldScore  = $MyRow->ElScore;
    		$oldGold = $MyRow->ElGold;
    		$oldXnine = $MyRow->ElXnine;
    	}
    */
    // Calcolo le rank Finali venendo dalle qualifiche
    $MySql = "SELECT EvCode, EvFinalFirstPhase, EvElim1, EvElim2 FROM Events WHERE EvTournament=" . StrSafe_DB($TournamentID) . " AND EvTeamEvent=0";
    $rs = safe_r_SQL($MySql);
    $eventsC = array();
    while ($MyRow = safe_fetch($rs)) {
        $eventsC[] = $MyRow->EvCode . "@-3";
        if ($MyRow->EvElim1 > 0) {
            $eventsC[] = $MyRow->EvCode . "@-1";
        }
        if ($MyRow->EvElim2 > 0) {
            $eventsC[] = $MyRow->EvCode . "@-2";
        }
        $eventsC[] = $MyRow->EvCode . "@" . $MyRow->EvFinalFirstPhase;
    }
    Obj_RankFactory::create('FinalInd', array('tournament' => $TournamentID, 'eventsC' => $eventsC))->calculate();
    safe_free_result($rs);
}
Example #6
0
 function __construct($DocTitolo, $Portrait = true, $Headers = '', $StaffVisibility = true)
 {
     global $CFG;
     $this->ShowStaff = $StaffVisibility;
     if ($Headers and is_file($Headers)) {
         $tmp = unserialize(file_get_contents($Headers));
         foreach ($tmp as $k => $v) {
             $this->{$k} = $v;
         }
         if (!defined('ProgramVersion')) {
             define('ProgramVersion', $tmp->ProgramVersion);
         }
         if (!defined('ProgramBuild')) {
             define('ProgramBuild', $tmp->ProgramBuild);
         }
         if (!defined('ProgramRelease')) {
             define('ProgramRelease', $tmp->ProgramRelease);
         }
         if (file_exists($this->TourPath . '/topleft.png')) {
             $this->ToPaths['ToLeft'] = $this->TourPath . '/topleft.png';
         }
         if (file_exists($this->TourPath . '/topright.png')) {
             $this->ToPaths['ToRight'] = $this->TourPath . '/topright.png';
         }
         if (file_exists($this->TourPath . '/bottom.png')) {
             $this->ToPaths['ToBottom'] = $this->TourPath . '/bottom.png';
         }
     } elseif (CheckTourSession()) {
         $Sql = "SELECT ToCode, ToName, ToComDescr, ToWhere, " . "date_format(ToWhenFrom, '" . get_text('DateFmtDB') . "') as ToWhenFrom, date_format(ToWhenTo, '" . get_text('DateFmtDB') . "') as ToWhenTo," . "ToWhenFrom AS DtFrom,ToWhenTo AS DtTo," . "(ToImgL) as ImgL, (ToImgR) as ImgR, (ToImgB) as ImgB, ToGolds AS TtGolds, ToXNine AS TtXNine,ToGoldsChars,ToXNineChars, " . "ToPrintPaper, ToPrintChars, ToCurrency, ToPrintLang " . "FROM Tournament   WHERE ToId = " . StrSafe_DB($_SESSION['TourId']);
         $Rs = safe_r_sql($Sql);
         //print $Sql;exit;
         if (safe_num_rows($Rs) == 1) {
             $r = safe_fetch($Rs);
             $this->Code = $r->ToCode;
             $this->Name = $r->ToName;
             $this->Oc = $r->ToComDescr;
             $this->Where = $r->ToWhere;
             $this->WhenF = $r->ToWhenFrom;
             $this->WhenT = $r->ToWhenTo;
             $this->imgL = $r->ImgL;
             $this->imgR = $r->ImgR;
             $this->imgB = $r->ImgB;
             $this->prnGolds = $r->TtGolds;
             $this->prnXNine = $r->TtXNine;
             $this->goldsChars = $r->ToGoldsChars;
             $this->xNineChars = $r->ToXNineChars;
             $this->docUpdate = date('Ymd.His');
             // patch
             $this->DtFrom = $r->DtFrom;
             $this->DtTo = $r->DtTo;
             $this->TournamentDate2String = TournamentDate2String($this->WhenF, $this->WhenT);
             // texts
             $this->Continue = get_text('Continue');
             $this->LegendSO = get_text('LegendSO', 'Tournament');
             $this->CoinTossShort = get_text('CoinTossShort', 'Tournament');
             $this->CoinToss = get_text('CoinToss', 'Tournament');
             $this->ShotOffShort = get_text('ShotOffShort', 'Tournament');
             $this->ShotOff = get_text('ShotOff', 'Tournament');
             $this->LegendStatus = get_text('LegendStatus', 'Tournament');
             $this->Partecipation = get_text('Partecipation');
             $this->IndQual = get_text('IndQual', 'Tournament');
             $this->IndFin = get_text('IndFin', 'Tournament');
             $this->TeamQual = get_text('TeamQual', 'Tournament');
             $this->TeamFin = get_text('TeamFin', 'Tournament');
             $this->MixedTeamFinEvent = get_text('MixedTeamFinEvent', 'Tournament');
             $this->Yes = get_text('Yes');
             $this->No = get_text('No');
             // ---
             if ($r->ToPrintPaper) {
                 $this->PageSize = 'LETTER';
             }
             switch ($r->ToPrintChars) {
                 case 0:
                     // helvetica & standard european fonts
                     $this->FontStd = 'helvetica';
                     break;
                 case 1:
                     $this->FontStd = 'dejavusans';
                     $this->FontFix = 'freemono';
                     break;
                 case 2:
                     // 						This font is more chinese friendly -- by uian2000@gmail.com
                     $this->FontStd = 'droidsansfallback';
                     $this->FontFix = 'droidsansfallback';
                     break;
             }
             if (is_null($r->ToCurrency)) {
                 $this->Currency = '€';
             } else {
                 $this->Currency = $r->ToCurrency;
             }
             // defines a constant that overrides printing if not empty
             @define('PRINTLANG', $r->ToPrintLang);
             safe_free_result($Rs);
             if (file_exists($CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToLeft.jpg')) {
                 $this->ToPaths['ToLeft'] = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToLeft.jpg';
             }
             if (file_exists($CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToRight.jpg')) {
                 $this->ToPaths['ToRight'] = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToRight.jpg';
             }
             if (file_exists($CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToBottom.jpg')) {
                 $this->ToPaths['ToBottom'] = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-ToBottom.jpg';
             }
         }
         $Ses = StrSafe_DB($_SESSION['TourId']);
         $Select = "\r\n\t\t\t\tSELECT ti.*, it.*,IF(ItJudge!=0,'CatJudge',IF(ItDoS!=0,'CatDos',IF(ItJury!=0,'CatJury','CatOC'))) AS `Category`\r\n\t\t\t\tFROM TournamentInvolved AS ti LEFT JOIN InvolvedType AS it ON ti.TiType=it.ItId\r\n\t\t\t\tWHERE ti.TiTournament={$Ses} AND it.ItId IS NOT NULL\r\n\t\t\t\tORDER BY IF(ItJudge!=0,1,IF(ItDoS!=0,2,IF(ItJury!=0,3,4))) ASC, IF(ItJudge!=0,ItJudge,IF(ItDoS!=0,ItDoS,IF(ItJury!=0,ItJury,ItOC))) ASC,ti.TiName ASC\r\n\t\t\t";
         $Rs = safe_r_sql($Select);
         $CurCategory = '';
         if (safe_num_rows($Rs) > 0) {
             while ($MyRow = safe_fetch($Rs)) {
                 if ($CurCategory != $MyRow->Category) {
                     $this->StaffCategories[get_text($MyRow->Category, 'Tournament')] = array();
                     $CurCategory = $MyRow->Category;
                     $tmp = array();
                 }
                 $this->StaffCategories[get_text($MyRow->Category, 'Tournament')][] = $MyRow->TiName;
             }
             foreach ($this->StaffCategories as $cat => $members) {
                 $this->StaffCategories[$cat] = implode(', ', $members);
             }
         }
     }
     parent::__construct($Portrait ? 'P' : 'L', 'mm', $this->PageSize);
     $this->setJPEGQuality(100);
     $this->AliasNbPages();
     $this->SetSubject($DocTitolo);
     $this->Titolo = $DocTitolo;
     $this->SetDefaultColor();
     $this->SetMargins(IanseoPdf::sideMargin, IanseoPdf::topMargin + 3.0 * count($this->StaffCategories), IanseoPdf::sideMargin);
     $this->SetAutoPageBreak(true, ($this->ToPaths['ToBottom'] ? IanseoPdf::footerImageH : 0) + IanseoPdf::bottomMargin);
     $this->SetAuthor('http://www.ianseo.net');
     $this->SetCreator('Software Design by Ianseo');
     $this->SetTitle('IANSEO - Integrated Result System - Version ' . ProgramVersion . (defined('ProgramBuild') ? ' (' . ProgramBuild . ')' : '') . ' - Release ' . ProgramRelease);
     $this->SetFont($this->FontStd, '', 8);
     $this->SetLineWidth(0.1);
     $this->pushMargins();
 }
Example #7
0
function tour_import($filename)
{
    // Tabelle che hanno il codice Tournament
    $tabs_on_tour = array('AccColors' => 'Ac', 'AccEntries' => 'AE', 'AccPrice' => 'AP', 'ACL' => 'Acl', 'AclDetails' => 'AclDt', 'AvailableTarget' => 'At', 'Awards' => 'Aw', 'Awarded' => 'Aw', 'BackNumber' => 'Bn', 'CasScore' => 'CaS', 'CasTeam' => 'Ca', 'CasTeamFinal' => 'CTF', 'CasTeamTarget' => 'CTT', 'Classes' => 'Cl', 'ClubTeam' => 'CT', 'ClubTeamScore' => 'CTS', 'Countries' => 'Co', 'Divisions' => 'Div', 'DistanceInformation' => 'Di', 'Emails' => 'Em', 'Entries' => 'En', 'EventClass' => 'Ec', 'Events' => 'Ev', 'Individuals' => 'Ind', "F2FGrid" => 'F2F', "F2FEntries" => "F2F", "F2FFinal" => "F2F", 'FinalReportA' => 'Fra', 'Finals' => 'Fin', 'FinSchedule' => 'FS', 'FinTraining' => 'Ft', 'FinTrainingEvent' => 'Fte', 'FinWarmup' => 'Fw', 'HhtData' => 'Hd', 'HhtEvents' => 'He', 'HhtSetup' => 'Hs', 'IdCardElements' => 'Ice', 'IdCards' => 'Ic', 'Images' => 'Im', 'ModulesParameters' => 'Mp', 'RecTournament' => 'Rt', 'Reviews' => 'Rev', 'SubClass' => 'Sc', 'TargetFaces' => 'Tf', 'TeamComponent' => 'Tc', 'TeamFinals' => 'Tf', 'TeamFinComponent' => 'Tfc', 'Teams' => 'Te', 'TournamentDistances' => 'Td', 'TournamentInvolved' => 'Ti', 'TourRecords' => 'Tr', 'TVContents' => 'TVC', 'TVOut' => 'TV', 'TVParams' => 'TVP', 'TVRules' => 'TVR', 'TVSequence' => 'TVS', 'Session' => 'Ses', 'Scheduler' => 'Sch', 'Eliminations' => 'El', 'VegasAwards' => 'Va');
    // Tabelle che hanno il codice Countries
    $tab_to_country = array('CasTeam' => 'CaTeam', 'ClubTeam' => 'CTTeam', 'Entries' => array('EnCountry', 'EnCountry2', 'EnCountry3'), 'TeamComponent' => 'TcCoId', 'TeamFinals' => 'TfTeam', 'TeamFinComponent' => 'TfcCoId', 'Teams' => 'TeCoId');
    // Tabelle che hanno il codice Entries
    $tab_to_entry = array('AccEntries' => 'AEId', 'Awarded' => 'AwEntry', 'ElabQualifications' => 'EqId', 'Eliminations' => 'ElId', 'ExtraData' => 'EdId', 'Individuals' => 'IndId', "F2FEntries" => "F2FEnId", "F2FFinal" => "F2FEnId", 'Finals' => 'FinAthlete', 'HhtData' => 'HdEnId', 'Photos' => 'PhEnId', 'Qualifications' => 'QuId', 'TeamComponent' => 'TcId', 'TeamFinComponent' => 'TfcId', 'Vegas' => 'VeId');
    // Tabelle che dipendono SOLO da Tournament
    $tabs_only_tour = array('AccColors', 'AccPrice', 'ACL', 'AclDetails', 'AvailableTarget', 'Awards', 'BackNumber', 'CasScore', 'CasTeamFinal', 'CasTeamTarget', 'Classes', 'ClubTeamScore', 'DistanceInformation', 'Divisions', 'Emails', 'EventClass', 'Events', 'F2FGrid', 'FinalReportA', 'FinSchedule', 'FinTraining', 'FinTrainingEvent', 'FinWarmup', 'HhtEvents', 'HhtSetup', 'IdCardElements', 'IdCards', 'Images', 'ModulesParameters', 'RecTournament', 'Reviews', 'SubClass', 'TargetFaces', 'TournamentDistances', 'TournamentInvolved', 'TourRecords', 'TVContents', 'TVOut', 'TVParams', 'TVRules', 'TVSequence', 'Session', 'Scheduler', 'Eliminations', 'VegasAwards');
    $Gara = unserialize(gzuncompress(implode('', file($filename))));
    // If is not compatible, exits
    if ($Gara['Tournament']['ToDbVersion'] > GetParameter('DBUpdate')) {
        return false;
    }
    require_once 'UpdateTournament.inc.php';
    $Gara = UpdateTournament($Gara);
    // CONTROLLA SE C'E' UN TORNEO CON LO STESSO CODICE E LO SEGA!
    $q = safe_r_sql("select ToId from Tournament where ToCode=" . strsafe_db($Gara['Tournament']['ToCode']));
    if ($r = safe_fetch($q)) {
        // esiste un tournament con lo stesso codice... ranzo tutto!
        tour_delete($r->ToId);
    }
    // Inserisce il torneo
    $quer = array();
    foreach ($Gara['Tournament'] as $key => $val) {
        if ($key != 'ToId') {
            $quer[] = "{$key}=" . strsafe_db($val);
            // 			if($key=='ToImgL') debug_svela(array('SAFE' => strsafe_db($val), '','','','','', 'ORG' => $val));
        }
    }
    safe_w_sql("Insert into Tournament set " . implode(', ', $quer));
    $TourId = safe_w_last_id();
    if (debug) {
        echo "Inserito Tournament<br />";
    }
    // aggiusta il nuovo valore del torneo nell'array...
    foreach ($tabs_on_tour as $tab => $code) {
        if (isset($Gara[$tab])) {
            foreach ($Gara[$tab] as $key => $val) {
                $Gara[$tab][$key][$code . 'Tournament'] = $TourId;
            }
            if (debug) {
                echo "Aggiornato Tournament Nr. in tabella {$tab}<br />";
            }
        }
    }
    // inserisce le tabelle che hanno SOLO il tournament
    foreach ($tabs_only_tour as $tab) {
        if (isset($Gara[$tab])) {
            foreach ($Gara[$tab] as $record) {
                $query = array();
                foreach ($record as $key => $val) {
                    $query[] = "{$key} = " . strsafe_db($val);
                }
                safe_w_sql("insert into {$tab} set " . implode(', ', $query) . " on duplicate key update " . implode(', ', $query));
            }
        }
        if (debug) {
            echo "Inserita tabella {$tab}<br />";
        }
    }
    // inserisce i paesi e mantieni l'array per il cambio country
    $Countries = array();
    if (array_key_exists('Countries', $Gara) && is_array($Gara['Countries']) && count($Gara['Countries']) > 0) {
        foreach ($Gara['Countries'] as $record) {
            $query = array();
            foreach ($record as $key => $val) {
                if ($key != 'CoId') {
                    $query[] = "{$key} = " . strsafe_db($val);
                }
            }
            safe_w_sql("insert into Countries set " . implode(', ', $query));
            $Countries[$record['CoId']] = safe_w_last_id();
        }
        if (debug) {
            echo "Inserita tabella Countries<br />";
        }
    }
    //aggiorna CoParent1 della Countries stessa
    $tmpSql = "SELECT DISTINCT CoParent1 FROM Countries WHERE CoTournament=" . $TourId . " AND CoParent1!=0";
    $tmpRs = safe_r_sql($tmpSql);
    if (safe_num_rows($tmpRs) != 0) {
        while ($tmpRow = safe_fetch($tmpRs)) {
            safe_w_sql("UPDATE Countries SET CoParent1=" . $Countries[$tmpRow->CoParent1] . " WHERE CoParent1=" . $tmpRow->CoParent1 . " AND CoTournament=" . $TourId);
        }
        safe_free_result($tmpRs);
    }
    //aggiorna CoParent2 della Countries stessa
    $tmpSql = "SELECT DISTINCT CoParent2 FROM Countries WHERE CoTournament=" . $TourId . " AND CoParent2!=0";
    $tmpRs = safe_r_sql($tmpSql);
    if (safe_num_rows($tmpRs) != 0) {
        while ($tmpRow = safe_fetch($tmpRs)) {
            safe_w_sql("UPDATE Countries SET CoParent2=" . $Countries[$tmpRow->CoParent2] . " WHERE CoParent2=" . $tmpRow->CoParent2 . " AND CoTournament=" . $TourId);
        }
        safe_free_result($tmpRs);
    }
    // aggiorna i paesi nelle tabelle che ne fanno uso
    foreach ($tab_to_country as $tab => $field) {
        if (array_key_exists($tab, $Gara)) {
            foreach ($Gara[$tab] as $key => $record) {
                if (is_array($field)) {
                    foreach ($field as $ff) {
                        if (array_key_exists($ff, $record) && $record[$ff]) {
                            $Gara[$tab][$key][$ff] = $Countries[$record[$ff]];
                        }
                    }
                } else {
                    if ($record[$field] && array_key_exists($record[$field], $Countries)) {
                        $Gara[$tab][$key][$field] = $Countries[$record[$field]];
                    }
                }
            }
        }
        if (debug) {
            echo "Aggiornata il Country di tabella {$tab}<br />";
        }
    }
    // inserisce le Entries e mantieni l'array per il cambio Entry
    $Entries = array();
    if (array_key_exists('Entries', $Gara) && is_array($Gara['Entries']) && count($Gara['Entries']) > 0) {
        foreach ($Gara['Entries'] as $record) {
            $query = array();
            foreach ($record as $key => $val) {
                if ($key != 'EnId') {
                    $query[] = "{$key} = " . strsafe_db($val);
                }
            }
            safe_w_sql("insert into Entries set " . implode(', ', $query));
            $Entries[$record['EnId']] = safe_w_last_id();
        }
        if (debug) {
            echo "Inserita tabella Entries<br />";
        }
    }
    // aggiorna le rimanenti tabelle con le Entries corrette
    foreach ($tab_to_entry as $tab => $field) {
        if (array_key_exists($tab, $Gara)) {
            foreach ($Gara[$tab] as $key => $record) {
                if (array_key_exists($record[$field], $Entries) && $record[$field]) {
                    $Gara[$tab][$key][$field] = $Entries[$record[$field]];
                }
            }
        }
        if (debug) {
            echo "Aggiornata l'Entry di tabella {$tab}<br />";
        }
    }
    // inserisce le tabelle restanti
    unset($tab_to_country['Entries']);
    $final_tabs = array_unique(array_merge(array_keys($tab_to_country), array_keys($tab_to_entry)));
    foreach ($final_tabs as $tab) {
        if (array_key_exists($tab, $Gara)) {
            foreach ($Gara[$tab] as $record) {
                $query = array();
                foreach ($record as $key => $val) {
                    $query[] = "{$key} = " . strsafe_db($val);
                }
                // attenzione: questa query era "commentata" per non far apparirer errori:
                // se questo comportamento è desiderato, chiamare la funzione safe_w_sql passando
                // come terzo parametro un array con gli errori numerici ammessi
                safe_w_sql("REPLACE INTO {$tab} set " . implode(', ', $query));
            }
        }
        if (debug) {
            echo "Inserita tabella {$tab}<br />";
        }
    }
    //Gestisce la tabella Flags
    if (array_key_exists('Flags', $Gara) && is_array($Gara['Flags']) && count($Gara['Flags']) > 0) {
        foreach ($Gara['Flags'] as $record) {
            if ($record['FlTournament'] != -1) {
                $record['FlTournament'] = $TourId;
            }
            $query = array();
            foreach ($record as $key => $val) {
                $query[] = "{$key} = " . strsafe_db($val);
            }
            safe_w_sql("insert into Flags set " . implode(', ', $query) . " on duplicate key update " . implode(', ', $query));
        }
        if (debug) {
            echo "Inserita tabella Flags<br />";
        }
    }
    return $TourId;
}