function get_already_scheduled_events($CurPhase, $CurEvent, $TeamEvent = 0)
{
    $ret = '';
    // get phase data
    $PhaseDesc = getEventArrowsParams($CurEvent, $CurPhase, $TeamEvent);
    // get time and date of 1st match of previous phase
    $q = safe_r_sql('select' . ' concat(FSScheduledDate, " ", FSScheduledTime) DateTime ' . 'from' . ' FinSchedule ' . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and FsTeamEvent=' . $TeamEvent . ' and fsscheduleddate >0 ' . ' and FSEvent="' . $CurEvent . '"' . ' and FSMatchNo>=' . $CurPhase * 2 . ' LIMIT 1');
    $r = safe_fetch($q);
    $MyQuery = 'SELECT' . ' @Phase:=ifnull(2*pow(2,truncate(log2(fsmatchno/2),0)),1) Phase' . ' , @RealPhase:=truncate(@Phase/2, 0) RealPhase' . ' , @PhaseMatch:=(@Phase & EvMatchArrowsNo)' . ' , EvMatchArrowsNo' . ' , if(@PhaseMatch, EvElimEnds, EvFinEnds) CalcEnds' . ' , if(@PhaseMatch, EvElimArrows, EvFinArrows) CalcArrows' . ' , if(@PhaseMatch, EvElimSO, EvFinSO) CalcSO' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDBshort') . '") AS Dt ' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDB') . '") AS Dat ' . ' , ' . (defined('hideSchedulerAndAdvancedSession') ? '-1' : 'FSScheduledLen') . ' AS matchLen ' . ' , EvFinalFirstPhase ' . ' , fs.* ' . 'FROM' . ' `FinSchedule` fs' . ' INNER JOIN Events on FsEvent=EvCode and FsTeamEvent=EvTeamEvent and FsTournament=EvTournament ' . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and FsTeamEvent=' . $TeamEvent . ' and fsscheduleddate >0 ' . ($r && $r->DateTime ? ' and concat(FSScheduledDate, " ", FSScheduledTime)>=\'' . $r->DateTime . '\' ' : '') . 'group by ' . ' CalcArrows, ' . ' FsScheduledDate, ' . ' FsScheduledTime, ' . ' FsEvent ' . 'HAVING CalcArrows=' . $PhaseDesc->arrows;
    //debug_svela($MyQuery);
    $q = safe_r_sql($MyQuery);
    $tmp = array();
    while ($r = safe_fetch($q)) {
        $tmp[$r->Dat . '§' . substr($r->FSScheduledTime, 0, 5) . '§' . $r->matchLen]['events'][get_text(namePhase($r->EvFinalFirstPhase, $r->RealPhase) . '_Phase')][] = $r->FSEvent;
        $tmp[$r->Dat . '§' . substr($r->FSScheduledTime, 0, 5) . '§' . $r->matchLen]['date'] = $r->Dt . ' ' . substr($r->FSScheduledTime, 0, 5) . (defined('hideSchedulerAndAdvancedSession') ? '' : '/' . $r->matchLen);
    }
    foreach ($tmp as $k => $v) {
        $val = array();
        foreach ($v['events'] as $ph => $ev) {
            $val[] = $ph . ' ' . implode('+', $ev) . '';
        }
        $ret .= '<option value="' . $k . '">' . $v['date'] . ': ' . implode('; ', $val) . '</option>';
    }
    if ($ret) {
        $ret = '<br/><select class="ScheduleSelect" onchange="insert_schedule_from_select(\'' . $CurEvent . '\', \'' . $CurPhase . '\', this.value)"><option value=""></option>' . $ret . '</select>';
    }
    return $ret;
}
Exemple #2
0
            } elseif (strlen(trim($myRow->arrowString1)) == $arrow4Match[$myRow->event] && strlen(trim($myRow->arrowString2)) == $arrow4Match[$myRow->event]) {
                if ($myRow->score1 != $myRow->score2 || ($myRow->tie1 == 1 || $myRow->tie2 == 1)) {
                    //echo strlen($myRow->arrowString1)."-".strlen($myRow->arrowString2)."-".$stdArrowShot."-".strlen($myRow->tiebreak1)."-".strlen($myRow->tiebreak2)."-".$tieArrowShot."\n";
                    if (strlen(trim($myRow->arrowString1)) == $stdArrowShot && strlen(trim($myRow->arrowString2)) == $stdArrowShot && strlen(trim($myRow->tiebreak1)) == $tieArrowShot && strlen(trim($myRow->tiebreak2)) == $tieArrowShot) {
                        $finished = 2;
                    } else {
                        $finished = 1;
                    }
                } elseif ($myRow->score1 == $myRow->score2) {
                    $finished = 3;
                }
            }
            if ($finished == 1) {
                $r = 1;
            }
            // controllo la request
            if (isset($_REQUEST['r_' . $id]) && preg_match('/^[0-1]{1}$/', $_REQUEST['r_' . $id]) && $myRow->lastUpdate < $serverDate) {
                $r = $_REQUEST['r_' . $id];
            }
            if (!empty($target)) {
                $xml .= '<m>' . '<id>' . $id . '</id>' . '<f>' . $finished . '</f>' . '<r>' . $r . '</r>' . '<ev>' . $myRow->event . '</ev>' . '<ph>' . get_text(namePhase($myRow->firstPhase, $myRow->phase) . '_Phase') . '</ph>' . '<evn><![CDATA[' . $myRow->eventName . ']]></evn>' . '<t>' . $target . '</t>' . '<n1><![CDATA[' . $myRow->name1 . ']]></n1>' . '<cn1><![CDATA[' . $myRow->countryName1 . ']]></cn1>' . '<ar1>' . strlen(str_replace(' ', '', $myRow->arrowString1)) . '</ar1>' . '<sar1>' . strlen(str_replace(' ', '', $myRow->tiebreak1)) . '</sar1>' . '<n2><![CDATA[' . $myRow->name2 . ']]></n2>' . '<cn2><![CDATA[' . $myRow->countryName2 . ']]></cn2>' . '<ar2>' . strlen(str_replace(' ', '', $myRow->arrowString2)) . '</ar2>' . '<sar2>' . strlen(str_replace(' ', '', $myRow->tiebreak2)) . '</sar2>' . '<sp1><![CDATA[' . $setPoints1 . ']]></sp1>' . '<sp2><![CDATA[' . $setPoints2 . ']]></sp2>' . '<s>' . $score . '</s>' . '<lu>' . $myRow->lastUpdate . '</lu>' . '</m>';
                ++$id;
            }
        }
    }
}
header('Content-Type: text/xml');
print '<response>' . "\n";
print '<error>' . $error . '</error>' . "\n";
print $xml;
print '</response>' . "\n";
function ComboSes($RowTour, $AllHHT = false, &$ComboSesArray = null)
{
    $ComboArr = array();
    $ComboSes = '';
    $numOptions = 0;
    if (isset($_REQUEST["x_Hht"]) && $_REQUEST["x_Hht"] != -1 or $AllHHT) {
        if (!$AllHHT) {
            $Select = 'SELECT HeEventCode FROM HhtEvents WHERE HeTournament=' . StrSafe_DB($_SESSION['TourId']) . ' AND HeHhtId=' . StrSafe_DB($_REQUEST["x_Hht"]);
            $Rs = safe_r_sql($Select);
        }
        if ($AllHHT or numHHT() == 1 && safe_num_rows($Rs) == 0) {
            if (!$AllHHT) {
                $sessions = GetSessions('Q');
                //Tutte le fasi di qualifica
                /*for ($i=1;$i<=$RowTour->ToNumSession;++$i)
                		{
                			$ComboSes.= '<option value="' . $i . '"' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$i ? ' selected' : '') . '>' . get_text('QualSession','HTT') . ' ' . $i . '</option>' . "\n";
                			$numOptions++;
                		}*/
                foreach ($sessions as $s) {
                    if ($ComboSesArray !== null) {
                        $ComboArr[] = $s->SesOrder;
                    }
                    $ComboSes .= '<option value="' . $s->SesOrder . '"' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session'] == $s->SesOrder ? ' selected' : '') . '>' . get_text('QualSession', 'HTT') . ' ' . $s->Descr . '</option>' . "\n";
                    $numOptions++;
                }
            }
            //Tutte le finali individuali
            if ($AllHHT != 'Teams') {
                //					$Select
                //						= "SELECT DISTINCT CONCAT(FSScheduledDate,' ',FSScheduledTime) AS MyDate,FSTeamEvent "
                //						. "FROM Tournament INNER JOIN FinSchedule ON ToId=FSTournament "
                //						. "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " and FSScheduledDate>0 and FSTeamEvent=0 "
                //						. "ORDER BY CONCAT(FSScheduledDate,FSScheduledTime) ASC ";
                $Select = 'SELECT' . ' @Phase:=ifnull(2*pow(2,truncate(log2(fsmatchno/2),0)),1) Phase' . ' , @RealPhase:=truncate(@Phase/2, 0) RealPhase' . ' , CONCAT(FSScheduledDate,\' \',FSScheduledTime) AS MyDate' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDBshort') . '") AS Dt ' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDB') . '") AS Dat ' . ' , FSTeamEvent ' . ' , FSEvent ' . ' , FSScheduledTime ' . ' , EvFinalFirstPhase ' . 'FROM' . ' `FinSchedule` fs ' . " inner join Events on FSEvent=EvCode and FSTeamEvent=EvTeamEvent and FsTournament=EvTournament " . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and FsTeamEvent=0' . ' and fsscheduleddate >0 ' . 'group by ' . ' FsScheduledDate, ' . ' FsScheduledTime, ' . ' FsEvent, ' . ' Phase';
                //					$Rs=safe_r_sql($Select);
                //					if (safe_num_rows($Rs)>0)
                //					{
                //						while ($MyRow=safe_fetch($Rs))
                //						{
                //							$val=$MyRow->FSTeamEvent . $MyRow->MyDate;
                //							$text= get_text('FinInd','HTT') . ': ' . $MyRow->MyDate ;
                //							$ComboSes.='<option value="' . $val . '" ' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$val ? ' selected' : '') . '>' . $text . '</option>' . "\n";
                //							$numOptions++;
                //						}
                //					}
                $tmp = array();
                $Rs = safe_r_sql($Select);
                while ($MyRow = safe_fetch($Rs)) {
                    $val = $MyRow->FSTeamEvent . $MyRow->MyDate;
                    $text = get_text('FinInd', 'HTT') . ': ' . $MyRow->MyDate;
                    //$ComboSes.='<option value="' . $val . '" ' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$val ? ' selected' : '') . '>' . $text . '</option>' . "\n";
                    $tmp[$val]['events'][get_text(namePhase($MyRow->EvFinalFirstPhase, $MyRow->RealPhase) . '_Phase')][] = $MyRow->FSEvent;
                    $tmp[$val]['date'] = $MyRow->Dt . ' ' . substr($MyRow->FSScheduledTime, 0, 5) . ' ' . get_text('FinInd', 'HTT');
                    $tmp[$val]['selected'] = isset($_REQUEST['x_Session']) && $_REQUEST['x_Session'] == $val ? ' selected' : '';
                    $numOptions++;
                }
                foreach ($tmp as $k => $v) {
                    $val = array();
                    foreach ($v['events'] as $ph => $ev) {
                        $val[] = $ph . ' (' . implode('+', $ev) . ')';
                    }
                    $ComboSes .= '<option value="' . $k . '"' . $v['selected'] . '>' . $v['date'] . ' ' . implode('; ', $val) . '</option>';
                    if ($ComboSesArray !== null) {
                        $ComboArr[] = $k;
                    }
                }
            }
            //Tutte le finali a squadre
            if ($AllHHT != 'Individuals') {
                $Select = "SELECT DISTINCT CONCAT(FSScheduledDate,' ',FSScheduledTime) AS MyDate,FSTeamEvent " . "FROM Tournament INNER JOIN FinSchedule ON ToId=FSTournament " . "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " and FSScheduledDate>0 and FSTeamEvent!=0 " . "ORDER BY CONCAT(FSScheduledDate,FSScheduledTime) ASC ";
                $Select = 'SELECT' . ' @Phase:=ifnull(2*pow(2,truncate(log2(fsmatchno/2),0)),1) Phase' . ' , @RealPhase:=truncate(@Phase/2, 0) RealPhase' . ' , CONCAT(FSScheduledDate,\' \',FSScheduledTime) AS MyDate' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDBshort') . '") AS Dt ' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDB') . '") AS Dat ' . ' , FSTeamEvent ' . ' , FSEvent ' . ' , FSScheduledTime ' . 'FROM' . ' `FinSchedule` fs ' . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and fsscheduleddate >0 ' . ' AND FSTeamEvent!=0 ' . 'group by ' . ' FsScheduledDate, ' . ' FsScheduledTime, ' . ' FsEvent, ' . ' Phase';
                $tmp = array();
                $Rs = safe_r_sql($Select);
                if (safe_num_rows($Rs) > 0) {
                    while ($MyRow = safe_fetch($Rs)) {
                        $val = $MyRow->FSTeamEvent . $MyRow->MyDate;
                        $text = get_text('FinTeam', 'HTT') . ': ' . $MyRow->MyDate;
                        //$ComboSes.='<option value="' . $val . '" ' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$val ? ' selected' : '') . '>' . $text . '</option>' . "\n";
                        $tmp[$val]['events'][get_text($MyRow->RealPhase . '_Phase')][] = $MyRow->FSEvent;
                        $tmp[$val]['date'] = get_text('FinTeam', 'HTT') . ': ' . $MyRow->Dt . ' ' . substr($MyRow->FSScheduledTime, 0, 5);
                        $tmp[$val]['selected'] = isset($_REQUEST['x_Session']) && $_REQUEST['x_Session'] == $val ? ' selected' : '';
                        $numOptions++;
                    }
                    foreach ($tmp as $k => $v) {
                        $val = array();
                        foreach ($v['events'] as $ph => $ev) {
                            $val[] = $ph . ' (' . implode('+', $ev) . ')';
                        }
                        $ComboSes .= '<option value="' . $k . '"' . $v['selected'] . '>' . $v['date'] . ': ' . implode('; ', $val) . '</option>';
                        if ($ComboSesArray !== null) {
                            $ComboArr[] = $k;
                        }
                    }
                }
            }
        } else {
            //Solo le fasi di qualifica associate alla catena HHT
            $Select = 'SELECT HeSession FROM HhtEvents WHERE HeTournament=' . StrSafe_DB($_SESSION['TourId']) . ' AND HeHhtId=' . StrSafe_DB($_REQUEST["x_Hht"]) . " AND HeSession!=0 ORDER BY HeSession";
            $Rs = safe_r_sql($Select);
            while ($MyRow = safe_fetch($Rs)) {
                if ($ComboSesArray !== null) {
                    $ComboArr[] = $MyRow->HeSession;
                }
                $ComboSes .= '<option value="' . $MyRow->HeSession . '"' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session'] == $MyRow->HeSession ? ' selected' : '') . '>' . get_text('QualSession', 'HTT') . ' ' . $MyRow->HeSession . '</option>' . "\n";
                $numOptions++;
            }
            //Solo le finali associate alla catena HHT
            $Select = 'SELECT' . ' @Phase:=ifnull(2*pow(2,truncate(log2(fsmatchno/2),0)),1) Phase' . ' , @RealPhase:=truncate(@Phase/2, 0) RealPhase' . ' , CONCAT(FSScheduledDate,\' \',FSScheduledTime) AS MyDate' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDBshort') . '") AS Dt ' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDB') . '") AS Dat ' . ' , FSTeamEvent ' . ' , FSEvent ' . ' , FSScheduledTime ' . ' , EvFinalFirstPhase ' . 'FROM' . ' `FinSchedule` fs ' . "\tINNER JOIN HhtEvents ON HeTournament=FSTournament AND HeSession=0 AND HeTeamEvent=FSTeamEvent AND HeFinSchedule = CONCAT(FSScheduledDate,' ',FSScheduledTime) " . " inner join Events on FSEvent=EvCode and FSTeamEvent=EvTeamEvent and FsTournament=EvTournament " . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and fsscheduleddate >0 ' . ' AND HeHhtId=' . StrSafe_DB($_REQUEST["x_Hht"]) . ' ' . 'group by ' . ' FsScheduledDate, ' . ' FsScheduledTime, ' . ' FsEvent, ' . ' Phase';
            $tmp = array();
            $Rs = safe_r_sql($Select);
            if (safe_num_rows($Rs) > 0) {
                while ($MyRow = safe_fetch($Rs)) {
                    $val = $MyRow->FSTeamEvent . $MyRow->MyDate;
                    $text = $MyRow->FSTeamEvent == 0 ? get_text('FinInd', 'HTT') . ': ' . $MyRow->MyDate : get_text('FinTeam', 'HTT') . ': ' . $MyRow->MyDate;
                    //$ComboSes.='<option value="' . $val . '" ' . (isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$val ? ' selected' : '') . '>' . $text . '</option>' . "\n";
                    $tmp[$val]['events'][get_text(namePhase($MyRow->EvFinalFirstPhase, $MyRow->RealPhase) . '_Phase')][] = $MyRow->FSEvent;
                    $tmp[$val]['date'] = $MyRow->Dt . ' ' . substr($MyRow->FSScheduledTime, 0, 5) . ' ' . ($MyRow->FSTeamEvent == 0 ? get_text('FinInd', 'HTT') : get_text('FinTeam', 'HTT'));
                    $tmp[$val]['selected'] = isset($_REQUEST['x_Session']) && $_REQUEST['x_Session'] == $val ? ' selected' : '';
                    $numOptions++;
                }
                foreach ($tmp as $k => $v) {
                    $val = array();
                    foreach ($v['events'] as $ph => $ev) {
                        $val[] = $ph . ' (' . implode('+', $ev) . ')';
                    }
                    $ComboSes .= '<option value="' . $k . '"' . $v['selected'] . '>' . $v['date'] . ' ' . implode('; ', $val) . '</option>';
                    if ($ComboSesArray !== null) {
                        $ComboArr[] = $k;
                    }
                }
            }
        }
        $ComboSes = '<select name="x_Session" id="x_Session">' . "\n" . ($numOptions > 1 ? '<option value="-1">---</option>' . "\n" : '') . $ComboSes . '</select>' . "\n";
    }
    if ($ComboSesArray !== null) {
        $ComboSesArray = $ComboArr;
    }
    return $ComboSes;
}
Exemple #4
0
    if ($match2) {
        $pdf->AddPage();
        $pdf->Line(5, $pdf->getPageHeight() / 2, 15, $pdf->getPageHeight() / 2);
        $pdf->Line($pdf->getPageWidth() - 15, $pdf->getPageHeight() / 2, $pdf->getPageWidth() - 5, $pdf->getPageHeight() / 2);
    }
    if ($match2) {
        $pdf->SetXY(10, 10);
    } else {
        $pdf->SetXY(10, $pdf->getPageHeight() / 2 + 10);
    }
    $pdf->SetFont('', '', 220);
    $pdf->Cell($pdf->getPageWidth() - 20, $pdf->getPageHeight() / 2 - 20, str_replace(array_keys($rep), array_values($rep), $MyRow->Athlete), 0, 1, 'L', 0);
    if (!empty($_REQUEST['TargetAssign'])) {
        // PArte di riconoscimento EVENTO e Paglione
        $tmpY = ($match2 ? $pdf->getPageHeight() / 2 : $pdf->getPageHeight()) - 10;
        $pdf->SetFont('', '', 10);
        $pdf->SetXY($pdf->getPageWidth() - 20, $tmpY);
        $pdf->Cell(10, 5, "G." . $MyRow->sGo, 1, 0, 'C', 0);
        $pdf->SetX($pdf->getX() - 20);
        $pdf->Cell(10, 5, "B." . $MyRow->sBr, 1, 0, 'C', 0);
        for ($i = 2; $i <= $MyRow->EvFinalFirstPhase; $i = $i * 2) {
            $pdf->SetX($pdf->getX() - 20);
            $pdf->Cell(10, 5, namePhase($MyRow->EvFinalFirstPhase, $i) . '.' . $MyRow->{'s' . $i}, 1, 0, 'C', 0);
        }
        $pdf->SetX($pdf->getX() - 20);
        $pdf->SetFont('', 'B', 10);
        $pdf->Cell(10, 5, $MyRow->EvCode, 1, 0, 'C', 0);
    }
}
$pdf->Output();
exit;
 public function read()
 {
     $f = $this->safeFilterR();
     $filter = "";
     if ($f !== false) {
         $filter = $f;
     }
     if (array_key_exists('cutRank', $this->opts) && is_numeric($this->opts['cutRank']) && $this->opts['cutRank'] > 0) {
         $filter .= "AND IndRankFinal<={$this->opts['cutRank']} ";
     }
     $EnFilter = empty($this->opts['enid']) ? '' : " AND EnId=" . intval($this->opts['enid']);
     $EnFilter .= empty($this->opts['coid']) ? '' : " AND EnCountry=" . intval($this->opts['coid']);
     $phases = null;
     /*
      *  prima passata per costruire la struttura del vettore.
      *  Tiro fuori le qualifiche, le posizioni finali e le eliminatorie (se ci sono)
      */
     $q = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tEnId,EnCode, upper(EnIocCode) EnIocCode, EnName AS Name, EnFirstName AS FirstName, upper(EnFirstName) AS FirstNameUpper, CoId, CoCode, CoName,\r\n\t\t\t\t\tEvCode,EvEventName,EvProgr,\r\n\t\t\t\t\tEvFinalPrintHead as PrintHeader,\r\n\t\t\t\t\tEvFinalFirstPhase,\tEvElim1, \tEvElim2,EvMatchMode, EvMedals,\r\n\t\t\t\t\tIndRank as QualRank, IF(EvShootOff+EvE1ShootOff+EvE2ShootOff=0, IndRank, IndRankFinal) as FinalRank, QuScore AS QualScore,\r\n\t\t\t\t\te1.ElRank AS E1Rank,e1.ElScore AS E1Score,\r\n\t\t\t\t\te2.ElRank AS E2Rank,e2.ElScore AS E2Score,\r\n\t\t\t\t\tIndTimestamp,IndTimestampFinal\r\n\t\t\t\tFROM\r\n\t\t\t\t\tTournament\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tEntries\r\n\t\t\t\t\tON ToId=EnTournament\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tCountries\r\n\t\t\t\t\tON EnCountry=CoId AND EnTournament=CoTournament AND EnTournament={$this->tournament}\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tQualifications\r\n\t\t\t\t\tON EnId=QuId\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tIndividuals\r\n\t\t\t\t\tON EnTournament=IndTournament AND EnId=IndId\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tEvents\r\n\t\t\t\t\tON EvCode=IndEvent AND EvTeamEvent=0 AND EvTournament=IndTournament\r\n\r\n\t\t\t\t\tLEFT JOIN\r\n\t\t\t\t\t\tEliminations AS e1\r\n\t\t\t\t\tON IndId=e1.ElId AND IndTournament=e1.ElTournament AND IndEvent=e1.ElEventCode AND e1.ElElimPhase=0\r\n\r\n\t\t\t\t\tLEFT JOIN\r\n\t\t\t\t\t\tEliminations AS e2\r\n\t\t\t\t\tON IndId=e2.ElId AND IndTournament=e2.ElTournament AND IndEvent=e2.ElEventCode AND e2.ElElimPhase=1\r\n\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tEnAthlete=1 AND EnIndFEvent=1 AND EnStatus <= 1  AND QuScore != 0 AND ToId = {$this->tournament}\r\n\t\t\t\t\t{$filter}\r\n\t\t\t\t\t{$EnFilter}\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\t\tEvProgr, EvCode, IF(EvShootOff+EvE1ShootOff+EvE2ShootOff=0, IndRank, IndRankFinal) ASC, EnFirstName, EnName\r\n\t\t\t";
     //print $q;exit;
     $r = safe_r_sql($q);
     $this->data['meta']['title'] = get_text('IndFinEvent', 'Tournament');
     //			$this->data['meta']['printHeader']='';
     //			$this->data['meta']['firstPhase']=-1;
     //			$this->data['meta']['elim1']=-1;
     //			$this->data['meta']['elim2']=-1;
     //			$this->data['meta']['matchMode']=-1;
     $this->data['meta']['lastUpdate'] = '0000-00-00 00:00:00';
     $this->data['sections'] = array();
     if (safe_num_rows($r) > 0) {
         $curEvent = '';
         $section = null;
         while ($myRow = safe_fetch($r)) {
             if ($curEvent != $myRow->EvCode) {
                 /*
                  *  se non sono all'inizio, prima di iniziare una sezione devo prendere quella appena fatta
                  *  e accodarla alle altre
                  */
                 if ($curEvent != '') {
                     $this->data['sections'][$curEvent] = $section;
                     $section = null;
                 }
                 // al cambio creo una nuova sezione
                 $curEvent = $myRow->EvCode;
                 $phases = getPhasesId($myRow->EvFinalFirstPhase);
                 // qui ci sono le descrizioni dei campi
                 $fields = array('id' => 'Id', 'bib' => get_text('Code', 'Tournament'), 'athlete' => get_text('Athlete'), 'familyname' => get_text('FamilyName', 'Tournament'), 'givenname' => get_text('Name', 'Tournament'), 'countryCode' => '', 'countryName' => get_text('Country'), 'countryIocCode' => '', 'qualRank' => get_text('RankScoreShort'), 'qualScore' => get_text('PositionShort'), 'rank' => get_text('PositionShort'), 'elims' => array('e1' => get_text('Eliminations_1'), 'e2' => get_text('Eliminations_2'), 'fields' => array('score' => get_text('Total'), 'rank' => get_text('PositionShort'))), 'finals' => array());
                 foreach ($phases as $k => $v) {
                     if ($v <= valueFirstPhase($myRow->EvFinalFirstPhase)) {
                         if (!($v == 32 && ($myRow->EvFinalFirstPhase == 24 || $myRow->EvFinalFirstPhase == 48))) {
                             $fields['finals'][$v] = get_text(namePhase($myRow->EvFinalFirstPhase, $v) . "_Phase");
                         }
                     }
                 }
                 $fields['finals']['fields'] = array('score' => get_text('TotalShort', 'Tournament'), 'setScore' => get_text('SetTotal', 'Tournament'), 'setPoints' => get_text('SetPoints', 'Tournament'), 'tie' => 'S.O.', 'arrowstring' => get_text('Arrows', 'Tournament'), 'tiebreak' => get_text('TieArrows'));
                 $section = array('meta' => array('event' => $curEvent, 'descr' => get_text($myRow->EvEventName, '', '', true), 'printHeader' => get_text($myRow->PrintHeader, '', '', true), 'firstPhase' => $myRow->EvFinalFirstPhase, 'elim1' => $myRow->EvElim1 != 0, 'elim2' => $myRow->EvElim2 != 0, 'matchMode' => $myRow->EvMatchMode, 'order' => $myRow->EvProgr, 'lastUpdate' => '0000-00-00 00:00:00', 'fields' => $fields, 'medals' => $myRow->EvMedals), 'items' => array());
             }
             $item = array('id' => $myRow->EnId, 'bib' => $myRow->EnCode, 'athlete' => $myRow->FirstNameUpper . ' ' . $myRow->Name, 'familyname' => $myRow->FirstName, 'familynameUpper' => $myRow->FirstNameUpper, 'givenname' => $myRow->Name, 'countryId' => $myRow->CoId, 'countryCode' => $myRow->CoCode, 'countryIocCode' => $myRow->EnIocCode, 'countryName' => $myRow->CoName, 'qualScore' => $myRow->QualScore, 'qualRank' => $myRow->QualRank, 'rank' => $myRow->FinalRank == 9999 ? 'DSQ' : $myRow->FinalRank, 'preseed' => ($myRow->EvFinalFirstPhase == 48 or $myRow->EvFinalFirstPhase == 24) and $myRow->QualRank <= 8 ? '1' : '', 'elims' => array(), 'finals' => array());
             if ($myRow->E1Rank !== null && $myRow->E1Score !== null) {
                 $item['elims']['e1']['score'] = $myRow->E1Score;
                 $item['elims']['e1']['rank'] = $myRow->E1Rank;
             }
             if ($myRow->E2Rank !== null && $myRow->E2Score !== null) {
                 $item['elims']['e2']['score'] = $myRow->E2Score;
                 $item['elims']['e2']['rank'] = $myRow->E2Rank;
             }
             $section['items'][$myRow->EnId] = $item;
             if ($myRow->IndTimestampFinal > $section['meta']['lastUpdate']) {
                 $section['meta']['lastUpdate'] = $myRow->IndTimestampFinal;
             }
             if ($myRow->IndTimestampFinal > $this->data['meta']['lastUpdate']) {
                 $this->data['meta']['lastUpdate'] = $myRow->IndTimestampFinal;
             }
         }
         // ultimo giro
         $this->data['sections'][$curEvent] = $section;
     }
     /*
      * A questo punto ho i nomi, le qualifiche,le eliminatorie (se ci sono)
      * e punti+rank delle precedenti.
      * Mi mancano le finali. Che prendo SOLO se lo shootoff è risolto
      *
      */
     $q = "(\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tf1.FinEvent AS `event`,f1.FinAthlete AS `athlete`,f1.FinMatchNo AS `matchNo`,f1.FinScore AS `score`,f1.FinSetScore AS `setScore`,f1.FinSetPoints AS `setPoints`,f1.FinTie AS `tie`,f1.FinArrowstring AS `arrowstring`,f1.FinTiebreak AS `tiebreak`,\r\n\t\t\t\t\tf2.FinAthlete AS `oppAthlete`,f2.FinMatchNo AS `oppMatchNo`,f2.FinScore AS `oppScore`,f2.FinSetScore AS `oppSetScore`,f2.FinSetPoints AS `oppSetPoints`,f2.FinTie AS `oppTie`,f2.FinArrowstring AS `oppArrowstring`,f2.FinTiebreak AS `oppTiebreak`,\r\n\t\t\t\t\tGrPhase, EvProgr, IndRankFinal\r\n\t\t\t\t\tFROM Finals AS f1\r\n\t\t\t\t\tINNER JOIN Events\r\n\t\t\t\t\t\tON EvTournament=f1.FinTournament AND EvCode=f1.FinEvent AND EvTeamEvent=0 AND EvShootOff=1\r\n\t\t\t\t\tINNER JOIN Finals AS f2\r\n\t\t\t\t\t\tON f2.FinEvent=f1.FinEvent AND f2.FinTournament=f1.FinTournament AND f2.FinMatchNo=f1.FinMatchNo+1\r\n\t\t\t\t\tINNER JOIN Grids\r\n\t\t\t\t\t\tON GrMatchNo=f1.FinMatchNo\r\n\t\t\t\t\tINNER JOIN Individuals\r\n\t\t\t\t\t\tON IndTournament={$this->tournament} AND IndEvent=f1.FinEvent AND IndId=f1.FinAthlete\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tf1.FinTournament={$this->tournament} and f1.FinMatchNo%2=0\r\n\t\t\t\t\t\t{$filter}\r\n\t\t\t\t) union (\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tf1.FinEvent AS `event`,f1.FinAthlete AS `athlete`,f1.FinMatchNo AS `matchNo`,f1.FinScore AS `score`,f1.FinSetScore AS `setScore`,f1.FinSetPoints AS `setPoints`,f1.FinTie AS `tie`,f1.FinArrowstring AS `arrowstring`,f1.FinTiebreak AS `tiebreak`,\r\n\t\t\t\t\tf2.FinAthlete AS `oppAthlete`,f2.FinMatchNo AS `oppMatchNo`,f2.FinScore AS `oppScore`,f2.FinSetScore AS `oppSetScore`,f2.FinSetPoints AS `oppSetPoints`,f2.FinTie AS `oppTie`,f2.FinArrowstring AS `oppArrowstring`,f2.FinTiebreak AS `oppTiebreak`,\r\n\t\t\t\t\tGrPhase, EvProgr, IndRankFinal\r\n\t\t\t\t\tFROM Finals AS f1\r\n\t\t\t\t\tINNER JOIN Events\r\n\t\t\t\t\t\tON EvTournament=f1.FinTournament AND EvCode=f1.FinEvent AND EvTeamEvent=0 AND EvShootOff=1\r\n\t\t\t\t\tINNER JOIN Finals AS f2\r\n\t\t\t\t\t\tON f2.FinEvent=f1.FinEvent AND f2.FinTournament=f1.FinTournament AND f2.FinMatchNo=f1.FinMatchNo-1\r\n\t\t\t\t\tINNER JOIN Grids\r\n\t\t\t\t\t\tON GrMatchNo=f1.FinMatchNo\r\n\t\t\t\t\tINNER JOIN Individuals\r\n\t\t\t\t\t\tON IndTournament={$this->tournament} AND IndEvent=f1.FinEvent AND IndId=f1.FinAthlete\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tf1.FinTournament={$this->tournament} and f1.FinMatchNo%2=1\r\n\t\t\t\t\t\t{$filter}\r\n  \t\t\t\t)\r\n  \t\t\t\tORDER BY\r\n  \t\t\t\t\tEvProgr ASC, IndRankFinal ASC, GrPhase DESC\r\n\t\t\t";
     //print $q;exit;
     //return;
     $rr = safe_r_sql($q);
     if (safe_num_rows($rr) > 0) {
         while ($row = safe_fetch($rr)) {
             $arrowstring = array();
             for ($i = 0; $i < strlen($row->arrowstring); ++$i) {
                 if (trim($row->arrowstring[$i]) != '') {
                     $arrowstring[] = DecodeFromLetter($row->arrowstring[$i]);
                 }
             }
             $tiebreak = array();
             for ($i = 0; $i < strlen($row->tiebreak); ++$i) {
                 if (trim($row->tiebreak[$i]) != '') {
                     $tiebreak[] = DecodeFromLetter($row->tiebreak[$i]);
                 }
             }
             $oppArrowstring = array();
             for ($i = 0; $i < strlen($row->oppArrowstring); ++$i) {
                 if (trim($row->oppArrowstring[$i]) != '') {
                     $oppArrowstring[] = DecodeFromLetter($row->oppArrowstring[$i]);
                 }
             }
             $oppTiebreak = array();
             for ($i = 0; $i < strlen($row->oppTiebreak); ++$i) {
                 if (trim($row->oppTiebreak[$i]) != '') {
                     $oppTiebreak[] = DecodeFromLetter($row->oppTiebreak[$i]);
                 }
             }
             if (!empty($this->data['sections'][$row->event]['items'][$row->athlete])) {
                 $this->data['sections'][$row->event]['items'][$row->athlete]['finals'][$row->GrPhase] = array('score' => $row->score, 'setScore' => $row->setScore, 'setPoints' => $row->setPoints, 'tie' => $row->tie, 'arrowstring' => implode('|', $arrowstring), 'tiebreak' => implode('|', $tiebreak), 'oppAthlete' => $row->oppAthlete, 'oppScore' => $row->oppScore, 'oppSetScore' => $row->oppSetScore, 'oppSetPoints' => $row->oppSetPoints, 'oppTie' => $row->oppTie, 'oppArrowstring' => implode('|', $oppArrowstring), 'oppTiebreak' => implode('|', $oppTiebreak));
             }
         }
     }
 }
                $Sql .= $RuleCnt == 1 ? " " : $RuleCnt . " ON C1=C" . $RuleCnt . " ";
            }
            $Rs = safe_r_sql($Sql);
            $tmpQuanti = safe_num_rows($Rs);
            $pdf->SetFont($pdf->FontStd, '', 8);
            $pdf->Cell(15, 5, $MyRowEv->EvCode, 1, 0, 'C', 1);
            $pdf->Cell($DivSize * 4 / 3, 5, $MyRowEv->EventName, 1, 0, 'L', 0);
            if ($MyRowEv->EvMultiTeam != 0) {
                $tmpQuanti = 0;
                while ($tmpRow = safe_fetch($Rs)) {
                    $tmpQuanti += intval($tmpRow->QuantiMulti / $MyRowEv->EvMaxTeamPerson);
                }
            }
            $pdf->Cell($DivSize * 2 / 3, 5, $tmpQuanti, 1, 0, 'R', 0);
            $tmpSaved = valueFirstPhase($MyRowEv->FirstPhase) == $MyRowEv->FirstPhase ? 0 : 8;
            $tmpQuantiIn = maxPhaseRank($MyRowEv->FirstPhase);
            $tmpQuantiOut = $tmpQuanti - $tmpQuantiIn;
            $tmpMatch = min($tmpQuantiIn, $tmpQuanti) - $tmpSaved - $MyRowEv->FirstPhase;
            $tmpBye = $MyRowEv->FirstPhase - $tmpMatch;
            $pdf->Cell($DivSize, 5, $MyRowEv->FirstPhase == 0 ? "" : get_text(namePhase($MyRowEv->FirstPhase, $MyRowEv->FirstPhase) . '_Phase'), 1, 0, 'R', $tmpMatch <= 0 ? 1 : 0);
            $pdf->Cell($DivSize / 2, 5, $MyRowEv->FirstPhase == 0 ? "" : $tmpMatch, 'TBL', 0, 'R', $tmpMatch <= 0 ? 1 : 0);
            $pdf->Cell($DivSize / 2, 5, $MyRowEv->FirstPhase == 0 || $tmpMatch < 0 ? "" : '(' . $tmpBye . ($tmpSaved != 0 ? '+' . $tmpSaved : '') . ')', 'TBR', 0, 'R', $tmpMatch <= 0 ? 1 : 0);
            $pdf->Cell($DivSize / 2, 5, $MyRowEv->FirstPhase == 0 ? "" : ($tmpQuanti < $tmpQuantiIn ? $tmpQuanti : $tmpQuantiIn), 'TBL', 0, 'R', $tmpMatch <= 0 ? 1 : 0);
            $pdf->Cell($DivSize / 2, 5, $MyRowEv->FirstPhase == 0 ? "" : ($tmpQuantiOut > 0 ? '(' . $tmpQuantiOut . ')' : '---'), 'TBR', 0, 'R', $tmpMatch <= 0 ? 1 : 0);
            $pdf->Cell($DivSize, 5, get_text($MyRowEv->EvMixedTeam ? 'Yes' : 'No'), 1, 1, 'C', 0);
        }
    }
}
if (!isset($isCompleteResultBook)) {
    $pdf->Output();
}
 public function read()
 {
     $filter = $this->safeFilter();
     /*
      *  prima passata per costruire la struttura del vettore.
      *  Tiro fuori le qualifiche, le posizioni finali e le eliminatorie (se ci sono)
      */
     $q = "SELECT" . " * " . "FROM (select" . " FinEvent Event," . " EvProgr," . " EvEventName AS EventDescr," . " EvMatchMode," . " EvFinalFirstPhase, " . " EvFinalPrintHead, " . " GrPhase Phase," . " EvShootOff," . " IF(EvFinalFirstPhase=48 || EvFinalFirstPhase=24,GrPosition2, GrPosition) Position," . " DATE_FORMAT(FSScheduledDate,'" . get_text('DateFmtDB') . "') as ScheduledDate," . " DATE_FORMAT(FSScheduledTime,'" . get_text('TimeFmt') . "') AS ScheduledTime, " . " FinTournament Tournament," . " FinDateTime LastUpdated," . " FinMatchNo MatchNo," . " EnCode Bib," . " EnId," . " FsTarget Target," . " TarId, TarDescr, EvDistance as Distance, EvTargetSize as TargetSize, " . " concat(upper(EnFirstName), ' ', EnName) Athlete," . " EnFirstName FamilyName," . " upper(EnFirstName) FamilyNameUpper," . " EnName GivenName," . " CoId CountryId," . " CoCode CountryCode," . " CoName CountryName," . " CoIocCode CountryIocCode," . " IndRank QualRank," . " IndRankFinal FinRank," . " QuScore QualScore," . "\tEvFinEnds, EvFinArrows, EvFinSO, EvElimEnds, EvElimArrows, EvElimSO, " . " FinWinLose Winner," . " FinScore Score," . " FinSetScore SetScore," . " FinSetPoints SetPoints," . " FinTie AS Tie," . " FinArrowstring ArrowString," . " FinTiebreak TieBreak," . " FinStatus Status, " . " FinLive LiveFlag " . "FROM " . " Finals " . "INNER JOIN Grids ON FinMatchNo=GrMatchNo " . "INNER JOIN Events ON FinEvent=EvCode AND FinTournament=EvTournament AND EvTeamEvent=0 " . "INNER JOIN Targets ON EvFinalTargetType=TarId " . "LEFT JOIN Individuals ON FinAthlete=IndId AND FinEvent=IndEvent AND FinTournament=IndTournament " . "LEFT JOIN Entries ON FinAthlete=EnId AND FinTournament=EnTournament " . "LEFT JOIN Qualifications ON QuId=EnId " . "LEFT JOIN Countries ON EnCountry=CoId AND EnTournament=CoTournament " . "LEFT JOIN FinSchedule ON FinEvent=FSEvent AND FinMatchNo=FSMatchNo AND FinTournament=FSTournament AND FSTeamEvent='0' " . "WHERE FinMatchNo%2=0 " . " AND FinTournament = " . $this->tournament . " " . $filter . ") f1 " . "INNER JOIN (select" . " FinEvent OppEvent," . " FinTournament OppTournament," . " FinDateTime OppLastUpdated," . " FinMatchNo OppMatchNo," . " EnCode OppBib," . " EnId OppEnId," . " FsTarget OppTarget," . " concat(upper(EnFirstName), ' ', EnName) OppAthlete," . " EnFirstName OppFamilyName," . " upper(EnFirstName) OppFamilyNameUpper," . " IF(EvFinalFirstPhase=48 || EvFinalFirstPhase=24,GrPosition2, GrPosition) OppPosition," . " EnName OppGivenName," . " CoId OppCountryId," . " CoCode OppCountryCode," . " CoName OppCountryName," . " CoIocCode OppCountryIocCode," . " IndRank OppQualRank," . " IndRankFinal OppFinRank," . " QuScore OppQualScore," . " FinWinLose OppWinner," . " FinScore OppScore," . " FinSetScore OppSetScore," . " FinSetPoints OppSetPoints," . " FinTie AS OppTie," . " FinArrowstring OppArrowString," . " FinTiebreak OppTieBreak, " . " FinStatus OppStatus " . "FROM " . " Finals " . "INNER JOIN Grids ON FinMatchNo=GrMatchNo " . "INNER JOIN Events ON FinEvent=EvCode AND FinTournament=EvTournament AND EvTeamEvent=0 " . "LEFT JOIN Individuals ON FinAthlete=IndId AND FinEvent=IndEvent AND FinTournament=IndTournament " . "LEFT JOIN Entries ON FinAthlete=EnId AND FinTournament=EnTournament " . "LEFT JOIN Qualifications ON QuId=EnId " . "LEFT JOIN Countries ON EnCountry=CoId AND EnTournament=CoTournament " . "LEFT JOIN FinSchedule ON FinEvent=FSEvent AND FinMatchNo=FSMatchNo AND FinTournament=FSTournament AND FSTeamEvent='0' " . "WHERE FinMatchNo%2=1 " . " AND FinTournament = " . $this->tournament . " " . $filter . ") f2 on Tournament=OppTournament and Event=OppEvent and MatchNo=OppMatchNo-1 " . (empty($this->opts['enid']) ? '' : " where (EnId=" . intval($this->opts['enid']) . " or OppEnId=" . intval($this->opts['enid']) . ") ") . (empty($this->opts['coid']) ? '' : " where (CountryId=" . intval($this->opts['coid']) . " or OppCountryId=" . intval($this->opts['coid']) . ") ") . (isset($this->opts['matchno']) ? " where MatchNo=" . intval($this->opts['matchno']) . ' ' : '') . (isset($this->opts['liveFlag']) ? " where LiveFlag=1 " : '') . "ORDER BY EvProgr ASC, Event, Phase DESC, MatchNo ASC ";
     $r = safe_r_sql($q);
     $this->data['meta']['title'] = get_text('BracketsInd');
     $this->data['meta']['saved'] = get_text('Seeded16th');
     $this->data['meta']['lastUpdate'] = '0000-00-00 00:00:00';
     $this->data['meta']['fields'] = array('scheduledDate' => get_text('Date', 'Tournament'), 'scheduledTime' => get_text('Time', 'Tournament'), 'winner' => get_text('Winner'), 'matchNo' => get_text('MatchNo'), 'bib' => get_text('Code', 'Tournament'), 'target' => get_text('Target'), 'athlete' => get_text('Athlete'), 'familyname' => get_text('FamilyName', 'Tournament'), 'givenname' => get_text('Name', 'Tournament'), 'countryId' => '', 'countryCode' => '', 'countryName' => get_text('Country'), 'countryIocCode' => '', 'qualRank' => get_text('RankScoreShort'), 'finRank' => get_text('FinalRank', 'Tournament'), 'qualscore' => get_text('TotalShort', 'Tournament'), 'score' => get_text('TotalShort', 'Tournament'), 'setScore' => get_text('SetTotal', 'Tournament'), 'setPoints' => get_text('SetPoints', 'Tournament'), 'tie' => 'S.O.', 'arrowstring' => get_text('Arrows', 'Tournament'), 'tiebreak' => get_text('TieArrows'), 'status' => get_text('Status', 'Tournament'), 'oppMatchNo' => get_text('MatchNo'), 'oppBib' => get_text('Code', 'Tournament'), 'oppTarget' => get_text('Target'), 'oppAthlete' => get_text('Athlete'), 'oppFamilyname' => get_text('FamilyName', 'Tournament'), 'oppGivenname' => get_text('Name', 'Tournament'), 'oppCountryId' => '', 'oppCountryCode' => '', 'oppCountryName' => get_text('Country'), 'oppCountryIocCode' => '', 'oppQualRank' => get_text('RankScoreShort'), 'oppFinRank' => get_text('FinalRank', 'Tournament'), 'oppQualScore' => get_text('TotalShort', 'Tournament'), 'oppScore' => get_text('TotalShort', 'Tournament'), 'oppSetScore' => get_text('SetTotal', 'Tournament'), 'oppSetPoints' => get_text('SetPoints', 'Tournament'), 'oppTie' => 'S.O.', 'oppArrowstring' => get_text('Arrows', 'Tournament'), 'oppTiebreak' => get_text('TieArrows'), 'oppStatus' => get_text('Status', 'Tournament'));
     $this->data['sections'] = array();
     while ($myRow = safe_fetch($r)) {
         if ($myRow->LastUpdated > $this->data['meta']['lastUpdate']) {
             $this->data['meta']['lastUpdate'] = $myRow->LastUpdated;
         }
         if ($myRow->OppLastUpdated > $this->data['meta']['lastUpdate']) {
             $this->data['meta']['lastUpdate'] = $myRow->OppLastUpdated;
         }
         if (!isset($this->data['sections'][$myRow->Event])) {
             $this->data['sections'][$myRow->Event]['meta'] = array('phase' => get_text('Phase'), 'eventName' => get_text($myRow->EventDescr, '', '', true), 'firstPhase' => $myRow->EvFinalFirstPhase, 'printHead' => get_text($myRow->EvFinalPrintHead, '', '', true), 'matchMode' => $myRow->EvMatchMode, 'order' => $myRow->EvProgr, 'shootOffSolved' => $myRow->EvShootOff, 'finEnds' => $myRow->EvFinEnds, 'finArrows' => $myRow->EvFinArrows, 'finSO' => $myRow->EvFinSO, 'elimEnds' => $myRow->EvElimEnds, 'elimArrows' => $myRow->EvElimArrows, 'elimSO' => $myRow->EvElimSO, 'targetType' => $myRow->TarDescr, 'targetTypeId' => $myRow->TarId, 'targetSize' => $myRow->TargetSize, 'distance' => $myRow->Distance);
             $this->data['sections'][$myRow->Event]['phases'] = array();
         }
         if (!isset($this->data['sections'][$myRow->Event]['phases'][$myRow->Phase])) {
             $this->data['sections'][$myRow->Event]['phases'][$myRow->Phase] = array('meta' => array(), 'items' => array());
             $this->data['sections'][$myRow->Event]['phases'][$myRow->Phase]['meta']['phaseName'] = get_text(namePhase($myRow->EvFinalFirstPhase, $myRow->Phase) . "_Phase");
         }
         $tmpArr = array();
         $oppArr = array();
         if ($myRow->TieBreak) {
             for ($countArr = 0; $countArr < strlen(trim($myRow->TieBreak)); $countArr++) {
                 $tmpArr[] = DecodeFromLetter(substr(trim($myRow->TieBreak), $countArr, 1));
             }
         }
         if ($myRow->OppTieBreak) {
             for ($countArr = 0; $countArr < strlen(trim($myRow->OppTieBreak)); $countArr++) {
                 $oppArr[] = DecodeFromLetter(substr(trim($myRow->OppTieBreak), $countArr, 1));
             }
         }
         $this->data['sections'][$myRow->Event]['phases'][$myRow->Phase]['items'][] = array('liveFlag' => $myRow->LiveFlag, 'scheduledDate' => $myRow->ScheduledDate, 'scheduledTime' => $myRow->ScheduledTime, 'matchNo' => $myRow->MatchNo, 'bib' => $myRow->Bib, 'id' => $myRow->EnId, 'target' => $myRow->Target, 'athlete' => $myRow->Athlete, 'familyName' => $myRow->FamilyName, 'familyNameUpper' => $myRow->FamilyNameUpper, 'givenName' => $myRow->GivenName, 'countryId' => $myRow->CountryId, 'countryCode' => $myRow->CountryCode, 'countryName' => $myRow->CountryName, 'countryIocCode' => $myRow->CountryIocCode, 'qualRank' => $myRow->QualRank, 'finRank' => $myRow->FinRank, 'qualScore' => $myRow->QualScore, 'winner' => $myRow->Winner, 'score' => $myRow->Score, 'setScore' => $myRow->SetScore, 'setPoints' => $myRow->SetPoints, 'tie' => $myRow->Tie, 'arrowstring' => $myRow->ArrowString, 'tiebreak' => $myRow->TieBreak, 'tiebreakDecoded' => implode(',', $tmpArr), 'status' => $myRow->Status, 'position' => $myRow->QualRank ? $myRow->QualRank : $myRow->Position, 'saved' => $myRow->Position > 0 and $myRow->Position < 9 and $myRow->EvFinalFirstPhase != valueFirstPhase($myRow->EvFinalFirstPhase), 'oppMatchNo' => $myRow->OppMatchNo, 'oppBib' => $myRow->OppBib, 'oppId' => $myRow->OppEnId, 'oppTarget' => $myRow->OppTarget, 'oppAthlete' => $myRow->OppAthlete, 'oppFamilyName' => $myRow->OppFamilyName, 'oppFamilyNameUpper' => $myRow->OppFamilyNameUpper, 'oppGivenName' => $myRow->OppGivenName, 'oppCountryId' => $myRow->OppCountryId, 'oppCountryCode' => $myRow->OppCountryCode, 'oppCountryName' => $myRow->OppCountryName, 'oppCountryIocCode' => $myRow->OppCountryIocCode, 'oppQualRank' => $myRow->OppQualRank, 'oppFinRank' => $myRow->OppFinRank, 'oppQualScore' => $myRow->OppQualScore, 'oppWinner' => $myRow->OppWinner, 'oppScore' => $myRow->OppScore, 'oppSetScore' => $myRow->OppSetScore, 'oppSetPoints' => $myRow->OppSetPoints, 'oppTie' => $myRow->OppTie, 'oppArrowstring' => $myRow->OppArrowString, 'oppTiebreak' => $myRow->OppTieBreak, 'oppTiebreakDecoded' => implode(',', $oppArr), 'oppStatus' => $myRow->OppStatus, 'oppPosition' => $myRow->OppQualRank ? $myRow->OppQualRank : $myRow->OppPosition, 'oppSaved' => $myRow->OppPosition > 0 and $myRow->OppPosition < 9 and $myRow->EvFinalFirstPhase != valueFirstPhase($myRow->EvFinalFirstPhase));
         $curEvent = '';
         $curPhase = '';
         $section = null;
     }
 }
