<?php
/**
 * @author Alessandro Vernassa <speleoalex@gmail.com>
 * @copyright Copyright (c) 2003-2009
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License
 * @package xmldb
 * 
 */
/**
 * edid xml tables
 * 
 * @param $tablename
 * @param $dbname
 * @param $params
 * @return unknown_type
 */
function XMLDB_editor($tablename, $dbname, $params = false)
{
    //--parametri ---->

    $html = "";
    $tname = $tablename;
    if (is_array($tablename))
    {
        if (isset($tablename['tablename']))
        {
            $tname = $tablename['tablename'];
        }
        else
        {
            die("tablename is not set");
        }
    }
    elseif (is_object($tablename))
    {
        $params['table'] = $tablename;
        $tablename = $tname = $tablename->tablename;
    }

    $errors = array();
    $postgetkey = "__xdb_{$tname}"; //identificatico della tabella
    $param['charset_page'] = empty($param['charset_page']) ? "UTF-8" : $param['charset_page'];
    $echo = isset($params['echo']) ? $params['echo'] : true;
    $path = isset($params['path']) ? $params['path'] : "";
    $lang = isset($params['lang']) ? $params['lang'] : "en";
    $languages = isset($params['languages']) ? $params['languages'] : "en";
    $restr = isset($params['restr']) ? $params['restr'] : false;
    $restr = isset($params['filters']) ? $params['filters'] : $restr;
    $table = isset($params['table']) ? $params['table'] : false;
    $fields = isset($params['fields']) ? $params['fields'] : false;
    $functionsview = isset($params['functionsview']) ? $params['functionsview'] : false;
    $show_translations = isset($params['show_translations']) ? $params['show_translations'] : false;
    $bgcolor = isset($params['bkrow']) ? $params['bkrow'] : "#ffffff";
    $bgcolor2 = isset($params['bkrow2']) ? $params['bkrow2'] : "#ffffff";
    $bgcolorover = isset($params['bgcolorover']) ? $params['bgcolorover'] : "#ffff00";
    $backgroundcolorheader = isset($params['bkheader']) ? $params['bkheader'] : "#dfdfdf";
    $bordercolor = isset($params['bordercolor']) ? $params['bordercolor'] : "#d8d8d8";
    $textcolor = isset($params['textcolor']) ? $params['textcolor'] : "#000000";
    $linkcolor = isset($params['linkcolor']) ? $params['linkcolor'] : "#000000";
    $flink = isset($params['link']) ? $params['link'] : "";
    $flink_listmode = isset($params['link_listmode']) ? $params['link_listmode'] : $params['link'];
    $enableview = isset($params['enableview']) ? $params['enableview'] : false;
    $enabledelete = isset($params['enabledelete']) ? $params['enabledelete'] : true;
    $enableedit = isset($params['enableedit']) ? $params['enableedit'] : true;
    $enablenew = isset($params['enablenew']) ? $params['enablenew'] : true;
    $defaultorder = isset($params['defaultorder']) ? $params['defaultorder'] : false;
    $reverse = isset($params['defaultorderdesc']) ? $params['defaultorderdesc'] : false;

    //function in insert form
    $functioninsert = isset($params['functioninsert']) ? $params['functioninsert'] : "";

    //html in insert form
    $oninsert = isset($params['oninsert']) ? $params['oninsert'] : "";
    $onupdate = isset($params['onupdate']) ? $params['onupdate'] : "";

    //function on insert form
    $function_on_insert = isset($params['function_on_insert']) ? $params['function_on_insert'] : "";
    $function_on_update = isset($params['function_on_update']) ? $params['function_on_update'] : "";
    $function_on_delete = isset($params['function_on_delete']) ? $params['function_on_delete'] : "";

    $htmlgrid = isset($params['htmlgrid']) ? $params['htmlgrid'] : "";

    //force values
    $forcevalues = isset($params['forcevalues']) ? $params['forcevalues'] : false;
    $forcevalues = isset($params['forcefieldvalues']) ? $params['forcefieldvalues'] : $forcevalues;
    //force in insert
    $forcevaluesinsert = isset($params['forcevaluesinsert']) ? $params['forcevaluesinsert'] : false;
    //force in update
    $forcevaluesupdate = isset($params['forcevaluesupdate']) ? $params['forcevaluesupdate'] : false;
    //force in form insert
    $forcenewvalues = isset($params['forcenewvalues']) ? $params['forcenewvalues'] : true;
    //force in form update
    $forceupdatevalues = isset($params['forceupdatevalues']) ? $params['forceupdatevalues'] : true;
    $recordsperpage = isset($params['recordsperpage']) ? $params['recordsperpage'] : false;
    $textrequired = isset($params['textrequired']) ? $params['textrequired'] : "*";
    $textfields = isset($params['textfields']) ? $params['textfields'] : "<legend>" . "*=required fields" . "</legend><br />";
    $textfields = str_replace("*", "", $textfields);
    $textsave = isset($params['textsave']) ? $params['textsave'] : "save";
    $textnorecord = isset($params['textnorecord']) ? $params['textnorecord'] : "no records found";
    $optionsedit = array();
    if ($enableview)
        $optionsedit[] = "view";
    if ($enableedit)
        $optionsedit[] = "edit";
    if ($enabledelete)
        $optionsedit[] = "delete";
    $textcancel = isset($params['textcancel']) ? $params['textcancel'] : "Cancel";
    $textnew = isset($params['textnew']) ? $params['textnew'] : "[ new ]";
    $textinsertok = isset($params['textinsertok']) ? $params['textinsertok'] : "the data were successfully inserted";
    $textupdateok = isset($params['textupdateok']) ? $params['textupdateok'] : "the data were successfully updated";
    $textinsertfail = isset($params['textinsertfail']) ? $params['textinsertfail'] : "error insert record";
    $textupdatefail = isset($params['textupdatefail']) ? $params['textupdatefail'] : "error update record";
    $textviewlist = isset($params['textviewlist']) ? $params['textviewlist'] : "&lt;&lt;&nbsp;" . "back" . "";
    $textpages = isset($params['textpages']) ? $params['textpages'] : "Pages :";
    $textview = isset($params['textview']) ? $params['textview'] : "view";
    $textmodify = isset($params['textmodify']) ? $params['textmodify'] : "modify";
    $textdelete = isset($params['textdelete']) ? $params['textdelete'] : "delete";
    $textexitwithoutsaving = isset($params['textexitwithoutsaving']) ? $params['textexitwithoutsaving'] : "want to exit without saving?";

    $list_oninsert = $list_onupdate = $list_onsave = isset($params['list_onsave']) ? $params['list_onsave'] : 1;
    $list_oninsert = isset($params['list_oninsert']) ? $params['list_oninsert'] : $list_onsave;
    $list_onupdate = isset($params['list_onupdate']) ? $params['list_onupdate'] : $list_onsave;



    //--parametri ----<
    //-----variabili da get --------->
    $opmod = isset($_GET["op_$postgetkey"]) ? htmlspecialchars($_GET["op_$postgetkey"]) : "";
    $pk = isset($_GET["pk_$postgetkey"]) ? htmlspecialchars($_GET["pk_$postgetkey"]) : "";
    $page = isset($_GET["page_$postgetkey"]) ? htmlspecialchars($_GET["page_$postgetkey"]) : "";
    $order = isset($_GET["order_$postgetkey"]) ? htmlspecialchars($_GET["order_$postgetkey"]) : "";
    if ($order != "")
    {
        $reverse = isset($_GET["desc_$postgetkey"]) ? htmlspecialchars($_GET["desc_$postgetkey"]) : "";
    }
    //-----variabili da get ---------<
    $tlink = "";
    $mlink = "&amp;page_$postgetkey=$page";
    if (is_array($forcevalues))
        foreach ($forcevalues as $key => $value)
        {
            $tlink .= "&amp;" . $key . "=" . $value;
            $mlink .= "&amp;" . $key . "=" . $value;
        }
    if ($flink != "")
    {
        $tlink .= "&amp;$flink";
        $mlink .= "&amp;$flink";
    }
    //-----tabella --------->
    if (!is_object($table))
        $table = new FieldFrm("$dbname", $tablename, $path, $lang, $languages);

    $table->charset_page = $param['charset_page'];
    if (isset($params['layout']))
    {
        $table->SetLayout($params['layout']);
    }
    if (!empty($params['layout_template']))
    {
        $table->SetlayoutTemplate($params['layout_template']);
    }

    //filtro sulle foreignkey---->
    if (!empty($params['restrfk']))
    {
        if (is_array($params['restrfk']))
        {
            foreach ($params['restrfk'] as $k => $v)
            {
                if (isset($table->formvals[$k]))
                {
                    $table->formvals[$k]['fk_filter_field'] = $v;
                }
            }
        }
        else
        {
            foreach ($table->formvals as $k => $v)
            {
                if (!empty($table->formvals[$k]['foreignkey']))
                {
                    $table->formvals[$k]['fk_filter_field'] = $params['restrfk'];
                }
            }
        }
    }
    //filtro sulle foreignkey----<



    $scriptOnExit = "
<script type=\"text/javascript\">
function set_changed()
{
	document.getElementById('exit_$postgetkey').setAttribute('onclick',
	'if(confirm (\"" . addslashes($textexitwithoutsaving) . "\")){window.location=\"?" . str_replace("&amp;", "&", $tlink) . "\";}');
	var allLinks = document.getElementsByTagName('a');
	for (var i in allLinks)
	{
		if (!allLinks[i].onclick || allLinks[i].onclick=='' || allLinks[i].onclick==undefined && allLinks[i].href )
		{
			if (allLinks[i].setAttribute)
			{
				allLinks[i].setAttribute('onclick','return confirm_exitnosave()');
			}
		}
	}
}
function confirm_exitnosave()
{
	if(confirm ('" . addslashes($textexitwithoutsaving) . "'))
	{
		return true;
	}
	return false;
}
</script>
	";
    if (isset($_POST['__NOSAVE']))
    {
        $scriptOnExit .= "
<script type=\"text/javascript\">
set_changed();
</script>";
    }


    //-----tabella --------->
    $toupdate = false;
    //----eliminazione del record
    if ($enabledelete && $opmod == "del")
    {
        $oldvalues = $table->xmltable->GetRecordByPk($pk);
        if ($function_on_delete && function_exists($function_on_delete))
        {
            ob_start();
            $function_on_delete($oldvalues);
            $html .= ob_get_clean();
        }
        $table->xmltable->DelRecord($pk);
    }
    $endloop = false;
    while ($endloop == false)
    {
        switch ($opmod)
        {
            //-------inserimento/aggiornamento record  --------->
            case "insnew" :
                $endloop = true;
                echo $scriptOnExit;
                //dprint_r($_POST);
                $newvalues = $table->getbypost();
                //dprint_r($newvalues);
                if (is_array($forcevalues))
                {
                    foreach ($forcevalues as $k => $v)
                    {
                        $newvalues[$k] = $v;
                    }
                }

                if ($pk != "")
                {
                    $oldvalues = $table->xmltable->GetRecordByPk($pk);
                    $toupdate = true; //se esiste la chiave primaria il record ï¿½ da aggiornare
                }

                if ($toupdate && is_array($forcevaluesupdate))
                {
                    foreach ($forcevaluesupdate as $k => $v)
                    {
                        $newvalues[$k] = $v;
                    }
                }
                if (!$toupdate && is_array($forcevaluesinsert))
                {
                    foreach ($forcevaluesinsert as $k => $v)
                    {
                        $newvalues[$k] = $v;
                    }
                }
                if ($toupdate && !$enableedit)
                    break;
                if (!$toupdate && !$enablenew)
                    break;
                if (isset($_POST["save_$postgetkey"]))
                {
                    if (isset($_POST[$table->xmltable->primarykey]) && $pk)
                    {
                        if ($table->xmltable->GetRecordByPk($_POST[$table->xmltable->primarykey]))
                        {
                            $toupdate = true;
                        }
                    }
                    $errors = $table->Verify($newvalues, $toupdate);
                    if (count($errors) == 0)
                    {
                        if ($toupdate)
                        {
                            $newvalues = $table->UpdateRecord($newvalues, $pk);
                            $pk = $newvalues[$table->xmltable->primarykey];
                            if ($onupdate != "")
                            {
                                $html .= $onupdate;
                                break;
                            }
                            if (is_array($newvalues))
                            {
                                if ($function_on_update && function_exists($function_on_update))
                                {
                                    ob_start();
                                    $function_on_update($newvalues, $oldvalues);
                                    $html .= ob_get_clean();
                                }
                                $html = FN_HtmlAlert($textupdateok) . $html;
                                if ($list_onupdate)
                                {
                                    $endloop = false;
                                    $opmod = "";
                                    break;
                                }
                            }
                            else
                            {
                                $html = FN_HtmlAlert($textupdatefail) . $html;
                            }
                        }
                        else
                        {
                            //insert record
                            $newvalues = $table->InsertRecord($newvalues);
                            if (isset($newvalues[$table->xmltable->primarykey]))
                            {
                                $pk = $newvalues[$table->xmltable->primarykey];
                                if ($function_on_insert && function_exists($function_on_insert))
                                {
                                    ob_start();
                                    $function_on_insert($newvalues);
                                    $html .= ob_get_clean();
                                }
                                if ($oninsert != "")
                                {
                                    $html .= $oninsert;
                                    break;
                                }
                                $html = FN_HtmlAlert($textinsertok) . $html;
                            }
                            else
                                $html = FN_HtmlAlert($textinsertfail) . $html;

                            if ($list_oninsert)
                            {
                                $endloop = false;
                                $opmod = "";
                                break;
                            }
                            $toupdate = true;
                        }
                    }
                }
                $html .= "<fieldset>$textrequired $textfields";
                $html .= "

";


                $html .= "<form onchange=\"set_changed()\" enctype=\"multipart/form-data\" action=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;pk_{$postgetkey}=$pk&amp;op_$postgetkey=insnew$tlink\" method=\"post\"><div>\n";
                if ($toupdate)
                {
                    $html .= "";

                    if (is_array($forceupdatevalues))
                        foreach ($forceupdatevalues as $fok => $fov)
                        {
                            if (!isset($_POST[$fok]))
                            {
                                $newvalues[$fok] = $fov;
                            }
                        }
                    $html .=$table->HtmlShowUpdateForm($pk, FN_IsAdmin(), $newvalues, $errors);
                }
                else
                {
                    if (is_array($forcenewvalues))
                        foreach ($forcenewvalues as $fok => $fov)
                        {
                            if (!isset($_POST[$fok]))
                            {
                                $newvalues[$fok] = $fov;
                            }
                        }
                    $html .= $table->HtmlShowInsertForm(FN_IsAdmin(), $newvalues, $errors);
                }
                if ($functioninsert != "" && function_exists($functioninsert))
                {
                    ob_start();
                    $functioninsert($newvalues);
                    $html .= ob_get_clean();
                }
                $html .= "<br /><input type=\"hidden\" name=\"save_$postgetkey\" value=\"$postgetkey\"/><button  type=\"submit\"  >" . $textsave . "</button>";
                $html .= "&nbsp;<button id='exit_$postgetkey' type=\"button\" onclick=\"window.location='?" . str_replace("&amp;", "&", $tlink) . "'\" >" . $textcancel . "</button>";
                $html .= "\n</div></form></fieldset>";
                if ($textviewlist)
                    $html .= "<br /><a  href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;$flink_listmode\">$textviewlist</a> ";
                if ($enablenew)
                    $html .= "&nbsp;<a href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;op_{$postgetkey}=insnew$mlink\">$textnew</a>";
                $html .="<br />";

                break;
            //-------inserimento/aggiornamento record  ---------<
            case "view" :
                $endloop = true;
                if (isset($params['layout_view']))
                {
                    $table->SetLayoutView($params['layout_view']);
                }
                if (isset($params['layout_template_view']))
                {
                    $table->SetlayoutTemplateView($params['layout_template_view']);
                }
                $html .=$table->HtmlShowView($table->GetRecordTranslatedByPrimarykey($pk));
                //$html .= xmldb_view($pk,$tablename,$dbname,$path,$lang,$languages);
                $html .= "<br /><br /><a style=\"color:$linkcolor\" href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;$flink_listmode\">$textviewlist</a><br /><br />";

                break;
            default :
                $endloop = true;
                if ($htmlgrid)
                    $html .= $htmlgrid;
                else
                {
                    $fieldstoread = $__fieldstoread = false;
                    if ($fields != false && !is_array($fields))
                    {
                        $fields = explode("|", $fields);
                        $__fieldstoread = $fields;
                        if (!isset($__fieldstoread[$table->xmltable->primarykey]))
                        {
                            $__fieldstoread[] = $table->xmltable->primarykey;
                        }
                    }
                    if ($__fieldstoread)
                    {
                        foreach ($__fieldstoread as $fieldname)
                        {
                            if (isset($table->xmltable->fields[$fieldname]))
                            {
                                $fieldstoread[] = $fieldname;
                            }
                        }
                    }
                    if ($defaultorder == false)
                        $defaultorder = $table->xmltable->primarykey;
                    if ($order == false)
                        $order = $defaultorder;
                    //echo "or=$order";
                   /*
                    if (!empty($params['searchfields']))
                    {
                        $html .= "<form method=\"post\" action=\"?$tlink&amp;order_{$postgetkey}=$order\">";
                        $html .= "<button type=\"submit\">".  FN_Translate("search")."</button>";
                        $html .= "</form>";
                    }*/
                    $numPages = 1;
                    if (intval($recordsperpage) != false)
                    {
                        //die ("r=$recordsperpage");
                        if ($page == "")
                            $page = 1;
                        $num_records = $table->xmltable->GetNumRecords($restr);
                        //echo "num_records=$num_records ";
                        $numPages = ceil($num_records / $recordsperpage);
                        if ($page > $numPages)
                            $page = $numPages;
                        $start = ($page * $recordsperpage - $recordsperpage) + 1;
                        $end = $start + $recordsperpage - 1;
                    }
                    else
                    {
                        $start = false;
                    }
                    //die ("ds");

                    if ($order == false)
                    {
                        $all = $table->xmltable->GetRecords($restr, $start, $recordsperpage, $order, $reverse, $fieldstoread);
                    }
                    else
                    {
                        $all = $table->xmltable->GetRecords($restr, false, false, false, false, $fieldstoread);
                    }
                    if ($recordsperpage && $numPages > 1)
                    {
                        $html .= $textpages;
                        for ($i = 1; $i <= $numPages; $i++)
                        {
                            if ($page == $i)
                                $html .= " <a style=\"color:$linkcolor\" href=\"?$tlink&amp;page_{$postgetkey}=$i&amp;order_{$postgetkey}=$order\"><b>$i</b></a>";
                            else
                                $html .= " <a style=\"color:$linkcolor\" href=\"?$tlink&amp;page_{$postgetkey}=$i&amp;order_{$postgetkey}=$order\">$i</a>";
                        }
                    }
                    if ($order != false)
                    {
                        if (is_array($all))
                            $all = xmldb_array_natsort_by_key($all, str_replace("{$postgetkey}", "", $order));
                    }
                    if ($reverse == true)
                    {
                        $all = array_reverse($all);
                    }
                    echo "
<script type=\"text/javascript\">
trh = function (over,elem){
	var old;
	if (over){
		this.old = elem.style.backgroundColor ;
		elem.style.backgroundColor='$bgcolorover';
	}
	else{
		elem.style.backgroundColor=this.old;
	}
}
</script>
";

                    $html .= "<table style=\"background-color:$bordercolor\" cellpadding=\"2\" cellspacing=\"1\" >";
                    $html .= "<tr >";
                    $orderfield = array();
                    if ($fields)
                    {
                        foreach ($fields as $ofield)
                        {
                            if (isset($table->formvals[$ofield]))
                            {
                                $orderfield[$ofield] = $table->formvals[$ofield];
                            }
                            else
                            {
                                $orderfield[$ofield] = "";
                            }
                        }
                    }
                    else
                        $orderfield = $table->formvals;
                    $numcols = 0;
                    foreach ($orderfield as $key => $value)
                    {
                        if ($fields && !in_array($key, $fields))
                        {
                            continue;
                        }
                        if ($show_translations == true || !isset($table->formvals[$key]['frm_multilanguage']) || $table->formvals[$key]['frm_multilanguage'] != "1")
                        {
                            $numcols++;
                            if (isset($value['title']))
                            {
                                $rev = "";
                                $t = "";
                                $desclink = "";
                                if ($order == $key)
                                {
                                    if ($reverse)
                                    {
                                        $t = "<img style=\"vertical-align:middle;float:right\" src=\"images/fn_up.png\" alt=\"\" />";
                                        $desclink = "";
                                    }
                                    else
                                    {
                                        $t = "<img style=\"vertical-align:middle;float:right\" src=\"images/fn_down.png\" alt=\"\" />";
                                        $desclink = "&amp;desc_{$postgetkey}=$key";
                                    }
                                }
                                $html .= "<td style=\"background-color:$backgroundcolorheader;font-weight:bold;color:$textcolor\" ><a style=\"color:$linkcolor\" href=\"?order_{$postgetkey}=$key{$desclink}&amp;$tlink\">" . $value['title'] . "</a>$t</td>";
                            }
                            else
                            {
                                $html .= "<td style=\"background-color:$backgroundcolorheader;font-weight:bold;color:$textcolor\" ></td>";
                            }
                        }
                    }
                    $colspan = count($optionsedit);
                    if ($colspan > 0)
                    {
                        $numcols+=3;
                        $html .= "<td style=\"background-color:$backgroundcolorheader;color:$textcolor\" colspan=\"3\">&nbsp;</td>";
                    }
                    $html .= "</tr>";
                    $i = 0;
                    static $tablefk = array();
                    if (is_array($all) && count($all) > 0)
                    {
                        foreach ($all as $row)
                        {
                            $backgroundcolor = ($i % 2 == 0) ? $bgcolor : $bgcolor2;
                            $i++;
                            //start - end --->
                            if ($recordsperpage != false && ($i < $start || $i > $end))
                                continue;
                            //start -end ---<
                            $html .= "<tr style=\"background-color:$backgroundcolor;color:$textcolor\" onmouseover=\"trh(1,this)\" onmouseout=\"trh(0,this)\" >";
                            foreach ($orderfield as $key => $field)
                            {
                                $kfunction = (false !== strpos($key, "()")) ? str_replace("()", "", $key) : false;
                                if ($fields && !in_array($key, $fields))
                                    continue;
                                $vimage = "";
                                if ($show_translations == true || !isset($table->formvals[$key]['frm_multilanguage']) || $table->formvals[$key]['frm_multilanguage'] != "1")
                                {
                                    if (isset($functionsview[$key]))
                                    {
                                        $value = $functionsview[$key]($row[$field['name']]);
                                    }
                                    elseif (function_exists($kfunction))
                                    {
                                        $value = $kfunction($row[$table->xmltable->primarykey], $table);
                                    }
                                    elseif (!isset($field['name']))
                                    {
                                        $value = "";
                                    }
                                    else
                                    {

                                        $value = $row[$field['name']];
                                        //print_r($field);
                                        if ($field['frm_type'] == "image")
                                        {
                                            $image = $table->xmltable->get_file($row, $field['name']);
                                            if ($image != "")
                                            {
                                                $himage = 16;
                                                if (isset($params['imagesize']))
                                                {
                                                    $himage = $params['imagesize'];
                                                }
                                                $image = dirname($image) . "/thumbs/" . basename($image) . ".jpg";
                                                $vimage = "<img src=\"" . $image . "\" height=\"$himage\" />";
                                                $value = "";
                                            }
                                        }
                                        if (!empty($field['foreignkey']) && !empty($field['fk_show_field']))
                                        {
                                            $r = array();
                                            $tfk[$field['fk_link_field']] = xmldb_table($dbname, $field['foreignkey'], $path);
                                            $tablefk = $tfk[$field['fk_link_field']];
                                            $f = $field['fk_link_field'];
                                            if ($field['fk_link_field'] != $field['fk_show_field'])
                                            {
                                                $f.= "|" . $field['fk_show_field'];
                                            }
                                            if (isset($tfk[$field['fk_link_field']]->fields[$field['fk_link_field'] . "_{$lang}"]))
                                                $f .= "|" . $field['fk_show_field'] . "_{$_FN['lang']}";
                                            //echo $f;

                                            $r[$field['fk_link_field']] = $row[$field['name']];
                                            //dprint_r($value);
                                            $showfields = explode(",", $field['fk_show_field']);
                                            $value = "";
                                            $sep = "";
                                            foreach ($showfields as $showfield)
                                            {
                                                $fname_tmp_array = $row[$field['name']];
                                                $fname_tmp_array = explode(",", $fname_tmp_array);
                                                foreach ($fname_tmp_array as $fname_tmp)
                                                {
                                                    $tvalue = $tablefk->GetRecord(array($field['fk_link_field'] => $fname_tmp));
                                                    if (isset($tvalue["{$showfield}_{$lang}"]) && $tvalue["{$showfield}_{$lang}"] != "")
                                                        $value .=$sep . $tvalue["{$showfield}_{$lang}"];
                                                    elseif (isset($tvalue["{$showfield}_en"]) && $tvalue["{$showfield}_en"] != "")
                                                        $value .=$sep . $tvalue[$showfield . "_en"];
                                                    else
                                                        $value .=$sep . $tvalue[$showfield];
                                                    $sep = "\n";
                                                }
                                                $sep = "-";
                                            }
                                        }
                                        else
                                        {
                                            if (isset($field['options']) && is_array($field['options']))
                                            {
                                                foreach ($field['options'] as $opt)
                                                {
                                                    if ($row[$field['name']] == $opt['value'])
                                                        $value = $opt['title'];
                                                }
                                            }
                                        }
                                        $value = XMLDB_FixEncoding(substr(strip_tags($value), 0, 40), $params['charset_page']);
                                        //dprint_r($vs);
                                    }
                                    $html .= "<td  style=\"background-color:transparent;color:$textcolor\" >$vimage" . $value . "</td>";
                                    /* if (!empty($params['columns']))
                                      {
                                      $columns = explode(",",$params['columns']);
                                      foreach ($columns as $column )
                                      {
                                      if (  function_exists($column))
                                      {
                                      $column($row[$table->xmltable->primarykey]);
                                      }
                                      }
                                      }

                                     */
                                }
                            }
                            if ($enableview && $numcols++)
                                $html .= "<td style=\"background-color:transparent;color:$textcolor\"><a style=\"color:$linkcolor\" href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;op_$postgetkey=view&amp;pk_{$postgetkey}=" . urlencode($row[$table->xmltable->primarykey]) . "$mlink\">" . $textview . "</a></td>";
                            if ($enableedit && $numcols++)
                                $html .= "<td style=\"background-color:transparent;color:$textcolor\"><a style=\"color:$linkcolor\" href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;op_$postgetkey=insnew&amp;pk_{$postgetkey}=" . urlencode($row[$table->xmltable->primarykey]) . "$mlink\">" . $textmodify . "</a></td>";
                            if ($enabledelete && $numcols++)
                                $html .= "<td style=\"background-color:transparent;color:$textcolor\"><a style=\"color:$linkcolor\" href=\"javascript:check('?page_$postgetkey=$page&order_$postgetkey=$order&desc_$postgetkey=$reverse&op_$postgetkey=del&amp;pk_$postgetkey=" . urlencode(urlencode($row[$table->xmltable->primarykey])) . "&$flink_listmode');\">" . $textdelete . "</a></td>";
                            $html .= "</tr>";
                        }
                    }
                    else
                    {
                        //$html = "<table border=\"\" style=\"background-color:$bordercolor\" cellpadding=\"2\" cellspacing=\"1\" >";
                        $html .= "<tr><td style=\"background-color:$bgcolor;color:$textcolor\" colspan=\"$numcols\">$textnorecord</td></tr>";
                    }
                    $html .= "</table>";
                }
                if ($enablenew)
                    $html .= "<a style=\"color:$linkcolor\" href=\"?page_$postgetkey=$page&amp;order_$postgetkey=$order&amp;desc_$postgetkey=$reverse&amp;op_{$postgetkey}=insnew$mlink\">$textnew</a>";
                $endloop = true;
                break;
        }
    }
    if ($echo == true)
        echo $html;
    //dprint_r($_POST);
    return $html;
}
/**
 * 
 * @param array $array
 * @param string $order
 * @param bool $desc
 */
