function UpdateTemplateMasters()
{
    /**********************************
     ******** Update Script for xml template to store the non existing Variable
     ***********************************/
    /*
    * developer: diddipoeler 
    * date: 13.01.2011
    * Bugtracker Backend Bug #579
    * change old textname in newtextname					
    */
    $convert = array('AGAINST' => 'JL_AGAINST', 'AVG' => 'JL_AVG', 'BONUS' => 'JL_BONUS', 'DIFF' => 'JL_DIFF', 'FOR' => 'JL_FOR', 'GB' => 'JL_GB', 'H2H' => 'JL_H2H', 'H2H_AWAY' => 'JL_H2H_AWAY', 'H2H_DIFF' => 'JL_H2H_DIFF', 'H2H_FOR' => 'JL_H2H_FOR', 'LEGS' => 'JL_LEGS', 'LEGS_DIFF' => 'JL_LEGS_DIFF', 'LEGS_RATIO' => 'JL_LEGS_RATIO', 'LEGS_WIN' => 'JL_LEGS_WIN', 'LOSSES' => 'JL_LOSSES', 'NEGPOINTS' => 'JL_NEGPOINTS', 'OLDNEGPOINTS' => 'JL_OLDNEGPOINTS', 'PLAYED' => 'JL_PLAYED', 'POINTS' => 'JL_POINTS', 'POINTS_RATIO' => 'JL_POINTS_RATIO', 'QUOT' => 'JL_QUOT', 'RESULTS' => 'JL_RESULTS', 'SCOREAGAINST' => 'JL_SCOREAGAINST', 'SCOREFOR' => 'JL_SCOREFOR', 'SCOREPCT' => 'JL_SCOREPCT', 'START' => 'JL_START', 'TIES' => 'JL_TIES', 'WINPCT' => 'JL_WINPCT', 'WINS' => 'JL_WINS');
    echo '<b>' . JText::_('Updating new variables and templates for usage in the Master-Templates') . '</b><br />';
    $db = JFactory::getDbo();
    $query = 'SELECT id,name,master_template FROM #__joomleague_project';
    $db->setQuery($query);
    if ($projects = $db->loadObjectList()) {
        //echo '<br />';
        $xmldir = JPATH_SITE . '/components/com_joomleague/settings/default';
        if ($handle = JFolder::files($xmldir)) {
            # check that each xml template has a corresponding record in the
            # database for this project (except for projects using master templates).
            # If not,create the rows with default values
            # from the xml file
            foreach ($handle as $file) {
                if (strtolower(substr($file, -3)) == 'xml' && substr($file, 0, strlen($file) - 4) != 'table' && substr($file, 0, 10) != 'prediction') {
                    $defaultconfig = array();
                    $template = substr($file, 0, strlen($file) - 4);
                    $out = simplexml_load_file($xmldir . '/' . $file, 'SimpleXMLElement', LIBXML_NOCDATA);
                    $temp = '';
                    $arr = obj2Array($out);
                    $outName = JText::_($out->name[0]);
                    echo '<br />' . JText::sprintf('Template: [%1$s] - Name: [%2$s]', "<b>{$template}</b>", "<b>{$outName}</b>") . '<br />';
                    if (isset($arr["params"]["param"])) {
                        foreach ($arr["params"]["param"] as $param) {
                            $temp .= $param["@attributes"]["name"] . "=" . $param["@attributes"]["default"] . "\n";
                            $defaultconfig[$param["@attributes"]["name"]] = $param["@attributes"]["default"];
                        }
                    } else {
                        foreach ($arr["params"] as $paramsgroup) {
                            foreach ($paramsgroup["param"] as $param) {
                                if (!isset($param["@attributes"])) {
                                    if (isset($param["name"])) {
                                        $temp .= $param["name"] . "=" . $param["default"] . "\n";
                                        $defaultconfig[$param["name"]] = $param["default"];
                                    }
                                } else {
                                    if (isset($param["name"])) {
                                        /*
                                        * developer: diddipoeler 
                                        * date: change on 13.01.2011
                                        * Bugtracker Backend Bug #579
                                        * error message string to object example template teamstats					
                                        */
                                        //$temp .= $param["@attributes"]["name"]."=".$param["@attributes"]["default"]."\n";
                                        $temp .= $param["name"] . "=" . $param["default"] . "\n";
                                        //$defaultconfig[$param["@attributes"]["name"]]=$param["@attributes"]["default"];
                                        $defaultconfig[$param["name"]] = $param["default"];
                                    }
                                }
                            }
                        }
                    }
                    $changeNeeded = false;
                    foreach ($projects as $proj) {
                        $count_diff = 0;
                        $configvalues = array();
                        $query = "SELECT params FROM #__joomleague_template_config WHERE project_id={$proj->id} AND template='" . $template . "'";
                        $db->setQuery($query);
                        if ($id = $db->loadResult()) {
                            //template present in db for this project
                            $string = '';
                            $templateTitle = '';
                            $params = explode("\n", trim($id));
                            foreach ($params as $param) {
                                list($name, $value) = explode("=", $param);
                                $configvalues[$name] = $value;
                            }
                            foreach ($defaultconfig as $key => $value) {
                                if (!array_key_exists($key, $configvalues)) {
                                    $count_diff++;
                                    $configvalues[$key] = $value;
                                }
                            }
                            if ($count_diff) {
                                foreach ($configvalues as $key => $value) {
                                    /*
                                    * developer: diddipoeler 
                                    * date: change on 13.01.2011
                                    * Bugtracker Backend Bug #579
                                    * change old textname in newtextname					
                                    */
                                    if (preg_match("/JL_/i", $value)) {
                                        // text ok
                                    } else {
                                        // change text
                                        $value = str_replace(array_keys($convert), array_values($convert), $value);
                                    }
                                    $value = trim($value);
                                    $string .= "{$key}={$value}\n";
                                }
                                echo JText::sprintf('Difference found for project [%1$s]', '<b>' . $proj->name . '</b>') . ' - ';
                                $changeNeeded = true;
                                $query = " UPDATE #__joomleague_template_config ";
                                $query .= " SET ";
                                $query .= " title='" . $out->name[0] . "',";
                                $query .= " params='{$string}' ";
                                $query .= " WHERE template='{$template}' AND project_id=" . $proj->id;
                                $db->setQuery($query);
                                if (!$db->execute()) {
                                    echo '<span style="color:red">';
                                    echo JText::sprintf('Problems while saving config for [%1$s] with project-ID [%2$s]!', '<b>' . $template . '</b>', '<b>' . $proj->id . '</b>');
                                    echo '</span>' . '<br />';
                                    echo $db->getErrorMsg() . '<br />';
                                } else {
                                    echo JText::sprintf('Updated template [%1$s] with project-ID [%2$s]', '<span style="color:green;"><b>' . $template . '</b></span>', '<span style="color:green"><b>' . $proj->id . '</b></span>') . PrintStepResult(true) . '<br />';
                                }
                            }
                        } elseif ($proj->master_template == 0) {
                            //check that project has own templates
                            //or if template not present,create a row with default values
                            echo '<br /><span style="color:orange;">' . JText::sprintf('Need to insert into project with project-ID [%1$s] - Project name is [%2$s]', '<b>' . $proj->id . '</b>', '<b>' . $proj->name . '</b>') . '</span><br />';
                            $changeNeeded = true;
                            $temp = trim($temp);
                            $query = "\tINSERT\n\t\t\t\t\t\t\t\t\t\t\tINTO #__joomleague_template_config\n\t\t\t\t\t\t\t\t\t\t\t\t(template,title,params,project_id)\n\t\t\t\t\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t\t\t\t\t\t('{$template}','" . $out->name[0] . "','{$temp}','{$proj->id}')";
                            $db->setQuery($query);
                            //echo error,allows to check if there is a mistake in the template file
                            if (!$db->execute()) {
                                echo '<span style="color:red; font-weight:bold; ">' . JText::sprintf('Error with [%s]:', $template) . '</span><br />';
                                echo $db->getErrorMsg() . '<br/>';
                            } else {
                                echo JText::sprintf('Inserted %1$s into project with ID %2$s', '<b>' . $template . '</b>', '<b>' . $proj->id . '</b>') . PrintStepResult(true) . '<br />';
                            }
                        }
                    }
                    if (!$changeNeeded) {
                        echo '<span style="color:green">' . JText::_('No changes needed for this template') . '</span>' . '<br />';
                    }
                }
            }
        } else {
            echo ' - <span style="color:red">' . JText::_('No templates found') . '</span>';
        }
    } else {
        echo ' - <span style="color:green">' . JText::_('No update was needed') . '</span>';
    }
    return '';
}
function UpdateTemplateMasters()
{
    /**
     * ********************************
     * ******* Update Script for xml template to store the non existing Variable
     * *********************************
     */
    /*
     * developer: diddipoeler date: 13.01.2011 Bugtracker Backend Bug #579 change old textname in newtextname
     */
    $convert = array('JL_AGAINST' => 'AGAINST', 'JL_AVG' => 'AVG', 'JL_BONUS' => 'BONUS', 'JL_DIFF' => 'DIFF', 'JL_FOR' => 'FOR', 'JL_GB' => 'GB', 'JL_H2H' => 'H2H', 'JL_H2H_AWAY' => 'H2H_AWAY', 'JL_H2H_DIFF' => 'H2H_DIFF', 'JL_H2H_FOR' => 'H2H_FOR', 'JL_LEGS' => 'LEGS', 'JL_LEGS_DIFF' => 'LEGS_DIFF', 'JL_LEGS_RATIO' => 'LEGS_RATIO', 'JL_LEGS_WIN' => 'LEGS_WIN', 'JL_LOSSES' => 'LOSSES', 'JL_NEGPOINTS' => 'NEGPOINTS', 'JL_OLDNEGPOINTS' => 'OLDNEGPOINTS', 'JL_PLAYED' => 'PLAYED', 'JL_POINTS' => 'POINTS', 'JL_POINTS_RATIO' => 'POINTS_RATIO', 'JL_QUOT' => 'QUOT', 'JL_RESULTS' => 'RESULTS', 'JL_SCOREAGAINST' => 'SCOREAGAINST', 'JL_SCOREFOR' => 'SCOREFOR', 'JL_SCOREPCT' => 'SCOREPCT', 'JL_START' => 'START', 'JL_TIES' => 'TIES', 'JL_WINPCT' => 'WINPCT', 'JL_WINS' => 'WINS');
    echo '<b>' . JText::_('Updating new variables and templates for usage in the Master-Templates') . '</b><br />';
    $db = JFactory::getDbo();
    $query = 'SELECT id,name,master_template FROM #__joomleague_project';
    $db->setQuery($query);
    if ($projects = $db->loadObjectList()) {
        // echo '<br />';
        $xmldir = JPATH_SITE . DS . 'components' . DS . 'com_joomleague' . DS . 'settings' . DS . 'default';
        if ($handle = JFolder::files($xmldir)) {
            // check that each xml template has a corresponding record in the
            // database for this project (except for projects using master templates).
            // If not,create the rows with default values
            // from the xml file
            foreach ($handle as $file) {
                if (strtolower(substr($file, -3)) == 'xml' && substr($file, 0, strlen($file) - 4) != 'table' && substr($file, 0, 10) != 'prediction') {
                    $defaultconfig = array();
                    $template = substr($file, 0, strlen($file) - 4);
                    $out = simplexml_load_file($xmldir . DS . $file, 'SimpleXMLElement', LIBXML_NOCDATA);
                    $temp = '';
                    $arr = obj2Array($out);
                    $outName = JText::_($out->name[0]);
                    echo '<br />' . JText::sprintf('Template: [%1$s] - Name: [%2$s]', "<b>{$template}</b>", "<b>{$outName}</b>") . '<br />';
                    if (isset($arr["fieldset"]["field"])) {
                        foreach ($arr["fieldset"]["field"] as $param) {
                            $temp .= $param["@attributes"]["name"] . "=" . $param["@attributes"]["default"] . "\n";
                            $defaultconfig[$param["@attributes"]["name"]] = $param["@attributes"]["default"];
                        }
                    } else {
                        foreach ($arr["fieldset"] as $paramsgroup) {
                            foreach ($paramsgroup["field"] as $param) {
                                if (!isset($param["@attributes"])) {
                                    if (isset($param["name"])) {
                                        $temp .= $param["name"] . "=" . $param["default"] . "\n";
                                        $defaultconfig[$param["name"]] = $param["default"];
                                    }
                                } else {
                                    if (isset($param["name"])) {
                                        /*
                                         * developer: diddipoeler date: change on 13.01.2011 Bugtracker Backend Bug #579 error message string to object example template teamstats
                                         */
                                        // $temp .= $param["@attributes"]["name"]."=".$param["@attributes"]["default"]."\n";
                                        $temp .= $param["name"] . "=" . $param["default"] . "\n";
                                        // $defaultconfig[$param["@attributes"]["name"]]=$param["@attributes"]["default"];
                                        $defaultconfig[$param["name"]] = $param["default"];
                                    }
                                }
                            }
                        }
                    }
                    $changeNeeded = false;
                    foreach ($projects as $proj) {
                        $count_diff = 0;
                        $configvalues = array();
                        $tblTemplate_Config = JTable::getInstance('template', 'table');
                        $loaded = $tblTemplate_Config->load(array('template' => $template, 'project_id' => $proj->id));
                        if ($loaded) {
                            // template present in db for this project
                            $string = '';
                            $templateTitle = '';
                            $params = explode("\n", trim($tblTemplate_Config->params));
                            foreach ($params as $param) {
                                $row = explode("=", $param);
                                if (isset($row[1])) {
                                    list($name, $value) = $row;
                                    $configvalues[$name] = $value;
                                }
                            }
                            foreach ($defaultconfig as $key => $value) {
                                if (!array_key_exists($key, $configvalues)) {
                                    $count_diff++;
                                    $configvalues[$key] = $value;
                                }
                            }
                            if ($count_diff || $template == 'ranking' || $template == 'overall' || $template == 'player') {
                                foreach ($configvalues as $key => $value) {
                                    if (preg_match("/%H:%m/i", $value)) {
                                        // change text
                                        $value = 'H:i';
                                    } else {
                                        // text ok
                                    }
                                    if (preg_match("/%A %B %d/i", $value)) {
                                        // change text
                                        $value = 'l, d.m.Y';
                                    } else {
                                        // text ok
                                    }
                                    /*
                                     * developer: diddipoeler date: change on 13.01.2011 Bugtracker Backend Bug #579 change old textname in newtextname
                                     */
                                    if (preg_match("/JL_/i", $value)) {
                                        // change text
                                        $value = str_replace(array_keys($convert), array_values($convert), $value);
                                    } else {
                                        // text ok
                                    }
                                    $value = trim($value);
                                    $string .= "{$key}={$value}\n";
                                }
                                echo JText::sprintf('Difference found for project [%1$s]', '<b>' . $proj->name . '</b>') . ' - ';
                                $changeNeeded = true;
                                $tblTemplate_Config = JTable::getInstance('template', 'table');
                                $tblTemplate_Config->load(array('template' => $template, 'project_id' => $proj->id));
                                $tblTemplate_Config->title = $out->name[0];
                                $tblTemplate_Config->params = $string;
                                if ($tblTemplate_Config->store()) {
                                    echo '<span style="color:red">';
                                    echo JText::sprintf('Problems while saving config for [%1$s] with project-ID [%2$s]!', '<b>' . $template . '</b>', '<b>' . $proj->id . '</b>, <b>' . $string . '</b>');
                                    echo '</span>' . '<br />';
                                    echo $db->getErrorMsg() . '<br />';
                                } else {
                                    echo JText::sprintf('Updated template [%1$s] with project-ID [%2$s]', '<span style="color:green;"><b>' . $template . '</b></span>', '<span style="color:green"><b>' . $proj->id . '</b></span>') . PrintStepResult(true) . '<br />';
                                }
                            }
                        } elseif ($proj->master_template == 0) {
                            // check that project has own templates
                            // or if template not present,create a row with default values
                            echo '<br /><span style="color:orange;">' . JText::sprintf('Need to insert into project with project-ID [%1$s] - Project name is [%2$s]', '<b>' . $proj->id . '</b>', '<b>' . $proj->name . '</b>') . '</span><br />';
                            $changeNeeded = true;
                            $temp = trim($temp);
                            $tblTemplate_Config = JTable::getInstance('template', 'table');
                            $tblTemplate_Config->title = $out->name[0];
                            $tblTemplate_Config->params = $temp;
                            $tblTemplate_Config->project_id = $proj->id;
                            $tblTemplate_Config->template = $template;
                            // echo error,allows to check if there is a mistake in the template file
                            if (!$tblTemplate_Config->store()) {
                                echo '<span style="color:red; font-weight:bold; ">' . JText::sprintf('Error with [%s]:', $template) . '</span><br />';
                                echo $db->getErrorMsg() . '<br/>';
                            } else {
                                echo JText::sprintf('Inserted %1$s into project with ID %2$s', '<b>' . $template . '</b>', '<b>' . $proj->id . '</b>, ' . $temp) . PrintStepResult(true) . '<br />';
                            }
                        }
                    }
                    if (!$changeNeeded) {
                        echo '<span style="color:green">' . JText::_('No changes needed for this template') . '</span>' . '<br />';
                    }
                }
            }
        } else {
            echo ' - <span style="color:red">' . JText::_('No templates found') . '</span>';
        }
    } else {
        echo ' - <span style="color:green">' . JText::_('No update was needed') . '</span>';
    }
    return '';
}