Example #1
0
function maxPhaseRank($phase)
{
    $max = 0;
    $q = "SELECT MAX(GrPosition" . ($phase == valueFirstPhase($phase) ? "" : "2") . ") AS `max` FROM Grids WHERE GrPhase=" . valueFirstPhase($phase);
    $r = safe_r_sql($q);
    if ($r && safe_num_rows($r) == 1) {
        $max = safe_fetch($r)->max;
    }
    return $max;
}
Example #2
0
 $MiddleRows = 2;
 // righe tra 2 scontri della fase
 $HeadLineRows = 2 * $HeadRows;
 // righe di testa del passaggio di fase
 /*
 	Righe per disegnare il passaggio di fase.
 	La chiave indica il tipo di cella, il valore il numero di celle di quel tipo
 */
 $MiddleLineRows = array('Top Right' => 1, 'Right' => 3, 'Top' => 1, '' => 3);
 // indici di $MyGrid
 $Row = 0;
 $Col = 0;
 $Ultima = 0;
 // Flag per disegnare l'ultima riga del passaggio di fase
 // Il ciclo gestisce fino alla semifinale
 $CurPhase = valueFirstPhase($StartPhase);
 $TabIndex = 1;
 $BitMask = 0;
 $Select = "SELECT EvFinalAthTarget " . "FROM Events " . "WHERE EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvCode=" . StrSafe_DB($_REQUEST['d_Event']) . " " . "AND EvTeamEvent='0' ";
 $Rs = safe_r_sql($Select);
 //print $Select;exit;
 if (safe_num_rows($Rs) == 1) {
     $Row = safe_fetch($Rs);
     $BitMask = $Row->EvFinalAthTarget;
 }
 while ($CurPhase > 1 && $Status == 0) {
     $JS_RedTarget .= "FindRedTarget('" . $_REQUEST['d_Event'] . "','" . $CurPhase . "','');";
     // Estraggo il bit corrispondete alla fase
     $Bit = $CurPhase > 0 ? ($CurPhase == 48 ? 64 : ($CurPhase == 24 ? 32 : $CurPhase)) * 2 : 1;
     $Ath4Tar = ($Bit & $BitMask) == $Bit ? 1 : 0;
     $AthPrinted = 0;
 /**
  * calcFromPhase()
  * Calcola la FinalRank per un evento in una certa fase
  * @param string $event: evento
  * @param int $phase: fase
  * @return boolean: true ok false altrimenti. In un ciclo il primo errore fa terminare il metodo con false!
  */
 protected function calcFromPhase($event, $phase)
 {
     // trasformo la fase
     $phase = valueFirstPhase($phase);
     $date = date('Y-m-d H:i:s');
     // reset delle RankFinal della fase x le persone di quell'evento e quella fase
     $q = "\r\n\t\t\t\tUPDATE\r\n\t\t\t\t\tIndividuals\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tFinals\r\n\t\t\t\t\tON IndId=FinAthlete AND IndTournament=FinTournament AND IndEvent=FinEvent\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tGrids\r\n\t\t\t\t\tON FinMatchNo=GrMatchNo AND GrPhase={$phase}\r\n\t\t\t\tSET\r\n\t\t\t\t\tIndRankFinal=0,\r\n\t\t\t\t\tIndTimestampFinal='{$date}'\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tGrPhase={$phase} AND IndTournament={$this->tournament} AND IndEvent='{$event}'\r\n\t\t\t";
     //print $q.'<br><br>';
     $r = safe_w_sql($q);
     if (!$r) {
         return false;
     }
     /*
      *  Tiro fuori gli scontri con i perdenti nei non Opp
      */
     $q = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tf.FinAthlete AS AthId,\r\n\t\t\t\t\tf2.FinAthlete AS OppAthId,\r\n\t\t\t\t\tIF(EvMatchMode=0,f.FinScore,f.FinSetScore) AS Score, f.FinScore AS CumScore,f.FinTie AS Tie,\r\n\t\t\t\t\tIF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) as OppScore, f2.FinScore AS OppCumScore,f2.FinTie as OppTie\r\n\t\t\t\tFROM\r\n\t\t\t\t\tFinals AS f\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tFinals AS f2\r\n\t\t\t\t\tON f.FinEvent=f2.FinEvent AND f.FinMatchNo=IF((f.FinMatchNo % 2)=0,f2.FinMatchNo-1,f2.FinMatchNo+1) AND f.FinTournament=f2.FinTournament\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 f.FinMatchNo=GrMatchNo\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 f.FinEvent=EvCode AND f.FinTournament=EvTournament AND EvTeamEvent=0\r\n\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tf.FinTournament={$this->tournament} AND f.FinEvent='{$event}' AND GrPhase={$phase}\r\n\t\t\t\t\tAND (IF(EvMatchMode=0,f.FinScore,f.FinSetScore) < IF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) OR (IF(EvMatchMode=0,f.FinScore,f.FinSetScore)=IF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) AND f.FinTie < f2.FinTie))\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\tIF(EvMatchMode=0,f.FinScore,f.FinSetScore) DESC,f.FinScore DESC\r\n\t\t\t";
     //print $q.'<br><br>';
     $rs = safe_r_sql($q);
     if ($rs) {
         if (safe_num_rows($rs) > 0) {
             /*
              * Se fase 0 (oro) il perdente ha la rank=2 e il vincente piglia 1,
              * se fase 1 (bronzo) il perdente ha la rank=4 e il vincete piglia 3
              * e in entrambi i casi avrò sempre e solo una riga.
              *
              * Se fase 2 (semi) non succede nulla.
              *
              * Per le altre fasi si cicla nel recordset che ha il numero di righe >=0
              */
             if ($phase == 0 || $phase == 1) {
                 $myRow = safe_fetch($rs);
                 $toWrite = array();
                 if ($phase == 0) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppAthId, 'rank' => 1);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->AthId, 'rank' => 2);
                 } elseif ($phase == 1) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppAthId, 'rank' => 3);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->AthId, 'rank' => 4);
                 }
                 foreach ($toWrite as $values) {
                     $x = $this->writeRow($values['id'], $values['event'], $values['rank']);
                     if ($x === false) {
                         return false;
                     }
                 }
             } elseif ($phase == 2) {
                 // non faccio nulla!
             } else {
                 // qui posso avere tante righe
                 $pos = 0;
                 /*
                  * Le posizioni partono dal numero della fase perchè poi l'incremento avverrà sempre.
                  * (@see Obj_Rank_FinalInd_calc base)
                  * I 1/48 quindi andranno inizializzati a 56 perchè la prima rank buona è 57.
                  * Con tutte le fase avverrno gli incrementi
                  */
                 switch ($phase) {
                     case 4:
                         $pos = 4;
                         // si parte da 5 quindi qui metto 4 dato che la fase è 4 (vedi commento qui sopra)
                         break;
                     case 8:
                         $pos = 8;
                         break;
                     case 16:
                         $pos = 16;
                         break;
                     case 32:
                         // (e 24)
                         $pos = 32;
                         break;
                     case 48:
                         $pos = 56;
                         break;
                     case 64:
                         $pos = 64;
                         break;
                     default:
                         return false;
                 }
                 $rank = $pos + 1;
                 $scoreOld = 0;
                 $cumOld = 0;
                 while ($myRow = safe_fetch($rs)) {
                     ++$pos;
                     //print $pos . ' - ';
                     if (!($myRow->Score == $scoreOld && $myRow->CumScore == $cumOld)) {
                         $rank = $pos;
                     }
                     //print $rank.'<br>';
                     $scoreOld = $myRow->Score;
                     $cumOld = $myRow->CumScore;
                     // devo scrivere solo il perdente
                     $x = $this->writeRow($myRow->AthId, $event, $rank);
                     if ($x === false) {
                         return false;
                     }
                 }
             }
         }
     } else {
         return false;
     }
     return true;
 }