/*
  function xmldb_array_natsort_by_key($array, $order, $desc = false)
  {
  $ret = $array;
  $newret = array();
  foreach ( $ret as $key => $value )
  {
  if ( isset($value[$order]) )
  {
  $i = $desc ? 99999999 : 0;
  $r = $value[$order];
  while ( isset($newret[$r . $i]) )
  {
  if ( $desc )
  $i--;
  else
  $i++;
  }
  $newret[$r . $i] = $ret[$key];
  }
  else
  {
  $i = $desc ? 99999999 : 0;
  $r = "";
  while ( isset($newret[$r . $i]) )
  {
  if ( $desc )
  $i--;
  else
  $i++;
  }
  $newret[$r . $i] = $ret[$key];
  }
  }
  //----era cc_natkcasesort ( $newret ); ---->
  $keys = array_keys($newret);
  $new_array = array();
  natcasesort($keys);
  foreach ( $keys as $k )
  {
  $new_array[$k] = $newret[$k];
  }
  $newret = $new_array;
  //----era cc_natkcasesort ( $newret ); ----<
  if ( $desc == true )
  {
  $newret = array_reverse($newret);
  }
  return $newret;
  }

 */
/**
 * 
 * @param string $unirecid
 * @param string $tablename
 * @param string $databasename
 * @param string $path
 * @param string $lang
 * @param string $languages
 * @param array $params
 * @return string
 */
