function smarty_function_custom_conf_save($params, &$smarty)
{
    global $site, $leht;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!$id) {
        return;
    }
    $objekt = new Objekt(array(objekt_id => $id, no_cache => 1));
    if ($objekt->permission['U']) {
        $conf = new CONFIG($objekt->all['ttyyp_params']);
        foreach ($params as $param => $value) {
            if ($param == 'id') {
                continue;
            }
            $conf->put($param, $value);
        }
        $sql = $site->db->prepare("\r\n\t\t\tUPDATE objekt SET ttyyp_params = ?\r\n\t\t\tWHERE objekt_id = ?", $conf->Export(), $id);
        $sth = new SQL($sql);
    } else {
        new Log(array('action' => 'update', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("Access denied: attempt to edit %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id)));
    }
    return;
}
/**
* save object info to database
*
* Uses sub-scripts to save different data for different object types.
* No parameters used, only globals, it is included script.
*
* @package CMS
*
* Call:
*		include_once("edit_object.php");
*		save_object();
*/
function save_object()
{
    global $site;
    global $objekt;
    global $class_path;
    global $keel;
    global $tyyp;
    verify_form_token();
    ###################
    # 1. special case: if object is NEW picture
    if ($tyyp['klass'] == "pilt" && !$objekt->objekt_id) {
        include_once "edit_" . $tyyp['klass'] . ".php";
        if (function_exists("save_objekts")) {
            save_objekts(array(tyyp_id => $tyyp[tyyp_id], keel => $keel));
        }
    } else {
        # pealkiri peab olema!
        if ($site->fdat[pealkiri] == '' && $tyyp['klass'] != "kommentaar") {
            $errors .= $site->sys_sona(array(sona => "maaratud pealkiri", tyyp => "editor")) . "<br>";
        }
        ###################
        # Salvestame tyybi parameetrid
        if (file_exists("edit_" . $tyyp['klass'] . ".php")) {
            include_once "edit_" . $tyyp['klass'] . ".php";
            if (function_exists("save_tyyp_params")) {
                $templ_params = save_tyyp_params(array(objekt => $objekt));
            }
        }
        ###################
        # Salvestame malli parameetrid - old ver3 style
        # arvestame, et malli parameetrid k�ivad ainult sisumalli kohta
        $sql = $site->db->prepare("SELECT ttyyp_id, templ_fail FROM templ_tyyp WHERE ttyyp_id = ?", $site->fdat['ttyyp_id']);
        $sth = new SQL($sql);
        $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
        $temp_ttyyp = $sth->fetch();
        if ($temp_ttyyp['templ_fail'] && strpos($temp_ttyyp['templ_fail'], '../') !== 0 && file_exists("../" . $temp_ttyyp['templ_fail'])) {
            include_once "../" . $temp_ttyyp['templ_fail'];
        }
        if (function_exists("save_params")) {
            $templ_params = save_params(array(objekt => $objekt));
        }
        ### ttyyp_params - ver3 style vs ver4. Bug #2506
        if (!empty($templ_params)) {
            $oldstyle_tyyp_params = true;
            # if old-ver-style fixed params are used
        } else {
            # use new ver4 style custom conf save/load by default
            $oldstyle_tyyp_params = false;
        }
        ###################
        # if no errors occured , begin saving to database
        if (!$errors) {
            $site->debug->msg("EDIT: Objekti salvestamine");
            ###################
            # strip HTML tags from headline, lyhi, sisu for strip-fields
            // folder title is folder filesystem name
            if ($site->fdat['tyyp_id'] == 22) {
                $site->fdat['pealkiri'] = safe_filename2($site->fdat['pealkiri']);
            }
            $pealkiri_strip = $site->fdat['pealkiri'];
            $sisu_strip = $site->fdat['scms_article_editor'] ? $site->fdat['scms_article_editor'] : ($site->fdat['sisu'] ? $site->fdat['sisu'] : $site->fdat['text']);
            # replace some tags with space before stripping tags (bug #1568 )
            $replace_tags_arr = array("<br>", "<BR>", "<br />", "<BR />", "&nbsp;");
            $pealkiri_strip = str_replace($replace_tags_arr, " ", $pealkiri_strip);
            $sisu_strip = str_replace($replace_tags_arr, " ", $sisu_strip);
            $replace_tags_arr = array("&amp;");
            $pealkiri_strip = str_replace($replace_tags_arr, "&", $pealkiri_strip);
            $sisu_strip = str_replace($replace_tags_arr, "&", $sisu_strip);
            $pealkiri_strip = strip_tags($pealkiri_strip);
            $sisu_strip = strip_tags($sisu_strip);
            // remove excess spaces
            $sisu_strip = preg_replace('/\\s+/', ' ', $sisu_strip);
            // overwrite catch for files, this is here so when a new file is being uploaded but
            // a file with a same name already exists
            // there wouldn't be double objects
            // instead use the existing object and move on as that objects update
            if ($site->fdat['tyyp_id'] == 21 && $_FILES['fileupload']['name']) {
                $parent_folder = new Objekt(array('objekt_id' => $objekt->parent_id, 'on_sisu' => 1));
                $parent_folder_path = preg_replace('#/$#', '', $site->absolute_path) . $parent_folder->all['relative_path'];
                // delete file
                if (file_exists($parent_folder_path . '/' . safe_filename2($_FILES['fileupload']['name']))) {
                    unlink($parent_folder_path . '/' . safe_filename2($_FILES['fileupload']['name']));
                }
                $file_path = preg_replace('#/$#', '', $site->absolute_path) . $objekt->all['relative_path'];
                // delete the file itself (bug #2586)
                if ($objekt->objekt_id && file_exists($file_path)) {
                    unlink($file_path);
                }
                $sql = $site->db->prepare('select objekt_id from obj_file where relative_path = ?', $parent_folder->all['relative_path'] . '/' . safe_filename2($_FILES['fileupload']['name']));
                $result = new SQL($sql);
                if ($result->rows && ($existing_id = $result->fetchsingle())) {
                    // delete the object used to overwrite
                    // don't delete if it's the same object (bug # 2576)
                    if ($objekt->objekt_id && $objekt->objekt_id != $existing_id) {
                        $objekt->del();
                    }
                    $objekt = new Objekt(array('objekt_id' => $existing_id, 'on_sisu' => 1, 'no_cache' => 1));
                }
            }
            // / overwrite catch
            ###################
            # UPDATE
            if ($objekt->objekt_id) {
                /* Check if avaldamise_algus & avaldamise_lopp has the right format
                			   if not fix it.
                			*/
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat[avaldamise_algus], $aa_reg)) {
                    if (!$aa_reg[2] && !$aa_reg[3]) {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " 00:00:00";
                    } else {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " " . $aa_reg[2] . ":" . $aa_reg[3] . ":00";
                    }
                }
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_lopp'], $al_reg)) {
                    if (!$al_reg[2] && !$al_reg[3]) {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " 23:59:59";
                    } else {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " " . $al_reg[2] . ":" . $al_reg[3] . ":59";
                    }
                }
                /* End of check */
                $sql = $site->db->prepare("UPDATE objekt SET pealkiri=?, on_pealkiri=?, on_foorum=?, on_saadetud=?, ttyyp_id=?, page_ttyyp_id=?, pealkiri_strip=?, sisu_strip=?, aeg=?, avaldamisaeg_algus=?, avaldamisaeg_lopp=?, last_modified=" . time() . ", author=?, friendly_url=?, is_hided_in_menu=?, kesk=?, check_in=?, changed_user_id=?, changed_user_name=?, changed_time=?, on_avaldatud = ? WHERE objekt_id=?", $site->fdat['pealkiri'], $site->fdat['on_pealkiri'], $site->fdat['on_foorum'] ? 1 : 0, $site->fdat['on_saadetud'] ? 0 : 1, $site->fdat['ttyyp_id'], $site->fdat['page_ttyyp_id'], $pealkiri_strip, $sisu_strip, $site->db->ee_MySQL($site->fdat['aeg']), $site->db->ee_MySQL_long($site->fdat['avaldamise_algus']), $site->db->ee_MySQL_long($site->fdat['avaldamise_lopp']), $site->fdat['author'], $site->fdat['friendly_url'], $site->fdat['is_hided_in_menu'] ? 1 : 0, $site->fdat['kesk'], 0, $site->user->id, $site->user->name, date("Y-m-d H:i:s"), isset($site->fdat['publish']) && is_numeric($site->fdat['publish']) ? (int) $site->fdat['publish'] : $objekt->all['on_avaldatud'], $objekt->objekt_id);
                $sth = new SQL($sql);
                $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                # save old-ver3-style tyyp_params. Bug #2506
                # this SQL should happen only as exception and not by default
                if ($oldstyle_tyyp_params === true) {
                    $sql = $site->db->prepare("UPDATE objekt SET ttyyp_params = ? WHERE objekt_id=?", $templ_params ? $templ_params : 'ttyyp_params', $objekt->objekt_id);
                    $sth = new SQL($sql);
                    $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                }
                # ------------------------
                # Kustutame chache-ist ka
                # ------------------------
                clear_cache("ALL");
                new Log(array('action' => 'update', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id, "changed")));
            } else {
                /* Check if avaldamise_algus & avaldamise_lopp has the right format
                			   if not fix it.
                			*/
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_algus'], $aa_reg)) {
                    if (!$aa_reg[2] && !$aa_reg[3]) {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " 00:00:00";
                    } else {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " " . $aa_reg[2] . ":" . $aa_reg[3] . ":00";
                    }
                }
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_lopp'], $al_reg)) {
                    if (!$al_reg[2] && !$al_reg[3]) {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " 23:59:59";
                    } else {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " " . $al_reg[2] . ":" . $al_reg[3] . ":59";
                    }
                }
                /* End of check */
                $sql = $site->db->prepare("INSERT INTO objekt (pealkiri, on_pealkiri, on_foorum, on_saadetud, tyyp_id, author, on_avaldatud, keel, kesk, ttyyp_id, page_ttyyp_id, pealkiri_strip, sisu_strip, aeg, sys_alias, ttyyp_params, avaldamisaeg_algus, avaldamisaeg_lopp, last_modified, friendly_url, is_hided_in_menu, check_in, check_in_admin_id, created_user_id, created_user_name, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $site->fdat['pealkiri'], $site->fdat['on_pealkiri'], $site->fdat['on_foorum'], $site->fdat['on_saadetud'] ? 0 : 1, $tyyp['tyyp_id'], $site->fdat['author'], $site->fdat['sys_alias'] || $site->fdat['publish'] ? 1 : 0, $tyyp['tyyp_id'] == 21 || $tyyp['tyyp_id'] == 22 ? 1 : $keel, $site->fdat['kesk'], $site->fdat['ttyyp_id'], $site->fdat['page_ttyyp_id'], $pealkiri_strip, $sisu_strip, $site->db->ee_MySQL($site->fdat['aeg']), $site->fdat['sys_alias'], $templ_params, $site->db->ee_MySQL_long($site->fdat['avaldamise_algus']), $site->db->ee_MySQL_long($site->fdat['avaldamise_lopp']), time(), $site->fdat['friendly_url'], $site->fdat['is_hided_in_menu'] ? 1 : 0, 0, $site->user->id, $site->user->id, $site->user->name, date("Y-m-d H:i:s"));
                $sth = new SQL($sql);
                $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                $obj_insert_id = $sth->insert_id;
                # ------------------------
                # Kustutame chache-ist ka
                # ------------------------
                clear_cache("ALL");
                $objekt = new Objekt(array(objekt_id => $obj_insert_id, no_cache => 1, creating => 1));
                if (!is_numeric($objekt->objekt_id)) {
                    $objekt->objekt_id = $obj_insert_id;
                }
                $site->fdat['id'] = $objekt->objekt_id;
                new Log(array('action' => 'create', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id, "inserted")));
                $is_new = 1;
            }
            # / INSERT
            ###################
            ###################
            # WHAT IS THIS?
            $objekt->all["on_peida_vmenyy"] = $site->fdat["on_peida_vmenyy"] ? 1 : 0;
            ###################
            # SALVESTA t��bist s�ltuv osa
            #$fdat{objekt}->{klass} = "artikkel" if ($fdat{objekt}->{klass} eq "oigusakt");
            # INCLUDE t��bist s�ltuv fail
            include_once "edit_" . $tyyp['klass'] . ".php";
            # salvesta objekti t��bist s�ltuv osa
            salvesta_objekt();
            # save all profile fields:
            if ($site->fdat['profile_id']) {
                # if profile set
                save_obj_profile();
            }
            # / SALVESTA t��bist s�ltuv osa
            ###################
            ###################
            # PARENTS (tbl 'objekt_objekt')
            ###################
            $site->debug->msg("------------ PARENTS -------------");
            ###################
            #######################
            # 1. FIND NEW PARENTS
            $new_parents = array();
            # parentit on lubatud select-boxis muuta j�rgmistel objektidel:
            # artikkel, dokument, rubriik, album, asset, gallup, kommentaar
            # 1) kui tegu on lubatud objektiga JA vormis oli parent rubriik valitud,
            # siis
            if (($tyyp['klass'] == "artikkel" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "rubriik" || $tyyp['klass'] == "album" || $tyyp['klass'] == "asset" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "kommentaar" || $tyyp['klass'] == "link") && is_array($site->fdat['rubriik'])) {
                # salvesta k�ik vormis valitud rubriigid massiivi
                foreach ($site->fdat['rubriik'] as $value) {
                    $new_parents[$value] = 1;
                }
                # kui parenti ID oli 0, siis what the hell siin tehakse?
                /*
                if ($site->fdat['parent_id']==0) {
                	$new_parents[$site->fdat['parent_id']] = 1;
                }
                */
            } elseif ($site->fdat['parent_id']) {
                $new_parents[$site->fdat['parent_id']] = 1;
            }
            ######### get parent object
            if ($site->fdat['parent_id']) {
                $parent = new Objekt(array(objekt_id => $site->fdat['parent_id']));
            }
            # kui objektil leidub korrektne parent ja pole tegu rubriigiga,
            # siis pane parentiks 'parent_id' parameeter (eee, j�lle?)
            # Lauri: parent ise ei tohiks saada new_parentiks. seega kommentaari juures konkreetselt keelan ara
            if ($parent && $parent->all['klass'] != "rubriik" && $tyyp['klass'] != "kommentaar") {
                $new_parents[$site->fdat['parent_id']] = 1;
            }
            ######## gallupi erijuht
            if ($tyyp['klass'] == "gallup") {
                if ($site->fdat['on_avatud']) {
                    $objekt->load_sisu();
                    $site->debug->msg("EDIT: vana parent rullib!");
                    # removed by Bug #1896: gallupit ei saa teise rubriigi alla t�sta
                    # $new_parents = array($objekt->all["orig_parent_id"] => 1);
                } else {
                    # kui suletud gallup, siis liiguta gallupi arhiivi
                    $new_parents = array($site->alias("gallup_arhiiv") => 1);
                }
            }
            $site->debug->msg("EDIT: Selected new parents: " . join(",", array_keys($new_parents)));
            # 1. / FIND NEW PARENTS
            #######################
            #######################
            # 2. FIND CURRENT PARENTS
            $current_parents = array();
            ########### RUBRIIK V�I LINGIKAST
            if ($tyyp['klass'] == "rubriik") {
                ######## Otsime, kas rubriik kuulub ka m�ne uudistekogu alla - need on vaja uutele parentitele vaikselt lisada
                $sql = $site->db->prepare("SELECT objekt_objekt.parent_id FROM objekt_objekt LEFT JOIN objekt ON objekt.objekt_id=objekt_objekt.parent_id WHERE objekt_objekt.objekt_id=? and objekt.tyyp_id=9", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetchsingle()) {
                    $newslist_parents[$tmp_data] = 1;
                    # lisa salaja uudistekogu ID samuti uute parentite massiivile
                    $new_parents[$tmp_data] = 1;
                }
                unset($tmp_data);
                if ($sth->rows) {
                    $site->debug->msg("EDIT: Parent news lists: " . join(",", array_keys($newslist_parents)));
                }
                ########## leia rubriigi praegused parentid
                $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=?", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetch()) {
                    $parent_id = $tmp_data['parent_id'];
                    $current_parents[$parent_id] = 1;
                }
                ######### K�IK �LEJ��NUD objektid v.a rubriik ja lingikast
            } else {
                # -----------------------------------
                # siin on need objektid mille jaoks
                # on lubatud rohkem kui 1 �lema omama
                # -----------------------------------
                $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=?", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetch()) {
                    $parent_id = $tmp_data['parent_id'];
                    $current_parents[$parent_id] = 1;
                }
                # mis siin tehakse?
                # Lauri: oeldakse jargmise IF-i jaoks, et ara sinna sisse mine. vaata 10 rida allapoole
                if ($current_parents[0]) {
                    $new_parents[0] = 1;
                }
            }
            $site->debug->msg("EDIT: Current parents: " . join(",", array_keys($current_parents)));
            # / 2. FIND CURRENT PARENTS
            #######################
            # kui uute parentite massiiv on t�hi, siis kasuta vormis alati kaasas olnud
            # peidetud v��rtust 'permanent_parent_id'
            if ($site->fdat['permanent_parent_id'] != "" && !count(array_keys($new_parents))) {
                $new_parents[$site->fdat['permanent_parent_id']] = 1;
            }
            $site->debug->msg("EDIT: Final parents: " . join(",", array_keys($new_parents)));
            #######################
            # 3. CHECK NEW PARENTS PERMISSIONS
            foreach (array_keys($new_parents) as $parent_id) {
                if ($parent_id) {
                    # kui uus �lem (varem polnud), siis kontrolli �iguseid
                    if (!$current_parents[$parent_id]) {
                        ####### check permissions
                        $perm = get_obj_permission(array("objekt_id" => $parent_id));
                        # kui uuel parentil on CREATE �igus, siis luba lisada objekt selle parenti alla,
                        # muidu mitte
                        if ($perm['C']) {
                            $site->debug->msg("EDIT: New parent " . $parent_id . " permissions " . $perm['mask'] . " allow to create object under it => OK");
                        } else {
                            $site->debug->msg("EDIT: New parent " . $parent_id . " permissions " . $perm['mask'] . " don't allow to create object under it => FORBIDDEN");
                            # v�ta see parent maha uute parentite massiivist
                            unset($new_parents[$parent_id]);
                        }
                        # new parent permissions
                    }
                }
                # if parent_id
            }
            $site->debug->msg("EDIT: Final parents after permission check: " . join(",", array_keys($new_parents)));
            # / 3. CHECK NEW PARENTS PERMISSIONS
            #######################
            # kui uute parentite arv on 0 st objekti ei tohi uue parenti alla lisada,
            # siis �ra tee �ldse midagi
            if (!count(array_keys($new_parents))) {
                $site->debug->msg("EDIT: Can't move under new parent => don't do anything at all");
                $fatal_parent_error = 1;
            }
            # kui uued parentid on ainult uudistekogud (samad mis enne), siis �ra tee �ldse midagi
            if (sizeof($newslist_parents) > 0) {
                $result = array_diff(array_keys($new_parents), array_keys($newslist_parents));
                if (sizeof($result) <= 0) {
                    # kui massiivid pole erinevad
                    $site->debug->msg("EDIT: New parents are equal to existing newslist parents => don't do anything at all");
                    $fatal_parent_error = 1;
                }
            } else {
                if (!$fatal_parent_error) {
                    # if not fatal parent error
                    #######################
                    # 4. INSERT NEW PARENTS (siin on juba ainult need parentid, mille alla v�ib objekti lisada)
                    foreach (array_keys($new_parents) as $parent_id) {
                        if ($parent_id) {
                            # �lem on olemas, siis pole vaja midagi teha
                            if ($current_parents[$parent_id]) {
                                $current_parents[$parent_id] = 0;
                                $site->debug->msg("EDIT: Parent {$parent_id} j��b nagu oli");
                            } else {
                                if ($site->fdat["sorting"]) {
                                    $sorteering = $site->fdat["sorting"];
                                } else {
                                    $sql = "SELECT max(sorteering) FROM objekt_objekt";
                                    $sth = new SQL($sql);
                                    $sorteering = $sth->fetchsingle();
                                }
                                #move objects forward so new object can be inserted in the middle
                                $sql = $site->db->prepare("UPDATE objekt_objekt SET sorteering=sorteering+1 WHERE sorteering>?", $sorteering);
                                $sth = new SQL($sql);
                                $site->debug->msg("EDIT: " . $sql);
                                ################ INSERT
                                $sql = $site->db->prepare("INSERT INTO objekt_objekt (objekt_id, parent_id, sorteering) VALUES (?,?,?)", $objekt->objekt_id, $parent_id, $sorteering + 1);
                                $sth = new SQL($sql);
                                $site->debug->msg("EDIT: " . $sql);
                                if ($tyyp['klass'] == 'kommentaar') {
                                    $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count+1 WHERE objekt_id=?", $parent_id);
                                    $sth = new SQL($sql);
                                    $site->debug->msg("EDIT: " . $sql);
                                }
                            }
                            # uus �lem, lisa
                        }
                        # if parent_id
                    }
                    # / 4. INSERT NEW PARENTS
                    #######################
                    #######################
                    # 5. DELETE OLD PARENTS
                    function notnull($a)
                    {
                        return $a > 0;
                    }
                    $to_delete = join(",", array_keys(array_filter($current_parents, "notnull")));
                    $site->debug->msg("EDIT: Current Parents, allowed to delete: " . $to_delete);
                    # kui vormis oli valitud m�ni parent rubriik JA objekt on lubatud t��pi (tal v�ib parentit muuta),
                    # siis... mis tehakse?
                    if (sizeof($site->fdat['rubriik']) > 0 && ($tyyp['klass'] == "artikkel" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "rubriik" || $tyyp['klass'] == "album" || $tyyp['klass'] == "asset" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "kommentaar" || $tyyp['klass'] == "link")) {
                        $parent_ids = array();
                        foreach (array_unique(array_merge($site->fdat['rubriik'], array_keys($new_parents))) as $tmp_id) {
                            if ((int) $tmp_id) {
                                $parent_ids[] = (int) $tmp_id;
                            }
                        }
                        ########### Lauri 04092009: store parents that will be deleted so we can reduce their comment_count
                        $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=? AND parent_id NOT IN(" . implode(',', $parent_ids) . ")", $objekt->objekt_id);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        $parents_to_delete = array();
                        while ($return_row = $sth->fetch()) {
                            $parents_to_delete[] = $return_row['parent_id'];
                        }
                        ############ DELETE
                        $sql = $site->db->prepare("DELETE FROM objekt_objekt WHERE objekt_id=? AND parent_id NOT IN(" . implode(',', $parent_ids) . ")", $objekt->objekt_id);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        ########## Lauri 04092009: reduce comment count for parents from which kommentaar was deleted
                        if ($tyyp['klass'] == 'kommentaar') {
                            $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count-1 WHERE objekt_id IN(" . implode(',', $parents_to_delete) . ")");
                            $sth = new SQL($sql);
                            $site->debug->msg("EDIT: " . $sql);
                        }
                    }
                    ############ DELETE
                    # kui on parenteid, mida kustutada:
                    if ($to_delete) {
                        $sql = $site->db->prepare("DELETE FROM objekt_objekt WHERE objekt_id=? AND parent_id IN(?)", $objekt->objekt_id, $to_delete);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        ############ Lauri 04092009: if some more parents got removed, reduce comment_count on them too. have to make sure not to do it twice tho
                        $comments_to_substract = array_diff((array) $to_delete, $parents_to_delete);
                        if ($tyyp['klass'] == 'kommentaar' && count($comments_to_substract)) {
                            $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count-1 WHERE objekt_id IN (" . implode(',', $comments_to_substract) . ")");
                            $sth = new SQL($sql);
                            $site->debug->msg("EDIT: " . $sql);
                        }
                    }
                    # / 5. DELETE OLD PARENTS
                    #######################
                }
            }
            # if not fatal parent error (new parent permissions)
            ################################## / DATABASE SQL-s ##################################
            $site->debug->msg("------------ PARENTS END -------------");
            # / PARENTS
            ###################
            ########################
            # INSERT PERMISSIONS
            # lisame uuele objektile t�pselt samad �igused nagu on tema parent objektile.
            # OBJ class check: save permissions only for objects having class "rubriik" (1) or "folder" (22).
            # NB! if you change class conditions here, be sure to change them in Repair database script also!
            # (see also bug #1545)
            if ($tyyp[tyyp_id] == 1 || $tyyp[tyyp_id] == 22) {
                # if object is section or folder
                if ($is_new) {
                    # leia k�ik parenti �igused userite/gruppide kohta:
                    $sql = $site->db->prepare("SELECT * FROM permissions WHERE type=? AND source_id=?", 'OBJ', $parent->objekt_id);
                    $sth = new SQL($sql);
                    # ts�kkel �le parenti �iguste
                    while ($perm = $sth->fetch()) {
                        # lisa �igus uuele objektile
                        $sql2 = $site->db->prepare("INSERT INTO permissions (type,source_id,role_id,group_id,user_id,C,R,U,P,D) VALUES (?,?,?,?,?,?,?,?,?,?)", 'OBJ', $objekt->objekt_id, $perm['role_id'], $perm['group_id'], $perm['user_id'], $perm['C'], $perm['R'], $perm['U'], $perm['P'], $perm['D']);
                        $sth2 = new SQL($sql2);
                    }
                    # ts�kkel �le parenti �iguste
                    // reload permissions for user
                    if (!$site->user->is_superuser) {
                        if ($site->user) {
                            $site->user->permissions = $site->user->load_objpermissions();
                        } elseif ($site->guest) {
                            $site->guest->permissions = $site->guest->load_objpermissions();
                        }
                    }
                }
                # if new, just created object
            }
            # if object is section or folder
            # / INSERT PERMISSIONS
            ########################
            return 1;
        } else {
            ?>
	<center><font class=txt>
		<br>
		<font color=red>&nbsp;<?php 
            echo $errors;
            ?>
</font>
		<br>
		<a href="javascript:history.back();"><?php 
            echo $site->sys_sona(array(sona => "Tagasi", tyyp => "editor"));
            ?>
</a>
	</font></center>
<?php 
        }
        # / print errors
        ###################
    }
    # / 2. usual case
    ###################
}
     # EDIT OBJECT
     if ($objekt) {
         if ($objekt->permission['R'] && $objekt->permission['U']) {
             $access = 1;
         }
     }
     # NEW OBJECT: tab is denied
 }
 // editing for public and shared folders is denied
 if ($site->fdat['tab'] == 'object' && ($objekt->all['sys_alias'] == 'public' || $objekt->all['sys_alias'] == 'shared')) {
     $access = 0;
 }
 ####################
 # access denied
 if (!$access) {
     new Log(array('action' => 'create', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => $objekt ? sprintf("Access denied: attempt to edit %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id) : sprintf("Access denied: attempt to create %s under restricted category ID = %s", ucfirst(translate_en($objekt->all['klass'])), $site->fdat['parent_id'])));
     ####### print error html
     print_error_html(array("message" => $site->sys_sona(array(sona => "access denied", tyyp => "editor"))));
     if ($site->user) {
         $site->user->debug->print_msg();
     }
     if ($site->guest) {
         $site->guest->debug->print_msg();
     }
     $site->debug->print_msg();
     ########### EXIT
     exit;
 }
 # / ACCESS allowed/denied
 ###########################
 ###########################
# GET PERMISSIONS
# get object permissions for current user
$site->debug->msg("EDIT: Liigutatava objekti " . $objekt->objekt_id . " õigused = " . $objekt->permission['mask']);
###########################
# ACCESS allowed/denied
# decide if accessing this page is allowed or not
# MOVE UP/DOWN: if current object has UPDATE permission => allow
if ($objekt->permission['U'] || $system_admin) {
    $access = 1;
} else {
    $access = 0;
}
####################
# access denied
if (!$access) {
    new Log(array('action' => 'update', 'objekt_id' => $objekt->objekt_id, 'type' => 'WARNING', 'message' => sprintf("access denied: attempt to move %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id)));
    print "<center><b><font class=\"txt\">" . $site->sys_sona(array(sona => "access denied", tyyp => "editor")) . "</font></b></center>";
    if ($site->user) {
        $site->user->debug->print_msg();
    }
    if ($site->guest) {
        $site->guest->debug->print_msg();
    }
    $site->debug->print_msg();
    ########### EXIT
    exit;
}
# / ACCESS allowed/denied
###########################
###########################
# GO ON with real work
function print_kast($kast, $is_custom = 0, $archive_link_on = 1)
{
    #Muutujad mis hoiab custom stringid
    $custom_buttons = '';
    $custom_title = '';
    $custom_contents = '';
    if (get_class($kast) == "Objekt" || is_subclass_of($kast, "Objekt")) {
        # ----------------------------
        # Uudiste kogumik
        # ----------------------------
        if ($kast->all[klass] == "kogumik") {
            $kast->load_sisu();
            if (!$is_custom) {
                ?>
				<table width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" border="0" cellspacing="0" cellpadding="1">
				  <tr> 
					<td width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" class="boxhead" height="24">
					&nbsp;&nbsp;<?php 
                echo $kast->pealkiri();
                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                ?>
</td>
				  </tr>
				  <tr> 
					<td width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" bgcolor="<?php 
                echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                ?>
"> 
					  <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="<?php 
                echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                ?>
">
						<tr> 
						  <td align="right" valign="top"><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="20" height="10"></td>
						  <td><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout") - 42;
                ?>
" height="10"></td>
						  <td><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="20" height="10"></td>
						</tr>
<?php 
            } else {
                //Custom print out
                ob_start();
                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                $custom_buttons .= ob_get_contents();
                ob_end_clean();
                $custom_title .= $kast->pealkiri();
                $custom_contents .= "<ul class=\"boxlist\">";
            }
            //if is_custom
            # rubriigid kus uudised otsida
            $sql = "SELECT objekt.objekt_id FROM objekt LEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id WHERE objekt_objekt.parent_id=" . $kast->objekt_id . " AND (objekt.kesk = 0 or objekt.kesk = 5 or objekt.kesk = 9) AND objekt.tyyp_id=1";
            ####### POOLELI
            if (!$kast->site->in_editor) {
                $sql .= " AND objekt.on_avaldatud=1";
            }
            if (!$kast->site->in_editor) {
                $sql .= " AND !FIND_IN_SET(objekt.objekt_id, '" . join(",", $kast->site->noaccess_hash) . "')";
            }
            $sth = new SQL($sql);
            while ($rid = $sth->fetchsingle()) {
                $news_rubrics .= "," . $rid;
            }
            $kast->debug->msg($sth->debug->get_msgs());
            $kast->debug->msg("Rubriigid: {$news_rubrics}");
            $sql = "\r\n\t\t\t\t\t\t\tSELECT objekt.objekt_id, objekt.pealkiri, objekt.aeg, objekt.on_avaldatud, objekt_objekt.parent_id \r\n\t\t\t\t\t\t\tFROM objekt \r\n\t\t\t\t\t\t\tLEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id \r\n\t\t\t\t\t\t\tWHERE find_in_set(objekt_objekt.parent_id,'{$news_rubrics}') AND (objekt.kesk=0 OR objekt.kesk=6) AND (objekt.tyyp_id=2 OR objekt.tyyp_id=15)";
            if (!$kast->site->in_editor) {
                $sql .= " AND objekt.on_avaldatud=1  ";
            }
            $sql .= " ORDER BY objekt.aeg DESC, objekt_objekt.sorteering DESC limit 0," . ($kast->all[art_arv] ? $kast->all[art_arv] : 5);
            $kast->debug->msg($sth->debug->get_msgs());
            $sth = new SQL($sql);
            $kast->debug->msg("Leitud " . $sth->rows . " alamobjekte");
            $esimene = 1;
            while ($ary = $sth->fetch()) {
                $kast->debug->msg("Objekt leitud: {$ary['objekt_id']}. " . $ary[pealkiri]);
                $obj = new Objekt(array(ary => $ary));
                if (!$is_custom) {
                    if (!$esimene) {
                        # eraldaja
                        ?>
								<tr valign="top"> 
								  <td align="right" valign="top"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="20" height="10"></td>
								  <td background="<?php 
                        echo $kast->site->img_path;
                        ?>
/stripe1.gif"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="1" height="10"></td>
								  <td><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="20" height="10"></td>
								</tr>
<?php 
                    }
                    if ($obj->site->in_editor) {
                        ?>
								
								<!--tr valign="top"> 
									<td colspan="3" align=left>&nbsp; &nbsp;
									
									</td>
								</tr-->
<?php 
                    }
                    # if in_editor
                    ?>
								<tr valign="top"> 
								  <td align="right" valign="top"><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
								  <td><a href="<?php 
                    echo $kast->site->self;
                    ?>
?id=<?php 
                    echo $obj->objekt_id;
                    ?>
" class="navi2_on"><?php 
                    echo $obj->pealkiri();
                    ?>
</a><?php 
                    echo $kast->all[on_kp_nahtav] ? "<br><font class=txt><font class=date>" . $obj->aeg() . "</font></font>" : "";
                    $obj->edit_buttons(array(tyyp_idlist => 3, only_edit => 1));
                    ?>
</td>
								  <td><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="20" height="10"></td>
								</tr>
<?php 
                    $esimene = 0;
                } else {
                    //Custom print out
                    if ($obj->site->in_editor) {
                        ob_start();
                        $obj->edit_buttons(array(tyyp_idlist => 3, only_edit => 1));
                        $custom_contents .= ob_get_contents();
                        ob_end_clean();
                    }
                    if ($kast->all[on_kp_nahtav]) {
                        $cu_date = '&nbsp;&nbsp;<font class=date>' . $obj->aeg() . ' </font>';
                    } else {
                        $cu_date = '';
                    }
                    $custom_contents .= '<li class="list"><a href="' . $kast->site->self . '?id=' . $obj->objekt_id . '" class="navi2_on">' . $obj->pealkiri() . $cu_date . '</a>' . '</li>' . ($obj->site->in_editor ? "<br clear=all>" : "");
                }
                //if is_custom
            }
            # while
            if (!$is_custom) {
                ?>
						<tr> 
						  <td colspan="3"><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="1" height="10"></td>
						</tr>
					  </table>
					</td>
				  </tr>
				</table>
							  <br>
<?php 
            } else {
                $custom_contents .= "</ul>";
            }
            //if is_custom
        } else {
            if ($kast->all[klass] == "rubriik") {
                # ----------------------------
                # Lingide kast
                # ----------------------------
                if (!$is_custom) {
                    ?>
        <table width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" border="0" cellspacing="0" cellpadding="1">
          <tr> 
            <td width="100%" class="boxhead" height="24">
		&nbsp;&nbsp;<?php 
                    echo $kast->pealkiri();
                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                    ?>
</td>
          </tr>
          <tr> 
            <td width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                    ?>
"> 
              <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                    ?>
">
				<tr> 
                  <td align="right" valign="top"><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="20" height="10"></td>
                  <td><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout") - 52;
                    ?>
" height="10" border=0></td>

                  <td><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="20" height="10"></td>
                </tr>
<?php 
                } else {
                    //Custom print out
                    $custom_contents .= '<div class="linkbox">';
                    ob_start();
                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                    $custom_buttons .= ob_get_contents();
                    ob_end_clean();
                    $custom_title .= $kast->pealkiri();
                }
                //if is_custom
                $lingi_alamlist = new Alamlist(array(parent => $kast->objekt_id, klass => "link", asukoht => $kast->all[kesk]));
                $esimene = 1;
                while ($viit = $lingi_alamlist->next()) {
                    if (!$is_custom) {
                        if (!$esimene) {
                            # eraldaja
                            ?>
                <tr valign="top"> 
                  <td align="right" valign="top"><img src="<?php 
                            echo $kast->site->img_path;
                            ?>
/px.gif" width="20" height="10"></td>
                  <td background="<?php 
                            echo $kast->site->img_path;
                            ?>
/stripe1.gif"><img src="<?php 
                            echo $kast->site->img_path;
                            ?>
/px.gif" width="1" height="10"></td>
                  <td><img src="<?php 
                            echo $kast->site->img_path;
                            ?>
/px.gif" width="20" height="10"></td>
                </tr>
<?php 
                        }
                        # if !esimene
                        $viit->load_sisu();
                        if ($viit->site->in_editor) {
                            ?>
		        <!--tr valign="top"> 
					<td colspan="3" align=left> &nbsp; &nbsp;

					</td>
                </tr-->
<?php 
                        }
                        # if in_editor
                        ?>
                <tr valign="top"> 
                  <td align="right" valign="top"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
                  <td><a href="<?php 
                        echo $viit->all[url];
                        ?>
" target="<?php 
                        echo $viit->all[on_uusaken] ? "_blank" : "_self";
                        ?>
" class="navi2_on"><?php 
                        echo $viit->pealkiri();
                        ?>
</a><?php 
                        $viit->edit_buttons(array(tyyp_idlist => 3));
                        ?>
</td>
                  <td><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="20" height="10"></td>
                </tr>
<?php 
                        $esimene = 0;
                    } else {
                        //Custom print out
                        $viit->load_sisu();
                        if ($viit->site->in_editor) {
                            ob_start();
                            $viit->edit_buttons(array(tyyp_idlist => 3));
                            $custom_contents .= ob_get_contents();
                            ob_end_clean();
                        }
                        $custom_contents .= '<a href="' . $viit->all[url] . '" target="' . ($viit->all[on_uusaken] ? "_blank" : "_self") . '" class="navi2_on">' . $viit->pealkiri() . '</a><br>';
                    }
                    //if is_custom
                }
                # while next()
                if (!$is_custom) {
                    if ($lingi_alamlist->size == 0) {
                        ?>
				<tr> 
                  <td colspan="3">
					<?php 
                        $lingi_alamlist->edit_buttons(array(tyyp_idlist => 3));
                        ?>
</td>
                </tr>
<?php 
                    }
                    ?>

                <tr> 
                  <td colspan="3"><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="1" height="10"></td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
					<br>
<?php 
                } else {
                    //Custom print out
                    if ($lingi_alamlist->size == 0) {
                        ob_start();
                        $lingi_alamlist->edit_buttons(array(tyyp_idlist => 3));
                        $custom_contents .= ob_get_contents();
                        ob_end_clean();
                    }
                    $custom_contents .= '</div>';
                }
                //if is_custom
            } else {
                if ($kast->all[klass] == "loginkast") {
                    # ----------------------------
                    # Login kast
                    # ----------------------------
                    if ($kast->all[on_pealkiri] || $kast->site->in_editor) {
                        if (!$is_custom) {
                            ?>
		<table width="<?php 
                            echo $kast->site->dbstyle("menyy_laius", "layout");
                            ?>
" border="0" cellspacing="0" cellpadding="1">
			<form action="<?php 
                            echo $kast->site->self;
                            ?>
" method=post>
			<tr>
				<td width="<?php 
                            echo $kast->site->dbstyle("menyy_laius", "layout");
                            ?>
" class="boxhead" height="24">&nbsp;&nbsp;<?php 
                            echo $kast->site->user->user_id ? $kast->site->sys_sona(array(sona => "tere", tyyp => "kasutaja")) . " " . $kast->site->user->all['username'] : $kast->pealkiri();
                            $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                            ?>
</td>
			</tr>
			<tr>
				<td width="100%" bgcolor="<?php 
                            echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                            ?>
">
					<table width="100%" border="0" cellspacing="0" cellpadding="11" bgcolor="<?php 
                            echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                            ?>
">
					<tr>
						<td width="<?php 
                            echo $kast->site->dbstyle("menyy_laius", "layout");
                            ?>
">
<?php 
                        } else {
                            //Custom print out
                            $custom_contents .= '<div class="loginbox">';
                            ob_start();
                            $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                            $custom_buttons .= ob_get_contents();
                            ob_end_clean();
                            $custom_title .= $kast->site->user->user_id ? $kast->site->sys_sona(array(sona => "tere", tyyp => "kasutaja")) . " " . $kast->site->user->all['username'] : $kast->pealkiri();
                        }
                        //if is_custom
                    }
                    # pealkiri
                    if ($is_custom) {
                        ob_start();
                    }
                    //if is_custom
                    ?>
				<font class=<?php 
                    echo $kast->site->agent ? "txt" : "txt1";
                    ?>
>
<?php 
                    # kasutaja login form
                    # vüi tema andmed ja lingid
                    if ($kast->site->user->user_id) {
                        ?>
								<table  width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr valign="top"> 
									<td align="right"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
									<td colspan=2><a href="<?php 
                        echo $kast->site->self;
                        ?>
?id=<?php 
                        echo $kast->objekt_id;
                        ?>
&op=register" class="navi2_on"><?php 
                        echo $kast->site->sys_sona(array(sona => "Muuda oma andmeid", tyyp => "kasutaja"));
                        ?>
</a></td>
								</tr>
								<tr valign="top"> 
									<td align="right"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
									<td colspan=2><a href="<?php 
                        echo $kast->site->self;
                        ?>
?id=<?php 
                        echo $kast->objekt_id;
                        ?>
&op=logout&url=<?php 
                        echo $kast->site->safeURI;
                        ?>
" class="navi2_on"><?php 
                        echo $kast->site->sys_sona(array(sona => "Logi valja", tyyp => "kasutaja"));
                        ?>
</a></td>
								</tr>
								</table>
<?php 
                    } else {
                        # ----------------
                        # login kast
                        # ----------------
                        ?>
								<form action="<?php 
                        echo $kast->site->self;
                        ?>
" method=post>
								<input type=hidden name="op" value="login">
								<input type=hidden name="url" value="<?php 
                        echo $kast->site->safeURI;
                        ?>
">
								<input type=hidden name="id" value="<?php 
                        echo $kast->objekt_id;
                        ?>
">
								<table  width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td width="1%"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="13" height="1"></td>
									<td><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="1" height="1"></td>
									<td><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="62" height="1"></td>
								</tr>
								<tr>
									<td colspan=2 align="right"><font class=txt1><?php 
                        echo $kast->site->sys_sona(array(sona => "Login", tyyp => "kasutaja"));
                        ?>
:&nbsp;</font></td>
									<td>
										<input type=text class=searchbox size=3 name=user style="width:60">
									</td>
								</tr>
								<tr>
									<td colspan=2 align="right"  width="1%"><font class=txt1><?php 
                        echo $kast->site->sys_sona(array(sona => "Password", tyyp => "kasutaja"));
                        ?>
:&nbsp;</font></td>
									<td>
										<input type=password class=searchbox size=3 name=pass style="width:60">
									</td>
								</tr>
								<tr>
									<td colspan=3 align=center height="34"> 
										<INPUT class=searchbtn type=submit value="<?php 
                        echo $kast->site->sys_sona(array(sona => "nupp login", tyyp => "kasutaja"));
                        ?>
">
									</td>
								</tr>
							<?php 
                        if ($kast->site->CONF['allow_forgot_password']) {
                            ?>
								<tr valign="top"> 
									<td align="right"><img src="<?php 
                            echo $kast->site->img_path;
                            ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
									<td colspan=2><a href="<?php 
                            echo $kast->site->self;
                            ?>
?id=<?php 
                            echo $kast->objekt_id;
                            ?>
&op=remindpass" class="navi2_on"><?php 
                            echo $kast->site->sys_sona(array(sona => "Unustasid parooli", tyyp => "kasutaja"));
                            ?>
</a></td>
								</tr>
							<?php 
                        }
                        if ($kast->site->CONF[users_can_register] == 1) {
                            ?>
								<tr valign="top"> 
									<td align="right"><img src="<?php 
                            echo $kast->site->img_path;
                            ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
									<td colspan=2><a href="<?php 
                            echo $kast->site->self;
                            ?>
?id=<?php 
                            echo $kast->objekt_id;
                            ?>
&op=register" class="navi2_on"><?php 
                            echo $kast->site->sys_sona(array(sona => "Registeeru", tyyp => "kasutaja"));
                            ?>
</a></td>
								</tr>
<?php 
                        }
                        ?>
								</table>
								</form>
<?php 
                    }
                    #					$kast->print_text();
                    ?>
							</font>
<?php 
                    if ($is_custom) {
                        $custom_contents .= ob_get_contents();
                        ob_end_clean();
                        $custom_contents .= '</div>';
                    }
                    //if is_custom
                    if ($kast->all[on_pealkiri] || $kast->site->in_editor) {
                        if (!$is_custom) {
                            ?>
						</td>
					</tr>
					</table>
				</td>
			</tr>
			</form>
		</table>
	<br>
<?php 
                        }
                        //if is_custom
                    } else {
                        if (!$is_custom) {
                            echo "<br>";
                        }
                        //if is_custom
                    }
                } else {
                    if ($kast->all[klass] == "artikkel") {
                        # ----------------------------
                        # Artikkel kastis
                        # ----------------------------
                        if ($kast->all[on_pealkiri] || $kast->site->in_editor) {
                            if (!$is_custom) {
                                ?>
		<table width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
" border="0" cellspacing="0" cellpadding="1">
			<tr>
				<td width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
" class="boxhead" height="24">&nbsp;&nbsp;<?php 
                                echo $kast->pealkiri();
                                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                ?>
</td>
			</tr>
			<tr>
			<td width="100%" bgcolor="<?php 
                                echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                                ?>
">
				 <table width="100%" border="0" cellspacing="0" cellpadding="11" bgcolor="<?php 
                                echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                                ?>
">                
				 <tr>                   
					 <td width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
">
<?php 
                            } else {
                                //Custom print out
                                $custom_contents .= '<div class="articlebox">';
                                ob_start();
                                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                $custom_buttons .= ob_get_contents();
                                ob_end_clean();
                                $custom_title .= $kast->pealkiri();
                            }
                            //if is_custom
                        }
                        # pealkiri
                        if (!$is_custom) {
                            ?>
					<font class=<?php 
                            echo $kast->site->agent ? "txt" : "txt1";
                            ?>
>
					<?php 
                            $kast->print_text();
                            ?>
					</font>
<?php 
                            if ($kast->all[on_pealkiri] || $kast->site->in_editor) {
                                ?>
					</td>
				 </tr>              
				 </table>
			 </td>
		 </tr>        
		 </table>
	<br>
<?php 
                            } else {
                                echo "<br>";
                            }
                        } else {
                            //Custom print out
                            ob_start();
                            echo "<font class=" . ($kast->site->agent ? "txt" : "txt1") . ">" . $kast->print_text() . "</font>";
                            $custom_contents .= ob_get_contents();
                            ob_end_clean();
                            $custom_contents .= '</div>';
                        }
                        //if is_custom
                        ############## GALLUP
                    } else {
                        if ($kast->all[klass] == "gallup") {
                            $kast->load_sisu();
                            ######### HEADER
                            ##### 1) default html
                            if (!$is_custom) {
                                ?>
		<table width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
" border="0" cellspacing="0" cellpadding="1">
		<tr>             
		 <td width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
" class="boxhead" height="24">
			&nbsp;&nbsp;<?php 
                                echo $kast->site->sys_sona(array(sona => 'Gallup', tyyp => "kujundus"));
                                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                ?>
</td>
		 </tr> 
		 <tr>  
		 <td width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
" bgcolor="<?php 
                                echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                                ?>
"> 
		 <table width="100%" border="0" cellspacing="0" cellpadding="11" bgcolor="<?php 
                                echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                                ?>
">
		 <tr> 
						  
		 <td width="<?php 
                                echo $kast->site->dbstyle("menyy_laius", "layout");
                                ?>
"><font class="<?php 
                                echo $kast->site->agent ? "txt" : "txt1";
                                ?>
"><?php 
                                echo $kast->pealkiri();
                                ?>
</font> <br>
		 <table width="100%" border="0" cellspacing="0" cellpadding="2">
		 <tr>
		 <td valign="top" colspan="2"><img src="<?php 
                                echo $kast->site->img_path;
                                ?>
/px.gif" width="1" height="3"></td>
		 </tr>
<?php 
                            } else {
                                $custom_contents .= '<div class="gallupbox">';
                                ob_start();
                                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                $custom_buttons .= ob_get_contents();
                                ob_end_clean();
                                $custom_title .= '&nbsp;&nbsp;' . $kast->site->sys_sona(array(sona => 'Gallup', tyyp => "kujundus"));
                                $custom_contents .= '<font class="' . ($kast->site->agent ? "txt" : "txt1") . '">' . $kast->pealkiri() . '</font><br>';
                            }
                            //if is_custom
                            ######### / HEADER
                            ######### CHECK voting
                            # 1) IP-based gallup
                            if ($kast->site->CONF[gallup_ip_check] == 1) {
                                $sql = $kast->site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND ip LIKE ?", $kast->objekt_id, $_SERVER["REMOTE_ADDR"]);
                                $sth = new SQL($sql);
                                $count = $sth->fetchsingle();
                                $kast->debug->msg($sth->debug->get_msgs());
                            } else {
                                if ($kast->site->CONF[gallup_ip_check] == 2 && $kast->site->cookie["gallup"][$kast->objekt_id] == 1) {
                                    $count = 1;
                                } else {
                                    if ($kast->site->CONF[gallup_ip_check] == 3) {
                                        $sql = $kast->site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND user_id=?", $kast->objekt_id, $kast->site->user->user_id);
                                        $sth = new SQL($sql);
                                        # count=1: not logged in users are not allowed to vote:
                                        $count = $kast->site->user->user_id ? $sth->fetchsingle() : 1;
                                        $kast->debug->msg($sth->debug->get_msgs());
                                    } else {
                                        $count = 0;
                                    }
                                }
                            }
                            ######### / CHECK voting
                            ######### GET VOTES (SUMS)
                            $sql = $kast->site->db->prepare("SELECT * FROM gallup_vastus WHERE objekt_id=?", $kast->objekt_id);
                            $sth = new SQL($sql);
                            if ($is_custom) {
                                # custom html
                                ob_start();
                                print '<table  width="100%" border="0" cellspacing="0" cellpadding="0">';
                            }
                            //if is_custom
                            #################### 1. SHOW FORM & radio buttons
                            if (!$count && !$kast->site->fdat[results] && !$kast->site->in_editor) {
                                ?>
				
			<SCRIPT LANGUAGE="JavaScript"><!--
				//See script on keerulisem kui see peaks olema
				//kuna muidu see ei tööta IE peal
				function do_it(vorm) {
					if (vorm.java_check.value==1) {
						return true
					} else {
						return false
					}
				}
			//--></SCRIPT>

			<form action="<?php 
                                echo $kast->site->self;
                                ?>
" method=get>
			<input type=hidden name="uri" value="<?php 
                                echo $kast->site->URI;
                                ?>
">
			<input type=hidden name="gallup_id" value="<?php 
                                echo $kast->objekt_id;
                                ?>
">
			<input type=hidden name="op" value="vote">

<?php 
                                ####### loop over VASTUS (votes sum)
                                while ($vastus = $sth->fetch()) {
                                    ?>
				 <tr>
				 <td valign="top" width="15">
				 <input type=radio id="vastus_<?php 
                                    echo $vastus[gv_id];
                                    ?>
" name=vastus value="<?php 
                                    echo $vastus[gv_id];
                                    ?>
" onclick="javascript:if(this.checked){this.form.java_check.value=1;};">
				 </td>
				 <td valign="top" class="<?php 
                                    echo $kast->site->agent ? "txt" : "txt1";
                                    ?>
"><label for="vastus_<?php 
                                    echo $vastus[gv_id];
                                    ?>
"><?php 
                                    echo $vastus[vastus];
                                    ?>
</label></td>
				 </tr>
<?php 
                                }
                                # while vastus
                                ?>
 

				<?php 
                                ######## submit-button
                                ?>
				<tr align="right">
					<input type="hidden" name="java_check" value="0">
					<td valign="top" colspan="2"><input type="submit" name="haaleta" value="<?php 
                                echo $kast->site->sys_sona(array(sona => 'haaleta', tyyp => "kujundus"));
                                ?>
" onclick="javascript:return do_it(this.form);" class="searchbtn"></td>
				</tr>
			  </form>
			 </table>
<?php 
                                $kast->debug->msg($sth->debug->get_msgs());
                            } else {
                                $sql = $kast->site->db->prepare("SELECT SUM(count) AS kokku, MAX(count) AS maksi FROM gallup_vastus WHERE objekt_id=? ", $kast->objekt_id);
                                $sth_c = new SQL($sql);
                                $stat = $sth_c->fetch();
                                $kast->debug->msg("kokku = {$stat['kokku']}, maks = {$stat['maksi']}");
                                $kast->debug->msg($sth_c->debug->get_msgs());
                                ###### voters vount:
                                ?>
		 <tr>
			 <td valign="top" class="<?php 
                                echo $kast->site->agent ? "txt" : "txt1";
                                ?>
"><?php 
                                echo $kast->site->sys_sona(array(sona => "vastajaid", tyyp => "kujundus"));
                                ?>
: <b><?php 
                                echo $stat[kokku];
                                ?>
</b></td>
			 </tr>
			 <tr>
			 <td valign="top"><img src="<?php 
                                echo $kast->site->img_path;
                                ?>
/px.gif" width="1" height="3"></td>
		 </tr>
<?php 
                                ###### one colored row
                                while ($vastus = $sth->fetch()) {
                                    $percent = $stat[kokku] ? sprintf('%2.0f', 100 * $vastus[count] / $stat[kokku]) : 0;
                                    ?>
				
		 <tr>
			 <td valign="top" class="<?php 
                                    echo $kast->site->agent ? "txt" : "txt1";
                                    ?>
"><?php 
                                    echo $vastus[vastus];
                                    ?>
</td>
		 </tr>
		 <tr>
			 <td valign="top"><b><font class="<?php 
                                    echo $kast->site->agent ? "txt" : "txt1";
                                    ?>
">- <?php 
                                    echo $percent;
                                    ?>
%</font></b> <img src="<?php 
                                    echo $kast->site->img_path;
                                    ?>
/gallup_bar<?php 
                                    echo $stat[maksi] == $vastus[count] && $vastus[count] ? "2" : "1";
                                    ?>
.gif" width="<?php 
                                    echo 110 * ($percent / 100);
                                    ?>
" height=8 border="1"></td>
		 </tr>
<?php 
                                }
                                # while vastus
                                ############## archive link     # added 12.12.2003 by Dima Bug #744
                                if ($archive_link_on) {
                                    ?>
			 <tr>
				 <td valign="top"><img src="<?php 
                                    echo $kast->site->img_path;
                                    ?>
/px.gif" width="1" height="3"></td>
				 </tr>
				 <tr align="right">
				 <td valign="top"><a href="<?php 
                                    echo $kast->site->self;
                                    ?>
?op=gallup_arhiiv" class="navi2_on"><?php 
                                    echo $kast->site->sys_sona(array(sona => 'Arhiiv', tyyp => "kujundus"));
                                    ?>
</a></td>
			 </tr>
			<?php 
                                }
                                ?>
			 </table>
<?php 
                            }
                            #################### / 2. SHOW RESULTS
                            ##### 1) default html
                            if (!$is_custom) {
                                ?>
			</td>
		 </tr>              
		 </table>
		 </td>
		 </tr>        
		 </table>
		<br>
<?php 
                            }
                            //if is_custom
                            ##### 2) custom html
                            if ($is_custom) {
                                $custom_contents .= ob_get_contents();
                                ob_end_clean();
                                $custom_contents .= '</div>';
                            }
                            //if is_custom
                        } else {
                            if ($kast->all[klass] == "iframekast") {
                                $kast->load_sisu();
                                $conf = new CONFIG($kast->all[ttyyp_params]);
                                $src_file = $conf->get("src_file");
                                $predefined = $conf->get("predefined");
                                $height = $conf->get("height");
                                # kui tegemist saidi sisese failiga, panna id juurde
                                if (trim($predefined) != '') {
                                    $src_file .= "&id=" . ($kast->site->fdat[id] ? $kast->site->fdat[id] : $kast->site->alias("rub_home_id"));
                                }
                                if (!$is_custom) {
                                    ?>
  <table width="<?php 
                                    echo $kast->site->dbstyle("menyy_laius", "layout");
                                    ?>
" border="0" cellspacing="0" cellpadding="2">
                
  <tr> 
                  
  <td class="boxhead" height="24">
	  &nbsp;&nbsp;<?php 
                                    echo $kast->pealkiri();
                                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                    ?>
</td>
  </tr>
                
  <tr valign="top"> 
                  
  <td class=box><?php 
                                    if (strlen(trim($src_file)) > 0) {
                                        ?>
<iframe name="iifreim" src="<?php 
                                        echo $src_file;
                                        ?>
" width="<?php 
                                        echo $is_custom ? "100%" : $kast->site->dbstyle("menyy_laius", "layout");
                                        ?>
" frameborder=0 height="<?php 
                                        echo $height;
                                        ?>
" ></iframe><?php 
                                    }
                                    ?>
</td>
  </tr>
  
              
  </table>
	  <br>


<?php 
                                } else {
                                    //Custom print out
                                    $custom_contents .= '<div class="iframebox">';
                                    ob_start();
                                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                                    $custom_buttons .= ob_get_contents();
                                    ob_end_clean();
                                    $custom_title .= $kast->pealkiri();
                                    if (strlen(trim($src_file)) > 0) {
                                        $custom_contents .= '<iframe name="iifreim" src="' . $src_file . '" width="100%" frameborder=0 height="' . $height . '" ></iframe>';
                                    }
                                    $custom_contents .= '</div>';
                                }
                                //if is_custom
                            }
                        }
                    }
                }
            }
        }
        ###########################################################
    } else {
        if (get_class($kast) == "Alamlist" || is_subclass_of($kast, "Alamlist")) {
            # ----------------------
            # kui parameetrina on alamlist,
            # siis teeme "uus kast" nupp
            # ----------------------
            if (!($kast->size > 0)) {
                if (!$is_custom) {
                    ?>
<table width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" border="0" cellspacing="0" cellpadding="1">          
 <tr>             
 <td width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" class="boxhead" height="24">
&nbsp; &nbsp;
<?php 
                    echo $kast->site->sys_sona(array(sona => 'new', tyyp => "editor"));
                    ?>
 
<?php 
                    echo $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17", no_br => 1));
                    ?>
	
</nobr></td>
 </tr>
 <tr>             
 <td width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                    ?>
"> 
              
 <table width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" border="0" cellspacing="0" cellpadding="11" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                    ?>
">                
 <tr>
	<td width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
">&nbsp;</td>
 </tr>              
 </table>

 </td>
 </tr>        
 </table>
	 <br>
<?php 
                } else {
                    //Custom print out
                    ob_start();
                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17", no_br => 1));
                    $custom_buttons .= ob_get_contents();
                    ob_end_clean();
                    $custom_title .= $kast->site->sys_sona(array(sona => 'new', tyyp => "editor"));
                }
                //if is_custom
            }
            # if ! size > 0
        } else {
            $GLOBALS[site]->debug->msg("print_kast() argument \"kast\" on vale");
        }
    }
    #print "<br>";
    return array('buttons' => $custom_buttons, 'title' => $custom_title, 'contents' => $custom_contents);
}
function auto_publishing($is_pageloaded = 0)
{
    global $site;
    ########################################
    # leida objektid, mis vajavad avaldamist JA mis ei kuulu prügikasti
    $sql = "SELECT DISTINCT objekt.objekt_id FROM objekt LEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id ";
    # bug 2817
    # pole praegu avaldatud JA ei ole prügikatis (Bug #1373) JA..
    $sql .= " WHERE on_avaldatud=0 AND objekt_objekt.parent_id<>'" . $site->alias("trash") . "' ";
    # ..alguskuupäev täidetud, varasem tänasest ja lõppkuupäev täidetud/tühi, hilisem tänasest VÕI..
    $sql .= " AND ( (avaldamisaeg_algus>0 AND avaldamisaeg_algus <= " . $site->db->unix2db_datetime(time()) . " AND (avaldamisaeg_lopp>=" . $site->db->unix2db_datetime(time()) . " OR NOT avaldamisaeg_lopp>0)) ";
    # ..alguskuupäev tühi ja lõppkuupäev täidetud, hilisem tänasest
    $sql .= " OR (avaldamisaeg_lopp>=" . $site->db->unix2db_datetime(time()) . " AND NOT avaldamisaeg_algus>0) )";
    $sth = new SQL($sql);
    $site->debug->msg($sth->debug->get_msgs());
    //print_r($sql);
    while ($objekt_id = $sth->fetchsingle()) {
        # tee objekt. ja tee seda superuserina, Bug #805 ( muidu on nii, et kui pageloadi ajal püütakse avaldada objekti, millele sellel juhuslikul useril õiguseid ei ole, siis seda ka autom. avaldada ei suudeta)
        $obj = new Objekt(array("id" => $objekt_id, "superuser" => 1));
        $sql = $site->db->prepare("UPDATE objekt SET on_avaldatud=1 WHERE objekt_id=?", $objekt_id);
        $sth2 = new SQL($sql);
        $site->debug->msg($sth2->debug->get_msgs());
        new Log(array('action' => 'publish', 'objekt_id' => $obj->objekt_id, 'user_id' => $is_pageloaded ? 0 : $site->user->id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($obj->all[klass])), $obj->pealkiri(), $obj->objekt_id, "published")));
    }
    ########################################
    # leida objektid, mis vajavad peitmist
    $sql = "SELECT DISTINCT objekt.objekt_id FROM objekt LEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id ";
    # bug 2817
    # on praegu avaldatud JA ei ole prügikatis (Bug #1373) JA..
    $sql .= " WHERE on_avaldatud=1  AND objekt_objekt.parent_id<>'" . $site->alias("trash") . "' ";
    # ..alguskuupäev täidetud ja hilisem praegusest VÕI.
    $sql .= " AND (avaldamisaeg_algus > " . $site->db->unix2db_datetime(time()) . " ";
    # ..lõppkuupäev täidetud ja varasem praegusest
    $sql .= " OR (avaldamisaeg_lopp>0 AND avaldamisaeg_lopp < " . $site->db->unix2db_datetime(time()) . ")) ";
    $sth = new SQL($sql);
    $site->debug->msg($sth->debug->get_msgs());
    while ($objekt_id = $sth->fetchsingle()) {
        # tee objekt. ja tee seda superuserina, Bug #805 ( muidu on nii, et kui pageloadi ajal püütakse avaldada objekti, millele sellel juhuslikul useril õiguseid ei ole, siis seda ka autom. avaldada ei suudeta)
        $obj = new Objekt(array("objekt_id" => $objekt_id, "superuser" => 1));
        $sql = $site->db->prepare("UPDATE objekt SET on_avaldatud=0 WHERE objekt_id=?", $objekt_id);
        $sth2 = new SQL($sql);
        $site->debug->msg($sth2->debug->get_msgs());
        new Log(array('action' => 'hide', 'objekt_id' => $obj->objekt_id, 'user_id' => $is_pageloaded ? 0 : $site->user->id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($obj->all[klass])), $obj->pealkiri(), $obj->objekt_id, "hided")));
    }
    # while
}
# PUBLISH: if current object has PUBLISH permission => allow
if( $objekt->permission['P']) {
	$access = 1;
}
else {
	$access = 0;
}

	####################
	# access denied
	if (!$access) {
		new Log(array(
			'action' => ($site->fdat['op'] == 'publish' ? 'publish' : 'hide'),
			'type' => 'WARNING',
			'objekt_id' => $objekt->objekt_id,
			'message' => sprintf("access denied: attempt to ".($site->fdat[op] == "publish"?'publish':'hide')." %s '%s' (ID = %s)" , ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id),
		));
		print "<center><b><font class=\"txt\">".$site->sys_sona(array(sona => "access denied", tyyp=>"editor"))."</font></b></center>";
		if($site->user) { $site->user->debug->print_msg(); }
		if($site->guest) { 	$site->guest->debug->print_msg(); }
		$site->debug->print_msg();
		########### EXIT
		exit;
	}
# / ACCESS allowed/denied
###########################


###########################
# GO ON with real work
/**
 * This source file is is part of Saurus CMS content management software.
 * It is licensed under MPL 1.1 (http://www.opensource.org/licenses/mozilla1.1.php).
 * Copyright (C) 2000-2010 Saurused Ltd (http://www.saurus.info/).
 * Redistribution of this file must retain the above copyright notice.
 * 
 * Please note that the original authors never thought this would turn out
 * such a great piece of software when the work started using Perl in year 2000.
 * Due to organic growth, you may find parts of the software being
 * a bit (well maybe more than a bit) old fashioned and here's where you can help.
 * Good luck and keep your open source minds open!
 * 
 * @package		SaurusCMS
 * @copyright	2000-2010 Saurused Ltd (http://www.saurus.info/)
 * @license		Mozilla Public License 1.1 (http://www.opensource.org/licenses/mozilla1.1.php)
 * 
 */
function smarty_function_save_profile($params, &$smarty)
{
    global $site, $class_path, $leht;
    include_once $class_path . 'adminpage.inc.php';
    // for check_profile_values()
    $id = (int) $params['id'];
    unset($params['id']);
    $parent_id = (int) $params['parent'];
    if (!$parent_id) {
        $parent_id = $leht->id;
        $current_objekt = $leht->objekt;
    } else {
        $current_objekt = new Objekt(array('objekt_id' => $parent_id));
    }
    unset($params['parent']);
    if (!isset($params['name'])) {
        $name = 'insert_id';
    } else {
        $name = $params['name'];
    }
    unset($params['name']);
    // for CMS objects on_create publishing
    $publish = strtoupper(trim($params['on_create'])) == 'PUBLISH' ? 1 : 0;
    unset($params['on_create']);
    # get all profile data from cash
    # profile name is case insensitive
    $profile = strtolower($params['profile']);
    unset($params['profile']);
    $profile = $site->get_profile(array('name' => $profile, 'id' => (int) $params['profile_id']));
    $profile_field_values = $params['fields'];
    unset($params['fields']);
    # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade
    if (!$profile['profile_id']) {
        if ($site->admin) {
            print "<font color=red><b>Profile '" . $profile['name'] . "' not found!</b></font>";
        }
        return;
    }
    // must go to source table
    $params['profile_id'] = $profile['profile_id'];
    // special cases for source table ID columns
    switch ($profile['source_table']) {
        case 'users':
            $source_table_id_column = 'user_id';
            break;
        case 'groups':
            $source_table_id_column = 'group_id';
            break;
        default:
            $source_table_id_column = 'objekt_id';
            break;
    }
    // if source_table is ext_ table
    if (strpos($profile['source_table'], 'ext_') === 0) {
        $source_table_id_column = 'id';
    }
    //printr($profile);
    $source_table_columns = array();
    $profile_data = unserialize($profile['data']);
    foreach ($profile_data as $column => $data) {
        if ($data['is_active']) {
            if ($data['is_general']) {
                $source_table_columns[] = 'objekt.' . $column;
            } else {
                $source_table_columns[] = $profile['source_table'] . '.' . $column;
            }
        }
    }
    //printr($source_table_columns);
    $profile_field_values = array();
    $profile_data['id'] = 0;
    foreach (array_keys($profile_data) as $key) {
        $profile_field_values[$key] = '';
    }
    //check profile filed values, errors go into $site->fdat['form_error']
    $sql_values = check_profile_values(array('profile_def' => $profile, 'skip_non_active_fields' => true, 'use_only_profile_fields' => true));
    $sql_values_skip_prepare = array();
    // add additional fields to sql values
    foreach ($params as $field_name => $field_value) {
        $sql_values[$field_name] = $field_value;
        if (array_search($profile['source_table'] . '.' . $field_name, $source_table_columns) === false) {
            $source_table_columns[] = $profile['source_table'] . '.' . $field_name;
        }
    }
    // add profile_id
    if (array_search($profile['source_table'] . '.profile_id', $source_table_columns) === false) {
        $source_table_columns[] = $profile['source_table'] . '.profile_id';
    }
    //$sql_values = array_unique($sql_values);
    // special case for users
    if ($profile['source_table'] == 'users') {
        // username is required field but readonly for already registered users
        if ($site->fdat['form_error']['username'] && $params['username']) {
            unset($site->fdat['form_error']['username']);
        }
        // username must be unique for new user
        if (!$id) {
            $sql = $site->db->prepare('select username from users where username = ?', $sql_values['username']);
            $result = new SQL($sql);
            if ($result->rows) {
                $site->fdat['form_error']['username'] = $site->sys_sona(array('sona' => 'user exists', 'tyyp' => 'kasutaja'));
            }
        }
        ############ E-MAIL: CHECK FOR CORRECT FORMAT
        if ($sql_values['email'] != '' && !preg_match("/^[\\w\\-\\&\\.\\d]+\\@[\\w\\-\\&\\.\\d]+\$/", $sql_values['email'])) {
            $site->fdat['form_error']['email'] = $site->sys_sona(array('sona' => 'wrong email format', 'tyyp' => 'kasutaja'));
        }
        ############ E-MAIL: CHECK FOR DUPLICATES
        if ($sql_values['email']) {
            $sql = $site->db->prepare("SELECT user_id FROM users WHERE email=? AND user_id<>?", $sql_values['email'], $id);
            $sth = new SQL($sql);
            if ($exists = $sth->fetchsingle()) {
                $site->fdat['form_error']['email'] = $site->sys_sona(array(sona => 'Email already exists', 'tyyp' => 'kasutaja'));
            }
        }
        ############ PASSWORD: CHECK FOR CONFIRM MATCH & ENCRYPT
        # if password is set
        if (!$id || $params['password']) {
            if (!$params['password']) {
                $site->fdat['form_error']['password'] = $site->sys_sona(array('sona' => 'field required', 'tyyp' => 'kasutaja'));
            }
            if (!$params['confirm_password']) {
                $site->fdat['form_error']['confirm_password'] = $site->sys_sona(array('sona' => 'field required', 'tyyp' => 'kasutaja'));
            }
            $old_user_enc_password = $site->user->all['password'];
            unset($site->user->all['password']);
            # if password expired, then check, if user inserted new password (check if this match with old one)
            if ($old_user_enc_password && $site->user->all['pass_expired']) {
                if ($old_user_enc_password == crypt($sql_values['password'], $old_user_enc_password)) {
                    $you_inserted_old_password = 1;
                }
            }
            if ($you_inserted_old_password) {
                $site->fdat['form_error']['password'] = $site->sys_sona(array('sona' => 'Password expired message', 'tyyp' => 'kasutaja'));
            } elseif ($params['confirm_password'] != $sql_values['password']) {
                $site->fdat['form_error']['password'] = $site->sys_sona(array('sona' => 'wrong confirmation', 'tyyp' => 'kasutaja'));
            } elseif ($site->CONF['users_require_safe_password'] == 1 && strlen($sql_values['password']) < 8 && !(preg_match('/[a-z]/', $sql_values['password']) && preg_match('/[A-Z]/', $sql_values['password']) && preg_match('/[0-9]/', $sql_values['password']))) {
                $site->fdat['form_error']['password'] = $site->sys_sona(array('sona' => 'pass_not_strong', 'tyyp' => 'kasutaja'));
            } else {
                $sql_values['password'] = crypt($sql_values['password'], Chr(rand(65, 91)) . Chr(rand(65, 91)));
                // set pass_expiring date
                if (!$sql_values['pass_expires'] || $sql_values['pass_expires'] == '0000-00-00') {
                    $source_table_columns[] = 'users.pass_expires';
                    $sql_values['pass_expires'] = "DATE_ADD(now(), INTERVAL " . $site->CONF['default_pass_expire_days'] . " DAY)";
                    $sql_values_skip_prepare['users.pass_expires'] = 1;
                }
            }
            # if confirm ok
        } else {
            unset($sql_values['password']);
            $key = array_search('users.password', $source_table_columns);
            if ($key !== false) {
                unset($source_table_columns[$key]);
            }
        }
        // remove confirm_password
        unset($sql_values['confirm_password']);
        $key = array_search('users.confirm_password', $source_table_columns);
        if ($key !== false) {
            unset($source_table_columns[$key]);
        }
        // set group_id only for new users
        if (!$sql_values['group_id'] && !$id) {
            $sth = new SQL('SELECT group_id FROM groups  WHERE is_predefined = 1');
            $site->debug->msg($sth->debug->get_msgs());
            $sql_values['group_id'] = $sth->fetchsingle();
            $source_table_columns[] = 'users.group_id';
        }
        // set created_date
        if (!$sql_values['created_date'] && !$id) {
            $source_table_columns[] = 'users.created_date';
            $sql_values['created_date'] = date('Y-m-d');
        }
    }
    // if no erros
    if (!sizeof($site->fdat['form_error'])) {
        // UPDATE a field
        if ($id) {
            $update_source_sql = '';
            $update_objekt_sql = '';
            foreach ($source_table_columns as $source_table_column) {
                if (strpos($source_table_column, 'objekt.') === 0) {
                    // only pealkir allowed and it must be prepared
                    if ($source_table_column == 'objekt.pealkiri') {
                        $title = $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)];
                        $update_objekt_sql .= $site->db->prepare($source_table_column . ' = ?, ', $title);
                        $update_objekt_sql .= $site->db->prepare('objekt.pealkiri_strip = ?, ', strip_tags($title));
                    }
                } else {
                    if ($sql_values_skip_prepare[$source_table_column]) {
                        $update_source_sql .= $source_table_column . ' = ' . $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)] . ', ';
                    } else {
                        $update_source_sql .= $site->db->prepare($source_table_column . ' = ?, ', $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)]);
                    }
                }
            }
            // remove trailing ,
            $update_source_sql = substr_replace($update_source_sql, '', strlen($update_source_sql) - 2);
            $update_objekt_sql = substr_replace($update_objekt_sql, '', strlen($update_objekt_sql) - 2);
            // if this is a CMS objekt
            if (strpos($profile['source_table'], 'obj_') === 0) {
                $objekt = new Objekt(array('objekt_id' => $id));
                // object must have READ and UPDATE permissions
                if ($objekt->objekt_id && $objekt->permission['R'] && $objekt->permission['U']) {
                    // update the object table first
                    // changed_user_id
                    $update_objekt_sql .= ($update_objekt_sql ? ', ' : ' ') . 'objekt.changed_user_id = ' . (int) $site->user->id;
                    // changed_user_name
                    $update_objekt_sql .= $site->db->prepare(',  objekt.changed_user_name = ?', $site->user->name);
                    // changed_time
                    $update_objekt_sql .= ', objekt.changed_time = now()';
                    $sql = 'update objekt set ' . $update_objekt_sql . ' where objekt.objekt_id = ' . $id;
                    //printr($sql);
                    new SQL($sql);
                    $sql = 'update ' . $profile['source_table'] . ' set ' . $update_source_sql . ' where ' . $profile['source_table'] . '.objekt_id = ' . $id;
                    //printr($sql);
                    new SQL($sql);
                    new Log(array('action' => 'update', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all['klass'])), $title, $objekt->objekt_id, "changed")));
                    $smarty->assign($name, $id);
                } else {
                    new Log(array('action' => 'update', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("Access denied: attempt to edit %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id)));
                    $smarty->assign($name, 0);
                }
            } else {
                if ($profile['source_table'] == 'users' && $site->user->all['is_readonly'] == 1) {
                    new Log(array('action' => 'update', 'type' => 'WARNING', 'component' => 'Users', 'message' => "User '" . $site->user->all['firstname'] . ' ' . $site->user->all['lastname'] . "'  tried to update an account but was unable because of a is_readonly flag"));
                    $smarty->assign($name, 0);
                } else {
                    $sql = 'update ' . $profile['source_table'] . ' set ' . $update_source_sql . ' where ' . $source_table_id_column . ' = ' . $id;
                    //printr($sql);
                    $result = new SQL($sql);
                    if ($result->rows != -1) {
                        // log values for new user
                        if ($profile['source_table'] == 'users') {
                            new Log(array('action' => 'update', 'component' => 'Users', 'message' => "User '" . $site->user->all['firstname'] . ' ' . $site->user->all['lastname'] . "' account updated"));
                        } else {
                            new Log(array('action' => 'update', 'message' => "Record (ID: " . $id . ") updated in " . $profile['source_table']));
                        }
                        $smarty->assign($name, $id);
                    } else {
                        $smarty->assign($name, 0);
                    }
                }
            }
        } else {
            $insert_source_sql = '';
            $insert_objekt_sql = '';
            foreach ($source_table_columns as $source_table_column) {
                if (strpos($source_table_column, 'objekt.') === 0) {
                    // only pealkir allowed and it must be prepared
                    if ($source_table_column == 'objekt.pealkiri') {
                        $title = $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)];
                        $insert_objekt_sql .= $site->db->prepare($source_table_column . ' = ?, ', $title);
                        $insert_objekt_sql .= $site->db->prepare('objekt.pealkiri_strip = ?, ', strip_tags($title));
                    }
                } else {
                    if ($sql_values_skip_prepare[$source_table_column]) {
                        $insert_source_sql .= $source_table_column . ' = ' . $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)] . ', ';
                    } else {
                        $insert_source_sql .= $site->db->prepare($source_table_column . ' = ?, ', $sql_values[substr($source_table_column, strpos($source_table_column, '.') + 1)]);
                    }
                }
            }
            // remove trailing ,
            $insert_objekt_sql = substr_replace($insert_objekt_sql, '', strlen($insert_objekt_sql) - 2);
            $insert_source_sql = substr_replace($insert_source_sql, '', strlen($insert_source_sql) - 2);
            // if this is a CMS objekt
            if (strpos($profile['source_table'], 'obj_') === 0) {
                // parent object must have create permission
                if ($current_objekt->permission['C']) {
                    //must be fields and cannot be overwritten by user data
                    // tyyp_id
                    $class_id = (int) array_search(str_replace('obj_', '', $profile['source_table']), $site->object_tyyp_id_klass);
                    $insert_objekt_sql .= ($insert_objekt_sql ? ', ' : ' ') . 'objekt.tyyp_id = ' . $class_id;
                    // keel
                    $insert_objekt_sql .= ', objekt.keel = ' . $site->keel;
                    // kesk (position)
                    //$insert_objekt_sql .= ', kesk = '.(int)$current_objekt->all['kesk'];
                    // aeg
                    $insert_objekt_sql .= ', objekt.aeg = now()';
                    // publishing
                    $insert_objekt_sql .= ', objekt.on_avaldatud = ' . $publish;
                    // created user_id
                    $insert_objekt_sql .= ', objekt.created_user_id = ' . (int) $site->user->id;
                    // created user_name
                    $insert_objekt_sql .= $site->db->prepare(', objekt.created_user_name = ?', $site->user->name);
                    // created time
                    $insert_objekt_sql .= ', objekt.created_time = now()';
                    // comment_count, for less errors in database_repair.php
                    $insert_objekt_sql .= ', objekt.comment_count = 0';
                    $sql = 'insert into objekt set ' . $insert_objekt_sql;
                    //printr($sql);
                    $result = new SQL($sql);
                    $id = $result->insert_id;
                    if ($id) {
                        $sql = 'select max(sorteering)+1 from objekt_objekt';
                        $result = new SQL($sql);
                        $sql = $site->db->prepare('insert into objekt_objekt set objekt_id = ?, parent_id = ?, sorteering = ?', $id, $parent_id, $result->fetchsingle());
                        //printr($sql);
                        $result = new SQL($sql);
                        $insert_source_sql .= ', ' . $profile['source_table'] . '.objekt_id = ' . $id;
                        $sql = 'insert into ' . $profile['source_table'] . ' set ' . $insert_source_sql;
                        //printr($sql);
                        $result = new SQL($sql);
                        new Log(array('action' => 'create', 'objekt_id' => $id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst($site->object_tyyp_id_nimi[$class_id]), $title, $id, "inserted")));
                        foreach (unserialize($profile['data']) as $key => $value) {
                            unset($site->fdat[$key]);
                        }
                        $smarty->assign($name, $id);
                    } else {
                        $smarty->assign($name, 0);
                    }
                } else {
                    // no create permission
                    new Log(array('action' => 'create', 'type' => 'WARNING', 'message' => sprintf("Access denied: attempt to create %s under restricted category ID = %s", ucfirst(translate_en(str_replace('obj_', '', $profile['source_table']))), $current_objekt->objekt_id)));
                    $smarty->assign($name, 0);
                }
            } elseif ($profile['source_table'] == 'users' && $site->user->all['is_readonly'] == 1) {
                new Log(array('action' => 'update', 'component' => 'Users', 'type' => 'WARNING', 'message' => "User '" . $site->user->all['firstname'] . ' ' . $site->user->all['lastname'] . "' tried to update his account, but was unable to because of a read_only flag on his/her account"));
            } else {
                $sql = 'insert into ' . $profile['source_table'] . ' set ' . $insert_source_sql;
                //printr($sql);
                $result = new SQL($sql);
                if ($result->insert_id) {
                    // log values for new user
                    if ($profile['source_table'] == 'users') {
                        new Log(array('action' => 'create', 'component' => 'Users', 'message' => "New user '" . $sql_field_values['username'] . "' inserted"));
                    } else {
                        new Log(array('action' => 'create', 'message' => "Record (ID: " . $result->insert_id . ") inserted into " . $profile['source_table']));
                    }
                    foreach (unserialize($profile['data']) as $key => $value) {
                        unset($site->fdat[$key]);
                    }
                    $smarty->assign($name, $result->insert_id);
                } else {
                    $smarty->assign($name, 0);
                }
            }
        }
    } else {
        $_POST['form_error'] = $site->fdat['form_error'];
        $smarty->assign($name, 0);
    }
}
# GET PERMISSIONS
# get object permissions for current user
$site->debug->msg("EDIT: Kustutava objekti " . $objekt->objekt_id . " �igused = " . ($system_admin ? "System admin" : $objekt->permission['mask']));
###########################
# ACCESS allowed/denied
# decide if accessing this page is allowed or not
# DELETE: if current object has DELETE => allow
if ($objekt->permission['D']) {
    $access = 1;
} else {
    $access = 0;
}
####################
# access denied
if (!$access) {
    new Log(array('action' => 'delete', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("access denied: attempt to delete %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id)));
    if (!$hidden_output) {
        print "<center><b><font class=\"txt\">" . $site->sys_sona(array(sona => "access denied", tyyp => "editor")) . "</font></b></center>";
    }
    if ($site->user) {
        $site->user->debug->print_msg();
    }
    if ($site->guest) {
        $site->guest->debug->print_msg();
    }
    $site->debug->print_msg();
    ########### EXIT
    exit;
}
# / ACCESS allowed/denied
###########################
function smarty_function_init_message($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "message";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ##############
    # luua objekt
    $obj = new Objekt(array(objekt_id => $id));
    ##############
    # minna edasi vaid siis kui tegemist on kommentaariga/kirjaga
    if (!$obj->all[klass] == "kommentaar") {
        # error pealkirja or smth
        # assign
        # exit;
    }
    ##############
    # load variables
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 14, publish => $publish));
    $obj->id = $obj->objekt_id;
    $obj->parent_href = $site->self . '?id=' . $obj->parent_id;
    $obj->title = $obj->pealkiri();
    $obj->load_sisu();
    $obj->body = nl2br(htmlspecialchars($obj->all[text]));
    $obj->author = $obj->all[nimi];
    $obj->author_email = $obj->all[email];
    $obj->hide_email = $obj->all[on_peida_email];
    $obj->started = $site->db->MySQL_ee_short($obj->all[aeg]);
    $obj->date = $obj->started;
    # alternative name
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
    ## crap data
    $obj->flast_modified = $obj->all['last_modified'];
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    # parent subject
    $obj->parent_subject = $leht->parents->get(1);
    $obj->parent_subject_id = $obj->parent_subject->objekt_id;
    $obj->parent_subject_title = $obj->parent_subject->pealkiri;
    # parent section
    $obj->parent_section = $leht->parents->get(2);
    $obj->parent_section_id = $obj->parent_section->objekt_id;
    $obj->parent_section_title = $obj->parent_section->pealkiri;
    #	$obj->parent_section_href = $obj->parent_section->objekt_id;
    $obj->hit_count = $obj->all['count'];
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
}
 function Leht()
 {
     $args = func_get_arg(0);
     $this->BaasObjekt();
     $this->id = $args[id];
     $fdat = array();
     # Get full path to the class folder. added by Dima 19.03.2004
     $path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
     $class_path = $path_parts["dirname"];
     # bugfix #1393, by merle 15.10.2004
     # if path ends with "/editor", cut it off
     if (substr($path_parts["dirname"], -7) == '/editor') {
         $class_path = substr($path_parts["dirname"], 0, -7);
     }
     # if path ends with "/admin", cut it off
     if (substr($path_parts["dirname"], -6) == '/admin') {
         $class_path = substr($path_parts["dirname"], 0, -6);
     }
     $class_path .= "/classes/";
     //testing:
     //require_once($class_path."auto.inc.php");
     //auto_error_notifications(1);
     //auto_maillist(0, 0, 0 , 1);
     #################################################
     # run mailinglist in CONF[maillist_interval] hour
     if ($this->site->CONF['next_mailinglist'] < time() && $this->site->CONF['maillist_interval'] && $this->site->CONF['enable_mailing_list']) {
         # set next run
         $sql = $this->site->db->prepare("\r\n\t\t\t\tupdate config set sisu = ? where nimi='next_mailinglist'", time() + intval($this->site->CONF['maillist_interval']) * 3600);
         $sth = new SQL($sql);
         $this->site->debug->msg($sth->debug->get_msgs());
         require_once $class_path . "auto.inc.php";
         auto_maillist(0, 0, 0, 1);
     }
     ########################
     # run in every 10 minutes
     if ($this->site->CONF['next_10min'] < time()) {
         # set next run
         $sql = $this->site->db->prepare("update config set sisu = ? where nimi='next_10min'", time() + 600);
         $sth = new SQL($sql);
         $this->site->debug->msg($sth->debug->get_msgs());
         require_once $class_path . "auto.inc.php";
         auto_publishing(1);
     }
     ########################
     # run in every hour
     if ($this->site->CONF['next_hour'] < time()) {
         # set next run
         $sql = $this->site->db->prepare("update config set sisu = ? where nimi='next_hour'", time() + 3600);
         $sth = new SQL($sql);
         $this->site->debug->msg($sth->debug->get_msgs());
         require_once $class_path . "auto.inc.php";
         # delete from cache old content:
         if (is_numeric($this->site->CONF['cache_expired'])) {
             ## delete cache by interval
             $cache_expired = time() + $this->site->CONF['cache_expired'] * 60 * 60;
             # now + interval in seconds
             $sql = $this->site->db->prepare("DELETE FROM cache WHERE aeg < " . $this->site->db->unix2db_datetime($cache_expired) . " AND objekt_id != ?", 0);
             $sth = new SQL($sql);
             $this->site->debug->msg($sth->debug->get_msgs());
         }
         // error notifications, only if setting is marked as pageload
         if ($this->site->CONF['send_error_notifiations_setting'] == 1) {
             auto_error_notifications(1);
         }
     }
     #################################################
     # We don't want to dublicate code, so will write it here:
     if ($this->site->admin && $this->site->fdat['empty_recycle_bin']) {
         $do_empty = 1;
     }
     #################################################
     # run every day
     if ($this->site->CONF['next_day'] < time() || $do_empty) {
         if (!$do_empty) {
             # set next run
             $sql = $this->site->db->prepare("update config set sisu = ? where nimi='next_day'", time() + 86400);
             $sth = new SQL($sql);
             $this->site->debug->msg($sth->debug->get_msgs());
         }
         #################################################
         # empty Recycle Bin
         if ($this->site->CONF['trash_expires'] || $do_empty) {
             $sql = "SELECT keel_id FROM keel WHERE on_kasutusel = '1'";
             $sth503 = new SQL($sql);
             $this->site->debug->msg($sth503->debug->get_msgs());
             while ($tmp_keel = $sth503->fetch()) {
                 $trash_id = $this->site->alias(array('key' => 'trash', 'keel' => $tmp_keel['keel_id']));
                 if ($trash_id) {
                     # find objects which changed_time + trash.expires.in.days < NOW (Bug #2602)
                     $sql502 = $this->site->db->prepare("SELECT objekt_objekt.* FROM objekt_objekt LEFT JOIN objekt ON objekt.objekt_id=objekt_objekt.objekt_id WHERE objekt_objekt.parent_id=? AND  DATE_ADD(objekt.changed_time,INTERVAL ? DAY) < NOW() ", $trash_id, $this->site->CONF['trash_expires']);
                     $sth502 = new SQL($sql502);
                     $this->site->debug->msg($sth502->debug->get_msgs());
                     while ($ttmp = $sth502->fetch()) {
                         $this->site->debug->msg('leht.class.php : Trying to remove object ' . $ttmp['objekt_id'] . ' from Recycle Bin...');
                         $del_objekt = new Objekt(array('objekt_id' => $ttmp['objekt_id'], 'superuser' => 1));
                         if ($del_objekt->objekt_id && $del_objekt->parent_id == $trash_id) {
                             $del_objekt->del();
                             new Log(array('action' => 'delete', 'component' => 'Recycle bin', 'objekt_id' => $del_objekt->objekt_id, 'user_id' => 0, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($del_objekt->all['klass'])), $del_objekt->pealkiri(), $del_objekt->objekt_id, " removed from Recycle Bin ")));
                         } else {
                             new Log(array('action' => 'delete', 'component' => 'Recycle bin', 'objekt_id' => $del_objekt->objekt_id, 'user_id' => 0, 'type' => 'ERROR', 'message' => "Couldn't remove object ID = '" . $ttmp['objekt_id'] . "' from Recycle Bin (Parent ID of this object ='" . $del_objekt->parent_id . "')"));
                         }
                     }
                 }
             }
         }
         # / empty Recycle Bin
         #################################################
         #################################################
         # lock inactive users
         $this->site->CONF['lock_inactive_user_after_x_days'] = (int) $this->site->CONF['lock_inactive_user_after_x_days'];
         if ($this->site->CONF['lock_inactive_user_after_x_days']) {
             $sql = 'select user_id, username, last_access_time, is_predefined, firstname, lastname, username from users where is_locked = 0 and date_sub(curdate(), interval ' . $this->site->CONF['lock_inactive_user_after_x_days'] . ' day) > last_access_time';
             $result = new SQL($sql);
             while ($row = $result->fetch('ASSOC')) {
                 // dont lock the last supersuser
                 if ($row['is_predefined'] == 1) {
                     $sql = 'select user_id from users where user_id <> ' . $row['user_id'] . ' and is_predefined = 1 and is_locked = 0 limit 1';
                     $_result = new SQL($sql);
                     if ($_result->rows) {
                         $lockuser = new user(array('user_id' => $row['user_id'], 'skip_last_access_time_update' => 1));
                         $lockuser->lock('Superuser ' . htmlspecialchars(xss_clean($row['firstname'])) . ' ' . htmlspecialchars(xss_clean($row['lastname'])) . ' (' . htmlspecialchars(xss_clean($row['username'])) . ') locked due to inactivity. Last access time: ' . ($row['last_access_time'] != '0000-00-00 00:00:00' ? date('d.m.Y h:i', strtotime($row['last_access_time'])) : 'never'), 0);
                     }
                 } else {
                     $lockuser = new user(array('user_id' => $row['user_id'], 'skip_last_access_time_update' => 1));
                     $lockuser->lock('User ' . htmlspecialchars(xss_clean($row['firstname'])) . ' ' . htmlspecialchars(xss_clean($row['lastname'])) . ' (' . htmlspecialchars(xss_clean($row['username'])) . ') locked due to inactivity. Last access time: ' . ($row['last_access_time'] != '0000-00-00 00:00:00' ? date('d.m.Y h:i', strtotime($row['last_access_time'])) : 'never'), 0);
                 }
             }
         }
         # / lock inactive users
         #################################################
     }
     # / run every day
     #################################################
     ########################
     # run every week - for alive site statistics (can be turned off from config.php by defining: disable_site_polling = 1)
     if ($this->site->CONF['next_week'] < time() && !$this->site->CONF['disable_site_polling']) {
         # set next week run
         $sql = $this->site->db->prepare("update config set sisu = ? where nimi='next_week'", time() + 604800);
         $sth = new SQL($sql);
         $this->site->debug->msg($sth->debug->get_msgs());
         $accessed_by = 1;
         # "CMS weekly"
         $latest_ver = $this->site->site_polling($accessed_by);
     }
     ########################
     # eriobjekt: op=...
     $eriobjekt = array("objekt_id" => $this->site->alias("rub_home_id"), "parent_id" => $this->site->alias("rub_home_id"), "on_avaldatud" => 1);
     if (isset($this->site->fdat['otsi']) && !$this->site->fdat['op']) {
         # Bug #1828: even if empty parameter "otsi" set in URL => go to search results page
         $sql = "select * from templ_tyyp where op='search'";
         $sth = new SQL($sql);
         $this->debug->msg($sth->debug->get_msgs());
         if ($this->template = $sth->fetch()) {
             $this->eritemplate = $this->template['templ_fail'];
         }
         /*
         $this->eritemplate = "templ_searchres.php";
         $eriobjekt[pealkiri] = $this->site->sys_sona(array("sona" => 'Otsing', "tyyp"=>"kujundus"));
         */
     } elseif ($this->site->fdat['op']) {
         #  op v�ib olla ka mitme v��rtusega - nt "cart,saveorder"
         $sql = "SELECT * FROM templ_tyyp WHERE op IN('" . str_replace(",", "','", mysql_real_escape_string($this->site->fdat[op])) . "')";
         $sth = new SQL($sql);
         $this->debug->msg($sth->debug->get_msgs());
         if ($this->template = $sth->fetch()) {
             $this->eritemplate = $this->template[templ_fail];
             # eriobjekt ehk vana fiks.op-mall (millel pole �ldse aimu, mis tema parent on)
             # on siis kui URL-il pole id-d antud (fixing Bug #1962,#1924)
             if (!$this->site->fdat['id']) {
                 $eriobjekt[pealkiri] = $this->site->sys_sona(array("sona" => $this->template[nimi], "tyyp" => "kujundus"));
             }
         }
         # found op-template
     }
     # op
     ########################
     # kui id = home id-ga, siis h�pata alla
     # condition "!$this->eritemplate" removed in 3.1.24 by bugfix #486
     #	if (!$this->eritemplate && $this->id == $this->site->alias("rub_home_id")) {
     if ($this->id == $this->site->alias("rub_home_id")) {
         $this->on_esileht = 1;
     }
     if (preg_match("/^\\d+\$/", $this->id)) {
         ####### PARENTS
         $this->parents = new vParents(array("parent" => $this->id, "on_esileht" => $this->on_esileht, "lisa_objekt" => $eriobjekt[pealkiri] && !$this->on_esileht ? new Objekt(array("ary" => $eriobjekt)) : 0, "on_custom" => 0));
         if ($this->parents->denied) {
             #				$this->parents ;
         }
         $this->id = $this->parents->aktiivne_id;
         $this->objekt = $this->parents->get(0);
         $this->meta =& $this->parents->meta;
         $this->debug->msg($this->parents->debug->get_msgs());
     } else {
         # if id
         $this->debug->msg("Vale ID {$args['id']}");
     }
     # if id
 }