Example #4
0
function SetTargetDb($Key, $Value)
{
    $ret = '';
    $Errore = 0;
    $Target = '';
    $Phase = '';
    $firstPhase = '';
    $realPhase = '';
    $Event = '';
    $Which = $Key;
    $Campo = '';
    $ee = '';
    $mm = '';
    // matchno estratto
    $ath = '';
    // ath per bersaglio (0 --> 1; 1 --> 2)
    list(, $Campo, $ee, $mm, $ath) = explode('_', $Key);
    $Event = $ee;
    // cerco la fase del matchno
    $Select = "SELECT GrPhase FROM Grids WHERE GrMatchNo=" . StrSafe_DB($mm) . " ";
    $Rs = safe_r_sql($Select);
    if (safe_num_rows($Rs) == 1) {
        $MyRow = safe_fetch($Rs);
        $Phase = $MyRow->GrPhase;
        $realPhase = $Phase;
        $firstPhase = getFirstPhase($Event, 0);
        if (valueFirstPhase($firstPhase) != $firstPhase && $Phase > 16) {
            $realPhase = $Phase == 32 ? 24 : ($Phase == 64 ? 48 : $Phase);
        }
    }
    // if target is followed by a "+" sign fills up the phase from this point up to the last with increments of 1
    if (substr($Value, -1) == '+') {
        $Value = intval($Value);
        $val = $Value;
        foreach (range($mm, $Phase * 4 - 1, $ath + 1) as $n) {
            $ret .= SetTargetDb('d_' . $Campo . '_' . $ee . '_' . $n . '_' . $ath, $val++);
        }
        return $ret;
    } elseif (substr($Value, -1) == '*') {
        $Value = intval($Value);
        $mm = 2 * floor($mm / 2);
        $val = $Value;
        $z = 1;
        foreach (range($mm, $Phase * 4 - 1, $ath + 1) as $n) {
            $ret .= SetTargetDb('d_' . $Campo . '_' . $ee . '_' . $n . '_' . $ath, $val++);
            $z = 1 - $z;
            if ($z) {
                $val++;
            }
        }
        return $ret;
    } elseif (substr($Value, -1) == '-') {
        // recupera gli scontri senza bye...
        // lo scontro parte da un numero pari
        $mm = 2 * floor($mm / 2);
        $Value = intval($Value);
        $val = $Value;
        // cerca i byes, quindi va a prendere la differenza tra il numero di atleti della fase e gli atleti presenti in quell'evento
        $MyQuery = "SELECT COUNT(EnId) as Quanti, EvFinalFirstPhase as FirstPhase\r\n\t\t\tFROM Events\r\n\t\t\tINNER JOIN EventClass ON EvCode=EcCode AND EvTeamEvent=EcTeamEvent AND EvTournament=EcTournament\r\n\t\t\tINNER JOIN Individuals ON EvCode=IndEvent AND EvTournament=IndTournament\r\n\t\t\tINNER JOIN Entries ON EnId=IndId AND EnTournament=IndTournament AND EcClass=EnClass AND EcDivision=EnDivision\r\n\t\t\tWHERE EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EcCode=" . StrSafe_DB($ee) . " AND EvTeamEvent=0 AND ((EnIndFEvent=1 AND EnStatus<=1) OR EnId IS NULL)";
        $q = safe_r_sql($MyQuery);
        $r = safe_fetch($q);
        //debug_svela($MyQuery, true);
        $tmpQuanti = $r->Quanti;
        $tmpSaved = $Phase <= 16 ? 0 : (valueFirstPhase($r->FirstPhase) == $r->FirstPhase ? 0 : 8);
        $tmpQuantiIn = maxPhaseRank($realPhase);
        $tmpQuantiOut = $tmpQuanti - $tmpQuantiIn;
        $tmpBye = ($tmpQuantiOut < 0 ? abs($tmpQuantiOut) : 0) + $tmpSaved;
        //echo $Phase . ",". $tmpQuanti . "," . $tmpSaved . "," . $tmpQuantiIn . "," . $tmpQuantiOut . "," . $tmpBye; exit;
        //		if($tmpBye<=0 && $tmpSaved<=0) {
        // NON ci sono byes, quindi fa il responso normale...
        //debug_svela(array($Key, $Value));
        //			return SetTargetDb($Key, $Value.'+');
        //		}
        // ci sono byes, quindi va a riempire solo i matchno dei match pieni cioè con una rank superiore all'ultimo bye!
        // esempio: 1/8, 13 presenti, sono 3 byes, quindi si parte dal 4° in ranking...
        //
        $MyQuery = 'SELECT distinct ' . ' GrMatchNo, ' . ($firstPhase == 48 || $firstPhase == 24 ? 'GrPosition2' : 'GrPosition') . '  as Position' . ' FROM Grids' . ' WHERE ' . " GrPhase = '{$Phase}' " . " AND GrMatchNo>= {$mm} " . ' ORDER BY GrMatchNo ASC';
        $q = safe_r_sql($MyQuery);
        while ($r = safe_fetch($q)) {
            $butt = $r->Position <= $tmpBye || $r->Position > $tmpQuanti ? '' : $val;
            if (!$ath or !($r->GrMatchNo % 2)) {
                if ($r->Position > $tmpBye) {
                    $ret .= SetTargetDb('d_' . $Campo . '_' . $ee . '_' . $r->GrMatchNo . '_' . $ath, $butt);
                    if ($butt) {
                        $val++;
                    }
                } else {
                    $ret .= SetTargetDb('d_' . $Campo . '_' . $ee . '_' . $r->GrMatchNo . '_' . $ath, '');
                    $ret .= '<field>';
                    $ret .= '<error>0</error>' . "\n";
                    $ret .= '<org>d_' . $Campo . '_' . $ee . '_' . $r->GrMatchNo . '_' . $ath . ' - </org>' . "\n";
                    $ret .= '<which><![CDATA[d_' . $Campo . '_' . $ee . '_' . $r->GrMatchNo . '_' . $ath . ']]></which>' . "\n";
                    $ret .= '<target><![CDATA[]]></target>' . "\n";
                    $ret .= '<phase><![CDATA[' . $Phase . ']]></phase>' . "\n";
                    $ret .= '<event><![CDATA[' . $Event . ']]></event>' . "\n";
                    $ret .= '</field>';
                }
            }
        }
        return $ret;
    }
    // verifico che il target sia un numero vero
    if (preg_match('/^[0-9]{1,' . TargetNoPadding . '}$/i', $Value) || strlen(trim($Value)) == 0) {
        if (strlen(trim($Value)) > 0) {
            $Target = str_pad($Value, TargetNoPadding, '0', STR_PAD_LEFT);
        }
        // scrivo il target
        $Insert = "INSERT INTO FinSchedule (FSEvent,FSTeamEvent,FSMatchNo,FSTournament,FSTarget, FSLetter) " . "VALUES(" . StrSafe_DB($ee) . "," . StrSafe_DB('0') . "," . StrSafe_DB($mm) . "," . StrSafe_DB($_SESSION['TourId']) . "," . StrSafe_DB($Target) . "," . StrSafe_DB($Target ? $Target : '') . "" . ") " . "ON DUPLICATE KEY UPDATE " . "FSTarget=" . StrSafe_DB($Target) . "," . "FSGroup=FSGroup," . "FSLetter=" . StrSafe_DB($Target ? $Target : '') . ", " . "FSScheduledTime=FSScheduledTime ";
        $Rs = safe_w_sql($Insert);
        if (debug) {
            print $Insert . '<br>';
        }
        if (!$Rs) {
            $Errore = 1;
        } else {
            if ($ath == 1) {
                $Insert = "INSERT INTO FinSchedule (FSEvent,FSTeamEvent,FSMatchNo,FSTournament,FSTarget, FSLetter) " . "VALUES(" . StrSafe_DB($ee) . "," . StrSafe_DB('0') . "," . StrSafe_DB($mm + 1) . "," . StrSafe_DB($_SESSION['TourId']) . "," . StrSafe_DB($Target) . "," . StrSafe_DB($Target ? $Target . 'B' : '') . "" . ") " . "ON DUPLICATE KEY UPDATE " . "FSTarget=" . StrSafe_DB($Target) . "," . "FSGroup=FSGroup," . "FSLetter=" . StrSafe_DB($Target ? $Target . 'B' : '') . ", " . "FSScheduledTime=FSScheduledTime ";
                $Rs = safe_w_sql($Insert);
                if (!$Rs) {
                    $Errore = 1;
                }
                $Update = "update FinSchedule " . " SET " . " FSLetter=" . StrSafe_DB($Target ? $Target . 'A' : '') . " " . "WHERE" . " FSEvent= " . StrSafe_DB($ee) . " AND FSTeamEvent= " . StrSafe_DB('0') . " AND FSMatchNo= " . StrSafe_DB($mm) . " AND FSTournament= " . StrSafe_DB($_SESSION['TourId']);
                $Rs = safe_w_sql($Update);
                if (!$Rs) {
                    $Errore = 1;
                }
            }
        }
    } else {
        $Errore = 1;
    }
    $ret .= '<field>';
    $ret .= '<error>' . $Errore . '</error>' . "\n";
    $ret .= '<org>' . $Key . ' - ' . $Value . '</org>' . "\n";
    $ret .= '<which><![CDATA[' . $Which . ']]></which>' . "\n";
    $ret .= '<target><![CDATA[' . $Target . ']]></target>' . "\n";
    $ret .= '<phase><![CDATA[' . $Phase . ']]></phase>' . "\n";
    $ret .= '<event><![CDATA[' . $Event . ']]></event>' . "\n";
    $ret .= '</field>';
    return $ret;
}
 /**
  * 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));
             }
         }
     }
 }
 /**
  * calcFromPhase()
  * Calcola la FinalRank per un evento in una certa fase
  * @param string $event: evento
  * @param int $phase: fase
  * @return boolean: true ok false altrimenti. In un ciclo il primo errore fa terminare il metodo con false!
  */
 protected function calcFromPhase($event, $phase, $FirstCycle = true)
 {
     // trasformo la fase
     $phase = valueFirstPhase($phase);
     $date = date('Y-m-d H:i:s');
     // reset delle RankFinal della fase x le persone di quell'evento e quella fase
     $q = "\r\n\t\t\t\tUPDATE\r\n\t\t\t\t\tTeams\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tTeamFinals\r\n\t\t\t\t\tON TeCoId=TfTeam AND TeSubTeam=TfSubTeam AND TeTournament=TfTournament AND TeEvent=TfEvent AND TeFinEvent=1\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tGrids\r\n\t\t\t\t\tON TfMatchNo=GrMatchNo AND GrPhase={$phase}\r\n\t\t\t\tSET\r\n\t\t\t\t\tTeRankFinal=0,\r\n\t\t\t\t\tTeTimeStampFinal='{$date}'\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tGrPhase={$phase} AND TeTournament={$this->tournament} AND TeEvent='{$event}' AND TeFinEvent=1\r\n\t\t\t";
     //print $q.'<br><br>';
     $r = safe_w_sql($q);
     if (!$r) {
         return false;
     }
     /*
      *  Tiro fuori gli scontri con i perdenti nei non Opp
      */
     $q = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t\ttf.TfTeam AS TeamId,\r\n\t\t\t\t\ttf.TfSubTeam AS SubTeam,\r\n\t\t\t\t\ttf2.TfTeam AS OppTeamId,\r\n\t\t\t\t\ttf2.TfSubTeam AS OppSubTeam,\r\n\t\t\t\t\tIF(EvMatchMode=0,tf.TfScore,tf.TfSetScore) AS Score, tf.TfScore AS CumScore,tf.TfTie AS Tie,\r\n\t\t\t\t\tIF(EvMatchMode=0,tf2.TfScore,tf2.TfSetScore) as OppScore, tf2.TfScore AS OppCumScore,tf2.TfTie as OppTie\r\n\r\n\t\t\t\tFROM\r\n\t\t\t\t\tTeamFinals AS tf\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tTeamFinals AS tf2\r\n\t\t\t\t\tON tf.TfEvent=tf2.TfEvent AND tf.TfMatchNo=IF((tf.TfMatchNo % 2)=0,tf2.TfMatchNo-1,tf2.TfMatchNo+1) AND tf.TfTournament=tf2.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 tf.TfMatchNo=GrMatchNo\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 tf.TfEvent=EvCode AND tf.TfTournament=EvTournament AND EvTeamEvent=1\r\n\r\n\t\t\t\t\tLEFT JOIN\r\n\t\t\t\t\t\t(select nm1.TfWinLose+nm2.TfWinLose Winner, nm1.TfMatchNo, nm1.TfEvent\r\n\t\t\t\t\t\tfrom TeamFinals nm1\r\n\t\t\t\t\t\tinner join TeamFinals nm2 on nm1.TfTournament=nm2.TfTournament and nm1.TfEvent=nm2.TfEvent and nm1.TfMatchNo=IF((nm1.TfMatchNo % 2)=0,nm2.TfMatchNo-1,nm2.TfMatchNo+1)\r\n\t\t\t\t\t\twhere nm1.TfTournament={$this->tournament} AND nm1.TfEvent='{$event}') NextMatch\r\n\t\t\t\t\ton NextMatch.TfMatchNo=floor(tf.TfMatchNo/2) and NextMatch.TfEvent=tf.TfEvent\r\n\r\n\t\t\t\tWHERE\r\n\t\t\t\t\ttf.TfTournament={$this->tournament} AND tf.TfEvent='{$event}' AND GrPhase={$phase}\r\n\t\t\t\t\tAND (\r\n\t\t\t\t\t\tIF(EvMatchMode=0,tf.TfScore,tf.TfSetScore) < IF(EvMatchMode=0,tf2.TfScore,tf2.TfSetScore)\r\n\t\t\t\t\t\tOR (IF(EvMatchMode=0,tf.TfScore,tf.TfSetScore)=IF(EvMatchMode=0,tf2.TfScore,tf2.TfSetScore) AND tf.TfTie < tf2.TfTie)\r\n\t\t\t\t\t\tOR (tf.TfWinLose+tf2.TfWinLose=0 and NextMatch.Winner>0)\r\n\t\t\t\t\t)\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\tIF(EvMatchMode=0,tf.TfScore,tf.TfSetScore) DESC,tf.TfScore DESC\r\n\t\t\t";
     // 			debug_svela($q);
     //print $q.'<br><br>';
     $rs = safe_r_sql($q);
     if ($rs) {
         if (safe_num_rows($rs) > 0) {
             /*
              * Se fase 0 (oro) il perdente ha la rank=2 e il vincente piglia 1,
              * se fase 1 (bronzo) il perdente ha la rank=4 e il vincete piglia 3
              * e in entrambi i casi avrò sempre e solo una riga.
              *
              * Se fase 2 (semi) non succede nulla.
              *
              * Per le altre fasi si cicla nel recordset che ha il numero di righe >=0
              */
             if ($phase == 0 || $phase == 1) {
                 $myRow = safe_fetch($rs);
                 $toWrite = array();
                 if ($phase == 0) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppTeamId, 'subteam' => $myRow->OppSubTeam, 'rank' => 1);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->TeamId, 'subteam' => $myRow->SubTeam, 'rank' => 2);
                 } elseif ($phase == 1) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppTeamId, 'subteam' => $myRow->OppSubTeam, 'rank' => 3);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->TeamId, 'subteam' => $myRow->SubTeam, 'rank' => 4);
                 }
                 foreach ($toWrite as $values) {
                     $x = $this->writeRow($values['id'], $values['subteam'], $values['event'], $values['rank']);
                     if ($x === false) {
                         return false;
                     }
                 }
             } elseif ($phase == 2) {
                 // non faccio nulla!
             } else {
                 // qui posso avere tante righe
                 $pos = 0;
                 /*
                  *  per la fase 4 pos viene inizializzato al valore iniziale -1
                  *  perchè poi nel ciclo come prima cosa ho un suo incremento dato che la if
                  *  che decide se incrementare o no sarà vera. Per gli altri non ci sarà
                  *  l'incremento così avrò sempre il valore iniziale (senza il -1)
                  */
                 switch ($phase) {
                     case 4:
                         $pos = 4;
                         // si parte da 5 quindi qui metto 4 dato che la fase è 4 (vedi commento qui sopra)
                         break;
                     case 8:
                         $pos = 9;
                         break;
                     case 16:
                         $pos = 17;
                         break;
                     case 32:
                         // (e 24)
                         $pos = 33;
                         break;
                     case 48:
                         $pos = 49;
                         break;
                     default:
                         return false;
                 }
                 if ($phase == 4) {
                     $rank = $pos + 1;
                 } else {
                     $rank = $pos;
                 }
                 $scoreOld = 0;
                 $cumOld = 0;
                 while ($myRow = safe_fetch($rs)) {
                     if ($phase == 4) {
                         ++$pos;
                         if (!($myRow->Score == $scoreOld && $myRow->CumScore == $cumOld)) {
                             $rank = $pos;
                         }
                     }
                     $scoreOld = $myRow->Score;
                     $cumOld = $myRow->CumScore;
                     // devo scrivere solo il perdente
                     $x = $this->writeRow($myRow->TeamId, $myRow->SubTeam, $event, $rank);
                     if ($x === false) {
                         return false;
                     }
                 }
             }
         }
         if ($FirstCycle) {
             // get all ranked 0 with next matches already won...
             $q = "\r\n\t\t\t\t\tSELECT distinct GrPhase\r\n\r\n\t\t\t\t\tFROM TeamFinals AS tf\r\n\t\t\t\t\tINNER JOIN Teams on TeCoId=tf.TfTeam and TeSubTeam=tf.TfSubTeam and TeTournament=tf.TfTournament and TeEvent=tf.TfEvent and TeRankFinal=0\r\n\t\t\t\t\tINNER JOIN Grids\r\n\t\t\t\t\t\tON tf.TfMatchNo=GrMatchNo\r\n\t\t\t\t\tINNER JOIN TeamFinals AS tf2\r\n\t\t\t\t\t\tON tf.TfEvent=tf2.TfEvent AND tf.TfMatchNo=IF((tf.TfMatchNo % 2)=0,tf2.TfMatchNo-1,tf2.TfMatchNo+1) AND tf.TfTournament=tf2.TfTournament\r\n\t\t\t\t\tINNER JOIN Events\r\n\t\t\t\t\t\tON tf.TfEvent=EvCode AND tf.TfTournament=EvTournament AND EvTeamEvent=1\r\n\t\t\t\t\tLEFT JOIN\r\n\t\t\t\t\t\t(select nm1.TfWinLose+nm2.TfWinLose Winner, nm1.TfMatchNo, nm1.TfEvent\r\n\t\t\t\t\t\t\tfrom TeamFinals nm1\r\n\t\t\t\t\t\t\tinner join TeamFinals nm2 on nm1.TfTournament=nm2.TfTournament and nm1.TfEvent=nm2.TfEvent and nm1.TfMatchNo=IF((nm1.TfMatchNo % 2)=0,nm2.TfMatchNo-1,nm2.TfMatchNo+1)\r\n\t\t\t\t\t\t\twhere nm1.TfTournament={$this->tournament} AND nm1.TfEvent='{$event}') NextMatch\r\n\t\t\t\t\t\ton NextMatch.TfMatchNo=floor(tf.TfMatchNo/2) and NextMatch.TfEvent=tf.TfEvent\r\n\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\ttf.TfTournament={$this->tournament} AND tf.TfEvent='{$event}'\r\n\t\t\t\t\tAND (\r\n\t\t\t\t\t\tIF(EvMatchMode=0,tf.TfScore,tf.TfSetScore) < IF(EvMatchMode=0,tf2.TfScore,tf2.TfSetScore)\r\n\t\t\t\t\t\tOR (IF(EvMatchMode=0,tf.TfScore,tf.TfSetScore)=IF(EvMatchMode=0,tf2.TfScore,tf2.TfSetScore) AND tf.TfTie < tf2.TfTie)\r\n\t\t\t\t\t\tOR (tf.TfWinLose+tf2.TfWinLose=0 and NextMatch.Winner>0)\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\tORDER BY\r\n\t\t\t\t\tIF(EvMatchMode=0,tf.TfScore,tf.TfSetScore) DESC,tf.TfScore DESC\r\n\t\t\t\t\t";
             $t = safe_r_sql($q);
             while ($u = safe_fetch($t)) {
                 $this->calcFromPhase($event, $u->GrPhase, false);
             }
         }
         // 				debug_svela($q);
     } else {
         return false;
     }
     return true;
 }
 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));
             }
         }
     }
 }