function xmldb_view($unirecid, $tablename, $databasename, $path, $lang, $languages, $params = false)
{
    global $_FN;
    $params['link'] = isset($params['link']) ? $params['link'] : "";
    $Table = new FieldFrm("$databasename", $tablename, $path, $lang, $languages,$params);
    $row = $Table->xmltable->GetRecordByPrimaryKey($unirecid);
    $htmlout = "";



    $unirecid = isset($row['unirecid']) ? $row['unirecid'] : false;
    if (true)
    {
        $htmlout = $Table->ShowView($row);
    }
    else
    {
        //dprint_r($Table->formvals);
        //dprint_r($row);
        $view_endgroup = "";
        foreach ($Table->formvals as $field)
        {
            if (isset($field['view_enabledgroups']) && $field['view_enabledgroups'] != "")
            {
                if (!FN_IsAdmin() && !user_in_group($_FN['user'], $field['view_enabledgroups']))
                    continue;
            }
            if (isset($field['view_group']))
            {
                $htmlout .= "\n<div class=\"xmldbgroup{$field['view_group']}\">";
            }
            $beforetitle = isset($field['view_beforetitle']) ? $field['view_beforetitle'] : "";
            $aftertitle = isset($field['view_aftertitle']) ? $field['view_aftertitle'] : ":";
            $beforevalue = isset($field['view_beforevalue']) ? $field['view_beforevalue'] : "";
            $aftervalue = isset($field['view_aftervalue']) ? $field['view_aftervalue'] : "";
            $title = "";
            if ($field['title'] != '')
            {
                $title = "$beforetitle" . $field['title'] . "$aftertitle";
            }
            //se e la traduzione di un campo
            if (isset($field['frm_multilanguage']) && $field['frm_multilanguage'] == 1)
            {
                continue;
            }
            if (isset($Table->formvals[$field['name'] . "_{$lang}"]))
            {
                $value = isset($row[$field['name'] . "_{$lang}"]) ? $row[$field['name'] . "_{$_FN['lang']}"] : "";
                if ($value == "")
                    $value = isset($row[$field['name']]) ? $row[$field['name']] : "";
            }
            else
            {
                $value = isset($row[$field['name']]) ? $row[$field['name']] : "";
            }
            if (!isset($field['frm_showinpage']) || $field['frm_showinpage'] |= 0)
                if ($value != "" && (!isset($field['frm_show']) || $field['frm_show'] != 0))
                {
                    if (!empty($field['foreignkey']) && !empty($field['fk_show_field']))
                    {
                        $r = array();
                        $f = array();
                        $tablefk = new XMLTable($databasename, $field['foreignkey'], $path);
                        $tf = explode(",", $field['fk_show_field']);
                        $f[$field['fk_link_field']] = $field['fk_link_field'];
                        foreach ($tf as $ttf)
                        {
                            if ($ttf != "")
                                $f[$ttf] = $ttf;
                            if (isset($tablefk->fields[$ttf . "_{$lang}"]))
                                $f[$ttf . "_{$lang}"] = $ttf . "_{$lang}";
                        }
                        $f = implode("|", $f);
                        $r[$field['fk_link_field']] = $row[$field['name']];
                        $vs = $tablefk->GetRecords($r, false, false, false, false, $f);
                        $value = isset($vs[0]) ? $vs[0] : null;
                        $tit = "";
                        $sep = "";
                        foreach ($tf as $ttf)
                        {
                            if (isset($tablefk->fields[$ttf . "_{$lang}"]) && $value[$ttf . "_{$lang}"] != "")
                                $tit .= $sep . $value[$ttf];
                            else
                                $tit .= $sep . $value[$ttf];
                            $sep = " - ";
                        }
                        $value = $tit;
                    }
                    $st = $et = "";
                    if (isset($field['view_tag']) && $field['view_tag'] != "")
                    {
                        $st = "<" . $field['view_tag'] . ">";
                        $et = "</" . $field['view_tag'] . ">";
                    }
                    if (isset($field['view_hiddentitle']) && $field['view_hiddentitle'] = 1)
                    {
                        $title = "";
                    }
                    else
                    {
                        if (isset($field['view_titletag']) && $field['view_titletag'] != "")
                        {
                            $title = "<" . $field['view_titletag'] . ">" . $title . "</" . $field['view_titletag'] . ">";
                        }
                        if (isset($field['iconview']) && $field['iconview'] != "")
                        {
                            $title = "<img alt='' border='0' src='" . $field['iconview'] . "' /> $title";
                        }
                    }
                    //---------------------------------valori---------------------->
                    $htmlout .= "\n<span class=\"xmldbcontent xmldbcontent{$field ['frm_type']} xmldbcontent{$field ['name']} \">";
                    $et = $aftervalue . $et;
                    if ($title == "")
                    {
                        // se non ha il titolo (st span type-value VALUE /span /et)
                        $st = "<span class=\"xmldbvalue xmldbvaluetype{$field ['frm_type']} xmldbvalue{$field ['name']}\">$st";
                        $et .= "</span><!-- \n end title -->";
                    }
                    else
                    {
                        $htmlout .= "<span class=\"xmldbtitle xmldbtitletype{$field ['frm_type']} xmldbtitle{$field ['name']} \">$st$title</span>";
                        $st = "";
                        $title = "";
                        $htmlout .= "<span class=\"xmldbvaluetype xmldbvaluetype{$field ['frm_type']} xmldbvalue{$field ['name']} \">$beforevalue";
                    }
                    switch ($field['frm_type'])
                    {
                        case "html" :
                            $htmlout .= " \n$st$title " . $value . "$et";
                            break;
                        case "separator" :
                            $htmlout .= "";
                            break;
                        case "url" :
                            $vaw = $value;
                            if (!preg_match('/^http\\:\\/\\//si', $vaw))
                                $vaw = "http://$value";
                            $htmlout .= "\n$st$title <a onclick=\"window.open(this.href);return false;\" href=\"$vaw\">$value</a>$et";
                            break;
                        case "email" :
                            $vaw = "mailto:$value";
                            $htmlout .= "\n$st$title <a href=\"$vaw\">$value</a>$et";
                            break;
                        default :
                            if (function_exists("xmldb_view" . $field['frm_type']))
                            {
                                $funct = "xmldb_view" . $field['frm_type'];
                                $htmlout .= $funct($row, $path, $databasename, $tablename, $field, $title, $value, $st, $et);
                            }
                            elseif (method_exists($Table->formclass[$field['name']], "view"))
                            {

                                $params['name'] = $field['name'];
                                $params['value'] = $value;
                                $params['values'] = $row;
                                $params['fieldform'] = $Table;

                                $htmlout .= " \n$st$title " . $Table->formclass[$field['name']]->view($params) . "$et";
                            }
                            else
                            {
                                if (preg_match("/^html/is", $field['frm_type']))
                                {
                                    $htmlout .= " \n$st$title " . $value . "$et";
                                }
                                else
                                {
                                    $htmlout .= " \n$st$title " . str_replace("\n", "<br />", htmlspecialchars($value)) . "$et";
                                }
                            }
                            break;
                    }
                    $htmlout .= "</span></span>";
                }
            if (isset($field['view_endgroup']))
            {
                $htmlout .= "</div>";
            }
        }
    }
    //----innertables---->
    /*
      $oldvalues = $row;
      if ( $Table->innertables )
      {
      foreach ( $Table->innertables as $k=>$v )
      {
      $params['echo'] = false;
      $params['path'] = $Table->path;
      $params['enableedit'] = true;
      $params['enablenew'] = false;
      $params['enabledelete'] = false;
      $params['enableview'] = true;
      $t = explode(",",$v["linkfield"]);
      if ( isset($t[1]) && $t[1] != "" && isset($oldvalues[$t[0]]) )
      $params['restr'] = array($t[1]=>$oldvalues[$t[0]]);
      else
      $params['restr'] = array($v["linkfield"]=>$oldvalues[$Table->xmltable->primarykey]);
      if ( isset($v["tablename"]) && isset($oldvalues[$Table->xmltable->primarykey]) )
      {
      $tmptable = xmldb_form($databasename,$v["tablename"],$path,$lang,$languages,$params);
      //dprint_r( $params);
      if ( $v['view'] == "list" )
      {
      $params['fields'] = $v["view_fields"];
      $params['enableview'] = false;
      $params['enableedit'] = false;
      $htmlout .= XMLDB_editor($v["tablename"],$Table->databasename,$params);
      }
      else
      {
      $allview = $tmptable->xmltable->getRecords($params['restr']);
      if ( is_array($allview) )
      foreach ( $allview as $view )
      {
      $htmlout .= xmldb_view($view[$tmptable->xmltable->primarykey],$v["tablename"],$databasename,$path,$lang,$languages,$params);
      }
      }
      }
      }
      }
     */
    //----innertables----<
    return $htmlout;
}
/**
 *
 * @global <type> $databasename
 * @global <type> $tablename
 * @global <type> $pathdatabase
 * @param <type> $file
 * @param <type> $databasename
 * @param <type> $tablename
 * @param <type> $pathdatabase 
 */