function ExportASC($Event = null, $IncludeZeroInfo = true)
{
    $ToCode = '';
    $ToType = 0;
    $NumDist = 0;
    $IocCode = '';
    /*$Select
    		= "SELECT ToCode, TtNumDist, ToType "
    		. "FROM Tournament INNER JOIN Tournament*Type ON ToType=TtId "
    		. "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " ";*/
    $Select = "SELECT ToCode, ToNumDist AS TtNumDist, ToType, ToIocCode " . "FROM Tournament  " . "WHERE ToId=" . StrSafe_DB($_SESSION['TourId']) . " ";
    $Rs = safe_r_sql($Select);
    if (safe_num_rows($Rs) == 1) {
        $row = safe_fetch($Rs);
        $ToCode = $row->ToCode;
        $ToType = $row->ToType;
        $NumDist = $row->TtNumDist;
        $IocCode = $row->ToIocCode;
    }
    if ($ToCode == '') {
        return array('', '');
    }
    $StrData = '';
    /*
     * Tipo 0: Informazioni varie sulla ver di ianseo usata
     * Versione - data aggiornamento archivio nomi
     */
    if ($IncludeZeroInfo) {
        $r = safe_r_sql("\n\t\t\t\tSELECT\n\t\t\t\t\tgroup_concat( CONCAT( if( LupIocCode = '', '___', LupIocCode ) , '-', date_format( LupLastUpdate, '%Y%m%d%H%i%s' ) ) SEPARATOR ',' ) AS up\n\t\t\t\tFROM\n\t\t\t\t\tLookUpPaths\n\t\t\t");
        $rowUp = safe_fetch($r);
        //$StrData.='0;' . ProgramVersion . ';' . ProgramRelease . ';' . (defined('ProgramBuild') ? ProgramBuild : '') .  ';'. GetParameter('SwUpdate') . ';' . GetParameter('LueUpdat') . "\n";
        $StrData .= '0;' . ProgramVersion . ';' . ProgramRelease . ';' . (defined('ProgramBuild') ? ProgramBuild : '') . ';' . GetParameter('SwUpdate') . ';' . $rowUp->up . "\n";
    }
    /*
     * Tipo 1: Classifica di classe - Individuale
     * Matricola-Divisione-Classe-CognomeNome-Societa-AgeClass-Totale1-ori1-X1-Totale2-Ori2-X2-CodiceDiControllo-PosizioneClassificaIndividuale(999 se nn partecipa)-Status-Singole distanze
     * N.B. NON USO l'oggettone poichè ho bisogno di avere anche i non pertecipanti cl/div individuali
     */
    $Query = "SELECT " . "'1' AS RowType,EnCode as Bib, EnDivision, EnClass," . "CONCAT(EnFirstName,' ',EnName) AS Name, CoCode,EnAgeClass, ";
    if ($ToType == 8) {
        $Query .= "(QuD1Score+QuD2Score) AS Score1, " . "(QuD1Gold+QuD2Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine) AS Xnine1, " . "(QuD3Score+QuD4Score) AS Score2, " . "(QuD3Gold+QuD4Gold) AS Gold2, " . "(QuD3Xnine+QuD4Xnine) AS Xnine2, ";
    } else {
        if ($ToType == 10 || $ToType == 12 || $ToType == 13) {
            $Query .= "(QuD1Score) AS Score1, " . "(QuD1Gold) AS Gold1, " . "(QuD1Xnine) AS Xnine1, " . "(QuD2Score) AS Score2, " . "(QuD2Gold) AS Gold2, " . "(QuD2Xnine) AS Xnine2, ";
        } else {
            $Query .= "(QuD1Score+QuD2Score+QuD3Score+QuD4Score) AS Score1, " . "(QuD1Gold+QuD2Gold+QuD3Gold+QuD4Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine+QuD3Xnine+QuD4Xnine) AS Xnine1, " . "(QuD5Score+QuD6Score+QuD7Score+QuD8Score) AS Score2, " . "(QuD5Gold+QuD6Gold+QuD7Gold+QuD8Gold) AS Gold2, " . "(QuD5Xnine+QuD6Xnine+QuD7Xnine+QuD8Xnine) AS Xnine2, ";
        }
    }
    $Query .= "IF(EnDob!='0000-00-000',CONCAT(EnDob,'|',EnSex),EnCtrlCode) AS EnCtrlCode, IF(EnIndClEvent=1,QuClRank,999) AS ClRank,EnStatus ";
    for ($i = 1; $i <= $NumDist; ++$i) {
        $Query .= ",QuD" . $i . "Score,QuD" . $i . "Gold,QuD" . $i . "Xnine ";
    }
    $Query .= ", if(EnIocCode!='', EnIocCode, '{$IocCode}') as IocCode ";
    $Query .= "FROM " . "Qualifications INNER JOIN Entries ON QuId=EnId AND EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EnAthlete=1 " . "INNER JOIN Countries ON EnCountry=CoId AND EnTournament=CoTournament " . "WHERE " . "EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EnStatus<=1 AND QuScore>0 " . "ORDER BY " . "EnCode ASC, CONCAT(EnDivision,EnClass) ASC ";
    //print $Query;exit;
    $Rs = safe_r_sql($Query);
    if (safe_num_rows($Rs) > 0) {
        while ($MyRow = safe_fetch($Rs)) {
            $cols = array();
            foreach ($MyRow as $key => $val) {
                $cols[] = stripslashes($val);
            }
            $StrData .= implode(';', $cols) . "\n";
        }
    }
    /*
     * Tipo 2: Finale Individuale
     * Matricola-Divisione-Classe-CognomeNome-Societa-Evento-PosPartenza|FaseIniziale-CodiceControllo-PosizioneClassificaAssoluta-Scores|SetPoints_arrostringDecodificata#tieArrowstringDecodificata
     */
    // Carico le fasi in un array
    $myPhases = getPhaseArray();
    /*print '<pre>';
    		print_r($myPhases);
    		print '</pre>';
    		exit;*/
    // Genero la query che mi ritorna tutti gli eventi individuali
    $MyQuery = "SELECT EvCode, EvFinalFirstPhase, EvEventName, EvFinalPrintHead,EvMatchMode,EvMatchArrowsNo  ";
    $MyQuery .= "FROM Events ";
    $MyQuery .= "WHERE EvTournament = " . StrSafe_DB($_SESSION['TourId']) . " AND EvTeamEvent=0 ";
    if (!is_null($Event) && preg_match("/^[0-9A-Z]{1,4}\$/i", $Event)) {
        $MyQuery .= "AND EvCode LIKE '" . $Event . "' ";
    }
    $MyQuery .= "ORDER BY  EvProgr ASC, EvCode ";
    $RsEv = safe_r_sql($MyQuery);
    if (safe_num_rows($RsEv) > 0) {
        $RsEvCounter = 0;
        while ($MyRowEv = safe_fetch($RsEv)) {
            //$target=$GLOBALS{GetTargetType($MyRowEv->EvCode,0)};
            //print_r($target);
            $PhaseFields = array();
            reset($myPhases);
            //Genero la query che mi da i risultati per ogni evento
            $MyQuery = "SELECT FinAthlete, CONCAT_WS(' ',EnFirstName, EnName) as Atleta, CoCode, CoName, ";
            $Tmp = "";
            $NumPhases = 0;
            $NeedTitle = true;
            foreach ($myPhases as $Key => $Value) {
                //print $Value.'<br><br>';
                if ($Key <= valueFirstPhase($MyRowEv->EvFinalFirstPhase)) {
                    // mi servirà dopo nei calcoli dei campi!
                    $PhaseFields[] = array("X_Phase" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Phase", "X_SetPoints" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints", "X_Arrowstring" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring", "X_TieArrowstring" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring", "X_Tie" => $Value . "Tie", "X_Live" => $Value . "Live", "X_Matchno" => $Value . "Matchno", "X_PhaseNo" => namePhase($MyRowEv->EvFinalFirstPhase, $Key));
                    //print_r($PhaseFields);
                    /*if($Key!=0)
                    		{
                    			$MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(FinScore=0 && FinTie=2,(QuScore*10),FinScore),0)) as `" . $Key  . "_Phase`, SUM(IF(GrPhase=" . $Key . ",FinTie,0)) as `" . $Value . "Tie`, SUM(IF(GrPhase=" . $Key . ",LENGTH(FinArrowstring),0)) as `" . $Value . "Live`, SUM(IF(GrPhase=" . $Key . ",FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                    			$Tmp = ", `" . $Key . "_Phase` DESC " . $Tmp;
                    			$NumPhases++;
                    		}
                    		else
                    		{
                    			$MyQuery .= "SUM(IF((GrPhase=0 OR GrPhase=1),FinScore,0)) as `" . $Key . "_Phase`, SUM(IF((GrPhase=0 OR GrPhase=1),FinTie,0)) as `" . $Value . "Tie`, SUM(IF((GrPhase=0 OR GrPhase=1),LENGTH(FinArrowstring),0)) as `" . $Value . "Live`, SUM(IF((GrPhase=0 OR GrPhase=1),FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                    			$Tmp = ", `" . $Key . "_Phase` DESC, `" . $Value . "Tie` DESC " . $Tmp;
                    			$NumPhases++;
                    		}*/
                    if ($Key != 0) {
                        //$MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(IF(EvMatchMode=0,FinScore,FinSetScore)=0 && FinTie=2,(QuScore*10),IF(EvMatchMode=0,FinScore,FinSetScore)),0)) as `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key)  . "_Phase`, SUM(IF(GrPhase=" . $Key . ",FinTie,0)) as `" . $Value . "Tie`, MAX(IF(GrPhase=" . $Key . ",/*FinTieBreak*/'','')) as `" . $Value . "TieBreak`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinSetPoints,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key) . "_SetPoints`, SUM(IF(GrPhase=" . $Key . ",FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(IF(EvMatchMode=0,FinScore,FinSetScore)=0 && FinTie=2,(QuScore*10),IF(EvMatchMode=0,FinScore,FinSetScore)),0)) as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Phase`, SUM(IF(GrPhase=" . $Key . ",FinTie,0)) as `" . $Value . "Tie`,GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinArrowstring,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinTieBreak,'') SEPARATOR '') as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinSetPoints,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints`, SUM(IF(GrPhase=" . $Key . ",FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $Tmp = ", `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Phase` DESC " . $Tmp;
                        if ($Key == 4 && $MyRowEv->EvMatchMode != 0) {
                            $MyQuery .= "SUM(IF(GrPhase=" . $Key . ",FinSetScore,0)) as `QuarterWinner`, SUM(IF(GrPhase=" . $Key . ",FinScore,0)) as `QuarterScore`, ";
                            $Tmp = ", `QuarterWinner` DESC, `QuarterScore` DESC " . $Tmp;
                        }
                        $NumPhases++;
                    } else {
                        $MyQuery .= "SUM(IF((GrPhase=0 OR GrPhase=1),IF(EvMatchMode=0,FinScore,FinSetScore),0)) as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Phase`, SUM(IF((GrPhase=0 OR GrPhase=1),FinTie,0)) as `" . $Value . "Tie`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinTieBreak,'') SEPARATOR '') as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinSetPoints,'')  SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinArrowstring,'')  SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring`,SUM(IF((GrPhase=0 OR GrPhase=1),FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $Tmp = ", `" . $Key . "_Phase` DESC, `" . $Value . "Tie` DESC " . $Tmp;
                        $NumPhases++;
                    }
                }
            }
            $MyQuery .= "MIN(GrPhase) as LastPhase, ifnull(CurrentPhase,128) as CurrentPhase, QuScore, IndRank,IndRankFinal,EnCode,EnDivision,EnClass,FinEvent, ";
            $MyQuery .= "IF(LENGTH(EnCtrlCode)=16,EnCtrlCode,CONCAT(EnDob,'|',EnSex)) AS EnCtrlCode,EnCode ";
            $MyQuery .= ", if(EnIocCode!='', EnIocCode, '{$IocCode}') as IocCode ";
            $MyQuery .= "FROM Finals ";
            $MyQuery .= "INNER JOIN Events ON FinEvent=EvCode AND FinTournament=EvTournament AND EvTeamEvent=0 ";
            $MyQuery .= "INNER JOIN Grids ON FinMatchNo=GrMatchNo ";
            $MyQuery .= "INNER JOIN Entries ON FinAthlete=EnId AND FinTournament=EnTournament ";
            $MyQuery .= "INNER JOIN Countries ON EnCountry=CoId AND EnTournament=CoTournament ";
            $MyQuery .= "INNER JOIN Qualifications ON EnId=QuId ";
            $MyQuery .= "INNER JOIN Individuals ON IndId=FinAthlete AND IndEvent=FinEvent AND IndTournament=FinTournament ";
            $MyQuery .= "LEFT JOIN (SELECT min(GrPhase) AS CurrentPhase, FinTournament AS SqyTournament, FinEvent AS SqyEvent " . "FROM Finals INNER JOIN Grids ON FinMatchNo=GrMatchNo " . "WHERE FinScore<>0 GROUP BY SqyTournament, SqyEvent) AS Sqy ON SqyTournament=FinTournament AND SqyEvent=FinEvent ";
            $MyQuery .= "WHERE FinTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND FinEvent=" . StrSafe_DB($MyRowEv->EvCode) . " ";
            $MyQuery .= "GROUP BY FinAthlete, CONCAT_WS(' ', EnFirstName, EnName), CoCode, CoName ";
            $MyQuery .= "ORDER BY FinEvent, LastPhase ASC " . $Tmp . ", IndRank ASC";
            ///*Debug*/echo $MyQuery. "<br>&nbsp;<br>";
            //print '<br><br>'.$MyQuery.'<br><br>';
            $Rs = safe_r_sql($MyQuery);
            $MyPos = 0;
            //				$MyRank=0;
            //Se Esistono righe caricate....
            if (safe_num_rows($Rs) > 0) {
                //					$OldScore=-1;
                //					$OldTie=-1;
                //					$OldLastPhase=-1;
                //					$OldRank=-1;
                $ActualScore = 0;
                $ActualTie = -1;
                while ($MyRow = safe_fetch($Rs)) {
                    $TmpScores = array();
                    $cols = array();
                    $MyPos++;
                    // Se non ho parimerito il ranking � uguale alla posizione
                    if ($MyPos > $MyRow->CurrentPhase) {
                        $TmpScores = array();
                        $ActualScore = 0;
                        $ActualTie = -1;
                        if ($MyRowEv->EvMatchMode == 0) {
                            foreach ($PhaseFields as $i => $Val) {
                                $ActualScore = $MyRow->{$Val['X_Phase']} != 0 ? $MyRow->{$Val['X_Phase']} : $ActualScore;
                                $ActualTie = $MyRow->LastPhase < 2 ? $MyRow->{$Val['X_Tie']} : -1;
                                $TmpScores[] = ($MyRow->{$Val["X_Phase"]} == $MyRow->QuScore * 10 ? 'bye' : $MyRow->{$Val["X_Phase"]}) . '|';
                                /*print '<pre>';
                                		print_r($Val);
                                		print '</pre>';*/
                                list($tmpPhase, ) = explode('_', $Val['X_Phase']);
                                //$x=DecodeArrowstring($MyRowEv->EvMatchMode,$MyRowEv->EvMatchArrowsNo,0,0,$tmpPhase,$MyRow->{$Val["X_Arrowstring"]},$target);
                                //$x=DecodeArrowstring($MyRowEv->EvMatchMode,$MyRowEv->EvMatchArrowsNo,0,0,$tmpPhase,$MyRow->{$Val["X_Arrowstring"]});
                                $numRows = 0;
                                $numCols = 0;
                                $obj = getEventArrowsParams($MyRowEv->EvCode, $tmpPhase, 0);
                                $numRows = $obj->ends;
                                $numCols = $obj->arrows;
                                $x = DecodeArrowstring($numRows, $numCols, $MyRow->{$Val["X_Arrowstring"]});
                                $TmpScores[count($TmpScores) - 1] .= '_' . $x;
                                //$x=DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']},$target);
                                $x = DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']});
                                $TmpScores[count($TmpScores) - 1] .= '#' . $x;
                                //print $TmpScores[count($TmpScores)-1] . '<br>';
                            }
                            //								if ($OldScore!=$ActualScore || $OldTie!=$ActualTie || $OldLastPhase!=$MyRow->LastPhase)
                            //									$MyRank = $MyPos;
                        } else {
                            foreach ($PhaseFields as $i => $Val) {
                                /*print '<pre>';
                                		print_r($Val);
                                		print '</pre>';*/
                                $TmpScores[] = ($MyRow->{$Val["X_Phase"]} == $MyRow->QuScore * 10 ? 'bye' : $MyRow->{$Val["X_Phase"]}) . '|' . ($MyRowEv->EvMatchMode == 1 ? str_replace('|', ',', $MyRow->{$Val["X_SetPoints"]}) : '');
                                list($tmpPhase, ) = explode('_', $Val['X_Phase']);
                                //$x=DecodeArrowstring($MyRowEv->EvMatchMode,$MyRowEv->EvMatchArrowsNo,0,0,$tmpPhase,$MyRow->{$Val["X_Arrowstring"]},$target);
                                $numRows = 0;
                                $numCols = 0;
                                $obj = getEventArrowsParams($MyRowEv->EvCode, $tmpPhase, 0);
                                $numRows = $obj->ends;
                                $numCols = $obj->arrows;
                                $x = DecodeArrowstring($numRows, $numCols, $MyRow->{$Val["X_Arrowstring"]});
                                $TmpScores[count($TmpScores) - 1] .= '_' . $x;
                                //$x=DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']},$target);
                                $x = DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']});
                                $TmpScores[count($TmpScores) - 1] .= '#' . $x;
                                //print $TmpScores[count($TmpScores)-1] . '<br>';
                            }
                            if ($MyRow->LastPhase >= 8) {
                                //$MyRank=$MyRow->LastPhase+1;
                            } elseif ($MyRow->LastPhase == 4) {
                                $ActualScore = $MyRow->QuarterWinner;
                                $ActualTie = $MyRow->QuarterScore;
                                //									if ($OldScore!=$ActualScore || $OldTie!=$ActualTie || $OldLastPhase!=$MyRow->LastPhase)
                                //									{
                                //										$MyRank = $MyPos;
                                //									}
                            }
                        }
                    }
                    //Per i primi 4 NON vale la regola sopra
                    //						if($MyPos<=4)
                    //						{
                    //							if($MyRow->CurrentPhase==1 && $MyRank>2)
                    //								$MyRank = $MyPos;
                    //							elseif($MyRow->CurrentPhase==0)
                    //								$MyRank = $MyPos;
                    //						}
                    //Tolgo tutti Quelli da non scrivere
                    //Salvo i valori attuali e risistemo i colori
                    //						$OldScore=$ActualScore;
                    //						$OldTie=$ActualTie;
                    //						$OldLastPhase=$MyRow->LastPhase;
                    //						$OldRank=$MyRank;
                    $cols[] = 2;
                    $cols[] = $MyRow->EnCode;
                    $cols[] = $MyRow->EnDivision;
                    $cols[] = $MyRow->EnClass;
                    $cols[] = stripslashes($MyRow->Atleta);
                    $cols[] = $MyRow->CoCode;
                    $cols[] = $MyRow->FinEvent;
                    $cols[] = $MyRow->IndRank . '|' . $MyRowEv->EvFinalFirstPhase;
                    $cols[] = $MyRow->EnCtrlCode;
                    //$cols[]=$MyRank;
                    //print $MyRow->IndRankFinal.'<br>';
                    $cols[] = $MyRow->IndRankFinal;
                    $cols[] = $MyRow->IocCode;
                    $StrData .= join(';', $cols) . ';' . join(';', $TmpScores) . "\n";
                }
            }
        }
    }
    //exit;
    /*
     * Tipo 3: Classifica di classe - Squadre
     * CodiceSocieta-Divisione-Classe-Totale1-ori1-X1-Totale2-Ori2-X2-PosizioneClassifica-MatricolaPartecipanti(in lista)
     */
    $MyQuery = "SELECT TcOrder,CoCode, TeEvent,Quanti,EnCode, EnClass, EnDivision,EnAgeClass, ";
    if ($ToType == 8) {
        $MyQuery .= "(QuD1Score+QuD2Score) AS Score1, " . "(QuD1Gold+QuD2Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine) AS Xnine1, " . "(QuD3Score+QuD4Score) AS Score2, " . "(QuD3Gold+QuD4Gold) AS Gold2, " . "(QuD3Xnine+QuD4Xnine) AS Xnine2, ";
    } else {
        if ($ToType == 10 || $ToType == 12 || $ToType == 13) {
            $MyQuery .= "(QuD1Score) AS Score1, " . "(QuD1Gold) AS Gold1, " . "(QuD1Xnine) AS Xnine1, " . "(QuD2Score) AS Score2, " . "(QuD2Gold) AS Gold2, " . "(QuD2Xnine) AS Xnine2, ";
        } else {
            $MyQuery .= "(QuD1Score+QuD2Score+QuD3Score+QuD4Score) AS Score1, " . "(QuD1Gold+QuD2Gold+QuD3Gold+QuD4Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine+QuD3Xnine+QuD4Xnine) AS Xnine1, " . "(QuD5Score+QuD6Score+QuD7Score+QuD8Score) AS Score2, " . "(QuD5Gold+QuD6Gold+QuD7Gold+QuD8Gold) AS Gold2, " . "(QuD5Xnine+QuD6Xnine+QuD7Xnine+QuD8Xnine) AS Xnine2, ";
        }
    }
    $MyQuery .= "QuScore, QuGold,QuXnine,TeScore, TeRank, TeGold, TeXnine, ToGolds AS TtGolds, ToXNine AS TtXNine ";
    $MyQuery .= ", if(EnIocCode!='', EnIocCode, '{$IocCode}') as IocCode ";
    $MyQuery .= "FROM Tournament AS t ";
    $MyQuery .= "INNER JOIN Teams AS te ON t.ToId=te.TeTournament AND te.TeFinEvent=0 ";
    $MyQuery .= "INNER JOIN Countries AS c ON te.TeCoId=c.CoId AND te.TeTournament=c.CoTournament ";
    $MyQuery .= "INNER JOIN (SELECT TcCoId, TcSubTeam, TcEvent, TcFinEvent, COUNT(TcId) as Quanti FROM TeamComponent WHERE TcTournament=" . StrSafe_DB($_SESSION['TourId']) . " GROUP BY TcCoId, TcSubTeam, TcEvent, TcFinEvent ORDER BY TcOrder ASC) AS sq ON te.TeCoId=sq.TcCoId AND te.TeEvent=sq.TcEvent AND te.TeSubTeam=sq.TcSubTeam AND te.TeFinEvent=sq.TcFinEvent ";
    $MyQuery .= "INNER JOIN TeamComponent AS tc ON te.TeCoId=tc.TcCoId AND te.TeEvent=tc.TcEvent AND te.TeTournament=tc.TcTournament AND te.TeFinEvent=tc.TcFinEvent ";
    $MyQuery .= "INNER JOIN Entries AS en ON tc.TcId=en.EnId ";
    $MyQuery .= "INNER JOIN Qualifications AS q ON en.EnId=q.QuId ";
    $MyQuery .= "LEFT JOIN Classes AS cl ON en.EnClass=cl.ClId AND ClTournament=" . StrSafe_DB($_SESSION['TourId']) . " ";
    $MyQuery .= "LEFT JOIN Divisions AS d ON en.EnDivision=d.DivId AND DivTournament=" . StrSafe_DB($_SESSION['TourId']) . " ";
    $MyQuery .= "WHERE ToId = " . StrSafe_DB($_SESSION['TourId']) . " ";
    $MyQuery .= "ORDER BY TeEvent, TeScore DESC, TeGold DESC, TeXnine DESC, CoCode,TcOrder";
    //print $MyQuery;exit;
    $Rs = safe_r_sql($MyQuery);
    if (safe_num_rows($Rs) > 0) {
        $CurEvent = "";
        $CurTeam = "";
        // Variabili per la gestione del ranking
        $MyRank = 1;
        $MyPos = 0;
        // Variabili che contengono i punti del precedente atleta per la gestione del rank
        $MyScoreOld = 0;
        $MyGoldOld = 0;
        $MyXNineOld = 0;
        $Score1 = 0;
        $Score2 = 0;
        $Gold1 = 0;
        $Gold2 = 0;
        $Xnine1 = 0;
        $Xnine2 = 0;
        $TmpMatr = '';
        while ($MyRow = safe_fetch($Rs)) {
            if ($CurEvent != $MyRow->TeEvent) {
                // ultimo totale prima di cambiare evento
                if ($CurEvent != '') {
                    $StrData .= $Score1 . ';' . $Gold1 . ';' . $Xnine1 . ';' . $Score2 . ';' . $Gold2 . ';' . $Xnine2 . ';' . $MyRank . ';' . substr($TmpMatr, 0, -1) . "\n";
                }
                $TmpMatr = '';
                $CurTeam = "";
                $MyRank = 1;
                $MyPos = 0;
                $MyScoreOld = 0;
                $MyGoldOld = 0;
                $MyXNineOld = 0;
                $Score1 = 0;
                $Score2 = 0;
                $Gold1 = 0;
                $Gold2 = 0;
                $Xnine1 = 0;
                $Xnine2 = 0;
            }
            if ($CurTeam != $MyRow->CoCode) {
                if ($CurTeam != '') {
                    $StrData .= $Score1 . ';' . $Gold1 . ';' . $Xnine1 . ';' . $Score2 . ';' . $Gold2 . ';' . $Xnine2 . ';' . $MyRank . ';' . substr($TmpMatr, 0, -1) . "\n";
                    $TmpMatr = '';
                    $Score1 = 0;
                    $Score2 = 0;
                    $Gold1 = 0;
                    $Gold2 = 0;
                    $Xnine1 = 0;
                    $Xnine2 = 0;
                }
                $MyPos++;
                // Se non ho parimerito il ranking ? uguale alla posizione
                if (!($MyRow->TeScore == $MyScoreOld && $MyRow->TeGold == $MyGoldOld && $MyRow->TeXnine == $MyXNineOld)) {
                    $MyRank = $MyPos;
                }
                $StrData .= '3;' . $MyRow->CoCode . ';' . substr($MyRow->TeEvent, 0, 2) . ';' . substr($MyRow->TeEvent, 2, 2) . ';';
            }
            $Score1 += $MyRow->Score1;
            $Gold1 += $MyRow->Gold1;
            $Xnine1 += $MyRow->Xnine1;
            $Score2 += $MyRow->Score2;
            $Gold2 += $MyRow->Gold2;
            $Xnine2 += $MyRow->Xnine2;
            $TmpMatr .= $MyRow->EnCode . ';';
            $CurEvent = $MyRow->TeEvent;
            $CurTeam = $MyRow->CoCode;
            $MyScoreOld = $MyRow->TeScore;
            $MyGoldOld = $MyRow->TeGold;
            $MyXNineOld = $MyRow->TeXnine;
        }
        // ultimissimo totale
        $StrData .= $Score1 . ';' . $Gold1 . ';' . $Xnine1 . ';' . $Score2 . ';' . $Gold2 . ';' . $Xnine2 . ';' . $MyRank . ';' . substr($TmpMatr, 0, -1) . "\n";
    }
    //print $StrData;Exit;
    /*
     * Tipo 4: Finale a Squadre
     * CodiceSocieta-Evento-PosPartenza|FaseIniziale-PosizioneClassifica-ScoresDelleFasi
     */
    //Carico le fasi in un array
    $myPhases = getPhaseArray();
    //Genero la query che mi ritorna tutti gli eventi a squadre
    $MyQuery = "SELECT EvCode, EvFinalFirstPhase, EvEventName, EvFinalPrintHead,EvMatchMode,EvMatchArrowsNo,EvMixedTeam ";
    $MyQuery .= "FROM Events ";
    $MyQuery .= "WHERE EvTournament = " . StrSafe_DB($_SESSION['TourId']) . " AND EvTeamEvent=1 ";
    if (!is_null($Event) && preg_match("/^[0-9A-Z]{1,4}\$/i", $Event)) {
        $MyQuery .= "AND EvCode LIKE '" . $Event . "' ";
    }
    $MyQuery .= "ORDER BY  EvProgr ASC, EvCode ";
    $RsEv = safe_r_sql($MyQuery);
    if (safe_num_rows($RsEv) > 0) {
        $RsEvCounter = 0;
        while ($MyRowEv = safe_fetch($RsEv)) {
            //$target=$GLOBALS{GetTargetType($MyRowEv->EvCode,1)};
            $PhaseFields = array();
            reset($myPhases);
            //Genero la query che mi da i risultati per ogni evento
            $MyQuery = "SELECT TfTeam, CoName, CoCode, TeRank,TeRankFinal, ";
            $Tmp = "";
            $NumPhases = 0;
            $NeedTitle = true;
            while (list($Key, $Value) = each($myPhases)) {
                if ($Key <= valueFirstPhase($MyRowEv->EvFinalFirstPhase)) {
                    // mi servirà dopo nei calcoli dei campi!
                    $PhaseFields[] = array("X_Phase" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Phase", "X_SetPoints" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints", "X_Arrowstring" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring", "X_TieArrowstring" => namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring", "X_Tie" => $Value . "Tie", "X_Live" => $Value . "Live", "X_Matchno" => $Value . "Matchno");
                    /*if($Key!=0)
                    		{
                    			$MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(TfScore=0 && TfTie=2,(TeScore*10),TfScore),0)) as `" . $Key  . "_Phase`, SUM(IF(GrPhase=" . $Key . ",TfTie,0)) as `" . $Value . "Tie`, SUM(IF(GrPhase=" . $Key . ",LENGTH(TfArrowstring),0)) as `" . $Value . "Live`, SUM(IF(GrPhase=" . $Key . ",TfMatchNo,0)) as `" . $Value . "Matchno`, ";
                    			$Tmp = ", `" . $Key . "_Phase` DESC " . $Tmp;
                    			$NumPhases++;
                    		}
                    		else
                    		{
                    			$MyQuery .= "SUM(IF((GrPhase=0 OR GrPhase=1),TfScore,0)) as `" . $Key . "_Phase`, SUM(IF((GrPhase=0 OR GrPhase=1),TfTie,0)) as `" . $Value . "Tie`, SUM(IF((GrPhase=0 OR GrPhase=1),LENGTH(TfArrowstring),0)) as `" . $Value . "Live`, SUM(IF((GrPhase=0 OR GrPhase=1),TfMatchNo,0)) as `" . $Value . "Matchno`, ";
                    			$Tmp = ", `" . $Key . "_Phase` DESC, `" . $Value . "Tie` DESC " . $Tmp;
                    			$NumPhases++;
                    		}*/
                    if ($Key != 0) {
                        //$MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(IF(EvMatchMode=0,FinScore,FinSetScore)=0 && FinTie=2,(QuScore*10),IF(EvMatchMode=0,FinScore,FinSetScore)),0)) as `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key)  . "_Phase`, SUM(IF(GrPhase=" . $Key . ",FinTie,0)) as `" . $Value . "Tie`,GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinArrowstring,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key) . "_Arrowstring`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinTieBreak,'') SEPARATOR '') as `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key) . "_TieArrowstring`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",FinSetPoints,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key) . "_SetPoints`, SUM(IF(GrPhase=" . $Key . ",FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $MyQuery .= "SUM(IF(GrPhase=" . $Key . ",IF(TfScore=0 && TfTie=2,(TeScore*10),TfScore),0)) as `" . $Key . "_Phase`, SUM(IF(GrPhase=" . $Key . ",TfTie,0)) as `" . $Value . "Tie`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",TfTieBreak,'') SEPARATOR '') as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",TfSetPoints,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints`, GROUP_CONCAT(IF(GrPhase=" . $Key . ",TfArrowstring,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring`, SUM(IF(GrPhase=" . $Key . ",TfMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $Tmp = ", `" . $Key . "_Phase` DESC " . $Tmp;
                        if ($Key == 4) {
                            $MyQuery .= "SUM(IF(GrPhase=" . $Key . ",TfScore,0)) as `QuarterScore`, ";
                            $Tmp = ", `QuarterScore` DESC " . $Tmp;
                        }
                        $NumPhases++;
                    } else {
                        //$MyQuery .= "SUM(IF((GrPhase=0 OR GrPhase=1),IF(EvMatchMode=0,FinScore,FinSetScore),0)) as `" . $Key . "_Phase`, SUM(IF((GrPhase=0 OR GrPhase=1),FinTie,0)) as `" . $Value . "Tie`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinTieBreak,'') SEPARATOR '') as `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key) . "_TieArrowstring`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinSetPoints,'')  SEPARATOR '') AS `" . $Key. "_SetPoints`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),FinArrowstring,'')  SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase,$Key). "_Arrowstring`,SUM(IF((GrPhase=0 OR GrPhase=1),FinMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $MyQuery .= "SUM(IF((GrPhase=0 OR GrPhase=1),TfScore,0)) as `" . $Key . "_Phase`, SUM(IF((GrPhase=0 OR GrPhase=1),TfTie,0)) as `" . $Value . "Tie`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),TfTieBreak,'')) as `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_TieArrowstring`,GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),TfSetPoints,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_SetPoints`, GROUP_CONCAT(IF((GrPhase=0 OR GrPhase=1),TfArrowstring,'') SEPARATOR '') AS `" . namePhase($MyRowEv->EvFinalFirstPhase, $Key) . "_Arrowstring`,  SUM(IF((GrPhase=0 OR GrPhase=1),TfMatchNo,0)) as `" . $Value . "Matchno`, ";
                        $Tmp = ", `" . $Key . "_Phase` DESC, `" . $Value . "Tie` DESC " . $Tmp;
                        $NumPhases++;
                    }
                }
            }
            $MyQuery .= "MIN(GrPhase) as LastPhase, ifnull(CurrentPhase,128) as CurrentPhase, TeScore ";
            $MyQuery .= "FROM TeamFinals ";
            $MyQuery .= "INNER JOIN Events ON TfEvent=EvCode AND TfTournament=EvTournament AND EvTeamEvent=1 ";
            $MyQuery .= "INNER JOIN Grids ON TfMatchNo=GrMatchNo ";
            $MyQuery .= "INNER JOIN Countries ON TfTeam=CoId AND TfTournament=CoTournament ";
            $MyQuery .= "INNER JOIN Teams ON TfTeam=TeCoId AND TfEvent=TeEvent AND TfTournament=TeTournament AND TeFinEvent=1 ";
            $MyQuery .= "LEFT JOIN (SELECT min(GrPhase) AS CurrentPhase, TfTournament AS SqyTournament, TfEvent AS SqyEvent " . "FROM TeamFinals INNER JOIN Grids ON TfMatchNo=GrMatchNo " . "WHERE TfScore<>0 GROUP BY SqyTournament, SqyEvent) AS Sqy ON SqyTournament=TfTournament AND SqyEvent=TfEvent ";
            $MyQuery .= "WHERE TfTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND TfEvent=" . StrSafe_DB($MyRowEv->EvCode) . " ";
            $MyQuery .= "GROUP BY TfTeam, CoName, CoCode ";
            $MyQuery .= "ORDER BY TfEvent, LastPhase ASC " . $Tmp . ", TeRank ASC";
            //print $MyQuery . "<br>";
            $Rs = safe_r_sql($MyQuery);
            $MyPos = 0;
            //	$MyRank=0;
            //Se Esistono righe caricate....
            if (safe_num_rows($Rs) > 0) {
                //					if($RsEvCounter++)
                //						$pdf->AddPage();
                //					$pdf->SetXY(10,$pdf->GetY()+5);
                //					$OldScore=-1;
                //					$OldTie=-1;
                //					$OldLastPhase=-1;
                $ActualScore = 0;
                $ActualTie = -1;
                $ActualMatch = 0;
                while ($MyRow = safe_fetch($Rs)) {
                    $TmpScores = array();
                    $cols = array();
                    $MyPos++;
                    // Se non ho parimerito il ranking � uguale alla posizione
                    if ($MyPos > $MyRow->CurrentPhase) {
                        $TmpScores = array();
                        $ActualScore = 0;
                        $ActualMatch = 0;
                        $ActualTie = -1;
                        foreach ($PhaseFields as $Key => $Val) {
                            $ActualScore = $MyRow->{$Val["X_Phase"]} != 0 ? $MyRow->{$Val["X_Phase"]} : $ActualScore;
                            $ActualMatch = $MyRow->{$Val["X_Matchno"]} != 0 ? $MyRow->{$Val["X_Matchno"]} : $ActualMatch;
                            $ActualTie = $MyRow->LastPhase < 2 ? $MyRow->{$Val["X_Tie"]} : -1;
                            $TmpScores[] = ($MyRow->{$Val["X_Phase"]} == $MyRow->TeScore * 10 ? 'bye' : $MyRow->{$Val["X_Phase"]}) . '|';
                            list($tmpPhase, ) = explode('_', $Val['X_Phase']);
                            //$x=DecodeArrowstring($MyRowEv->EvMatchMode,$MyRowEv->EvMatchArrowsNo,1,$MyRowEv->EvMixedTeam,$tmpPhase,$MyRow->{$Val["X_Arrowstring"]},$target);
                            //$x=DecodeArrowstring($MyRowEv->EvMatchMode,$MyRowEv->EvMatchArrowsNo,1,$MyRowEv->EvMixedTeam,$tmpPhase,$MyRow->{$Val["X_Arrowstring"]});
                            $numRows = 0;
                            $numCols = 0;
                            $obj = getEventArrowsParams($MyRowEv->EvCode, $tmpPhase, 1);
                            $numRows = $obj->ends;
                            $numCols = $obj->arrows;
                            $x = DecodeArrowstring($numRows, $numCols, $MyRow->{$Val["X_Arrowstring"]});
                            $TmpScores[count($TmpScores) - 1] .= '_' . $x;
                            //$x=DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']},$target);
                            $x = DecodeTieArrowstring($MyRow->{$Val['X_TieArrowstring']});
                            $TmpScores[count($TmpScores) - 1] .= '#' . $x;
                        }
                        if ($MyRow->LastPhase >= 8) {
                            //	$MyRank=$MyRow->LastPhase+1;
                        } elseif ($MyRow->LastPhase == 4) {
                            $ActualScore = $MyRow->QuarterScore;
                            $ActualTie = $MyRow->QuarterScore;
                            //								if ($OldScore!=$ActualScore || $OldTie!=$ActualTie || $OldLastPhase!=$MyRow->LastPhase)
                            //								{
                            //									$MyRank = $MyPos;
                            //								}
                        }
                    }
                    //						else
                    //							$MyRank = -1;
                    //Per i primi 4 NON vale la regola sopra
                    //						if($MyPos<=4)
                    //						{
                    //							if($MyRow->CurrentPhase==1 && $MyRank>2)
                    //								$MyRank = $MyPos;
                    //							elseif($MyRow->CurrentPhase==0)
                    //								$MyRank = $MyPos;
                    //
                    //						}
                    //Tolgo tutti Quelli da non scrivere
                    //Salvo i valori attuali e risistemo i colori
                    //						$OldScore=$ActualScore;
                    //						$OldTie=$ActualTie;
                    //						$OldLastPhase=$MyRow->LastPhase;
                    //						$OldMatch=$ActualMatch;
                    $cols[] = '4';
                    $cols[] = $MyRow->CoCode;
                    $cols[] = $MyRowEv->EvCode;
                    $cols[] = $MyRow->TeRank . '|' . $MyRowEv->EvFinalFirstPhase;
                    //$cols[]=$MyRank;
                    $cols[] = $MyRow->TeRankFinal;
                    $StrData .= join(';', $cols) . ';' . join(';', $TmpScores) . "\n";
                }
            }
        }
    }
    /*
     * Tipo 5/6: Classifica eliminatorie, fase 1 e fase 2
     * Matricola-Divisione-Classe-CognomeNome-Societa-Evento-Totale-Ori-X-CodiceFiscale-PosizioneClassifica
     *
     */
    for ($tipo = 5; $tipo <= 6; ++$tipo) {
        $phase = $tipo - 5;
        $Query = "SELECT " . "'" . $tipo . "' AS RowType,EnCode as Bib, EnDivision, EnClass," . "CONCAT(EnFirstName,' ',EnName) AS Name, CoCode,ElEventCode, " . "ElScore,ElGold,ElXnine,EnCtrlCode,ElRank " . "FROM " . "Entries " . "INNER JOIN " . "Countries " . "ON EnCountry=CoId AND EnTournament=CoTournament " . "INNER JOIN " . "Eliminations " . "ON EnId=ElId AND EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND ElElimPhase=" . $phase . " " . "ORDER BY " . "ElEventCode ASC, (ElScore*1.0) DESC, ElRank ASC, ElGold DESC, ElXnine DESC ";
        //print $Query . '<br><br/>';
        $Rs = safe_r_sql($Query);
        $CurEvent = "";
        // Variabili per la gestione del ranking
        //			$MyRank = 1;
        //			$MyPos = 0;
        // Variabili che contengono i punti del precedente atleta per la gestione del rank
        //			$MyScoreOld = 0;
        //			$MyGoldOld = 0;
        //			$MyXNineOld = 0;
        if (safe_num_rows($Rs) > 0) {
            while ($myRow = safe_fetch($Rs)) {
                //					if ($CurEvent!=$myRow->ElEventCode)
                //					{
                //
                //						$MyRank = 1;
                //						$MyPos = 0;
                //						$MyScoreOld = 0;
                //						$MyGoldOld = 0;
                //						$MyXNineOld = 0;
                //					}
                //
                //					++$MyPos;
                //					if (!($myRow->ElScore==$MyScoreOld && $myRow->ElGold==$MyGoldOld && $myRow->ElXnine==$MyXNineOld))
                //						$MyRank = $MyPos;
                $StrData .= $myRow->RowType . ';' . $myRow->Bib . ';' . $myRow->EnDivision . ';' . $myRow->EnClass . ';' . $myRow->Name . ';' . $myRow->CoCode . ';' . $myRow->ElEventCode . ';' . $myRow->ElScore . ';' . $myRow->ElGold . ';' . $myRow->ElXnine . ';' . $myRow->EnCtrlCode . ';' . $myRow->ElRank . "\n";
                //					$MyScoreOld = $myRow->ElScore;
                //					$MyGoldOld = $myRow->ElGold;
                //					$MyXNineOld = $myRow->ElXnine;
                $CurEvent = $myRow->ElEventCode;
            }
        }
    }
    /*
     * Tipo 7: assoluti individuali
     * Matricola-Divisione-Classe-CognomeNome-Societa-CodiceEvento-Totale1-ori1-X1-Totale2-Ori2-X2-CodiceDiControllo-PosizioneClassificaIndividuale(999 se nn partecipa)-Status-Singole distanze-tiearrowstring
     */
    $MyQuery = "SELECT EnCode as Bib, EnName AS Name, CONCAT(EnFirstName,' ',EnName) AS Name,SUBSTRING(QuTargetNo,1,1) AS Session, SUBSTRING(QuTargetNo,2) AS TargetNo, CoCode AS NationCode, CoName AS Nation, EnClass AS ClassCode, EnAgeClass as AgeClass, EnDivision AS DivCode, EvCode as EventCode, EvEventName as EventName, EvQualPrintHead,";
    $MyQuery .= "IF(EvElim1=0 && EvElim2=0,(EvFinalFirstPhase*2),IF(EvElim1=0,EvElim2,EvElim1)) as QualifiedNo, ";
    $MyQuery .= "ToNumDist AS NumDist, Td1, Td2, Td3, Td4, Td5, Td6, Td7, Td8, ";
    for ($i = 1; $i <= $NumDist; ++$i) {
        $MyQuery .= "QuD" . $i . "Score,QuD" . $i . "Gold,QuD" . $i . "Xnine,QuD" . $i . "Arrowstring AS Arrowstring" . $i . ", ";
    }
    $MyQuery .= "QuScore, IndRank, QuGold, QuXnine, ToGolds AS TtGolds, ToXNine AS TtXNine,  ";
    if ($ToType == 8) {
        $MyQuery .= "(QuD1Score+QuD2Score) AS Score1, " . "(QuD1Gold+QuD2Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine) AS Xnine1, " . "(QuD3Score+QuD4Score) AS Score2, " . "(QuD3Gold+QuD4Gold) AS Gold2, " . "(QuD3Xnine+QuD4Xnine) AS Xnine2, ";
    } else {
        if ($ToType == 10 || $ToType == 12 || $ToType == 13) {
            $MyQuery .= "(QuD1Score) AS Score1, " . "(QuD1Gold) AS Gold1, " . "(QuD1Xnine) AS Xnine1, " . "(QuD2Score) AS Score2, " . "(QuD2Gold) AS Gold2, " . "(QuD2Xnine) AS Xnine2, ";
        } else {
            $MyQuery .= "(QuD1Score+QuD2Score+QuD3Score+QuD4Score) AS Score1, " . "(QuD1Gold+QuD2Gold+QuD3Gold+QuD4Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine+QuD3Xnine+QuD4Xnine) AS Xnine1, " . "(QuD5Score+QuD6Score+QuD7Score+QuD8Score) AS Score2, " . "(QuD5Gold+QuD6Gold+QuD7Gold+QuD8Gold) AS Gold2, " . "(QuD5Xnine+QuD6Xnine+QuD7Xnine+QuD8Xnine) AS Xnine2, ";
        }
    }
    $MyQuery .= "QuTieBreak AS ArrowstringTie, ";
    $MyQuery .= "IF(LENGTH(EnCtrlCode)=16,EnCtrlCode,CONCAT(EnDob,'|',EnSex)) AS EnCtrlCode, IndRank, EnStatus ";
    $MyQuery .= "FROM Tournament AS t ";
    $MyQuery .= "INNER JOIN Entries AS e ON t.ToId=e.EnTournament ";
    $MyQuery .= "INNER JOIN Countries AS c ON e.EnCountry=c.CoId AND e.EnTournament=c.CoTournament ";
    $MyQuery .= "INNER JOIN Qualifications AS q ON e.EnId=q.QuId ";
    $MyQuery .= "INNER JOIN EventClass AS ec ON e.EnClass=ec.EcClass AND e.EnDivision=ec.EcDivision AND e.EnTournament=ec.EcTournament AND ec.EcTeamEvent=0 ";
    $MyQuery .= "INNER JOIN Events AS ev ON ev.EvCode=ec.EcCode AND ev.EvTeamEvent=ec.EcTeamEvent AND ev.EvTournament=ec.EcTournament ";
    $MyQuery .= "INNER JOIN Individuals i ON i.IndId=e.EnId AND i.IndEvent=ev.EvCode AND i.IndTournament=e.EnTournament ";
    $MyQuery .= "LEFT JOIN TournamentDistances AS td ON t.ToType=td.TdType and TdTournament=ToId AND CONCAT(TRIM(e.EnDivision),TRIM(e.EnClass)) LIKE TdClasses ";
    //Where Normale
    $MyQuery .= "WHERE EnAthlete=1 AND EnIndFEvent=1 AND EnStatus <= 1  AND QuScore<>'0' AND ToId = " . StrSafe_DB($_SESSION['TourId']) . " ";
    $MyQuery .= "ORDER BY EvProgr, EvCode, QuScore DESC, IndRank ASC, QuGold DESC, QuXnine DESC, IndRank, EnFirstName,EnName ";
    //print $MyQuery;exit;
    $Rs = safe_r_sql($MyQuery);
    //$target=$GLOBALS['TrgOutdoor'];
    if ($Rs && safe_num_rows($Rs) > 0) {
        $CurGroup = "....";
        // Variabili per la gestione del ranking
        $MyRank = 1;
        //$MyPos = 0;
        $EndQualified = false;
        // Variabili che contengono i punti del precedente atleta per la gestione del rank
        //			$MyScoreOld = 0;
        //			$MyGoldOld = 0;
        //			$MyXNineOld = 0;
        $MyEndScore = -1;
        $MyGroupStartPos = 0;
        $CurrentRow = -1;
        while ($MyRow = safe_fetch($Rs)) {
            $CurrentRow++;
            if ($CurGroup != $MyRow->EventCode) {
                $CurGroup = $MyRow->EventCode;
                //					$MyRank = 1;
                //					$MyPos = 0;
                //					$MyScoreOld = 0;
                //					$MyGoldOld = 0;
                //					$MyXNineOld = 0;
                $EndQualified = false;
                $MyGroupStartPos = $CurrentRow;
                //Carico l'ultimo punteggio per entrare
                // Vado a brancare la riga con l'ultimo Score buono
                if (safe_num_rows($Rs) > $MyGroupStartPos + $MyRow->QualifiedNo) {
                    safe_data_seek($Rs, $MyGroupStartPos + $MyRow->QualifiedNo - 1);
                    $tmpMyRow = safe_fetch($Rs);
                    if ($CurGroup == $tmpMyRow->EventCode) {
                        $MyEndScore = $tmpMyRow->QuScore;
                        $tmpMyRow = safe_fetch($Rs);
                        //Controllo se c'è parimerito per entrare
                        if ($MyEndScore != $tmpMyRow->QuScore || $CurGroup != $tmpMyRow->EventCode) {
                            $MyEndScore *= -1;
                        }
                    } else {
                        $MyEndScore = -1;
                    }
                    $tmpMyRow = NULL;
                } else {
                    safe_data_seek($Rs, safe_num_rows($Rs) - 1);
                    $tmpMyRow = safe_fetch($Rs);
                    $MyEndScore = -1;
                }
                safe_data_seek($Rs, $MyGroupStartPos + 1);
            }
            $MyRank = $MyRow->IndRank;
            //$MyPos++;
            // Se non ho parimerito il ranking è uguale alla posizione
            //				if($MyEndScore == $MyRow->QuScore)  //Spareggio
            //				{
            //					if ($MyRow->QuScore!=$MyScoreOld)
            //						$MyRank = $MyPos;
            //				}
            //				else
            //				{
            //					if (!($MyRow->QuScore==$MyScoreOld && $MyRow->QuGold==$MyGoldOld && $MyRow->QuXnine==$MyXNineOld))
            //						$MyRank = $MyPos;
            //				}
            if ($MyRank > $MyRow->QualifiedNo && !$EndQualified) {
                $EndQualified = true;
            }
            //				$MyScoreOld = $MyRow->QuScore;
            //				$MyGoldOld = $MyRow->QuGold;
            //				$MyXNineOld = $MyRow->QuXnine;
            // qui butto fuori la riga
            $cols = array();
            $cols[] = 7;
            $cols[] = $MyRow->Bib;
            $cols[] = $MyRow->DivCode;
            $cols[] = $MyRow->ClassCode;
            $cols[] = $MyRow->Name;
            $cols[] = $MyRow->NationCode;
            $cols[] = $MyRow->EventCode;
            $cols[] = $MyRow->Score1;
            $cols[] = $MyRow->Gold1;
            $cols[] = $MyRow->Xnine1;
            $cols[] = $MyRow->Score2;
            $cols[] = $MyRow->Gold2;
            $cols[] = $MyRow->Xnine2;
            $cols[] = $MyRow->EnCtrlCode;
            //$cols[]=($MyRow->IndRank==0 ? $MyRank : $MyRow->IndRank);
            $cols[] = $MyRank;
            $cols[] = $MyRow->EnStatus;
            for ($i = 1; $i <= $NumDist; ++$i) {
                $cols[] = $MyRow->{'QuD' . $i . 'Score'};
                $cols[] = $MyRow->{'QuD' . $i . 'Gold'};
                $cols[] = $MyRow->{'QuD' . $i . 'Xnine'};
                $c = array();
                $v = $MyRow->{'Arrowstring' . $i};
                for ($k = 0; $k < strlen($v); ++$k) {
                    $c[] = DecodeFromLetter($v[$k]);
                }
                $cols[] = implode(',', $c);
            }
            $c = array();
            $v = $MyRow->ArrowstringTie;
            for ($k = 0; $k < strlen($v); ++$k) {
                $c[] = DecodeFromLetter($v[$k]);
            }
            $cols[] = implode(',', $c);
            $StrData .= join(';', $cols) . "\n";
        }
    }
    /*
     * Tipo 8: Assoluti a squadre
     * CodiceSocieta-Evento-Totale1-ori1-X1-Totale2-Ori2-X2-PosizioneClassifica-MatricolaPartecipanti(in lista)
     */
    /*$MyQuery = "SELECT EnCode,CoCode AS NationCode, TeSubTeam as SubTeam, CoName AS Nation, TeEvent, EvEventName, Quanti, EnFirstName as FirstName, EnName AS Name,  EnClass AS ClassCode, EnDivision AS DivCode,EnAgeClass as AgeClass,  EnSubClass as SubClass, sqY.QuantiPoss as NumGialli, (EvFinalFirstPhase*2) as QualifiedNo, EvQualPrintHead, ";
    		$MyQuery.= "QuScore, TeScore, TeRank, TeGold, TeXnine, TtGolds, TtXNine, ";
    		if ($ToType==8)
    		{
    			$MyQuery .= "(QuD1Score+QuD2Score) AS Score1, "
    				. "(QuD1Gold+QuD2Gold) AS Gold1, "
    				. "(QuD1Xnine+QuD2Xnine) AS Xnine1, "
    				. "(QuD3Score+QuD4Score) AS Score2, "
    				. "(QuD3Gold+QuD4Gold) AS Gold2, "
    				. "(QuD3Xnine+QuD4Xnine) AS Xnine2 ";
    		}
    		else if ($ToType==10 || $ToType==12 || $ToType==13)
    		{
    			$MyQuery .= "(QuD1Score) AS Score1, "
    				. "(QuD1Gold) AS Gold1, "
    				. "(QuD1Xnine) AS Xnine1, "
    				. "(QuD2Score) AS Score2, "
    				. "(QuD2Gold) AS Gold2, "
    				. "(QuD2Xnine) AS Xnine2 ";
    		}
    		else
    		{
    			$MyQuery .= "(QuD1Score+QuD2Score+QuD3Score+QuD4Score) AS Score1, "
    				. "(QuD1Gold+QuD2Gold+QuD3Gold+QuD4Gold) AS Gold1, "
    				. "(QuD1Xnine+QuD2Xnine+QuD3Xnine+QuD4Xnine) AS Xnine1, "
    				. "(QuD5Score+QuD6Score+QuD7Score+QuD8Score) AS Score2, "
    				. "(QuD5Gold+QuD6Gold+QuD7Gold+QuD8Gold) AS Gold2, "
    				. "(QuD5Xnine+QuD6Xnine+QuD7Xnine+QuD8Xnine) AS Xnine2 ";
    		}
    		$MyQuery.= "FROM Tournament AS t ";
    		$MyQuery.= "INNER JOIN Tournament*Type AS tt ON t.ToType=tt.TtId ";
    		$MyQuery.= "INNER JOIN Teams AS te ON t.ToId=te.TeTournament AND te.TeFinEvent=1 ";
    		$MyQuery.= "INNER JOIN Countries AS c ON te.TeCoId=c.CoId AND te.TeTournament=c.CoTournament ";
    		$MyQuery.= "INNER JOIN Events AS ev ON te.TeEvent=ev.EvCode AND t.ToId=ev.EvTournament AND EvTeamEvent=1 ";
    		$MyQuery.= "INNER JOIN (SELECT TcCoId, TcSubTeam, TcEvent, TcTournament, TcFinEvent, COUNT(TcId) as Quanti FROM TeamComponent GROUP BY TcCoId, TcSubTeam, TcEvent, TcTournament) AS sq ON te.TeCoId=sq.TcCoId AND te.TeSubTeam=sq.TcSubTeam AND te.TeEvent=sq.TcEvent AND te.TeTournament=sq.TcTournament AND te.TeFinEvent=sq.TcFinEvent ";
    		$MyQuery.= "INNER JOIN TeamComponent AS tc ON te.TeCoId=tc.TcCoId AND te.TeSubTeam=tc.TcSubTeam AND  te.TeEvent=tc.TcEvent AND te.TeTournament=tc.TcTournament AND te.TeFinEvent=tc.TcFinEvent ";
    		$MyQuery.= "INNER JOIN Entries AS en ON tc.TcId=en.EnId ";
    		$MyQuery.= "INNER JOIN Qualifications AS q ON en.EnId=q.QuId ";
    		//Contatori per Coin toss  & Spareggi
    		$MyQuery .= "INNER JOIN (SELECT Count(*) as QuantiPoss, EvCode as SubCode, TeScore AS Score, TeGold AS Gold, TeXnine AS XNine "
    			. "FROM  Teams "
    			. "INNER JOIN Events ON TeEvent=EvCode AND TeTournament=EvTournament AND EvTeamEvent=1 "
    			. "WHERE TeTournament = " . StrSafe_DB($_SESSION['TourId']) . " "
    			. "GROUP BY TeScore, EvCode, TeGold, TeXnine) AS sqY ON sqY.Score=te.TeScore AND sqY.Gold=te.TeGold AND sqY.Xnine=te.TeXnine AND ev.EvCode=sqY.SubCode ";
    		//Where Normale
    		$MyQuery.= "WHERE ToId = " . StrSafe_DB($_SESSION['TourId']) . " ";
    		//if(isset($_REQUEST["Definition"]))
    		//	$MyQuery .= "AND te.TeEvent LIKE " . StrSafe_DB($_REQUEST["Definition"]) . " ";
    		$MyQuery.= "ORDER BY EvProgr,TeEvent, TeScore DESC, TeGold DESC, TeXnine DESC, TeRank, NationCode, SubTeam, TcOrder ";*/
    $MyQuery = "SELECT EnCode,CoCode AS NationCode, TeSubTeam as SubTeam, CoName AS Nation, TeEvent, EvEventName, Quanti, EnFirstName as FirstName, EnName AS Name,  EnClass AS ClassCode, EnDivision AS DivCode,EnAgeClass as AgeClass,  EnSubClass as SubClass, sqY.QuantiPoss as NumGialli, (EvFinalFirstPhase*2) as QualifiedNo, EvQualPrintHead, ";
    $MyQuery .= "QuScore, TeScore, TeRank, TeGold, TeXnine, ToGolds AS TtGolds, ToXNine AS TtXNine, ";
    if ($ToType == 8) {
        $MyQuery .= "(QuD1Score+QuD2Score) AS Score1, " . "(QuD1Gold+QuD2Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine) AS Xnine1, " . "(QuD3Score+QuD4Score) AS Score2, " . "(QuD3Gold+QuD4Gold) AS Gold2, " . "(QuD3Xnine+QuD4Xnine) AS Xnine2 ";
    } else {
        if ($ToType == 10 || $ToType == 12 || $ToType == 13) {
            $MyQuery .= "(QuD1Score) AS Score1, " . "(QuD1Gold) AS Gold1, " . "(QuD1Xnine) AS Xnine1, " . "(QuD2Score) AS Score2, " . "(QuD2Gold) AS Gold2, " . "(QuD2Xnine) AS Xnine2 ";
        } else {
            $MyQuery .= "(QuD1Score+QuD2Score+QuD3Score+QuD4Score) AS Score1, " . "(QuD1Gold+QuD2Gold+QuD3Gold+QuD4Gold) AS Gold1, " . "(QuD1Xnine+QuD2Xnine+QuD3Xnine+QuD4Xnine) AS Xnine1, " . "(QuD5Score+QuD6Score+QuD7Score+QuD8Score) AS Score2, " . "(QuD5Gold+QuD6Gold+QuD7Gold+QuD8Gold) AS Gold2, " . "(QuD5Xnine+QuD6Xnine+QuD7Xnine+QuD8Xnine) AS Xnine2 ";
        }
    }
    $MyQuery .= "FROM Tournament AS t ";
    $MyQuery .= "INNER JOIN Teams AS te ON t.ToId=te.TeTournament AND te.TeFinEvent=1 ";
    $MyQuery .= "INNER JOIN Countries AS c ON te.TeCoId=c.CoId AND te.TeTournament=c.CoTournament ";
    $MyQuery .= "INNER JOIN Events AS ev ON te.TeEvent=ev.EvCode AND t.ToId=ev.EvTournament AND EvTeamEvent=1 ";
    $MyQuery .= "INNER JOIN (SELECT TcCoId, TcSubTeam, TcEvent, TcTournament, TcFinEvent, COUNT(TcId) as Quanti FROM TeamComponent GROUP BY TcCoId, TcSubTeam, TcEvent, TcTournament) AS sq ON te.TeCoId=sq.TcCoId AND te.TeSubTeam=sq.TcSubTeam AND te.TeEvent=sq.TcEvent AND te.TeTournament=sq.TcTournament AND te.TeFinEvent=sq.TcFinEvent ";
    $MyQuery .= "INNER JOIN TeamComponent AS tc ON te.TeCoId=tc.TcCoId AND te.TeSubTeam=tc.TcSubTeam AND  te.TeEvent=tc.TcEvent AND te.TeTournament=tc.TcTournament AND te.TeFinEvent=tc.TcFinEvent ";
    $MyQuery .= "INNER JOIN Entries AS en ON tc.TcId=en.EnId ";
    $MyQuery .= "INNER JOIN Qualifications AS q ON en.EnId=q.QuId ";
    //Contatori per Coin toss  & Spareggi
    $MyQuery .= "INNER JOIN (SELECT Count(*) as QuantiPoss, EvCode as SubCode, TeScore AS Score, TeGold AS Gold, TeXnine AS XNine " . "FROM  Teams " . "INNER JOIN Events ON TeEvent=EvCode AND TeTournament=EvTournament AND EvTeamEvent=1 " . "WHERE TeTournament = " . StrSafe_DB($_SESSION['TourId']) . " " . "GROUP BY TeScore, EvCode, TeGold, TeXnine) AS sqY ON sqY.Score=te.TeScore AND sqY.Gold=te.TeGold AND sqY.Xnine=te.TeXnine AND ev.EvCode=sqY.SubCode ";
    //Where Normale
    $MyQuery .= "WHERE ToId = " . StrSafe_DB($_SESSION['TourId']) . " ";
    //if(isset($_REQUEST["Definition"]))
    //	$MyQuery .= "AND te.TeEvent LIKE " . StrSafe_DB($_REQUEST["Definition"]) . " ";
    $MyQuery .= "ORDER BY EvProgr,TeEvent, TeScore DESC, TeGold DESC, TeXnine DESC, TeRank, NationCode, SubTeam, TcOrder ";
    //print $MyQuery;exit;
    $Rs = safe_r_sql($MyQuery);
    if ($Rs && safe_num_rows($Rs) > 0) {
        $CurGroup = "....";
        $CurTeam = "";
        // Variabili per la gestione del ranking
        //$MyRank = 1;
        //$MyPos = 0;
        $EndQualified = false;
        // Variabili che contengono i punti del precedente atleta per la gestione del rank
        //			$MyScoreOld = 0;
        //			$MyGoldOld = 0;
        //			$MyXNineOld = 0;
        $MyEndScore = -1;
        $MyGroupStartPos = 0;
        $CurrentRow = -1;
        $cols = array();
        $tmpMatr = array();
        $score1 = 0;
        $score2 = 0;
        $gold1 = 0;
        $gold2 = 0;
        $x1 = 0;
        $x2 = 0;
        while ($MyRow = safe_fetch($Rs)) {
            $CurrentRow++;
            if ($CurGroup != $MyRow->TeEvent) {
                $CurGroup = $MyRow->TeEvent;
                //					$MyRank = 1;
                //					$MyPos = 0;
                //					$MyScoreOld = 0;
                //					$MyGoldOld = 0;
                //					$MyXNineOld = 0;
                $EndQualified = false;
                $MyGroupStartPos = $CurrentRow;
                if (safe_num_rows($Rs) > $MyGroupStartPos + $MyRow->QualifiedNo * $MyRow->Quanti) {
                    safe_data_seek($Rs, $MyGroupStartPos + ($MyRow->QualifiedNo - 1) * $MyRow->Quanti);
                    $tmpMyRow = safe_fetch($Rs);
                    if ($CurGroup == $tmpMyRow->TeEvent) {
                        $MyEndScore = $tmpMyRow->TeScore;
                        safe_data_seek($Rs, $MyGroupStartPos + $MyRow->QualifiedNo * $MyRow->Quanti);
                        $tmpMyRow = safe_fetch($Rs);
                        //Controllo se c'è parimerito per entrare
                        if ($MyEndScore != $tmpMyRow->TeScore || $CurGroup != $tmpMyRow->TeEvent) {
                            $MyEndScore *= -1;
                        }
                    } else {
                        $MyEndScore = -1;
                    }
                    $tmpMyRow = NULL;
                } else {
                    safe_data_seek($Rs, safe_num_rows($Rs) - 1);
                    $tmpMyRow = safe_fetch($Rs);
                    $MyEndScore = -1;
                }
                safe_data_seek($Rs, $MyGroupStartPos + 1);
                //$CurTeam = "";
            }
            if ($CurTeam != $MyRow->NationCode . "|" . $MyRow->TeEvent) {
                if ($CurTeam != '') {
                    // sostituisco i punti nelle colonne generate in (*) più sotto
                    $cols[3] = $score1;
                    $cols[4] = $gold1;
                    $cols[5] = $x1;
                    $cols[6] = $score2;
                    $cols[7] = $gold2;
                    $cols[8] = $x2;
                    $StrData .= implode(';', $cols) . ';' . implode(';', $tmpMatr) . "\n";
                    /*print '<pre>';
                    		print_r($cols);
                    		print_r($tmpMatr);
                    		print '</pre>';*/
                    $cols = array();
                    $tmpMatr = array();
                    $score1 = 0;
                    $score2 = 0;
                    $gold1 = 0;
                    $gold2 = 0;
                    $x1 = 0;
                    $x2 = 0;
                }
                $MyPos++;
                $MyRank = $MyRow->TeRank;
                // Se non ho parimerito il ranking è uguale alla posizione
                //					if($MyEndScore == $MyRow->TeScore)  //Spareggio
                //					{
                //						if ($MyRow->QuScore!=$MyScoreOld)
                //							$MyRank = $MyPos;
                //					}
                //					else
                //					{
                //						if (!($MyRow->TeScore==$MyScoreOld && $MyRow->TeGold==$MyGoldOld && $MyRow->TeXnine==$MyXNineOld))
                //							$MyRank = $MyPos;
                //					}
                if ($MyRank > $MyRow->QualifiedNo && !$EndQualified) {
                    $EndQualified = true;
                }
                $cols[] = 8;
                $cols[] = $MyRow->NationCode;
                $cols[] = $MyRow->TeEvent;
                // colonne (*)
                $cols[] = 0;
                $cols[] = 0;
                $cols[] = 0;
                $cols[] = 0;
                $cols[] = 0;
                $cols[] = 0;
                // fine colonne (*)
                //$cols[]=($MyRow->TeRank==0 ? $MyRank : $MyRow->TeRank);
                $cols[] = $MyRank;
            }
            $tmpMatr[] = $MyRow->EnCode;
            $score1 += $MyRow->Score1;
            $score2 += $MyRow->Score2;
            $gold1 += $MyRow->Gold1;
            $gold2 += $MyRow->Gold2;
            $x1 += $MyRow->Xnine1;
            $x2 += $MyRow->Xnine2;
            //				$MyScoreOld = $MyRow->TeScore;
            //				$MyGoldOld = $MyRow->TeGold;
            //				$MyXNineOld = $MyRow->TeXnine;
            $CurTeam = $MyRow->NationCode . "|" . $MyRow->TeEvent;
        }
        // ultima
        $cols[3] = $score1;
        $cols[4] = $gold1;
        $cols[5] = $x1;
        $cols[6] = $score2;
        $cols[7] = $gold2;
        $cols[8] = $x2;
        $StrData .= implode(';', $cols) . ';' . implode(';', $tmpMatr) . "\n";
        /*print '<pre>';
        		print_r($cols);
        		print_r($tmpMatr);
        		print '</pre>';*/
    }
    /*
     * Tipo 99: Verbale arbitri
     * Domanda - Risposte
     */
    /*$MyQuery = "SELECT '99' AS RowType, FraQuestion, REPLACE(FraAnswer,';','\";\"') AS Ans "
    		. "FROM FinalReportQ "
    		. "INNER JOIN Tournament ON ToId=" . StrSafe_DB($_SESSION['TourId']) . " "
    		. "INNER JOIN Tournament*Type ON TtId=ToType "
    		. "LEFT JOIN FinalReportA ON FrqId=FraQuestion AND FraTournament=ToId "
    		. "WHERE (FrqStatus & TtCategory) > 0 AND FraQuestion IS NOT NULL "
    		. "ORDER BY FrqId";*/
    $MyQuery = "SELECT '99' AS RowType, FraQuestion, REPLACE(FraAnswer,';','\";\"') AS Ans " . "FROM FinalReportQ " . "INNER JOIN Tournament ON ToId=" . StrSafe_DB($_SESSION['TourId']) . " " . "LEFT JOIN FinalReportA ON FrqId=FraQuestion AND FraTournament=ToId " . "WHERE (FrqStatus & ToCategory) > 0 AND FraQuestion IS NOT NULL " . "ORDER BY FrqId";
    //print $MyQuery;exit;
    $Rs = safe_r_sql($MyQuery);
    if (safe_num_rows($Rs) > 0) {
        while ($MyRow = safe_fetch($Rs)) {
            $cols = array();
            $cols[] = $MyRow->RowType;
            $cols[] = $MyRow->FraQuestion;
            $cols[] = $MyRow->Ans;
            $StrData .= join(';', $cols) . "\n";
        }
    }
    //exit;
    return array($StrData, $ToCode);
}
 /**
  * read()
  *
  * @Override
  *
  * (non-PHPdoc)
  * @see ianseo/Common/Rank/Obj_Rank#read()
  */
 public function read()
 {
     $f = $this->safeFilterR();
     $filter = "";
     if ($f !== false) {
         $filter = $f;
     }
     if (array_key_exists('cutRank', $this->opts) && is_numeric($this->opts['cutRank']) && $this->opts['cutRank'] > 0) {
         $filter .= "AND IF(EvFinalFirstPhase=0, TeRank, TeRankFinal)<={$this->opts['cutRank']} ";
     }
     $EnFilter = empty($this->opts['enid']) ? '' : " AND EnId=" . intval($this->opts['enid']);
     $EnFilter .= empty($this->opts['coid']) ? '' : " AND EnCountry=" . intval($this->opts['coid']);
     $phases = null;
     /*
      * prima passata per costruire la struttura del vettore.
      * Tiro fuori le posizioni di qualifica e le posizioni finali con i nomi.
      * La query è divisa in due: la prima parte tira fuori le squadre che sono andate in finale
      * e la seconda quelle che si son fermate prima.
      * Devo far così perchè i nomi dei membri dei team provengono da due tabelle diverse.
      */
     $q = "\r\n\t\t\t/* parte delle finali */\r\n\t\t\t\t(\r\n\t\t\t\t\tSELECT 1,\r\n\t\t\t\t\t\tCoId, TeSubTeam, CoCode, CoName,\r\n\t\t\t\t\t\tEvProgr, TeEvent, EvEventName, EvMaxTeamPerson,\r\n\t\t\t\t\t\tEvFinalPrintHead as PrintHeader,\r\n\t\t\t\t\t\tEvFinalFirstPhase, EvMatchMode, EvMedals,\r\n\t\t\t\t\t\tEnId,EnCode,EnFirstName,upper(EnFirstName) EnFirstNameUpper,EnName,tc.TfcOrder AS personOrder,\r\n\t\t\t\t\t\tTeRank as QualRank, IF(EvFinalFirstPhase=0, TeRank, TeRankFinal) as FinalRank, TeScore,\r\n\t\t\t\t\t\tTeTimestamp,TeTimestampFinal/*,'0' AS rowType*/\r\n\t\t\t\t\tFROM\r\n\t\t\t\t\t\tTournament\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tTeams\r\n\t\t\t\t\t\tON ToId=TeTournament AND TeFinEvent=1\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tCountries\r\n\t\t\t\t\t\tON TeCoId=CoId AND TeTournament=CoTournament\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tTeamFinComponent AS tc\r\n\t\t\t\t\t\tON Teams.TeCoId=tc.TfcCoId AND Teams.TeSubTeam=tc.TfcSubTeam AND  Teams.TeEvent=tc.TfcEvent AND Teams.TeTournament=tc.TfcTournament AND Teams.TeFinEvent=1\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tEntries\r\n\t\t\t\t\t\tON TfcId=EnId\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tEvents\r\n\t\t\t\t\t\tON TeEvent=EvCode AND ToId=EvTournament AND EvTeamEvent=1\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tIF(EvFinalFirstPhase=0, TeRank, TeRankFinal)<=(EvFinalFirstPhase*2) AND TeScore != 0 AND ToId = {$this->tournament}\r\n\t\t\t\t\t\t{$filter}\r\n\t\t\t\t\t\t{$EnFilter}\r\n\r\n\t\t\t\t)\r\n\t\t\t\tUNION ALL\r\n\t\t\t\t(\r\n\t\t\t\t\tSELECT 2,\r\n\t\t\t\t\t\tCoId,TeSubTeam,CoCode,CoName,\r\n\t\t\t\t\t\tEvProgr,TeEvent,EvEventName,EvMaxTeamPerson,\r\n\t\t\t\t\t\tEvFinalPrintHead as PrintHeader,\r\n\t\t\t\t\t\tEvFinalFirstPhase,EvMatchMode,EvMedals,\r\n\t\t\t\t\t\tEnId,EnCode,EnFirstName,upper(EnFirstName) EnFirstNameUpper,EnName,tc.TcOrder,\r\n\t\t\t\t\t\tTeRank as QualRank, IF(EvFinalFirstPhase=0, TeRank, TeRankFinal) as FinalRank, TeScore,\r\n\t\t\t\t\t\tTeTimestamp,TeTimestampFinal\r\n\t\t\t\t\tFROM\r\n\t\t\t\t\t\tTournament\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tTeams\r\n\t\t\t\t\t\tON ToId=TeTournament AND TeFinEvent=1\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tCountries\r\n\t\t\t\t\t\tON TeCoId=CoId AND TeTournament=CoTournament\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tTeamComponent AS tc\r\n\t\t\t\t\t\tON Teams.TeCoId=tc.TcCoId AND Teams.TeSubTeam=tc.TcSubTeam AND  Teams.TeEvent=tc.TcEvent AND Teams.TeTournament=tc.TcTournament AND Teams.TeFinEvent=tc.TcFinEvent AND Teams.TeFinEvent=1\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tEntries\r\n\t\t\t\t\t\tON TcId=EnId\r\n\r\n\t\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\t\tEvents\r\n\t\t\t\t\t\tON TeEvent=EvCode AND ToId=EvTournament AND EvTeamEvent=1\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tIF(EvFinalFirstPhase=0, TeRank, TeRankFinal)>(EvFinalFirstPhase*2)  AND TeScore != 0 AND ToId = {$this->tournament}\r\n\t\t\t\t\t\t/*AND CONCAT(TeCoId,'_',TeSubTeam) NOT IN (SELECT DISTINCT CONCAT(TfTeam,'_',TfSubTeam) FROM TeamFinals WHERE TfTournament={$this->tournament})*/\r\n\t\t\t\t\t\t{$filter}\r\n\t\t\t\t\t\t{$EnFilter}\r\n\t\t\t\t)\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\tEvProgr, TeEvent,/*rowType ASC,*/ FinalRank ASC, CoCode ASC, TeSubTeam, personOrder ASC, EnFirstName, EnName\r\n\t\t\t";
     //			print $q;exit;
     //			debug_svela($q, true);
     $r = safe_r_sql($q);
     $this->data['meta']['title'] = get_text('TeamFinEvent', 'Tournament');
     $this->data['meta']['lastUpdate'] = '0000-00-00 00:00:00';
     $this->data['sections'] = array();
     $myEv = '';
     $myTeam = '';
     if (safe_num_rows($r) > 0) {
         $section = null;
         while ($myRow = safe_fetch($r)) {
             if ($myEv != $myRow->TeEvent) {
                 if ($myEv != '') {
                     $this->data['sections'][$myEv] = $section;
                     $section = null;
                 }
                 $myEv = $myRow->TeEvent;
                 $phases = getPhasesId($myRow->EvFinalFirstPhase);
                 $fields = array('id' => 'Id', 'countryCode' => '', 'countryName' => get_text('Country'), 'subteam' => get_text('PartialTeam'), 'athletes' => array('name' => get_text('Name', 'Tournament'), 'fields' => array('id' => 'Id', 'bib' => get_text('Code', 'Tournament'), 'athlete' => get_text('Athlete'), 'familyname' => get_text('FamilyName', 'Tournament'), 'givenname' => get_text('Name', 'Tournament'))), 'qualRank' => get_text('RankScoreShort'), 'qualScore' => get_text('PositionShort'), 'rank' => get_text('PositionShort'), 'finals' => array());
                 foreach ($phases as $k => $v) {
                     if ($v <= valueFirstPhase($myRow->EvFinalFirstPhase)) {
                         $fields['finals'][$v] = get_text(namePhase($myRow->EvFinalFirstPhase, $v) . "_Phase");
                     }
                 }
                 $fields['finals']['fields'] = array('score' => get_text('TotalShort', 'Tournament'), 'setScore' => get_text('SetTotal', 'Tournament'), 'setPoints' => get_text('SetPoints', 'Tournament'), 'tie' => 'S.O.', 'arrowstring' => get_text('Arrows', 'Tournament'), 'tiebreak' => get_text('TieArrows'));
                 $section = array('meta' => array('event' => $myEv, 'descr' => get_text($myRow->EvEventName, '', '', true), 'printHeader' => get_text($myRow->PrintHeader, '', '', true), 'firstPhase' => $myRow->EvFinalFirstPhase, 'matchMode' => $myRow->EvMatchMode, 'maxTeamPerson' => $myRow->EvMaxTeamPerson, 'order' => $myRow->EvProgr, 'lastUpdate' => '0000-00-00 00:00:00', 'fields' => $fields, 'medals' => $myRow->EvMedals), 'items' => array());
             }
             if ($myTeam != $myRow->CoId . $myRow->TeSubTeam . $myRow->TeEvent) {
                 $item = array('id' => $myRow->CoId, 'countryCode' => $myRow->CoCode, 'countryName' => $myRow->CoName, 'subteam' => $myRow->TeSubTeam, 'athletes' => array(), 'qualScore' => $myRow->TeScore, 'qualRank' => $myRow->QualRank, 'rank' => $myRow->FinalRank == 9999 ? 'DSQ' : $myRow->FinalRank, 'finals' => array());
                 $section['items'][$myRow->CoId . '_' . $myRow->TeSubTeam] = $item;
                 if ($myRow->TeTimestampFinal > $section['meta']['lastUpdate']) {
                     $section['meta']['lastUpdate'] = $myRow->TeTimestampFinal;
                 }
                 if ($myRow->TeTimestampFinal > $this->data['meta']['lastUpdate']) {
                     $this->data['meta']['lastUpdate'] = $myRow->TeTimestampFinal;
                 }
                 $myTeam = $myRow->CoId . $myRow->TeSubTeam . $myRow->TeEvent;
             }
             if (!array_key_exists('components', $this->opts) || $this->opts['components']) {
                 $athlete = array('id' => $myRow->EnId, 'bib' => $myRow->EnCode, 'athlete' => $myRow->EnFirstNameUpper . ' ' . $myRow->EnName, 'familyname' => $myRow->EnFirstName, 'familynameUpper' => $myRow->EnFirstNameUpper, 'givenname' => $myRow->EnName);
                 //$section['items'][count($section['items'])-1]['athletes'][]=$athlete;
                 $section['items'][$myRow->CoId . '_' . $myRow->TeSubTeam]['athletes'][] = $athlete;
             }
         }
         // ultimo giro
         $this->data['sections'][$myEv] = $section;
     }
     //	print count($this->data['sections']['OLMT']['items']);exit;
     /*
      * A questo punto ho i nomi e le qualifiche
      * e punti+rank delle precedenti.
      * Mi mancano le finali.
      *
      */
     $q = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tf1.TfEvent AS `event`,CONCAT(f1.TfTeam,'_',f1.TfSubTeam) AS `athlete`,f1.TfMatchNo AS `matchNo`,f1.TfScore AS `score`,f1.TfSetScore AS `setScore`,f1.TfSetPoints AS `setPoints`,f1.TfTie AS `tie`,f1.TfArrowstring AS `arrowstring`,f1.TfTiebreak AS `tiebreak`,\r\n\t\t\t\t\tCONCAT(f2.TfTeam,'_',f2.TfSubTeam) AS `oppAthlete`,f2.TfMatchNo AS `oppMatchNo`,f2.TfScore AS `oppScore`,f2.TfSetScore AS `oppSetScore`,f2.TfSetPoints AS `oppSetPoints`,f2.TfTie AS `oppTie`,f2.TfArrowstring AS `oppArrowstring`,f2.TfTiebreak AS `oppTiebreak`,\r\n\t\t\t\t\tGrPhase, EvMaxTeamPerson\r\n\t\t\t\tFROM\r\n\t\t\t\t\tTeams\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tTeamFinals AS f1\r\n\t\t\t\t\tON TeTournament=f1.TfTournament AND TeEvent=f1.TfEvent AND CONCAT(TeCoId,'_',TeSubTeam)=CONCAT(f1.TfTeam,'_',f1.TfSubTeam)\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tTeamFinals AS f2\r\n\t\t\t\t\tON f1.TfEvent=f2.TfEvent AND f1.TfMatchNo=IF((f1.TfMatchNo % 2)=0,f2.TfMatchNo-1,f2.TfMatchNo+1) AND f1.TfTournament=f2.TfTournament\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tGrids\r\n\t\t\t\t\tON f1.TfMatchNo=GrMatchNo\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tEvents\r\n\t\t\t\t\tON f1.TfTournament=EvTournament AND f1.TfEvent=EvCode AND EvTeamEvent=1\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tf1.TfTournament={$this->tournament}\r\n\t\t\t\t\t{$filter}\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\tEvProgr ASC,EvCode,TeRankFinal ASC,GrPhase DESC\r\n\t\t\t";
     $rr = safe_r_sql($q);
     if (safe_num_rows($rr) > 0) {
         while ($row = safe_fetch($rr)) {
             $arrowstring = array();
             for ($i = 0; $i < strlen($row->arrowstring); ++$i) {
                 if (trim($row->arrowstring[$i]) != '') {
                     $arrowstring[] = DecodeFromLetter($row->arrowstring[$i]);
                 }
             }
             $tiebreak = array();
             for ($i = 0; $i < strlen($row->tiebreak); ++$i) {
                 if (trim($row->tiebreak[$i]) != '') {
                     $tiebreak[] = DecodeFromLetter($row->tiebreak[$i]);
                 }
             }
             $oppArrowstring = array();
             for ($i = 0; $i < strlen($row->oppArrowstring); ++$i) {
                 if (trim($row->oppArrowstring[$i]) != '') {
                     $oppArrowstring[] = DecodeFromLetter($row->oppArrowstring[$i]);
                 }
             }
             $oppTiebreak = array();
             for ($i = 0; $i < strlen($row->oppTiebreak); ++$i) {
                 if (trim($row->oppTiebreak[$i]) != '') {
                     $oppTiebreak[] = DecodeFromLetter($row->oppTiebreak[$i]);
                 }
             }
             $tmpArr = array();
             $oppArr = array();
             if ($row->tiebreak) {
                 for ($countArr = 0; $countArr < strlen(trim($row->tiebreak)); $countArr += $row->EvMaxTeamPerson) {
                     $tmp = ValutaArrowString(substr(trim($row->tiebreak), $countArr, $row->EvMaxTeamPerson));
                     if (!ctype_upper(trim($row->tiebreak))) {
                         $tmp .= "*";
                     }
                     $tmpArr[] = $tmp;
                 }
                 //debug_svela($myRow);
             }
             if ($row->oppTiebreak) {
                 for ($countArr = 0; $countArr < strlen(trim($row->oppTiebreak)); $countArr += $row->EvMaxTeamPerson) {
                     $tmp = ValutaArrowString(substr(trim($row->oppTiebreak), $countArr, $row->EvMaxTeamPerson));
                     if (!ctype_upper(trim($row->oppTiebreak))) {
                         $tmp .= "*";
                     }
                     $oppArr[] = $tmp;
                 }
             }
             if (isset($this->data['sections'][$row->event]['items'][$row->athlete]['finals'])) {
                 $this->data['sections'][$row->event]['items'][$row->athlete]['finals'][$row->GrPhase] = array('score' => $row->score, 'setScore' => $row->setScore, 'setPoints' => $row->setPoints, 'tie' => $row->tie, 'arrowstring' => implode('|', $arrowstring), 'tiebreak' => implode('|', $tiebreak), 'tiebreakDecoded' => implode(',', $tmpArr), 'oppAthlete' => $row->oppAthlete, 'oppScore' => $row->oppScore, 'oppSetScore' => $row->oppSetScore, 'oppSetPoints' => $row->oppSetPoints, 'oppTie' => $row->oppTie, 'oppArrowstring' => implode('|', $oppArrowstring), 'oppTiebreak' => implode('|', $oppTiebreak), 'oppTiebreakDecoded' => implode(',', $oppArr));
             }
         }
     }
 }
 //print $Select . '<br><br>';
 $StrValue = '';
 if (safe_num_rows($Rs) > 0) {
     $obj = getEventArrowsParams($_REQUEST['d_Event'], $CurPhase, 0);
     $Bottone = '<input type="button" name="CmdBlockPhase_' . $CurPhase . '" id="CmdBlockPhase_' . $CurPhase . '" value="' . get_text('CmdEnable') . '" onClick="javascript:BlockPhase(' . $CurPhase . ',\'' . get_text('CmdEnable') . '\',\'' . get_text('CmdDisable') . '\',' . $obj->so . ');">';
     // righe di testa della fase
     for ($i = 0; $i <= $HeadRows + 2; ++$i) {
         // se sto stampando l'ultima riga di testa scrivo la fase
         //$MyGrid[$Row++][$Col].= '<td  nowrap class="Center" colspan="5">' . ($i==$HeadRows ? get_text($CurPhase . '_Phase') : '&nbsp;') . '</td>';
         $Txt = '';
         if ($i == 1) {
             $Txt = '<th nowrap class="Center" colspan="5">' . get_text(namePhase($StartPhase, $CurPhase) . '_Phase') . '</th>';
         } elseif ($i == 2) {
             $Txt = '<td  nowrap class="Center" colspan="5">' . $Bottone . '</td>';
         } elseif ($i == $HeadRows + 2) {
             $Txt = '<td  nowrap class="Center" colspan="5">' . get_text(namePhase($StartPhase, $CurPhase) . '_Phase') . '</td>';
         } else {
             $Txt = '<td  nowrap class="Center" colspan="5">&nbsp;</td>';
         }
         $MyGrid[$Row++][$Col] .= $Txt;
     }
     while ($MyRow = safe_fetch($Rs)) {
         $obj = getEventArrowsParams($MyRow->FinEvent, $MyRow->GrPhase, 0);
         if (!isFirstPhase($StartPhase, $MyRow->GrPhase)) {
             $TipoBordo = $Ultima % 2 == 0 ? 'Bottom' : '';
             $MyGrid[$Row][$Col] .= '<td  nowrap class="Center ' . $TipoBordo . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>';
         }
         if (isFirstPhase($StartPhase, $MyRow->GrPhase)) {
             // Posizione
             $MyGrid[$Row][$Col] .= '<td nowrap class="' . ($AthPrinted == 1 ? 'Bottom ' : '') . 'Top Right Left">' . $MyRow->GrPosition . '</td>';
         }
Exemple #11
0
    echo '<td colspan="2">' . $SesNames[$i] . '</td>';
    echo '</tr>';
    $listCodes[] = StrSafe_DB($tmpCode);
}
// Finali
$Select = "SELECT DISTINCT CONCAT(FSScheduledDate,' ',FSScheduledTime) AS MyDate,FSTeamEvent " . "FROM FinSchedule " . "WHERE FSTournament=" . StrSafe_DB($_SESSION['TourId']) . " and FSScheduledDate>0 " . "ORDER BY FSTeamEvent ASC,CONCAT(FSScheduledDate,FSScheduledTime) ASC ";
$Select = 'SELECT' . ' @Phase:=ifnull(2*pow(2,truncate(log2(fsmatchno/2),0)),1) Phase' . ' , @RealPhase:=truncate(@Phase/2, 0) RealPhase' . ' , CONCAT(FSScheduledDate,\' \',FSScheduledTime) AS MyDate' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDBshort') . '") AS Dt ' . ' , DATE_FORMAT(FSScheduledDate,"' . get_text('DateFmtDB') . '") AS Dat ' . ' , FSTeamEvent ' . ' , FSEvent ' . ' , EvFinalFirstPhase ' . ' , FSScheduledTime ' . 'FROM' . ' `FinSchedule` fs ' . " inner join Events on FSEvent=EvCode and FSTeamEvent=EvTeamEvent and FsTournament=EvTournament " . 'where' . ' FsTournament=' . $_SESSION['TourId'] . ' and fsscheduleddate >0 ' . 'group by ' . ' FsScheduledDate, ' . ' FsScheduledTime, ' . ' FsEvent, ' . ' Phase';
$tmp = array();
$Rs = safe_r_sql($Select);
if (safe_num_rows($Rs) > 0) {
    while ($MyRow = safe_fetch($Rs)) {
        if ($tmpCode = phaseEncode($MyRow->FSTeamEvent, $MyRow->MyDate, 0)) {
            if (!in_array(StrSafe_DB($tmpCode), $listCodes)) {
                $listCodes[] = StrSafe_DB($tmpCode);
            }
            $tmp[$tmpCode]['events'][get_text(namePhase($MyRow->EvFinalFirstPhase, $MyRow->RealPhase) . '_Phase')][] = $MyRow->FSEvent;
            $tmp[$tmpCode]['date'] = $MyRow->Dt . ' ' . substr($MyRow->FSScheduledTime, 0, 5) . ' ' . ($MyRow->FSTeamEvent == 0 ? get_text('FinInd', 'HTT') : get_text('FinTeam', 'HTT'));
            //$tmp[$tmpCode]['selected']= isset($_REQUEST['x_Session']) && $_REQUEST['x_Session']==$val ? ' selected' : '';
        }
    }
    foreach ($tmp as $k => $v) {
        $val = array();
        foreach ($v['events'] as $ph => $ev) {
            $val[] = $ph . ' (' . implode('+', $ev) . ')';
        }
        //					$ComboSes.='<option value="'.$k.'"'.$v['selected'].'>'.$v['date']  . ' '. implode('; ',$val).'</option>';
        echo '<tr id="row_' . $k . '">';
        echo '<td class="Center">';
        if ($k && array_key_exists($k, $EventArray) && $EventArray[$k] != $_REQUEST['Id']) {
            echo "&nbsp;";
        } else {
Exemple #12
0
function getStatEntriesByEvent($ORIS = '')
{
    $Data = new StdClass();
    $Data->Code = 'C30A';
    $Data->Order = '2';
    $Data->Description = 'Number of Entries by Event';
    $Data->Continue = get_text('Continue');
    $Data->Data = array();
    if ($ORIS) {
        // Individuals
        $Data->Header = array("Event", "No. Athletes", "No. Countries", "No. Teams");
        $Data->HeaderWidth = array(60, 40, 40, 40);
        $MyQuery = getStatEntriesByEventQuery('IF');
        $Rs = safe_r_sql($MyQuery);
        while ($Row = safe_fetch($Rs)) {
            $Data->Data[$Row->Code] = array('Name' => $Row->EventName, 'Number' => $Row->Quanti, 'Countries' => $Row->Countries, 'Teams' => 0);
        }
        // Teams
        $Teams = array();
        $MyQuery = getStatEntriesByEventQuery('TF');
        $RsEv = safe_r_sql($MyQuery);
        while ($MyRowEv = safe_fetch($RsEv)) {
            $Sql = "SELECT DISTINCT EcCode, EcTeamEvent, EcNumber FROM EventClass WHERE EcCode=" . StrSafe_DB($MyRowEv->EvCode) . " AND EcTeamEvent!=0 AND EcTournament=" . StrSafe_DB($_SESSION['TourId']);
            $RsEc = safe_r_sql($Sql);
            if (safe_num_rows($RsEc) > 0) {
                $RuleCnt = 0;
                $Sql = "Select * ";
                while ($MyRowEc = safe_fetch($RsEc)) {
                    $ifc = ifSqlForCountry($MyRowEv->EvTeamCreationMode);
                    $Sql .= ++$RuleCnt == 1 ? "FROM " : "INNER JOIN ";
                    $Sql .= "(SELECT {$ifc} as C" . $RuleCnt . ", SUM(IF(EnSubTeam=0,1,0)) AS QuantiMulti\n\t\t\t\t\t  FROM Entries\n\t\t\t\t\t  INNER JOIN EventClass ON EnClass=EcClass AND EnDivision=EcDivision AND EnTournament=EcTournament AND EcTeamEvent=" . $MyRowEc->EcTeamEvent . " AND EcCode=" . StrSafe_DB($MyRowEc->EcCode) . "\n\t\t\t\t\t\t\t  WHERE {$ifc}<>0 AND EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EnTeam" . ($MyRowEv->EvMixedTeam ? 'Mix' : 'F') . "Event=1\n\t\t\t\t\t\t\t  \t\tgroup by {$ifc}, EnSubTeam\n\t\t\t\t\t\t\t  \t\tHAVING COUNT(EnId)>=" . $MyRowEc->EcNumber . ") as sqy";
                    $Sql .= $RuleCnt == 1 ? " " : $RuleCnt . " ON C1=C" . $RuleCnt . " ";
                }
                $Rs = safe_r_sql($Sql);
                $tmpQuanti = safe_num_rows($Rs);
                $Countries = $tmpQuanti;
                if ($MyRowEv->EvMultiTeam != 0) {
                    $tmpQuanti = 0;
                    while ($tmpRow = safe_fetch($Rs)) {
                        $Countries++;
                        $tmpQuanti += intval($tmpRow->QuantiMulti / $MyRowEv->EvMaxTeamPerson);
                    }
                }
                $tmpSaved = valueFirstPhase($MyRowEv->FirstPhase) == $MyRowEv->FirstPhase ? 0 : 8;
                $tmpQuantiIn = maxPhaseRank($MyRowEv->FirstPhase);
                $tmpQuantiOut = $tmpQuanti - $tmpQuantiIn;
                $tmpMatch = min($tmpQuantiIn, $tmpQuanti) - $tmpSaved - $MyRowEv->FirstPhase;
                $tmpBye = $MyRowEv->FirstPhase - $tmpMatch;
                $Teams[$MyRowEv->EvCode] = array('Name' => $MyRowEv->EventName, 'Number' => $tmpQuanti, 'Countries' => $Countries);
            }
        }
        foreach ($Teams as $EvCode => $Items) {
            if (empty($Data->Data[$EvCode])) {
                $Data->Data[$EvCode] = array('Name' => $Items['Name'], 'Number' => 0, 'Countries' => $Items['Countries'], 'Teams' => $Items['Number']);
            } else {
                $Data->Data[$EvCode]['Teams'] = $Items['Number'];
            }
        }
    } else {
        // Start with Qualification Rounds
        $MyQuery = getStatEntriesByEventQuery('QR');
        $QR = array();
        $QR['Title'] = get_text('StatEvents', 'Tournament');
        $QR['SubTitle'] = array(get_text('Individual'), get_text('Team'));
        $QR['Div'] = array();
        $QR['Cls'] = array();
        $QR['Data'] = array();
        $Rs = safe_r_sql($MyQuery);
        while ($Row = safe_fetch($Rs)) {
            if (!in_array($Row->Divisione, $QR['Div'])) {
                $QR['Div'][] = $Row->Divisione;
            }
            if (!in_array($Row->Classe, $QR['Cls'])) {
                $QR['Cls'][] = $Row->Classe;
            }
            $QR['Data'][$Row->Divisione][$Row->Classe] = array($Row->QuantiInd, $Row->QuantiSq);
        }
        $Data->Data['QR'] = $QR;
        // Go with Individual Finals
        $MyQuery = getStatEntriesByEventQuery('IF');
        $QR = array();
        $QR['Title'] = get_text('IndFinal');
        $QR['SubTitle'] = array(get_text('EvName'), get_text('Athletes'), get_text('FirstPhase'), get_text('FirstPhaseMatchesBye', 'Tournament'), get_text('FirstPhaseInOut', 'Tournament'));
        $QR['Data'] = array();
        $Rs = safe_r_sql($MyQuery);
        while ($Row = safe_fetch($Rs)) {
            $tmpSaved = valueFirstPhase($Row->FirstPhase) == $Row->FirstPhase ? 0 : 8;
            $tmpQuantiIn = maxPhaseRank($Row->FirstPhase);
            $tmpQuantiOut = $Row->Quanti - $tmpQuantiIn;
            $tmpMatch = min($tmpQuantiIn, $Row->Quanti) - $tmpSaved - $Row->FirstPhase;
            $tmpBye = $Row->FirstPhase - $tmpMatch;
            $QR['Data'][$Row->Code] = array('Name' => $Row->EventName, 'FirstPhase' => $Row->FirstPhase, 'Number' => $Row->Quanti, 'Invalid' => $tmpMatch <= 0, 'Phase' => $Row->FirstPhase == 0 ? "" : get_text(namePhase($Row->FirstPhase, $Row->FirstPhase) . '_Phase'), 'Matches' => $Row->FirstPhase == 0 ? "" : $tmpMatch, 'Byes' => $Row->FirstPhase == 0 || $tmpMatch < 0 ? "" : ($tmpBye + $tmpSaved == 0 ? '' : '(' . $tmpBye . ($tmpSaved != 0 ? '+' . $tmpSaved : '') . ')'), 'ArchersIn' => $Row->FirstPhase == 0 ? "" : ($Row->Quanti < $tmpQuantiIn ? $Row->Quanti : $tmpQuantiIn), 'ArchersOut' => $Row->FirstPhase == 0 ? "" : ($tmpQuantiOut > 0 ? '(' . $tmpQuantiOut . ')' : '-----'));
        }
        $Data->Data['IF'] = $QR;
        // Go with Team Finals
        $QR = array();
        $QR['Title'] = get_text('TeamFinal');
        $QR['SubTitle'] = array(get_text('EvName'), get_text('MixedTeamEvent'), get_text('Teams'), get_text('FirstPhase'), get_text('FirstPhaseMatchesBye', 'Tournament'), get_text('FirstPhaseInOut', 'Tournament'));
        $QR['Data'] = array();
        $MyQuery = getStatEntriesByEventQuery('TF');
        $RsEv = safe_r_sql($MyQuery);
        while ($MyRowEv = safe_fetch($RsEv)) {
            $Sql = "SELECT DISTINCT EcCode, EcTeamEvent, EcNumber FROM EventClass WHERE EcCode=" . StrSafe_DB($MyRowEv->EvCode) . " AND EcTeamEvent!=0 AND EcTournament=" . StrSafe_DB($_SESSION['TourId']);
            $RsEc = safe_r_sql($Sql);
            if (safe_num_rows($RsEc) > 0) {
                $RuleCnt = 0;
                $Sql = "Select * ";
                while ($MyRowEc = safe_fetch($RsEc)) {
                    $ifc = ifSqlForCountry($MyRowEv->EvTeamCreationMode);
                    $Sql .= ++$RuleCnt == 1 ? "FROM " : "INNER JOIN ";
                    $Sql .= "(SELECT {$ifc} as C" . $RuleCnt . ", SUM(IF(EnSubTeam=0,1,0)) AS QuantiMulti\n\t\t\t\t\t  FROM Entries\n\t\t\t\t\t  INNER JOIN EventClass ON EnClass=EcClass AND EnDivision=EcDivision AND EnTournament=EcTournament AND EcTeamEvent=" . $MyRowEc->EcTeamEvent . " AND EcCode=" . StrSafe_DB($MyRowEc->EcCode) . "\n\t\t\t\t\t\t  WHERE {$ifc}<>0 AND EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EnTeam" . ($MyRowEv->EvMixedTeam ? 'Mix' : 'F') . "Event=1\n\t\t\t\t\t\t  group by {$ifc}, EnSubTeam\n\t\t\t\t\t\t  HAVING COUNT(EnId)>=" . $MyRowEc->EcNumber . ") as sqy";
                    $Sql .= $RuleCnt == 1 ? " " : $RuleCnt . " ON C1=C" . $RuleCnt . " ";
                }
                $Rs = safe_r_sql($Sql);
                $tmpQuanti = safe_num_rows($Rs);
                if ($MyRowEv->EvMultiTeam != 0) {
                    $tmpQuanti = 0;
                    while ($tmpRow = safe_fetch($Rs)) {
                        $tmpQuanti += intval($tmpRow->QuantiMulti / $MyRowEv->EvMaxTeamPerson);
                    }
                }
                $tmpSaved = valueFirstPhase($MyRowEv->FirstPhase) == $MyRowEv->FirstPhase ? 0 : 8;
                $tmpQuantiIn = maxPhaseRank($MyRowEv->FirstPhase);
                $tmpQuantiOut = $tmpQuanti - $tmpQuantiIn;
                $tmpMatch = min($tmpQuantiIn, $tmpQuanti) - $tmpSaved - $MyRowEv->FirstPhase;
                $tmpBye = $MyRowEv->FirstPhase - $tmpMatch;
                $QR['Data'][$MyRowEv->EvCode] = array('Name' => $MyRowEv->EventName, 'Number' => $tmpQuanti, 'Invalid' => $tmpMatch <= 0, 'FirstPhase' => $MyRowEv->FirstPhase == 0 ? "" : get_text(namePhase($MyRowEv->FirstPhase, $MyRowEv->FirstPhase) . '_Phase'), 'Matches' => $MyRowEv->FirstPhase == 0 ? "" : $tmpMatch, 'Byes' => $MyRowEv->FirstPhase == 0 || $tmpMatch < 0 ? "" : '(' . $tmpBye . ($tmpSaved != 0 ? '+' . $tmpSaved : '') . ')', 'ArchersIn' => $MyRowEv->FirstPhase == 0 ? "" : ($tmpQuanti < $tmpQuantiIn ? $tmpQuanti : $tmpQuantiIn), 'ArchersOut' => $MyRowEv->FirstPhase == 0 ? "" : ($tmpQuantiOut > 0 ? '(' . $tmpQuantiOut . ')' : '---'), 'MixedTeam' => get_text($MyRowEv->EvMixedTeam ? 'Yes' : 'No'));
            }
        }
        $Data->Data['TF'] = $QR;
    }
    return $Data;
}
Exemple #13
0
// tiro fuori solo gli eventi spareggiati
$Select = "SELECT FinEvent,FinMatchNo,FinTournament,FinAthlete, IF(EvMatchMode=0,FinScore,FinSetScore) AS Score, FinTie, FinTiebreak, FinSetPoints,  /* Finals*/ " . "EvProgr,EvFinalFirstPhase,EvEventName, EvMatchMode, EvMatchArrowsNo, FsTarget,\t/* Events*/ " . "GrMatchNo,GrPhase,IF(EvFinalFirstPhase=48 || EvFinalFirstPhase=24,GrPosition2, GrPosition) as GrPosition,\t/* Grids */ " . "CONCAT(EnFirstName,' ',EnName) AS Athlete,EnCountry,\t/* Entries*/ " . "CoCode,CoName\t/* Countries */ " . "FROM Finals " . "left JOIN FinSchedule ON FinEvent=FSEvent AND FsMatchNo=FinMatchNo AND FsTeamEvent='0' AND FsTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . "INNER JOIN Events ON FinEvent=EvCode AND EvTeamEvent='0' AND EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . "INNER JOIN Grids ON FinMatchNo=GrMatchNo " . "LEFT JOIN Entries ON FinAthlete=EnId " . "LEFT JOIN Countries ON EnCountry=CoId " . "WHERE FinTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvShootOff='1' " . $QueryFilter . "ORDER BY EvProgr ASC,GrMatchNo ASC ";
$Rs = safe_r_sql($Select);
//print $Select;
if (safe_num_rows($Rs) > 0) {
    $MyEvent = '-----';
    while ($MyRow = safe_fetch($Rs)) {
        $obj = getEventArrowsParams($MyRow->FinEvent, $MyRow->GrPhase, 0);
        if ($MyEvent != $MyRow->FinEvent) {
            $ii = 0;
            $StileRiga = "";
            if ($MyEvent != '-----') {
                print '<tr><td colspan="' . (8 - $Cols2Remove) . '" class="Center"><input type="submit" value="' . get_text('CmdSave') . '" onclick="document.Frm.Command.value=\'SAVE\'"></td></tr>' . "\n";
                print '<tr class="Divider"><td></td></tr>' . "\n";
            }
            print '<tr><th colspan="' . (8 - $Cols2Remove) . '" class="Title">' . get_text($MyRow->EvEventName, '', '', true) . ' (' . $MyRow->FinEvent . ') - ' . get_text('Phase') . ' ' . get_text(namePhase($MyRow->EvFinalFirstPhase, $MyRow->GrPhase) . '_Phase') . '</th></tr>' . "\n";
            print '<tr>';
            print '<td colspan="' . (8 - $Cols2Remove) . '">';
            //$PrecPhase = ($_REQUEST['d_Phase']==0 ? 1 : ($_REQUEST['d_Phase']==32 ? 48 :$_REQUEST['d_Phase']*2));
            //$NextPhase = ($_REQUEST['d_Phase']>1 ? ($_REQUEST['d_Phase']==48 ? 32 : ($_REQUEST['d_Phase']==24 ? 16 : $_REQUEST['d_Phase']/2)) : 0);
            //print '<a class="Link" href="javascript:ChangePhase(' . $PrecPhase . ');">' . get_text('PrecPhase') . '</a>'
            if (!$useSession) {
                list($PP, $NP) = PrecNextPhaseForButton();
                // queste due solo per i nomi e gli score del turno successivo (e volendo precedente)
                $PrecPhase = $PP;
                $NextPhase = $NP;
            }
            print '<a class="Link" href="javascript:ChangePhase(\'' . $PP . '\',' . $Sch . ');">' . get_text('PrecPhase') . '</a>' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Link" href="javascript:ChangePhase(\'' . $NP . '\',' . $Sch . ');">' . get_text('NextPhase') . '</a>' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Link" href="PrnIndividual.php?Event=' . $MyRow->FinEvent . '&IncBrackets=1&ShowTargetNo=1" target="Griglie">' . get_text('Brackets') . '</a>';
            if ($_REQUEST['d_Phase'] > 0) {
                print '' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Link" href="PDFScoreMatch.php?Event=' . $MyRow->FinEvent . '&Phase=' . $NextPhase . '" target="Scores">' . get_text('NextMatchScores') . '</a>' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Link" href="PrnName.php?Event=' . $MyRow->FinEvent . '&Phase=' . $NextPhase . '" target="Names">' . get_text('NextMatchNames') . '</a>';
            }
Exemple #14
0
 $Select = "SELECT GrPhase,IF(EvFinalFirstPhase=48 || EvFinalFirstPhase=24,GrPosition2, GrPosition) as GrPosition,GrMatchNo,\t/* Grids*/ " . "FinEvent, /* Finals*/" . "FSTarget /* FinSchedule*/" . "FROM Finals JOIN Grids ON FinMatchNo=GrMatchNo AND GrPhase=" . StrSafe_DB($CurPhase) . " " . "INNER JOIN Events ON FinEvent=EvCode AND EvTeamEvent='0' AND EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . "LEFT JOIN FinSchedule ON FinEvent=FSEvent AND FinMatchNo=FSMatchNo AND FinTournament=FSTournament AND (FSTeamEvent='0' OR FSTeamEvent IS NULL) " . "WHERE FinTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND FinEvent=" . StrSafe_DB($_REQUEST['d_Event']) . " " . "ORDER BY  GrPhase DESC , GrMatchNo ASC ";
 $Rs = safe_r_sql($Select);
 //debug_svela( $Select );
 if (safe_num_rows($Rs) > 0) {
     // righe di testa della fase
     for ($i = 0; $i <= $HeadRows + 2; ++$i) {
         // se sto stampando l'ultima riga di testa scrivo la fase
         //$MyGrid[$Row++][$Col].= '<td  nowrap class="Center" colspan="5">' . ($i==$HeadRows ? get_text($CurPhase . '_Phase') : '&nbsp;') . '</td>';
         $Txt = '';
         /*if ($i==1)
         			$Txt = '<th nowrap class="Center" colspan="3">' . get_text($CurPhase . '_Phase') . '</th>';
         		else
         			$Txt = '<td  nowrap class="Center" colspan="3">&nbsp;</td>';*/
         $Colspan = $CurPhase == $StartPhase || $StartPhase == 24 && $CurPhase == 32 || $StartPhase == 48 && $CurPhase == 64 ? '3' : '4';
         if ($i == 1) {
             $Txt = '<th nowrap class="Center" colspan="' . $Colspan . '">' . get_text(namePhase($StartPhase, $CurPhase) . '_Phase') . '</th>';
         } else {
             $Txt = '<td  nowrap class="Center" colspan="' . $Colspan . '">&nbsp;</td>';
         }
         $MyGrid[$Row++][$Col] .= $Txt;
     }
     while ($MyRow = safe_fetch($Rs)) {
         if (!isFirstPhase($StartPhase, $MyRow->GrPhase)) {
             $TipoBordo = $Ultima % 2 == 0 ? 'Bottom' : '';
             $MyGrid[$Row][$Col] .= '<td  nowrap class="Center ' . $TipoBordo . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>';
         }
         // posizione
         $pos = $MyRow->GrPosition;
         $MyGrid[$Row][$Col] .= '<td nowrap class="' . ($AthPrinted == 1 ? 'Bottom ' : '') . 'Top Right Left Center">' . $pos . '</td>';
         // target
         $Target = !is_null($MyRow->FSTarget) ? $MyRow->FSTarget : '';
Exemple #15
0
    list($hasElim, $hasFin) = eventHasScoreTypes($r->EvCode, 1);
    if ($hasElim) {
        $tmp[] = array(get_text('EliminationShort', 'Tournament'), get_text('EventDetails', 'Tournament', array($r->EvElimEnds, $r->EvElimArrows, $r->EvElimSO)));
    }
    if ($hasFin) {
        $tmp[] = array(get_text('FinalShort', 'Tournament'), get_text('EventDetails', 'Tournament', array($r->EvFinEnds, $r->EvFinArrows, $r->EvFinSO)));
    }
    //$txt.='<b>'. ($r->EvMatchMode?'<br/>'.get_text('MatchMode_1').':</b> ':'');
    foreach ($tmp as $t) {
        $txt .= '<br>' . (count($tmp) > 1 && $dif ? $t[0] . ' ' : '') . $t[1];
    }
    //$txt=substr($txt,0,-5);
    echo $txt;
    //			echo '<br/><b>'. ($r->EvMatchMode?get_text('MatchMode_1').':</b> ':'') . ($dif?get_text('EliminationShort', 'Tournament').' ':'') . get_text('EventDetails', 'Tournament', array($r->EvElimEnds, $r->EvElimArrows, $r->EvElimSO)) ;
    //			if($dif) echo '<br/>'. get_text('FinalShort', 'Tournament').' ' . get_text('EventDetails', 'Tournament', array($r->EvFinEnds, $r->EvFinArrows, $r->EvFinSO)) ;
    echo '<br/>' . get_text('FirstPhase') . ': 1/' . namePhase($r->EvFinalFirstPhase, $r->EvFinalFirstPhase);
    echo '</a></td>';
}
echo '</tr>';
echo '</table>';
echo '</td>';
//Scores per singolo match
echo '<td width="50%" class="Center">';
// recupera per questo torneo quanti formati ci sono...
//	$q=safe_r_sql("(select distinct EvMatchMode, EvElimEnds, EvElimArrows, EvElimSO from Events where EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvTeamEvent=1 AND EvFinalFirstPhase!=0 )"
//		. "UNION (select distinct EvMatchMode, EvFinEnds, EvFinArrows, EvFinSO from Events where EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvTeamEvent=1 AND EvFinalFirstPhase!=0 )");
$query = "\r\n\t\tSELECT\r\n\t\t\tEvCode,EvFinalFirstPhase,EvMatchArrowsNo,\r\n\t\t\tEvElimEnds, EvElimArrows, EvElimSO,\r\n\t\t\tEvFinEnds, EvFinArrows, EvFinSO\r\n\t\tFROM\r\n\t\t\tEvents\r\n\t\tWHERE\r\n\t\t\tEvTournament={$_SESSION['TourId']} AND EvTeamEvent=1\r\n\t";
/*
 * Per ogni evento scopro se le sue fasi prevedono o no l'uso dei parametri elim e fin.
 * Se almeno una fase usa un tipo di parametri, memorizzo la terna in $list (purchè non l'abbia già messa prima).
 * Poi per tutte le terne (che saranno diverse) preparo i link
 public function MakeNormal()
 {
     global $CFG;
     $TourCode = empty($_REQUEST['TestCountries']) ? $_SESSION['TourCodeSafe'] : 'All';
     while ($MyRow = safe_fetch($this->ResultStream)) {
         if (!trim($MyRow->Athlete)) {
             continue;
         }
         $this->AddPage();
         //				$this->Line(5,($this->getPageHeight()/2),15,($this->getPageHeight()/2));
         //				$this->Line($this->getPageWidth()-15,($this->getPageHeight()/2),$this->getPageWidth()-5,($this->getPageHeight()/2));
         // Box del Rank
         $this->SetXY(5, 55);
         $this->SetFontSize(180);
         $H = $this->getPageHeight() - 80;
         $tmpPad = $this->getCellPaddings();
         $this->SetCellPadding(0);
         if ($this->IncludeLogo) {
             if (file_exists($svg = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $TourCode . '-Fl-svg-' . $MyRow->CoCode . '.svg')) {
                 $this->ImageSVG($svg, 5, 55, 60, 40);
             } elseif (file_exists($svg = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $TourCode . '-Fl-' . $MyRow->CoCode . '.jpg')) {
                 list($w, $h) = getimagesize($svg);
                 $ratio = $w / $h;
                 $h = 38;
                 $w = $h * $ratio;
                 if ($w > 58) {
                     $w = 58;
                     $h = $w / $ratio;
                 }
                 $this->Image($svg, 5 + (60 - $w) / 2, 55 + (40 - $h) / 2, $w, $h, '', '', '', 2);
             }
             $this->rect(5, 55, 60, 40);
             $this->y += 45;
             $H -= 45;
         }
         $this->Cell(60, $H, $MyRow->Rank, 1, 1, 'C', 0, null, 1);
         $this->SetCellPaddings($tmpPad['L'], $tmpPad['T'], $tmpPad['R'], $tmpPad['B']);
         // box Atleta/Country
         $this->SetXY(70, 41.3);
         $this->SetFontSize(159);
         $this->Cell($this->getPageWidth() - 80, 60, $MyRow->Athlete, 0, 1, 'L', 0, null, 1);
         // box Country/Athletes
         $Names = explode('|', $MyRow->CoName);
         if (count($Names) > 4) {
             $this->SetFontSize(30);
         } else {
             if (count($Names) > 1) {
                 $this->SetFontSize(50);
             } else {
                 $this->SetFontSize(100);
             }
         }
         $StartY = 110 + 8 * (count($Names) == 1);
         foreach ($Names as $name) {
             $this->SetXY(70, $StartY);
             $this->Cell($this->getPageWidth() - 80, 10, $name, 0, 0, 'L', 0, 0, 1);
             $StartY += count($Names) > 4 ? 12 : 18;
         }
         if ($this->TargetAssignment) {
             // PArte di riconoscimento EVENTO e Paglione
             $tmpY = ($MyRow->GrMatchNo % 2 == 0 ? $this->getPageHeight() / 2 : $this->getPageHeight()) - 10;
             $this->SetFont('', '', 20);
             $this->SetXY($this->getPageWidth() - 25, $this->getPageHeight() - 35);
             $this->Cell(15, 10, "Gold: " . ltrim($MyRow->sGo, '0'), 1, 0, 'C', 0);
             $this->SetX($this->getX() - 30);
             $this->Cell(15, 10, "Bronze: " . ltrim($MyRow->sBr, '0'), 1, 0, 'C', 0);
             for ($i = 2; $i <= 64; $i = $i * 2) {
                 if (!isset($MyRow->{'s' . $i}) or is_null($MyRow->{'s' . $i})) {
                     break;
                 }
                 $this->SetX($this->getX() - 30);
                 $this->Cell(15, 10, '1/' . namePhase($MyRow->EvFinalFirstPhase, $i) . ': ' . ltrim($MyRow->{'s' . $i}, '0'), 1, 0, 'C', 0);
             }
             $this->SetX($this->getX() - 30);
             $this->SetFont('', 'B', 20);
             $this->Cell(15, 10, $MyRow->EvCode, 1, 0, 'C', 0);
             $this->SetFont('', '', 20);
         }
     }
     $this->Output();
 }
Exemple #17
-1
function DrawScore(&$pdf, $MyRow, $MyRowOpp)
{
    global $CFG, $defTotalW, $defGoldW, $defArrowTotW, $FollowingRows, $TrgOutdoor, $WhereStartX, $WhereStartY, $Score3D, $FillWithArrows;
    $NumRow = $MyRow->CalcEnds;
    $NumCol = $MyRow->CalcArrows;
    $ArrowW = $defArrowTotW / $NumCol;
    $TotalW = $defTotalW;
    $GoldW = $defGoldW;
    //		echo $MyRow->EvMatchArrowsNo . "." . $MyRow->GrPhase ."." . ($MyRow->EvMatchArrowsNo & ($MyRow->GrPhase>0 ? $MyRow->GrPhase*2:1)) . "/" . $NumRow . "--<br>";
    if ($MyRow->GrMatchNo % 2 == 0 && $FollowingRows) {
        $pdf->AddPage();
    }
    $FollowingRows = true;
    $WhichScore = $MyRow->GrMatchNo % 2;
    $WhereX = $WhereStartX;
    $WhereY = $WhereStartY;
    //Intestazione Atleta
    $pdf->SetLeftMargin($WhereStartX[$WhichScore]);
    $pdf->SetY(35);
    // Flag of Country/Club
    if ($pdf->PrintFlags) {
        if (is_file($file = $CFG->DOCUMENT_PATH . 'TV/Photos/' . $_SESSION['TourCodeSafe'] . '-Fl-' . $MyRow->CoCode . '.jpg')) {
            $H = 12;
            $W = 18;
            $OrgY = $pdf->gety();
            $OrgX = $NumCol * $ArrowW + $TotalW + $GoldW + $TotalW - 18;
            $pdf->Image($file, $pdf->getx() + $OrgX, $OrgY, $W, $H, 'JPG', '', '', true, 300, '', false, false, 1, true);
            $FlagOffset = $W + 1;
        }
    }
    $pdf->SetFont($pdf->FontStd, '', 10);
    $pdf->Cell(20, 6, get_text('Athlete') . ': ', 'TL', 0, 'L', 0);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->Cell($NumCol * $ArrowW + 2 * $TotalW + $GoldW - 20 - ($pdf->PrintFlags ? 18 : 0), 6, $MyRow->Athlete, 'T', 1, 'L', 0);
    $pdf->SetFont($pdf->FontStd, '', 10);
    $pdf->Cell(20, 6, get_text('Country') . ': ', 'L', 0, 'L', 0);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->Cell($NumCol * $ArrowW + 2 * $TotalW + $GoldW - 20, 6, $MyRow->CoName . (strlen($MyRow->CoCode) > 0 ? ' (' . $MyRow->CoCode . ')' : ''), 0, 1, 'L', 0);
    $pdf->SetFont($pdf->FontStd, '', 10);
    $pdf->Cell(20, 6, get_text('DivisionClass') . ': ', 'LB', 0, 'L', 0);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->Cell($NumCol * $ArrowW + $TotalW + $GoldW - 20, 6, get_text($MyRow->EvEventName, '', '', true), 'B', 0, 'L', 0);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->Cell($TotalW, 6, get_text('Target') . ' ' . $MyRow->FSTarget, '1', 1, 'C', 1);
    $pdf->SetXY($NumCol * $ArrowW + 2 * $TotalW + $GoldW + $WhereStartX[$WhichScore], 35);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->Cell(2 * $GoldW, 6, get_text('Rank'), 'TLR', 1, 'C', 1);
    $pdf->SetXY($NumCol * $ArrowW + 2 * $TotalW + $GoldW + $WhereStartX[$WhichScore], $pdf->GetY());
    $pdf->SetFont($pdf->FontStd, 'B', 25);
    $pdf->Cell(2 * $GoldW, 12, $MyRow->IndRank, 'BLR', 1, 'C', 1);
    //Header
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->Cell($GoldW, CellH, '', 0, 0, 'C', 0);
    $pdf->Cell(2 * $GoldW + 2 * $TotalW + $NumCol * $ArrowW, CellH, get_text(namePhase($MyRow->EvFinalFirstPhase, $MyRow->GrPhase) . '_Phase'), 1, 0, 'C', 1);
    //Winner Checkbox
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->Cell(2 * $GoldW, CellH, '', 0, 0, 'C', 0);
    //$pdf->Rect($WhereX[$WhichScore]+$GoldW+2,$WhereY[$WhichScore]+2,$GoldW-4,CellH-4,'DF',array(),array(255,255,255));
    $pdf->Rect($WhereX[$WhichScore] + $GoldW + 2, $WhereY[$WhichScore] + 2, CellH - 4, CellH - 4, 'DF', array(), array(255, 255, 255));
    if ($FillWithArrows && ($MyRow->Score > $MyRowOpp->Score || $MyRow->Score == $MyRowOpp->Score && $MyRow->FinTie > $MyRowOpp->FinTie)) {
        $tmpWidth = $pdf->GetLineWidth();
        $pdf->SetLineWidth($tmpWidth * 5);
        $pdf->Line($WhereX[$WhichScore] + $GoldW + 1, $WhereY[$WhichScore] + 1, $WhereX[$WhichScore] + 2 * $GoldW - 1, $WhereY[$WhichScore] + CellH - 1);
        $pdf->Line($WhereX[$WhichScore] + $GoldW + 1, $WhereY[$WhichScore] + CellH - 1, $WhereX[$WhichScore] + 2 * $GoldW - 1, $WhereY[$WhichScore] + 1);
        $pdf->SetLineWidth($tmpWidth);
    }
    $pdf->SetDefaultColor();
    $pdf->Cell($GoldW + 2 * $TotalW + $NumCol * $ArrowW, CellH, get_text('Winner'), 0, 1, 'L', 0);
    $WhereY[$WhichScore] = $pdf->GetY();
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->Cell($GoldW, CellH, '', 0, 0, 'C', 0);
    if ($Score3D) {
        $pdf->Cell($NumCol * $ArrowW, CellH, get_text('Arrow'), 1, 0, 'C', 1);
    } else {
        for ($j = 0; $j < $NumCol; $j++) {
            $pdf->Cell($ArrowW, CellH, $j + 1, 1, 0, 'C', 1);
        }
    }
    $pdf->Cell($TotalW * ($MyRow->EvMatchMode == 0 ? 1 : 4 / 5), CellH, get_text($MyRow->EvMatchMode == 0 ? 'TotalProg' : 'SetTotal', 'Tournament'), 1, 0, 'C', 1);
    $pdf->Cell($TotalW * ($MyRow->EvMatchMode == 0 ? 1 : 4 / 5), CellH, get_text('RunningTotal', 'Tournament'), 1, 0, 'C', 1);
    if ($MyRow->EvMatchMode == 0) {
        $pdf->Cell($GoldW, CellH, $pdf->prnGolds, 1, 0, 'C', 1);
        $pdf->Cell($GoldW, CellH, $pdf->prnXNine, 1, 1, 'C', 1);
    } else {
        $pdf->Cell(2 * $GoldW, CellH, get_text('SetPoints', 'Tournament'), 1, 0, 'C', 1);
        $pdf->Cell(2 / 5 * $TotalW, CellH, get_text('TotalShort', 'Tournament'), 1, 1, 'C', 1);
    }
    $WhereY[$WhichScore] = $pdf->GetY();
    //Righe
    $ScoreTotal = 0;
    $ScoreGold = 0;
    $ScoreXnine = 0;
    $SetTotal = '';
    for ($i = 1; $i <= $NumRow; $i++) {
        $ScoreEndTotal = 0;
        $ScoreEndGold = 0;
        $ScoreEndXnine = 0;
        $pdf->SetFont($pdf->FontStd, 'B', 10);
        $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
        $pdf->Cell($GoldW, CellH, $i, 1, 0, 'C', 1);
        $pdf->SetFont($pdf->FontStd, '', 10);
        if ($Score3D) {
            $pdf->Cell($ArrowW / 5, CellH, '11', 1, 0, 'C', 0);
            $pdf->Cell($ArrowW / 5, CellH, '10', 1, 0, 'C', 0);
            $pdf->Cell($ArrowW / 5, CellH, '8', 1, 0, 'C', 0);
            $pdf->Cell($ArrowW / 5, CellH, '5', 1, 0, 'C', 0);
            $pdf->Cell($ArrowW / 5, CellH, 'M', 1, 0, 'C', 0);
        } else {
            for ($j = 0; $j < $NumCol; $j++) {
                $pdf->Cell($ArrowW, CellH, $FillWithArrows ? DecodeFromLetter(substr($MyRow->FinArrowString, ($i - 1) * $NumCol + $j, 1)) : '', 1, 0, 'C', 0);
            }
            $IsEndScore = trim(substr($MyRow->FinArrowString, ($i - 1) * $NumCol, $NumCol));
            list($ScoreEndTotal, $ScoreEndGold, $ScoreEndXnine) = ValutaArrowStringGX(substr($MyRow->FinArrowString, ($i - 1) * $NumCol, $NumCol), $pdf->goldsChars, $pdf->xNineChars);
            $ScoreTotal += $ScoreEndTotal;
            $ScoreGold += $ScoreEndGold;
            $ScoreXnine += $ScoreEndXnine;
        }
        $pdf->SetFont($pdf->FontStd, '', $MyRow->EvMatchMode == 0 ? 10 : 12);
        $pdf->Cell($TotalW * ($MyRow->EvMatchMode == 0 ? 1 : 4 / 5), CellH, $FillWithArrows && $IsEndScore ? $ScoreEndTotal : '', 1, 0, 'C', 0);
        $pdf->SetFont($pdf->FontStd, '', $MyRow->EvMatchMode == 0 ? 12 : 10);
        $pdf->Cell($TotalW * ($MyRow->EvMatchMode == 0 ? 1 : 4 / 5), CellH, $FillWithArrows && $IsEndScore ? $ScoreTotal : '', 1, 0, 'C', 0);
        if ($MyRow->EvMatchMode == 0) {
            $pdf->SetFont($pdf->FontStd, '', 9);
            $pdf->Cell($GoldW, CellH, $FillWithArrows && $IsEndScore ? $ScoreEndGold : '', 1, 0, 'C', 0);
            $pdf->Cell($GoldW, CellH, $FillWithArrows && $IsEndScore ? $ScoreEndXnine : '', 1, 1, 'C', 0);
        } else {
            $SetTotSx = '';
            if ($IsEndScore && $FillWithArrows) {
                $SetPointSx = ValutaArrowString(substr($MyRow->FinArrowString, ($i - 1) * $NumCol, $NumCol));
                $SetPointDx = ValutaArrowString(substr($MyRowOpp->FinArrowString, ($i - 1) * $NumCol, $NumCol));
                if ($SetPointSx > $SetPointDx) {
                    $SetTotSx = 2;
                } elseif ($SetPointSx < $SetPointDx) {
                    $SetTotSx = 0;
                } else {
                    $SetTotSx = 1;
                }
                $SetTotal = intval($SetTotal) + $SetTotSx;
            }
            $pdf->SetFont($pdf->FontStd, 'B', 11);
            if ($SetTotSx == 2 && $FillWithArrows) {
                $pdf->Circle($pdf->GetX() + $GoldW / 3, $pdf->GetY() + CellH / 2, $GoldW / 3, 0, 360, 'FD');
            }
            $pdf->Cell(2 * $GoldW / 3, CellH, '2', 1, 0, 'C', 0);
            if ($SetTotSx == 1 && $FillWithArrows) {
                $pdf->Circle($pdf->GetX() + $GoldW / 3, $pdf->GetY() + CellH / 2, $GoldW / 3, 0, 360, 'FD');
            }
            $pdf->Cell(2 * $GoldW / 3, CellH, '1', 1, 0, 'C', 0);
            if ($SetTotSx == 0 && $IsEndScore && $FillWithArrows) {
                $pdf->Circle($pdf->GetX() + $GoldW / 3, $pdf->GetY() + CellH / 2, $GoldW / 3, 0, 360, 'FD');
            }
            $pdf->Cell(2 * $GoldW / 3, CellH, '0', 1, 0, 'C', 0);
            $pdf->Cell($TotalW * 2 / 5, CellH, $IsEndScore && $FillWithArrows ? $SetTotal : '', 1, 1, 'C', 0);
        }
        $WhereY[$WhichScore] = $pdf->GetY();
    }
    //Shoot Off
    $closeToCenter = false;
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore] + CellH / 4);
    $pdf->SetFont($pdf->FontStd, 'B', 8);
    $pdf->Cell($GoldW, CellH * 11 / 8, get_text('TB'), 1, 0, 'C', 1);
    $ShootOffW = $MyRow->CalcSO <= $NumCol ? $ArrowW : $ArrowW * $NumCol / $MyRow->CalcSO;
    for ($j = 0; $j < $MyRow->CalcSO; $j++) {
        $pdf->SetXY($pdf->GetX() + 0.5, $pdf->GetY());
        $pdf->SetFont($pdf->FontStd, '', 10);
        $pdf->Cell($ShootOffW - 0.5, CellH * 3 / 4, $FillWithArrows ? DecodeFromLetter(substr($MyRow->FinTieBreak, $j, 1)) : '', 1, 0, 'C', 0);
        if (substr($FillWithArrows ? DecodeFromLetter(substr($MyRow->FinTieBreak, $j, 1)) : '', -1, 1) == "*") {
            $closeToCenter = true;
        }
    }
    if ($NumCol > $j) {
        $pdf->Cell($ArrowW * ($NumCol - $j), CellH * 3 / 4, '', 0, 0, 'L', 0);
    }
    //Totale
    $pdf->SetXY($pdf->GetX(), $WhereY[$WhichScore]);
    $pdf->SetFont($pdf->FontStd, 'B', 10);
    if ($MyRow->EvMatchMode == 0) {
        $pdf->Cell($TotalW, CellH, get_text('Total'), 0, 0, 'R', 0);
        $pdf->SetFont($pdf->FontStd, 'B', 11);
        $pdf->Cell($TotalW, CellH, $FillWithArrows ? $ScoreTotal : '', 1, 0, 'C', 0);
        $pdf->SetFont($pdf->FontStd, '', 10);
        $pdf->Cell($GoldW, CellH, $FillWithArrows ? $ScoreGold : '', 1, 0, 'C', 0);
        $pdf->Cell($GoldW, CellH, $FillWithArrows ? $ScoreXnine : '', 1, 1, 'C', 0);
    } else {
        $pdf->Cell($TotalW * 8 / 5, CellH, '', 0, 0, 'R', 0);
        $pdf->SetFont($pdf->FontStd, 'B', 10);
        $pdf->Cell(2 * $GoldW, CellH, get_text('Total'), 0, 0, 'R', 0);
        $pdf->SetFont($pdf->FontStd, 'B', 14);
        $pdf->Cell(2 / 5 * $TotalW, CellH, $FillWithArrows ? $MyRow->FinSetScore : '', 1, 1, 'C', 0);
    }
    $WhereY[$WhichScore] = $pdf->GetY();
    //Closet to the center
    $pdf->SetFont($pdf->FontStd, '', 9);
    $pdf->SetXY($WhereX[$WhichScore] + $GoldW + $ShootOffW / 2, $WhereY[$WhichScore] + CellH / 8);
    $pdf->Cell($ShootOffW / 2, CellH / 2, '', 1, 0, 'R', 0);
    if ($closeToCenter) {
        $tmpWidth = $pdf->GetLineWidth();
        $pdf->SetLineWidth($tmpWidth * 5);
        $pdf->Line($WhereX[$WhichScore] + $GoldW + $ShootOffW / 2 - 1, $WhereY[$WhichScore] + CellH / 8 - 1, $WhereX[$WhichScore] + $GoldW + $ShootOffW + 1, $WhereY[$WhichScore] + CellH * 5 / 8 + 1);
        $pdf->Line($WhereX[$WhichScore] + $GoldW + $ShootOffW / 2 - 1, $WhereY[$WhichScore] + CellH * 5 / 8 + 1, $WhereX[$WhichScore] + $GoldW + $ShootOffW + 1, $WhereY[$WhichScore] + CellH / 8 - 1);
        $pdf->SetLineWidth($tmpWidth);
    }
    $pdf->Cell($ArrowW * ($NumCol - 1), CellH * 2 / 4, get_text('Close2Center', 'Tournament'), 0, 0, 'L', 0);
    $WhereY[$WhichScore] = $pdf->GetY() + 10;
    //Firme
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->SetFont($pdf->FontStd, 'I', 7);
    $pdf->Cell(3 * $GoldW + 2 * $TotalW + $NumCol * $ArrowW, 4, get_text('Archer'), 'B', 0, 'L', 0);
    $WhereY[$WhichScore] = $pdf->GetY() + 10;
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->Cell(3 * $GoldW + 2 * $TotalW + $NumCol * $ArrowW, 4, get_text('Scorer'), 'B', 0, 'L', 0);
    $WhereY[$WhichScore] = $pdf->GetY() + 15;
    $pdf->SetXY($WhereX[$WhichScore], $WhereY[$WhichScore]);
    $pdf->Cell(3 * $GoldW + 2 * $TotalW + $NumCol * $ArrowW, 4, get_text('JudgeNotes'), 'B', 0, 'L', 0);
    $WhereY[$WhichScore] = $pdf->GetY();
}