Example #8
0
     if ($veto) {
         $VetoEvents[] = $Event;
     }
 }
 sort($VetoEvents);
 //print '<pre>';
 //print_r($VetoEvents);
 //print '</pre>';
 $Select = "SELECT " . "IndId,IndRank, IndEvent,GrMatchNo,EvFinalFirstPhase " . "FROM " . "Individuals INNER JOIN Events ON IndTournament=EvTournament AND IndEvent=EvCode AND EvTeamEvent=0 " . "INNER JOIN Grids ON IF(EvFinalFirstPhase=24,32,IF(EvFinalFirstPhase=48,64,EvFinalFirstPhase))=GrPhase AND IndRank=IF(EvFinalFirstPhase=48 || EvFinalFirstPhase=24,GrPosition2, GrPosition) " . "WHERE " . "IndRank>0 and IndTournament=" . StrSafe_DB($_SESSION['TourId']) . " " . (count($Events) > 0 ? " AND IndEvent IN('" . implode("','", $Events) . "')" : "") . " " . ($VetoEvents ? " AND EvCode not in ('" . implode("','", $VetoEvents) . "')" : '') . "ORDER BY EvCode,IndRank ASC,GrMatchNo ASC ";
 //print $Select;exit;
 //exit;
 $RsSel = safe_r_sql($Select);
 if (safe_num_rows($RsSel)) {
     while ($MyRow = safe_fetch($RsSel)) {
         if (!array_key_exists($MyRow->IndEvent, $EventList)) {
             $EventList[$MyRow->IndEvent] = valueFirstPhase($MyRow->EvFinalFirstPhase);
         }
         if ($MyRow->IndRank <= $MaxRank[$MyRow->IndEvent]) {
             $Update = "UPDATE Finals SET " . "FinAthlete='" . $MyRow->IndId . "', " . "FinDateTime='" . date('Y-m-d H:i:s') . "' " . "WHERE FinEvent='" . $MyRow->IndEvent . "' AND " . "FinMatchNo='" . $MyRow->GrMatchNo . "' AND " . "FinTournament=" . StrSafe_DB($_SESSION['TourId']) . " ";
             $RsUp = safe_w_sql($Update);
         }
         //print $Update . '<br>';
     }
     // setto a 1 i flags che dicono che ho fatto gli spareggi per gli eventi
     //				$Update
     //					= "UPDATE Events SET "
     //					. "EvShootOff='1' "
     //					. "WHERE EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvCode IN('" . implode("','",$Events) . "')  AND EvTeamEvent='0' ";
     //				$RsUp=safe_w_sql($Update);
     $Update = "UPDATE Events SET " . "EvShootOff='1' " . "WHERE EvTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EvTeamEvent='0' " . (count($Events) > 0 ? " AND EvCode IN('" . implode("','", $Events) . "')" : "") . " " . ($VetoEvents ? " AND EvCode not in ('" . implode("','", $VetoEvents) . "')" : '');
     $RsUp = safe_w_sql($Update);
                $Sql .= "(SELECT {$ifc} as C" . $RuleCnt . ", SUM(IF(EnSubTeam=0,1,0)) AS QuantiMulti\r\n\t\t\t\t\t  FROM Entries\r\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) . "\r\n\t\t\t\t\t  WHERE {$ifc}<>0 AND EnTournament=" . StrSafe_DB($_SESSION['TourId']) . " AND EnTeam" . ($MyRowEv->EvMixedTeam ? 'Mix' : 'F') . "Event=1\r\n\t\t\t\t\t  group by {$ifc}, EnSubTeam\r\n\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);
            $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();