function xmldb_go_download($file, $databasename, $tablename, $pathdatabase, $tablepath)
{
    // evita di accedere a directory esterne
    if (stristr($file, ".."))
        die(fn_i18n("operation not allowed"));
    // se il file non esiste lo crea
    if (!file_exists("$pathdatabase/$databasename/$tablename" . "_download_stat.php"))
    {
        //echo "<br>creazione statistiche $tablename";
        $sfields = array();
        $sfields[1]['name'] = "filename";
        $sfields[1]['primarykey'] = "1";
        $sfields[2]['name'] = "numdownload";
        $sfields[2]['defaultvalue'] = "0";
        echo createxmltable($databasename, $tablename . "_download_stat", $sfields, $pathdatabase);
    }
    $stat = new XMLTable($databasename, $tablename . "_download_stat", $pathdatabase);
    $oldval = $stat->GetRecordByPrimaryKey($file);
    $r['filename'] = $file;
    if ($oldval == null)
    {
        $r['numdownload'] = 1;
        $stat->InsertRecord($r);
    }
    else
    {
        //incrementa download
        $r['numdownload'] = $oldval['numdownload'] + 1;
        $stat->UpdateRecord($r);
    }
    $file = "$pathdatabase/$databasename/$tablepath/$file";

    //First, see if the file exists
    if (!is_file($file))
    {
        die("<b>$file 404 File not found!</b>");
    }

    //Gather relevent info about file
    $len = filesize($file);
    $filename = basename($file);
    $file_extension = strtolower(substr(strrchr($filename, "."), 1));
    //This will set the Content-Type to the appropriate setting for the file
    switch ($file_extension)
    {
        case "pdf" :
            $ctype = "application/pdf";
            break;
        case "exe" :
            $ctype = "application/octet-stream";
            break;
        case "zip" :
            $ctype = "application/zip";
            break;
        case "doc" :
            $ctype = "application/msword";
            break;
        case "xls" :
            $ctype = "application/vnd.ms-excel";
            break;
        case "ppt" :
            $ctype = "application/vnd.ms-powerpoint";
            break;
        case "gif" :
            $ctype = "image/gif";
            break;
        case "png" :
            $ctype = "image/png";
            break;
        case "jpeg" :
        case "jpg" :
            $ctype = "image/jpg";
            break;
        case "mp3" :
            $ctype = "audio/mpeg";
            break;
        case "wav" :
            $ctype = "audio/x-wav";
            break;
        case "mpeg" :
        case "mpg" :
        case "mpe" :
            $ctype = "video/mpeg";
            break;
        case "mov" :
            $ctype = "video/quicktime";
            break;
        case "avi" :
            $ctype = "video/x-msvideo";
            break;

        //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
        case "php" :
        case "htm" :
        case "html" :
        case "txt" :
            $ctype = "application/force-download";
            break;

        default :
            $ctype = "application/force-download";
    }
    while (ob_get_clean())
    {
        
    }
    //Begin writing headers
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Type: $ctype");
    $header = "Content-Disposition: attachment; filename=" . $filename . ";";
    header($header);
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $len);
    @readfile($file);
    die("");
}
/**
 * 
 * @param string $field
 * @param string $title
 * @param string $value
 * @param string $st
 * @param string $et
 */