# MOVE UP/DOWN: if current object has UPDATE permission => allow
if( $objekt->permission['U'] || $system_admin) {
	$access = 1;
}
else {
	$access = 0;
}

####################
# access denied
if (!$access) {
	new Log(array(
		'action' => 'update',
		'objekt_id' => $objekt->objekt_id,
		'type' => 'WARNING',
		'message' => sprintf("access denied: attempt to move %s '%s' (ID = %s)" , ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id),
	));
	print "<center><b><font class=\"txt\">".$site->sys_sona(array(sona => "access denied", tyyp=>"editor"))."</font></b></center>";
	if($site->user) { $site->user->debug->print_msg(); }
	if($site->guest) { 	$site->guest->debug->print_msg(); }
	$site->debug->print_msg();
	########### EXIT
	exit;
}
# / ACCESS allowed/denied
###########################

###########################
# GO ON with real work

# -------------------------------------
# Objekt leitud
# -------------------------------------
if ($objekt) {
    ###########################
    # ACCESS allowed/denied
    # decide if accessing this page is allowed or not
    # PUBLISH: if current object has PUBLISH permission => allow
    if ($objekt->permission['P']) {
        $access = 1;
    } else {
        $access = 0;
    }
    ####################
    # access denied
    if (!$access) {
        new Log(array('action' => $site->fdat['op'] == 'publish' ? 'publish' : 'hide', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("access denied: attempt to " . ($site->fdat[op] == "publish" ? 'publish' : 'hide') . " %s '%s' (ID = %s)", ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id)));
        print "<center><b><font class=\"txt\">" . $site->sys_sona(array(sona => "access denied", tyyp => "editor")) . "</font></b></center>";
        if ($site->user) {
            $site->user->debug->print_msg();
        }
        if ($site->guest) {
            $site->guest->debug->print_msg();
        }
        $site->debug->print_msg();
        ########### EXIT
        exit;
    }
    # / ACCESS allowed/denied
    ###########################
    ###########################
    # GO ON with real work
# DELETE: if current object has DELETE => allow
if( $objekt->permission['D']) {
	$access = 1;
}
else {
	$access = 0;
}

	####################
	# access denied
	if (!$access) {
		new Log(array(
			'action' => 'delete',
			'type' => 'WARNING',
			'objekt_id' => $objekt->objekt_id,
			'message' =>  sprintf("access denied: attempt to delete %s '%s' (ID = %s)" , ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id),
		));
		if (!$hidden_output){
			print "<center><b><font class=\"txt\">".$site->sys_sona(array(sona => "access denied", tyyp=>"editor"))."</font></b></center>";
		}
		if($site->user) { $site->user->debug->print_msg(); }
		if($site->guest) { 	$site->guest->debug->print_msg(); }
		$site->debug->print_msg();
		########### EXIT
		exit;
	}
# / ACCESS allowed/denied
###########################


###########################