Example #10
0
 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;
     }
 }
 /**
  * calcFromPhase()
  * Calcola la FinalRank per un evento in una certa fase
  * @param string $event: evento
  * @param int $phase: fase
  * @return boolean: true ok false altrimenti. In un ciclo il primo errore fa terminare il metodo con false!
  */
 protected function calcFromPhase($event, $phase)
 {
     // trasformo la fase
     $phase = valueFirstPhase($phase);
     $date = date('Y-m-d H:i:s');
     // reset delle RankFinal della fase x le persone di quell'evento e quella fase
     $q = "\r\n\t\t\t\tUPDATE\r\n\t\t\t\t\tIndividuals\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tFinals\r\n\t\t\t\t\tON IndId=FinAthlete AND IndTournament=FinTournament AND IndEvent=FinEvent\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tGrids\r\n\t\t\t\t\tON FinMatchNo=GrMatchNo AND GrPhase={$phase}\r\n\t\t\t\tSET\r\n\t\t\t\t\tIndRankFinal=0,\r\n\t\t\t\t\tIndTimestampFinal='{$date}'\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tGrPhase={$phase} AND IndTournament={$this->tournament} AND IndEvent='{$event}'\r\n\t\t\t";
     //print $q.'<br><br>';
     $r = safe_w_sql($q);
     if (!$r) {
         return false;
     }
     /*
      *  Tiro fuori gli scontri con i perdenti nei non Opp
      */
     $q = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tf.FinAthlete AS AthId,\r\n\t\t\t\t\tf2.FinAthlete AS OppAthId,\r\n\t\t\t\t\tIF(EvMatchMode=0,f.FinScore,f.FinSetScore) AS Score, f.FinScore AS CumScore,f.FinTie AS Tie,\r\n\t\t\t\t\tIF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) as OppScore, f2.FinScore AS OppCumScore,f2.FinTie as OppTie\r\n\t\t\t\tFROM\r\n\t\t\t\t\tFinals AS f\r\n\r\n\t\t\t\t\tINNER JOIN\r\n\t\t\t\t\t\tFinals AS f2\r\n\t\t\t\t\tON f.FinEvent=f2.FinEvent AND f.FinMatchNo=IF((f.FinMatchNo % 2)=0,f2.FinMatchNo-1,f2.FinMatchNo+1) AND f.FinTournament=f2.FinTournament\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 f.FinMatchNo=GrMatchNo\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 f.FinEvent=EvCode AND f.FinTournament=EvTournament AND EvTeamEvent=0\r\n\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tf.FinTournament={$this->tournament} AND f.FinEvent='{$event}' AND GrPhase={$phase}\r\n\t\t\t\t\tAND (IF(EvMatchMode=0,f.FinScore,f.FinSetScore) < IF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) OR (IF(EvMatchMode=0,f.FinScore,f.FinSetScore)=IF(EvMatchMode=0,f2.FinScore,f2.FinSetScore) AND f.FinTie < f2.FinTie))\r\n\t\t\t\tORDER BY\r\n\t\t\t\t\tIF(EvMatchMode=0,f.FinScore,f.FinSetScore) DESC,f.FinScore DESC\r\n\t\t\t";
     //print $q.'<br><br>';
     $rs = safe_r_sql($q);
     if ($rs) {
         if (safe_num_rows($rs) > 0) {
             /*
              * Se fase 0 (oro) il perdente ha la rank=2 e il vincente piglia 1,
              * se fase 1 (bronzo) il perdente ha la rank=4 e il vincete piglia 3
              * e in entrambi i casi avrò sempre e solo una riga.
              *
              * Se fase 2 (semi) non succede nulla.
              *
              * Per le altre fasi si cicla nel recordset che ha il numero di righe >=0
              */
             if ($phase == 0 || $phase == 1) {
                 $myRow = safe_fetch($rs);
                 $toWrite = array();
                 if ($phase == 0) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppAthId, 'rank' => 1);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->AthId, 'rank' => 2);
                 } elseif ($phase == 1) {
                     // vincente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->OppAthId, 'rank' => 3);
                     // perdente
                     $toWrite[] = array('event' => $event, 'id' => $myRow->AthId, 'rank' => 4);
                 }
                 foreach ($toWrite as $values) {
                     $x = $this->writeRow($values['id'], $values['event'], $values['rank']);
                     if ($x === false) {
                         return false;
                     }
                 }
             } elseif ($phase == 2) {
                 // non faccio nulla!
             } else {
                 // qui posso avere tante righe
                 $pos = 0;
                 /*
                  *  per la fase 4 pos viene inizializzato al valore iniziale -1
                  *  perchè poi nel ciclo come prima cosa ho un suo incremento dato che la if
                  *  che decide se incrementare o no sarà vera. Per gli altri non ci sarà
                  *  l'incremento così avrò sempre il valore iniziale (senza il -1)
                  */
                 switch ($phase) {
                     case 4:
                         $pos = 4;
                         // si parte da 5 quindi qui metto 4 dato che la fase è 4 (vedi commento qui sopra)
                         break;
                     case 8:
                         $pos = 9;
                         break;
                     case 16:
                         $pos = 17;
                         break;
                     case 32:
                         // (e 24)
                         $pos = 33;
                         break;
                     case 48:
                         $pos = 57;
                         break;
                     case 64:
                         // gets the real firstpase of the event
                         $tt = safe_r_sql("select EvFinalFirstPhase from Events WHERE EvTournament={$this->tournament} AND EvCode='{$event}' ");
                         $uu = safe_fetch($tt);
                         $pos = $uu->EvFinalFirstPhase == 48 ? 57 : 65;
                         break;
                     default:
                         return false;
                 }
                 if ($phase == 4) {
                     $rank = $pos + 1;
                 } else {
                     $rank = $pos;
                 }
                 $scoreOld = 0;
                 $cumOld = 0;
                 while ($myRow = safe_fetch($rs)) {
                     if ($phase == 4) {
                         ++$pos;
                         if (!($myRow->Score == $scoreOld && $myRow->CumScore == $cumOld)) {
                             $rank = $pos;
                         }
                     }
                     $scoreOld = $myRow->Score;
                     $cumOld = $myRow->CumScore;
                     // devo scrivere solo il perdente
                     $x = $this->writeRow($myRow->AthId, $event, $rank);
                     if ($x === false) {
                         return false;
                     }
                 }
             }
         }
     } else {
         return false;
     }
     return true;
 }
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);
}
Example #13
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;
}