function xmldb_viewlink($row, $path, $databasename, $tablename, $field, $title, $value, $st, $et)
{
    $htmlout = "$st";
    if ($value != "")
    {
        if (!preg_match("/^http:\\/\\//si", $value))
        {
            $value = htmlspecialchars($value);
            $value = "http://$value";
        }
        $htmlout .= "<a onclick=\"window.open(this.href);return false;\" href=\"$value\">$value</a>";
    }
    $htmlout .= "$et";
    return $htmlout;
}
/**
 * 
 * @param string $field
 * @param string $title
 * @param string $value
 * @param string $st
 * @param string $et
 */
function xmldb_viewswf($row, $path, $databasename, $tablename, $field, $title, $value, $st, $et)
{
    $htmlout = "$st";
    if (preg_match('/\.swf/is', $row[$field['name']]))
    {
        $fileflash = isset($row['unirecid']) ? "$path/$databasename/$tablename/" . $row['unirecid'] . "/" . $field['name'] . "/" . $row[$field['name']] : "";
        $htmlout .= "\n$st$title ";
        $htmlout .= "\n<object width=\"550\" height=\"400\">
<param name=\"movie\" value=\"$fileflash\">
<embed src=\"$fileflash\" width=\"550\" height=\"400\">
</embed>
</object>$et";
    }
    else
    {
        $htmlout = "$st$et";
    }
    return $htmlout;
}
/**
 * 
 * @param string $field
 * @param string $title
 * @param string $value
 * @param string $st
 * @param string $et
 */
function xmldb_viewyoutubelink($row, $path, $databasename, $tablename, $field, $title, $value, $st, $et)
{
    $htmlout = "$st";
    $html = "";
    $codes = explode(",", $value);
    foreach ($codes as $value)
    {
        $c = "v";
        $code = explode("/v/", $value);
        if (!isset($code[1]))
            $code = explode("?v=", $value);
        if (!isset($code[1]))
        {
            $code = explode("/p/", $value);
            $c = "p";
        }
        if (!isset($code[1]))
        {
            $code = explode("?p=", $value);
            $c = "p";
        }
        if (isset($code[1]))
        {
            $h = 344;
            $w = 425;
            $code = $code[1];
            if (false !== strstr($code, "&"))
                $code = substr($code, 0, strpos($code, "&"));
            if (false !== strstr($code, "?"))
                $code = substr($code, 0, strpos($code, "?"));
            if ($code != "")
            {
                $code = "http://www.youtube.com/$c/$code&amp;autoplay=0&amp;rel=0";
                $html .= "<div style=\"height:$h;width:$w;overflow:auto\">";
                //$html .= "<center>";
                $html .= "<object width=\"$w\" height=\"$h\">
					<param name=\"movie\" value=\"$code\"></param>
					<param name=\"enablejsapi\" value=\"1\"></param>
					<param name=\"allowFullScreen\" value=\"true\"></param>
					<embed src=\"$code\" type=\"application/x-shockwave-flash\" enablejsapi=\"1\" allowfullscreen=\"true\" width=\"$w\" height=\"$h\"></embed></object>";
                //$html .= "</center>";
                $html .= "</div>";
            }
            else
            {
                $html .= htmlentities($value);
            }
        }
    }
    $htmlout .= " \n$st$title " . $html . "$et";
    return $htmlout;
}
?>