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;
}
# PERMISSIONS tab : if current user has READ privilege for this adminpage => allow
if( $site->fdat['tab'] == 'permissions'){

	# kas useril on selle admin-lehe kohta Read õigus?
	if($site->user->allowed_adminpage(array("adminpage_id" => $site->fdat['id'])) ) {
		$access = 1;
	}
}
	####################
	# 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']),
		));
		?>
		<center><b><?=$site->sys_sona(array(sona => "access denied", tyyp=>"editor"))?></b>
		<?
		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_section($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $section = array();
    ##############
    # default values
    extract($params);
    if (!isset($level) && !isset($parent)) {
        $parent_id = $leht->id;
    } elseif (isset($level) && !isset($parent)) {
        $level = 0 - $level;
        /* put '-' at the beginning */
        $tmp = $leht->parents->get($level);
        $parent_id = $tmp->objekt_id;
    } elseif (isset($parent)) {
        $parent_id = $parent;
    }
    if (!isset($name)) {
        $name = "section";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    if (!$parent_id) {
        $smarty->assign(array($name => $section, $name . '_newbutton' => '', $name . '_counttotal' => 0, $name . '_rows' => 0, $name . '_count' => 0));
        return;
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    if (!isset($classes)) {
        $classes = "section";
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    ################
    # position
    # default values for position
    if (!isset($position)) {
        $position = 0;
    }
    ##############
    # alamlist
    # change class values for language compability:
    $tyyp_idlist = $classes;
    $classes = str_replace("section", translate_ee("section"), $classes);
    # tyyp_id = 1
    $classes = str_replace("link", translate_ee("link"), $classes);
    # tyyp_id = 3
    # strip out all spaces
    $classes = preg_replace("/(\\s)*/", "", $classes);
    # for buttons:
    $tyyp_idlist = str_replace("section", "1", $tyyp_idlist);
    # tyyp_id = 1
    $tyyp_idlist = str_replace("link", "3", $tyyp_idlist);
    # tyyp_id = 3
    $alamlist = new Alamlist(array(parent => $parent_id, klass => $classes ? $classes : "rubriik", asukoht => $position, order => $order, start => $start, limit => $limit));
    #$alamlist->debug->print_msg();
    # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
    if (isset($limit)) {
        $alamlist_count = new Alamlist(array(parent => $parent_id, klass => $classes ? $classes : "rubriik", asukoht => $position, on_counter => 1));
    }
    ##############
    # load variables
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => $tyyp_idlist ? $tyyp_idlist : "1", publish => $publish));
    while ($obj = $alamlist->next()) {
        ################
        # object parameters
        $obj->id = $obj->objekt_id;
        # kui rubriik:
        if ($obj->all[klass] == "rubriik") {
            $obj->get_object_href();
        } elseif ($obj->all[klass] == 'link') {
            # load sisu, et saada vļæ½ļæ½rtused "url" ja "on_uusaken"
            $obj->load_sisu();
            $objektUrl = $obj->all['url'];
            // replace index.php?id=xxx or ?id=xxx style local url with its alias
            if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
                $objektUrl = convert_local_link_to_alias($objektUrl);
            }
            $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
        }
        $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
        $obj->title .= $obj->pealkiri;
        $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $tyyp_idlist ? $tyyp_idlist : "1", publish => $publish));
        $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
        $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'];
        ###############
        # push array
        # kui objektil featuur "Peida menļæ½ļæ½s" sisselļæ½litatud (NB! erinev tingimus kui avaldatus)
        # ja pole admin siis mitte lisada objekti massiivi
        if (!$obj->all[is_hided_in_menu] || $site->in_editor) {
            array_push($section, $obj);
        }
    }
    $count = sizeof($section);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    ## This is how we __should__ have assigned the
    ## variables !!
    ##
    $smarty->assign(array($name => $section, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_rows' => $counttotal, $name . '_count' => $count));
}
     $tmp_sort = array();
     $uus_sort = array_merge($tmp_sort, $back_sort);
     # echo "Before: ".printr($back_sort)."<hr>";
     #echo "After: ".printr($uus_sort)."<hr>";
     for ($i = 0; $i < sizeof($objekt_id); $i++) {
         $sql = $site->db->prepare("update objekt_objekt set sorteering = ? where objekt_id =? and parent_id = ?", $uus_sort[$i], $objekt_id[$i], $objekt->parent_id);
         $sth = new SQL($sql);
         $site->debug->msg($sth->debug->get_msgs());
         $site->debug->msg("i=" . $i . "; sort=" . $uus_sort[$i] . "; obj=" . $objekt_id[$i] . "; parent=" . $objekt->parent_id);
         # 20.03.2003 Evgeny bugfix: kui sorteering=0
         if (!$uus_sort[$i]) {
             $viga['parent_id'] = $objekt->parent_id;
         }
     }
 }
 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, "re-sorted")));
 if ($viga['parent_id']) {
     $site->debug->msg("Wrong sort parameter found! Trying to fix it...");
     $sql = $site->db->prepare("SELECT objekt.objekt_id, sorteering FROM objekt \r\n\t\t\tLEFT JOIN objekt_objekt on objekt.objekt_id=objekt_objekt.objekt_id \r\n\t\t\tWHERE kesk=? AND parent_id=? AND sorteering='0'\r\n\t\t\tORDER BY objekt_objekt.sorteering DESC", $args['asukoht'], $viga['parent_id']);
     $sth = new SQL($sql);
     $site->debug->msg($sth->debug->get_msgs());
     $sth2 = new SQL("SELECT MAX(sorteering) FROM objekt_objekt");
     $site->debug->msg($sth2->debug->get_msgs());
     $max_sort = $sth2->fetchsingle();
     $super_sort = $max_sort + $sth->rows;
     while ($data = $sth->fetch()) {
         $sql3 = $site->db->prepare("UPDATE objekt_objekt SET sorteering=? WHERE objekt_id=? AND sorteering=0", $super_sort, $data['objekt_id']);
         $sth3 = new SQL($sql3);
         $site->debug->msg($sth3->debug->get_msgs());
         $super_sort--;
     }
          <td class="r<?php 
        echo $i % 2 + 1;
        ?>
" ><?php 
        echo $myttyyp[templ_fail];
        ?>
</td>
		<?php 
        if ($type != 'page') {
            # dont show op for page templates (bug #1964)
            ?>
          <td class="r<?php 
            echo $i % 2 + 1;
            ?>
" ><?php 
            echo translate_en($myttyyp['op']);
            ?>
</td>
		<?php 
        }
        ?>
          <td class="r<?php 
        echo $i % 2 + 1;
        ?>
" ><?php 
        echo $myttyyp[on_nahtav] ? "Y" : "N";
        ?>
</td>
<!--          <td class="r<?php 
        echo $i % 2 + 1;
        ?>
function smarty_function_init_objects($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $objects_arr = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent_system_alias) && !isset($parent)) {
        $parent_id = $leht->id;
    } elseif (isset($parent_system_alias)) {
        //$parent_id = $site->alias(array('key' => $parent_system_alias));
        $parent_id = $site->alias(array('key' => $parent_system_alias, 'keel' => $site->keel));
    } elseif (isset($parent)) {
        $parent_id = $parent;
    }
    // if parent_id not found
    if (!$parent_id) {
        $parent_id = $leht->id;
    }
    if (!isset($name)) {
        $name = "objects";
    }
    $classes = trim($classes);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    ##################
    # classes
    if ($classes) {
        ######### translate classes: change class values for language compability
        $transl_class_arr = array();
        foreach (split(",", $classes) as $class) {
            if (trim($class) != '') {
                $transl_class_arr[] = translate_ee($class);
                # translate it to estonian
            }
        }
        #		echo printr($transl_class_arr);
        $classes = join(",", $transl_class_arr);
        ######## gather tyyp ID values => to array
        $tyyp_id_arr = array();
        $sql = "SELECT tyyp_id, klass FROM tyyp";
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        while ($tmp = $sth->fetch()) {
            # if ID found in classes array, then add it:
            if (in_array($tmp['klass'], $transl_class_arr)) {
                $tyyp_id_arr[] = $tmp['tyyp_id'];
            }
        }
        #		echo printr($tyyp_id_arr);
        # tyyp_idlist ID numeric values for buttons:
        $tyyp_idlist = join(",", $tyyp_id_arr);
    }
    # if classes parameter provided
    # / classes
    ##################
    ##############
    # alamlist
    $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => $classes, asukoht => $position, order => $order));
    if ($select) {
        $alamlistSQL->add_select($select);
    }
    if ($where) {
        $alamlistSQL->add_where($where);
    }
    if ($group) {
        $alamlistSQL->add_group($site->db->prepare('group by ' . $group));
    }
    $alamlist = new Alamlist(array('alamlistSQL' => $alamlistSQL, start => $start, limit => $limit));
    $alamlist->debug->print_msg();
    # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
    if (isset($limit)) {
        $alamlist_count = new Alamlist(array(parent => $parent_id, klass => $classes, asukoht => $position, on_counter => 1));
    }
    ##############
    # load variables
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => $tyyp_idlist, publish => $publish));
    while ($obj = $alamlist->next()) {
        ################
        # object parameters
        $obj->id = $obj->objekt_id;
        # kui link
        if ($obj->all[klass] == "link") {
            # load sisu, et saada vļæ½ļæ½rtused "url" ja "on_uusaken"
            $obj->load_sisu();
            $objektUrl = $obj->all['url'];
            // replace index.php?id=xxx or ?id=xxx style local url with its alias
            if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
                $objektUrl = convert_local_link_to_alias($objektUrl);
            }
            $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
        } else {
            $obj->get_object_href();
        }
        $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
        $obj->title = $obj->pealkiri;
        $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $tyyp_idlist, publish => $publish));
        $obj->fdate = $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->author = $obj->all[author];
        $obj->class = translate_en($obj->all[klass]);
        # translate it to english
        $obj->details_link = $obj->href;
        $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
        $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
        $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
        $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'];
        ###############
        # push array, in case we don't have "peida menuus" turned on (section objects)
        if (!$obj->all[is_hided_in_menu] || $site->in_editor) {
            array_push($objects_arr, $obj);
        }
    }
    $count = sizeof($objects_arr);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $objects_arr, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
		
		# Run mailinglists after each publishing
		if ($site->CONF['maillist_sending_after_publishing'] && $site->fdat['op'] == "publish") {
			require_once($class_path."auto.inc.php");
			auto_maillist(0,0);
		}
		
		# ------------------------
		# Kustutame chache-ist
		# ------------------------
		clear_cache("ALL");

		if (!$site->on_debug) {
			header("Location: ".(empty($_SERVER['HTTPS']) ? 'http://' : 'https://').$site->CONF[hostname].$site->fdat[url]);
		}

		new Log(array(
			'action' => ($on_avaldatud ? 'publish' : 'hide'),
			'type' => 'WARNING',
			'objekt_id' => $objekt->objekt_id,
			'message' => sprintf("%s '%s' (ID = %s) %s" , ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id, $on_avaldatud ? "published" : "hidden"),
		));
	} else {
	?>
	Wrong ID
	<?
}
if($site->user) { $site->user->debug->print_msg(); }
if($site->guest) { 	$site->guest->debug->print_msg(); }

$site->debug->print_msg();
 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
 }
function smarty_function_init_page(&$smarty, $params)
{
    global $site, $leht, $template, $class_path;
    include_once $class_path . 'extension.class.php';
    $content_template = $leht->content_template;
    # load all possible data for current object
    #	load_current_obj_data();
    ## This is how we __should__ have assigned the
    ## variables !!
    ##
    $title = $leht->objekt->all['meta_title'] ? $leht->objekt->all['meta_title'] : $leht->meta[title];
    $keywords = $leht->objekt->all['meta_keywords'] ? $leht->objekt->all['meta_keywords'] : $leht->meta[keywords];
    $description = $leht->objekt->all['meta_description'] ? $leht->objekt->all['meta_description'] : $leht->meta[description];
    $c_tpl = is_object($leht->content_template) ? $leht->content_template->ttyyp_id : $site->fdat['c_tpl'];
    $curr_objekt = new Objekt(array(objekt_id => $site->alias(array("key" => "rub_home_id", "keel" => $site->keel))));
    $conf = new CONFIG($curr_objekt->all["ttyyp_params"]);
    foreach ($conf->CONF as $k => $v) {
        if ($k != "page_end_html") {
            if ($k == "site_name") {
                $site_name = $v;
            }
            if ($k == "slogan") {
                $site_slogan = $v;
            }
        }
    }
    $sql = $site->db->prepare("SELECT locale, nimi FROM keel WHERE on_kasutusel=1 AND keel_id=?", $site->glossary_id);
    $sth = new SQL($sql);
    $glossary = $sth->fetch("ASSOC");
    // registered user should not be able to use {$in_editor} and {$admin} tags, only those with update permission
    if ($site->in_editor && $leht->objekt->permission['U']) {
        $in_editor = 1;
    } else {
        $in_editor = 0;
    }
    // create template object to be passed as global variable
    $template_obj->all = $template->all;
    $template_obj->title = $template->all['nimi'];
    $template_obj->name = $template->all['nimi'];
    $template_obj->id = $template->all['ttyyp_id'];
    $template_obj->op = $template->all['op'];
    $template_obj->extension = $template->all['extension'];
    $smarty->assign(array('id' => $leht->id, 'title' => $title, 'meta_title' => $title, 'meta_keywords' => $keywords, 'meta_description' => $description, 'encoding' => $leht->site->encoding, 'img_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF[img_path], 'adm_img_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF[adm_img_path], 'custom_img_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF[custom_img_path], 'styles_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF['styles_path'], 'js_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF[js_path], 'file_path' => $leht->site->CONF[wwwroot] . $leht->site->CONF[file_path], 'self' => $site->self, 'url' => $site->URI, 'protocol' => $leht->site->CONF[protocol], 'wwwroot' => $leht->site->CONF[wwwroot], 'hostname' => $leht->site->CONF[hostname], 'current_level' => $leht->level, 'op' => $site->fdat[op], 'tpl' => is_object($template) ? $template->ttyyp_id : $site->fdat['tpl'], 'c_tpl' => $c_tpl, 'ext_id' => $site->fdat[ext_id], 'admin' => $in_editor, 'in_editor' => $in_editor, 'user' => $site->user ? 1 : 0, 'userdata' => $site->user, 'current_obj' => $leht->objekt, 'lang' => $site->extension, 'site_extension' => $site->extension, 'locale' => $glossary["locale"], 'glossary' => $glossary["nimi"], 'current_class' => translate_en($leht->objekt->all['klass']), 'content_tpl' => $leht->content_template->all[nimi], 'page_tpl' => $template->all[nimi], 'prod_id' => eregi_replace("[^0-9]", "", $site->fdat[prod_id]), 'form_error' => $site->fdat['form_error'], 'form_data' => $site->fdat['form_data'], 'conf' => $site->CONF, 'template' => $template_obj, 'site_name' => $site_name, 'site_slogan' => $site_slogan));
    ##Registreeri prefilter
    if (!empty($template->all[smarty_prefilter])) {
        $smarty->register_prefilter('smarty_prefilter');
    } else {
        if (!empty($content_template->all[smarty_prefilter])) {
            $smarty->register_prefilter('smarty_prefilter');
        }
    }
    ##Registreeri postfilter
    if (!empty($template->all[smarty_postfilter])) {
        $smarty->register_postfilter('smarty_postfilter');
    } else {
        if (!empty($content_template->all[smarty_postfilter])) {
            $smarty->register_postfilter('smarty_postfilter');
        }
    }
    #####################################
    # load all EXTENSION CONFIGS as SAPI variable $EXTENSION_NAME, and load filters.
    $pre_filters_for_page_templates = $params['on_page_templ'] ? array('page_end_html', 'editor_toolbar', 'context_menu_init', 'flowplayer') : array();
    $autoload_filters = array('pre' => $pre_filters_for_page_templates, 'output' => array(), 'post' => array());
    foreach (get_extensions() as $extension) {
        $EXTENSION =& load_extension_config($extension);
        $smarty->assign($extension['name'], $EXTENSION);
        # assign to SAPI variable $extension_name
        $smarty->assign(strtoupper($extension['name']), $EXTENSION);
        # assign to SAPI variable $EXTENSION_NAME
        // post, pre, outputfilter loading and registering
        if (is_array($EXTENSION['smarty_filters'])) {
            foreach ($EXTENSION['smarty_filters'] as $template_id => $filters) {
                if ($template_id == 'all' || $params['on_page_templ'] && $template_id == $template->ttyyp_id || !$params['on_page_templ'] && $template_id == $content_template->ttyyp_id) {
                    foreach (array_keys($autoload_filters) as $filter_type) {
                        if (is_array($filters[$filter_type])) {
                            $autoload_filters[$filter_type] = array_unique(array_merge($autoload_filters[$filter_type], $filters[$filter_type]));
                        }
                    }
                }
            }
        }
        // /post, pre, outputfilter loading and registering
    }
    $smarty->autoload_filters = $autoload_filters;
    #	$smarty->autoload_filters['pre'][] = 'foobar';
    //printr($smarty->autoload_filters);
    # / load all EXTENSION CONFIGS as SAPI variable $EXTENSION_NAME, and load filters.
    #####################################
}
function smarty_function_init_albums($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    $albumlist = array();
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = 'albumlist';
    }
    if (!isset($thumbnail_type)) {
        $thumbnail_type = 'first';
    }
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    $parent_id = trim($parent);
    if ($parent_id) {
        $alamlist = new Alamlist(array(parent => $parent_id, klass => "album", start => $start, limit => $limit, asukoht => $position, order => $order, where => $where));
        # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
        if (isset($limit)) {
            $alamlist_count = new Alamlist(array(parent => $parent_id, klass => "album", asukoht => $position, on_counter => 1));
        }
        ##############
        # load variables
        $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => "16", publish => $publish));
        while ($obj = $alamlist->next()) {
            $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => "16", publish => $publish));
            $obj->id =& $obj->objekt_id;
            $obj->get_object_href();
            //$obj->href = $site->self.'?id='.$obj->objekt_id;
            $obj->class = translate_en($obj->all[klass]);
            # translate it to english
            $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
            $obj->title = $obj->pealkiri;
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $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->details_link = $site->self . '?id=' . $obj->objekt_id;
            $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
            $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'];
            ### custom conf parameters
            $conf = new CONFIG($obj->all['ttyyp_params']);
            $obj->description = $conf->get('desc');
            if ($conf->get('path')) {
                include_once $class_path . 'picture.inc.php';
                # full relative path to the first/random thumbnail
                $obj->thumbnail = $site->CONF['wwwroot'] . '/' . get_images($site->absolute_path . $conf->get('path'), $conf->get('path'), $thumbnail_type);
            }
            #printr($obj->all['ttyyp_params']);
            $obj->thumbnail_size = $conf->get('tn_size');
            # in pixels
            $obj->image_size = $conf->get('pic_size');
            # in pixels
            $obj->folder_id = $conf->get('folder_id');
            # source folder ID
            $obj->folder_path = $conf->get('path');
            # source folder path, eg "public/images"
            ### / custom conf parameters
            array_push($albumlist, $obj);
        }
    }
    ##############
    # assign to template variables
    $count = $alamlist->rows;
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    $smarty->assign(array($name => $albumlist, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_rows' => $counttotal, $name . '_count' => $count));
}
			$sth = new SQL ($sql);
			$site->debug->msg($sth->debug->get_msgs());

			$site->debug->msg("i=".$i."; sort=".$uus_sort[$i]."; obj=".$objekt_id[$i]."; parent=".$objekt->parent_id);

				# 20.03.2003 Evgeny bugfix: kui sorteering=0
				if (!$uus_sort[$i]){
					$viga['parent_id'] = $objekt->parent_id;
				}
		}

	}
	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, "re-sorted"),
	));

	if ($viga['parent_id']){

			$site->debug->msg("Wrong sort parameter found! Trying to fix it...");

			$sql = $site->db->prepare("SELECT objekt.objekt_id, sorteering FROM objekt 
			LEFT JOIN objekt_objekt on objekt.objekt_id=objekt_objekt.objekt_id 
			WHERE kesk=? AND parent_id=? AND sorteering='0'
			ORDER BY objekt_objekt.sorteering DESC", 
			$args['asukoht'], $viga['parent_id']);
			$sth = new SQL ($sql);
			$site->debug->msg($sth->debug->get_msgs());

function smarty_function_init_article($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if ($system_message || $system_alias) {
        $system_message = $system_alias ? $system_alias : $system_message;
        $id = $site->alias(array('key' => translate_ee($system_message), 'keel' => $site->keel));
    }
    if (!isset($name)) {
        $name = "article";
    }
    // on_create statements:
    $on_create = explode(',', $on_create);
    // default on_create statements:
    $publish = 0;
    $allow_comments = $site->CONF['default_comments'];
    // cycle statements
    foreach ($on_create as $on_create_statement) {
        $on_create_statement = trim($on_create_statement);
        switch ($on_create_statement) {
            case 'publish':
                $publish = 1;
                break;
            case 'hide':
                $publish = 0;
                break;
            case 'allow_comments':
                $allow_comments = 1;
                break;
        }
    }
    # if parameter "get_object_fields" is given (may be comma sep.list), then split it to array
    if (isset($get_object_fields)) {
        $get_object_fields_arr = split(",", $get_object_fields);
        $i = 0;
        foreach ($get_object_fields_arr as $tmp) {
            $get_object_fields_arr[$i] = trim($tmp);
            $i++;
        }
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    if (!isset($ttyyp_id)) {
        $ttyyp_id = 0;
    }
    // system alias given but no such article, can be created under system section
    if (!$id) {
        $parent_id = $site->alias('system');
        $alamlist = new Alamlist(array('parent' => $parent_id, 'klass' => 'artikkel', 'asukoht' => $position, 'start' => 0, 'limit' => 1));
        $new_button = $alamlist->get_edit_buttons(array('tyyp_idlist' => 2, 'publish' => $publish, 'allow_comments' => $allow_comments, 'sys_alias' => $system_message));
        $smarty->assign($name . '_newbutton', $new_button);
        return;
    }
    ##############
    # luua objekt
    $objSettings = array();
    $objSettings['objekt_id'] = $id;
    $obj = new Objekt($objSettings);
    $allObjParents = $obj->get_obj_all_parents($objSettings['objekt_id']);
    if (in_array($leht->parents->list[0]->parent_id, $allObjParents)) {
        $objSettings['parent_id'] = $leht->parents->list[0]->parent_id;
        $obj = new Objekt($objSettings);
    }
    ##############
    # minna edasi vaid siis kui tegemist on artikliga
    if (!$obj->all[klass] == "artikkel") {
        # error pealkirja or smth
        # assign
        # exit;
    }
    ##############
    # load variables
    #PREVIOUS ARTICLE
    $alamlistSQL = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0, order => "objekt_objekt.sorteering ASC"));
    $alamlistSQL->add_where("sorteering>'" . $obj->all['sorteering'] . "'");
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => 0, limit => 1));
    #NEXT ARTICLE
    $alamlistSQL2 = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0));
    $alamlistSQL2->add_where("sorteering<'" . $obj->all['sorteering'] . "'");
    $alamlist2 = new Alamlist(array(alamlistSQL => $alamlistSQL2, start => 0, limit => 1));
    $prev_art = $alamlist->next();
    $next_art = $alamlist2->next();
    $obj->id = $obj->objekt_id;
    $obj->get_object_href();
    $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
    $obj->title = $obj->pealkiri;
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $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->show_headline = $obj->all['on_pealkiri'];
    $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    # added 08.11.2002:
    $obj->comment_link = $site->self . '?id=' . $obj->objekt_id . '#comm';
    $obj->comment_title = $site->sys_sona(array(sona => "Kommentaarid", tyyp => "kujundus"));
    $obj->add_comment_link = $site->self . '?id=' . $obj->objekt_id . '#cbox';
    $obj->add_comment_title = $site->sys_sona(array(sona => "Add", tyyp => "kujundus"));
    # existing already by default: $obj->comment_count
    $obj->forum_allowed = $obj->all[on_foorum];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    # added 21.01.2003:
    $obj->author = $obj->all[author];
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    $obj->next_id = $next_art->objekt_id;
    $obj->prev_id = $prev_art->objekt_id;
    $obj->hit_count = $obj->all['count'];
    ##############
    # load sisu
    $obj->load_sisu();
    if (0 && $context_start) {
        $obj->lead = $context_start . $obj->lyhi->get_text() . '</editor:context>';
        $obj->body = $context_start . $obj->sisu->get_text() . '</editor:context>';
    } else {
        $obj->lead = $obj->lyhi->get_text();
        $obj->body = $obj->sisu->get_text();
    }
    if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
        $hostUrl = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $site->wwwroot . '/';
        //body urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->body, $searchResults, PREG_SET_ORDER);
        //body urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed body urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed lead urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        foreach ($searchResults as $key => $value) {
            //create an object with the id found in url
            $linkObj = new Objekt(array(objekt_id => $value[4]));
            $variables = array();
            $separator = strpos($value[3], '&amp;') !== false ? '&amp;' : '&';
            foreach (explode($separator, $value[3]) as $param) {
                $paramArray = explode('=', $param);
                if ($paramArray[0] != 'id') {
                    $variables[] = $param;
                }
            }
            if (count($variables) > 0) {
                $param = '?' . implode('&amp;', $variables);
            } else {
                $param = '';
            }
            $replaceValue = str_replace($value[1], (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $linkObj->get_object_href() . $param, $value[0]);
            $obj->lead = str_replace($value[0], $replaceValue, $obj->lead);
            $obj->body = str_replace($value[0], $replaceValue, $obj->body);
        }
    }
    #############
    # buttons (must be after load_sisu(), Bug #1963)
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => $obj->all['tyyp_id'], nupud => $buttons, ttyyp_id => $ttyyp_id, profile_id => $obj->all['profile_id'], publish => $publish, 'allow_comments' => $allow_comments));
    ########## KUI artiklil on Mļæ½ļæ½RATUD mļæ½ni PROFIIL, siis korja andmed "->" omadustena kokku
    if ($obj->all['profile_id']) {
        #printr($obj->objekt_id.' PROFILE_ID: '.$obj->all['profile_id']);
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ####### / profile is set
    $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'];
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
    //return $obj; # bug #1921 # for {init_object} tag
}
        $on_avaldatud = 0;
    }
    $sql = $site->db->prepare("update objekt set on_avaldatud=? where objekt_id=?", $on_avaldatud, $objekt->objekt_id);
    $sth = new SQL($sql);
    $site->debug->msg($sth->debug->get_msgs());
    # Run mailinglists after each publishing
    if ($site->CONF['maillist_sending_after_publishing'] && $site->fdat['op'] == "publish") {
        require_once $class_path . "auto.inc.php";
        auto_maillist(0, 0);
    }
    # ------------------------
    # Kustutame chache-ist
    # ------------------------
    clear_cache("ALL");
    if (!$site->on_debug) {
        $url = preg_replace("!\r|\n.*!s", "", (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $site->CONF[hostname] . $site->fdat[url]);
        header("Location: " . $url);
    }
    new Log(array('action' => $on_avaldatud ? 'publish' : 'hide', 'type' => 'WARNING', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id, $on_avaldatud ? "published" : "hidden")));
} else {
    ?>
	Wrong ID
	<?php 
}
if ($site->user) {
    $site->user->debug->print_msg();
}
if ($site->guest) {
    $site->guest->debug->print_msg();
}
$site->debug->print_msg();
function smarty_function_init_subjects($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $subjects = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent)) {
        $parent_id = $leht->id;
    } else {
        $parent_id = $parent;
    }
    if (!isset($name)) {
        $name = "subject";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ##################
    # find template id by parameter subjectdetail_tpl (= template name)
    $sth = new SQL("SELECT ttyyp_id FROM templ_tyyp WHERE nimi = '" . $subjectdetail_tpl . "' AND ttyyp_id >= '1000' LIMIT 1");
    $subjectdetail_tpl_id = $sth->fetchsingle();
    # if dynamical template not found, use fixed template 1
    if (!$subjectdetail_tpl_id) {
        $subjectdetail_tpl_id = 1;
        # default, templ1.php
    }
    ##############
    # alamlist
    $alamlist = new Alamlist(array(parent => $parent_id, klass => "teema", start => $start, limit => $limit));
    ##############
    # load variables
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => 15, publish => $publish));
    while ($obj = $alamlist->next()) {
        $obj->id = $obj->objekt_id;
        $obj->detail_href = $site->self . '?' . (isset($content_template) ? 'c_tpl' : 'tpl') . '=' . $subjectdetail_tpl_id . '&id=' . $obj->objekt_id;
        $obj->title = $obj->pealkiri;
        $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 15, publish => $publish));
        $alamlist_count = new Alamlist(array(parent => $obj->objekt_id, klass => "kommentaar", asukoht => 0, on_counter => 1));
        $obj->message_count = $alamlist_count->rows;
        $obj->started = $site->db->MySQL_ee_short($obj->all[aeg]);
        $alamlist2 = new Alamlist(array(parent => $obj->objekt_id, klass => "kommentaar", asukoht => 0, start => 0, limit => 1));
        $last = $alamlist2->next();
        $obj->last_message = $last ? $site->db->MySQL_ee_short($last->all[aeg]) : "&nbsp;";
        $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
        $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'];
        array_push($subjects, $obj);
    }
    $count = sizeof($subjects);
    ##############
    # assign to template variables
    $smarty->assign(array($name => $subjects, $name . '_newbutton' => $new_button, $name . '_count' => $count));
}
function smarty_function_init_documents($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $documents = array();
    $parent_ary = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    if (!isset($name)) {
        $name = "documents";
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    $parent_id = trim($parent);
    if ($parent_id) {
        ##############
        # alamlist
        $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "dokument", asukoht => $position, order => $order, where => $where));
        $alamlistSQL->add_select(" obj_dokument.tyyp, obj_dokument.mime_tyyp, obj_dokument.fail, obj_dokument.kirjeldus, obj_dokument.autor, obj_dokument.size, obj_dokument.download_type");
        $alamlistSQL->add_from("LEFT JOIN obj_dokument ON objekt.objekt_id=obj_dokument.objekt_id");
        $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => $start, limit => $limit));
        #		$alamlist->debug->print_msg();
        #		$alamlist->sql->debug->print_msg();
        # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
        if (isset($limit)) {
            $alamlist_count = new Alamlist(array(alamlistSQL => $alamlistSQL, on_counter => 1));
        }
        ##############
        # load variables
        $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => 7, publish => $publish));
        while ($obj = $alamlist->next()) {
            $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 7, asukoht => $position, publish => $publish));
            $obj->id = $obj->objekt_id;
            $obj->href = $site->self . '?id=' . $obj->objekt_id;
            $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
            $obj->title = $obj->pealkiri;
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $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->file = $obj->filename = $obj->all['fail'];
            $obj->description = $obj->all['kirjeldus'];
            $obj->size = $obj->all['size'];
            $obj->type = $obj->all['tyyp'];
            $obj->mime_type = $obj->all['mime_tyyp'];
            $obj->size_formated = print_filesize($obj->all['size']);
            $obj->author = $obj->all['author'] ? $obj->all['author'] : $obj->all['autor'];
            $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
            $obj->download_link = $site->wwwroot . '/doc.php?' . $obj->objekt_id;
            $obj->class = translate_en($obj->all[klass]);
            # translate it to english
            $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'];
            array_push($documents, $obj);
        }
    }
    # / loop over all parent id
    #######################
    ##################
    # fix objects order, if more than 1 parent_id was given
    # because database sort is not enough for this case
    if (sizeof($parent_ary) > 1) {
        list($order_field, $order_sort) = split(" ", $order);
        # exception for dates: for array sort rename db field date:
        $order_field = str_replace("aeg", "fdate", $order_field);
        # sort objects by required field
        if (trim($order_field)) {
            $documents = casort($documents, $order_field);
        }
        # if sortorder is 'desc', then reverse array
        if (strtolower(trim($order_sort)) == 'desc') {
            $documents = array_reverse($documents);
        }
    }
    # / fix objects order, if more than 1 parent_id was given
    ##################
    $count = sizeof($documents);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $documents, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
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 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
}
function smarty_function_init_album($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $albums = array();
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "album";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    $album = new Objekt(array(objekt_id => $id));
    $conf = new CONFIG($album->all['ttyyp_params']);
    $col = $conf->get("cols") > 0 ? $conf->get("cols") : 3;
    $row = $conf->get("rows") > 0 ? $conf->get("rows") : 3;
    $args['num'] = $args['col'];
    $alamlist_count = new Alamlist(array(parent => $album->objekt_id, klass => "pilt", asukoht => 0, on_counter => 1));
    $alamlist = new Alamlist(array(parent => $album->objekt_id, klass => "pilt", asukoht => 0, start => $start, limit => $limit));
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => "12", publish => $publish));
    $edit_button = $album->get_edit_buttons(array(tyyp_idlist => "16", publish => $publish));
    $title =& $album->pealkiri;
    while ($obj = $alamlist->next()) {
        $obj->load_sisu();
        $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => "12", publish => $publish));
        $obj->get_object_href();
        //$obj->href = $site->self.'?id='.$obj->objekt_id;
        $obj->title = $obj->pealkiri;
        $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
        $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->id = $obj->objekt_id;
        $obj->class = translate_en($obj->all[klass]);
        # translate it to english
        $obj->thumbnail = "<a href=\"" . $site->self . "?id=" . $obj->objekt_id . "\"><img src=\"" . $site->CONF['wwwroot'] . ($site->admin ? "/editor" : "") . "/image.php?" . $obj->objekt_id . "t\" border=\"0\"></a>";
        $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'];
        $obj->forum_allowed = $obj->all['on_foorum'];
        #####push
        array_push($albums, $obj);
    }
    ##############
    # assign to template variables
    $smarty->assign(array($name => $albums, $name . '_newbutton' => $new_button, $name . '_editbutton' => $edit_button, $name . '_title' => $title, $name . '_col' => $col, $name . '_row' => $row, $name . '_count' => $alamlist_count->rows));
}
/**
 * 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_init_file($params, &$smarty)
{
    global $site, $leht, $class_path;
    extract($params);
    $id = (int) $id;
    if (!$id) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = 'file';
    }
    if (!isset($buttons)) {
        $buttons = array('new', 'edit', 'hide', 'move', 'delete');
    } else {
        $buttons = split(',', $buttons);
    }
    $obj = new Objekt(array('objekt_id' => $id));
    $obj->load_sisu();
    $obj->id = $obj->objekt_id;
    $obj->parent = $obj->parent_id;
    $obj->title = $obj->pealkiri;
    $obj->class = translate_en($obj->all['klass']);
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $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->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'];
    $obj->href = $site->CONF['wwwroot'] . '/file.php?' . $obj->objekt_id;
    $obj->fullpath = preg_replace('#/$#', '', $site->absolute_path) . $obj->all['relative_path'];
    unset($obj->all['fullpath']);
    $obj->filename = $obj->all['filename'];
    $obj->mimetype = $obj->all['mimetype'];
    $obj->profile_id = $obj->all['profile_id'];
    $obj->url = $site->CONF['wwwroot'] . $obj->all['relative_path'];
    $obj->size = print_filesize($obj->all['size']);
    $pathinfo = pathinfo($obj->fullpath);
    $obj->extension = strtolower($pathinfo['extension']);
    // for images give gallery thumbs and images
    if (strpos($obj->all['mimetype'], 'image/') === 0) {
        $folder = preg_replace('#/$#', '', $site->absolute_path) . str_replace($obj->all['filename'], '', $obj->all['relative_path']);
        $folder_url = $site->CONF['wwwroot'] . $folder;
        //thumbs
        if (file_exists($folder . '.gallery_thumbnails/' . $obj->all['filename']) && ($thumb_info = @getimagesize($folder . '.gallery_thumbnails/' . $obj->all['filename']))) {
            $obj->thumb_path = $folder_url . '.gallery_thumbnails/' . $obj->all['filename'];
            $obj->thumb_width = $thumb_info[0];
            $obj->thumb_height = $thumb_info[1];
        }
        //image
        if (file_exists($folder . '.gallery_pictures/' . $obj->all['filename']) && ($image_info = @getimagesize($folder . '.gallery_pictures/' . $obj->all['filename']))) {
            $obj->image_path = $folder_url . '.gallery_pictures/' . $obj->all['filename'];
            $obj->image_width = $image_info[0];
            $obj->image_height = $image_info[1];
        }
        //actual image
        if (file_exists($site->absolute_path . $obj->all['relative_path']) && ($actual_image_info = @getimagesize($site->absolute_path . $obj->all['relative_path']))) {
            $obj->actual_image_path = $obj->url;
            $obj->actual_image_width = $actual_image_info[0];
            $obj->actual_image_height = $actual_image_info[1];
        }
    }
    if ($icons) {
        if (!preg_match("/\\/\$/", $icons)) {
            $icons .= '/';
        }
        if (file_exists($site->absolute_path . $icons . $obj->extension . '.gif')) {
            $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . $obj->extension . '.gif';
        } elseif (file_exists($site->absolute_path . $icons . 'unknown.gif')) {
            $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . 'unknown.gif';
        }
    }
    if (!$profile) {
        $default_profile_def = $site->get_profile(array('id' => $site->get_default_profile_id(array(source_table => 'obj_file'))));
        # get profile name
        $profile = $default_profile_def['name'];
        unset($default_profile_def);
    }
    ##############
    # put all profile names into arr
    if ($profile) {
        $profile_names = split(",", $profile);
    } else {
        $profile_names = array();
        $profile_ids = array();
    }
    # get all profile data from cash
    foreach ($profile_names as $profile_name) {
        # profile name is case insensitive
        $profile_name = strtolower($profile_name);
        $profile_def = $site->get_profile(array(name => $profile_name));
        # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade
        if (!$profile_def['profile_id']) {
            if ($site->admin) {
                print "<font color=red><b>Profile '" . $profile_name . "' not found!</b></font>";
            }
            return;
        }
        $profile_ids[] = $profile_def['profile_id'];
        $profile_arr[$profile_def['profile_id']] = $profile_def;
    }
    $obj->buttons = $obj->get_edit_buttons(array('nupud' => $buttons, 'tyyp_idlist' => 21, 'publish' => $publish, 'profile_id' => join(',', $profile_ids)));
    $profile_def = $site->get_profile(array('id' => $obj->all['profile_id']));
    if ($profile_def[profile_id]) {
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array('id' => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array('obj' => &$obj, 'get_object_fields' => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array('selectlist' => $obj_profile->selectlist));
            ### 3. save object rest of attributes
            $obj_profile->set_obj_selectlist_fields(array('obj' => &$obj, 'change_fields' => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    foreach ($obj->all as $fieldname => $value) {
        $obj->{$fieldname} = $value;
    }
    $smarty->assign($name, $obj);
}
function smarty_function_init_search_results($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    //translate url params
    foreach ($site->fdat as $key => $value) {
        if (!array_key_exists($site->fdat[translate_en($key)], $site->fdat)) {
            $site->fdat[translate_en($key)] =& $site->fdat[$key];
        }
    }
    extract($params);
    if (!isset($name)) {
        $name = 'search';
    }
    if (!isset($query)) {
        $query = $site->fdat['query'];
    }
    if (!isset($sites)) {
        $sites = $site->fdat['sites'];
    }
    if (!empty($sites)) {
        if (strtolower($sites) == "all") {
            $sql_keel = "SELECT keel_id FROM keel WHERE on_kasutusel=1";
        } else {
            $pre_search_explode = explode(",", strtolower(trim($sites)));
            foreach ($pre_search_explode as $k => $v) {
                $pre_search_explode[$k] = $site->db->prepare('?', trim($v));
            }
            $sql_keel = 'SELECT keel_id FROM keel WHERE on_kasutusel=1 AND extension IN (' . implode(',', $pre_search_explode) . ')';
        }
        $sth = new SQL($sql_keel);
        while ($r = $sth->fetch("ASSOC")) {
            $keeled[] = $r['keel_id'];
        }
        $keel = implode(",", (array) $keeled);
    } else {
        $keel = $site->keel;
    }
    if (!isset($search_type)) {
        $search_type = $site->fdat['bool'];
    }
    $bool_array = array("or", "and", "phrase");
    if (!in_array(strtolower($search_type), $bool_array)) {
        $search_type = "or";
    }
    if (!isset($exclude)) {
        $exclude = $site->fdat['exclude'];
    }
    if (!isset($section)) {
        $section = $site->fdat['section'];
    }
    if (!isset($last_changed)) {
        $last_changed = $site->fdat['time'];
    }
    if ($last_changed != "") {
        if (is_numeric($last_changed) && $last_changed >= 1 && $last_changed <= 6) {
        } elseif (!is_numeric($last_changed)) {
            $time_array = array("1 DAY", "7 DAY", "1 MONTH", "3 MONTH", "6 MONTH", "1 YEAR");
            foreach ($time_array as $k => $v) {
                if (strtoupper(trim($last_changed)) == $v) {
                    $last_changed = $k + 1;
                }
            }
            if (!is_numeric($last_changed)) {
                $last_changed = "0";
            }
        } else {
            $last_changed = "0";
        }
    }
    if (!isset($order)) {
        $order = $site->fdat['order'];
    }
    if (!isset($name)) {
        $name = 'search';
    }
    if (!isset($classes)) {
        foreach ($site->object_classes as $class_def) {
            if ($class_def['on_otsingus']) {
                $classes[] = $class_def['klass'];
            }
        }
    } else {
        $classes = explode(',', trim($classes));
        foreach ($classes as $i => $class) {
            $classes[$i] = translate_ee(trim($class));
        }
    }
    /*
    if(!isset($buttons))
    	$buttons = array('new', 'edit', 'hide', 'move', 'delete');
    else
    	$buttons = split(',', $buttons);
    */
    //check cache
    if (is_array($site->cash(array('klass' => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS')))) {
        //read from cache
        $search = $site->cash(array('klass' => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS'));
    } else {
        include_once $class_path . 'FulltextSearch.class.php';
        $do_boolean = false;
        foreach (explode(' ', $query) as $query_word) {
            if (preg_match('/\\*$/', $query_word)) {
                $do_boolean = true;
                break;
            }
        }
        if (strtolower($search_type) != 'or') {
            $do_boolean = true;
        }
        if ($do_boolean || $exclude || $section || $last_changed) {
            //boolean search
            if ($use_fulltext) {
                $search = new FulltextSearchBoolean($query, $exclude, $search_type, $last_changed, $order, $section, $classes, $keel);
            } else {
                $search = new AdvancedSearch($query, $exclude, $search_type, $last_changed, $order, $section, $classes, $keel);
            }
        } else {
            //simple search
            $search = new FulltextSearch($query, 0, $classes, $use_fulltext ? true : false, $keel);
        }
        if ($keel != "") {
            $search->execSearch();
        }
        //write to cache
        $site->cash(array(klass => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS', 'sisu' => $search));
    }
    $labels = array();
    $k = 0;
    foreach ($search->getResults() as $class_name => $objects) {
        if (in_array($class_name, $classes)) {
            $labels[$k]->title = $site->sys_sona(array('sona' => 'lipik ' . $class_name, 'tyyp' => 'otsing'));
            $labels[$k]->name = translate_en($class_name);
            $labels[$k]->counttotal = count($objects);
            $labels[$k]->results = isset($start) && $limit ? array_slice($objects, $start, $limit) : $objects;
            $labels[$k]->count = count($labels[$k]->results);
            foreach ($labels[$k]->results as $i => $obj) {
                /* @var $labels[$k]->results[$i] Objekt */
                // copy-paste from init_object
                $labels[$k]->results[$i]->id =& $labels[$k]->results[$i]->objekt_id;
                # kui link
                if ($labels[$k]->results[$i]->all['klass'] == 'link') {
                    # load sisu, et saada vļæ½ļæ½rtused "url" ja "on_uusaken"
                    $labels[$k]->results[$i]->load_sisu();
                    $labels[$k]->results[$i]->all['url'] && $labels[$k]->results[$i]->all['on_uusaken'] ? $labels[$k]->results[$i]->href = $labels[$k]->results[$i]->all['url'] . '" target="_blank' : ($labels[$k]->results[$i]->href = $labels[$k]->results[$i]->all['url']);
                } else {
                    $labels[$k]->results[$i]->href = $site->self . '?id=' . $labels[$k]->results[$i]->objekt_id;
                }
                // if an article mark for excerpt loading
                if ($labels[$k]->results[$i]->all['klass'] == 'artikkel') {
                    $sql = "select substring(sisu_strip, if(locate('" . $search->search_words[0] . "', sisu_strip) < (" . floor($site->CONF['search_result_excerpt_length'] / 2) . "), 1, if(locate('" . $search->search_words[0] . "', sisu_strip) + (" . floor($site->CONF['search_result_excerpt_length'] / 2) . ") > char_length(sisu_strip), char_length(sisu_strip) - " . $site->CONF['search_result_excerpt_length'] . ", locate('" . $search->search_words[0] . "', sisu_strip) - (" . floor($site->CONF['search_result_excerpt_length'] / 2) . "))), " . $site->CONF['search_result_excerpt_length'] . ") as excerpt from objekt where objekt_id = " . $labels[$k]->results[$i]->all['objekt_id'];
                    $result = new SQL($sql);
                    $labels[$k]->results[$i]->excerpt = $result->fetchsingle();
                } else {
                    $labels[$k]->results[$i]->excerpt = '';
                }
                $labels[$k]->results[$i]->score =& $labels[$k]->results[$i]->all['fulltext_score'];
                $labels[$k]->results[$i]->title =& $labels[$k]->results[$i]->pealkiri;
                $labels[$k]->results[$i]->fdate =& $labels[$k]->results[$i]->all['aeg'];
                $labels[$k]->results[$i]->author =& $labels[$k]->results[$i]->all['author'];
                $labels[$k]->results[$i]->class = translate_en($labels[$k]->results[$i]->all['klass']);
                # translate it to english
                /* maybe fields
                			$labels[$k]->results[$i]->is_selected = $leht->parents->on_parent($labels[$k]->results[$i]->objekt_id);
                			$labels[$k]->results[$i]->buttons = $labels[$k]->results[$i]->get_edit_buttons(array(
                				'nupud' => $buttons,
                				//'tyyp_idlist' => $tyyp_idlist,//???
                			));
                			$labels[$k]->results[$i]->created_user_id =& $labels[$k]->results[$i]->all['created_user_id'];
                			$labels[$k]->results[$i]->created_user_name =& $labels[$k]->results[$i]->all['created_user_name'];
                			$labels[$k]->results[$i]->changed_user_id =& $labels[$k]->results[$i]->all['changed_user_id'];
                			$labels[$k]->results[$i]->changed_user_name =& $labels[$k]->results[$i]->all['changed_user_name'];
                			$labels[$k]->results[$i]->created_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['created_time']);
                			$labels[$k]->results[$i]->fcreated_time =& $labels[$k]->results[$i]->all['created_time'];
                			$labels[$k]->results[$i]->changed_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['changed_time']);
                			$labels[$k]->results[$i]->fchanged_time =& $labels[$k]->results[$i]->all['changed_time'];
                			$labels[$k]->results[$i]->last_commented_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['last_commented_time']);;
                			$labels[$k]->results[$i]->comment_count =& $labels[$k]->results[$i]->all['comment_count'];
                			*/
            }
            //$labels[] = $label;
            $k++;
        }
    }
    $smarty->assign(array($name => $labels, $name . '_counttotal' => $search->search_count));
}
	$sql .= $pagenumbers['limit_sql'];

#print $sql;
	$sth = new SQL($sql);
	$site->debug->msg($sth->debug->get_msgs());

		###########################
		# loop over rows
		while ( $myttyyp = $sth->fetch() ) {
	?>
        <tr> 
          <td class="r<?= $i%2+1 ?>"><?=$myttyyp['ttyyp_id'];?></td>
          <td class="r<?= $i%2+1 ?>" nowrap><a href="javascript:void(avaaken('<?=$site->self?>?op=edit&id=<?=$myttyyp[ttyyp_id]?>','670','620','template'))"><?=$myttyyp[nimi]?></a></td>
          <td class="r<?= $i%2+1 ?>" ><?=$myttyyp[templ_fail]?></td>
		<?if($type != 'page'){ # dont show op for page templates (bug #1964)?>
          <td class="r<?= $i%2+1 ?>" ><?=translate_en($myttyyp['op']);?></td>
		<?}?>
          <td class="r<?= $i%2+1 ?>" ><?=$myttyyp[on_nahtav]?"Y":"N"?></td>
<!--          <td class="r<?= $i%2+1 ?>" ><?=$myttyyp[extension]?></td>-->
          <td class="r<?= $i%2+1 ?>" align="right">
		<? 
		# if default template, dont show edit & delete buttons 
		if($myttyyp[ttyyp_id] < 2000) { ?>
			<a href="javascript:void(avaaken('<?=$site->self?>?op=edit&id=<?=$myttyyp[ttyyp_id]?>','670','620','template'))"><img src="<?=$site->CONF[wwwroot].$site->CONF[styles_path]?>/gfx/icons/16x16/actions/edit.png" border="0" id="pt"></a
		
		  ><a href='javascript: if (confirm("<?=$site->sys_sona(array(sona => "Kas tahate kustutada", tyyp=>"editor"))?>")) {void(avapopup("<?=$site->self?>?op=delete_confirmed&id=<?=$myttyyp[ttyyp_id] ?>","template","400","400","no"))}'><img src="<?=$site->CONF[wwwroot].$site->CONF[styles_path]?>/gfx/icons/16x16/actions/delete.png" border="0" id="pt"></a
			><? 
		} 
		 else {
			 print "default";
		 } #if default templ ?></td>
/**
 * 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);
    }
}
function smarty_function_init_messages($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $messages = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent)) {
        $parent_id = $leht->id;
    } else {
        $parent_id = $parent;
    }
    if (!isset($name)) {
        $name = "messages";
    }
    if (!isset($order)) {
        $order = "aeg DESC, objekt_id DESC";
        $default_order = 1;
    } else {
        $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
        $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    # from dd.mm.yyyy to yyyy-mm-dd
    if ($start_date) {
        $start_date = $site->db->ee_MySQL($start_date);
    }
    if ($end_date) {
        $end_date = $site->db->ee_MySQL($end_date);
    }
    ##############
    # where & start_date, end_date
    if ($start_date && $end_date) {
        $where_add = " objekt.aeg BETWEEN '" . $start_date . "' AND '" . $end_date . "' ";
    } elseif ($start_date && !$end_date) {
        $where_add = " objekt.aeg >= '" . $start_date . "' ";
    } elseif (!$start_date && $end_date) {
        $where_add = " objekt.aeg <= '" . $end_date . "' ";
    }
    ######## add it to parameter "where"
    if (trim($where_add) != '') {
        $where = (trim($where) != '' ? $where . " AND " : "") . " (" . $where_add . ") ";
    }
    if (trim($where) != '') {
        $where = " (" . $where . ") ";
    }
    ##################
    # find template id by parameter messagedetail_tpl (= template name)
    $sth = new SQL("SELECT ttyyp_id FROM templ_tyyp WHERE nimi = '" . $messagedetail_tpl . "' AND ttyyp_id >= '1000' LIMIT 1");
    $messagedetail_tpl_id = $sth->fetchsingle();
    # if dynamical template not found, use fixed template 1
    if (!$messagedetail_tpl_id) {
        $messagedetail_tpl_id = 1;
        # default, templ1.php
    }
    ##############
    # alamlist counter
    # kirjade arv teemas
    $alamlist_count = new Alamlist(array(parent => $parent_id, klass => "kommentaar", asukoht => 0, where => $where, on_counter => 1));
    ###### pages: if paging needed (GET/POST variable "page" or parameter "rows_on_page" should exist ):
    if (isset($site->fdat['page']) || isset($rows_on_page)) {
        if (!$site->fdat['page']) {
            $tmp_page = 0;
        } else {
            $tmp_page = intval($site->fdat['page']) - 1;
        }
        if ($tmp_page < 0) {
            $tmp_page = 0;
        }
        $rows_on_page = isset($rows_on_page) ? $rows_on_page : $site->CONF['komment_arv_lehel'];
    }
    ##############
    # alamlist
    $alamlist = new Alamlist(array(parent => $parent_id, klass => "kommentaar", asukoht => 0, on_alampuu_kontroll => 14, start => isset($start) ? $start : $tmp_page * $rows_on_page, limit => isset($limit) ? $limit : $rows_on_page, order => $order, from => $from, where => $where, select_strip_fields => $where ? 1 : 0));
    ##############
    # load variables
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => 14, publish => $publish));
    while ($obj = $alamlist->next()) {
        $obj->id = $obj->objekt_id;
        $obj->detail_href = $site->self . '?' . (isset($content_template) ? 'c_tpl' : 'tpl') . '=' . $messagedetail_tpl_id . '&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->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 14, publish => $publish));
        $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'];
        ### CHECK & TEST: selle pļæ½ringu vļæ½ib siit maha vļæ½tta alates featuurist "objekt.comment_count"
        # praegu ei vļæ½ta, sest pole aega testida (merle, 8 juuli 2005)
        $alamlist_count2 = new Alamlist(array(parent => $obj->objekt_id, klass => "kommentaar", asukoht => 0, on_counter => 1));
        $obj->message_replies = $alamlist_count2->rows;
        $obj->message_count = $alamlist_count->rows;
        $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
        $obj->comment_count = $obj->all['comment_count'];
        ########################
        # Generate delete link
        # Only site users who wrote comment will see delete link, rules are following:
        # 1) delete comments to comments that are LAST in conversation
        # 2) delete comments in topics, that have no answers
        if ($site->user->user_id == $obj->all['kasutaja_id'] && $alamlist_count2->rows == 0 && ($leht->objekt->all['klass'] == "teema" || $leht->objekt->all['klass'] != "teema" && $alamlist->index == 0 && $default_order)) {
            $obj->delete = "<a href=\"javascript:avapopup('com_del.php?id=" . $obj->objekt_id . "','delete','413','108');\">" . $site->sys_sona(array("sona" => "Kustuta", "tyyp" => "Editor")) . "</a>";
        }
        #######################
        $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->class = translate_en($obj->all[klass]);
        # translate it to english
        $alamlist2 = new Alamlist(array(parent => $obj->objekt_id, klass => "kommentaar", asukoht => 0, start => 0, limit => 1));
        $last = $alamlist2->next();
        # viimane vastus kirjale
        $obj->last_message = $last ? $site->db->MySQL_ee_short($last->all[aeg]) : "&nbsp;";
        $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'];
        array_push($messages, $obj);
    }
    $count = sizeof($messages);
    $counttotal = $alamlist_count->rows;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $messages, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
            # Move to Recycle Bin here:
            if ($site->fdat['kinnitus']) {
                verify_form_token();
                $sql = $site->db->prepare("UPDATE objekt_objekt SET parent_id=? WHERE objekt_id=? AND parent_id=?", $rub_trash_id, $objekt->objekt_id, $objekt->parent_id);
                $sth15 = new SQL($sql);
                $site->debug->msg($sth15->debug->get_msgs());
                # DELETE all other parents except trash
                # (Bug #491: ja tegelikult ka n��d pannakse rubriik ikka t�ielikult pr�gikasti. mitte ei panda �heks parentiks pr�gikast ja teiseks j�etakse teine vana parent alles, nagu vanasti)
                $sql = $site->db->prepare("DELETE FROM objekt_objekt WHERE objekt_id=? AND parent_id<>?", $objekt->objekt_id, $rub_trash_id);
                $sth15 = new SQL($sql);
                $site->debug->msg($sth15->debug->get_msgs());
                // v3 style: $sql = $site->db->prepare("UPDATE objekt SET on_avaldatud='0', last_modified=?, friendly_url='' WHERE objekt_id=?", time(), $objekt->objekt_id);
                $sql = $site->db->prepare("UPDATE objekt SET on_avaldatud = 0, changed_time = now(), changed_user_id = ?, changed_user_name = ? WHERE objekt_id = ?", $site->user->user_id, $site->user->name ? $site->user->name : $site->user->username, $objekt->objekt_id);
                $sth15 = new SQL($sql);
                $site->debug->msg($sth15->debug->get_msgs());
                new Log(array('action' => 'delete', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all[klass])), $objekt->pealkiri(), $objekt->objekt_id, " moved to Recycle Bin")));
                ?>
			<script type="text/javascript">
				window.opener.location=mylocation;
				window.close();
			</script>
<?php 
                exit;
                ################################
                # Ask confirmation
            } else {
                ?>
	<form action="<?php 
                echo $site->self;
                ?>
" method=get>
        foreach ($site->fdat['objects'][$i] as $object_id => $values) {
            if ($object_id) {
                $delete_objs = new Alamlist(array('parent' => $object_id, 'klass' => $classes));
                while ($object = $delete_objs->next()) {
                    $object->del();
                    //printr($object->objekt_id.' deleted');
                    new Log(array('action' => 'delete', 'component' => 'Recycle bin', 'objekt_id' => $objekt_id->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($object->all['klass'])), $object->pealkiri(), $object->objekt_id, ' removed from Recycle Bin ')));
                }
            }
        }
    }
    $delete_objs = new Alamlist(array('parent' => $trash_id, 'klass' => $classes));
    while ($object = $delete_objs->next()) {
        $object->del();
        //printr($object->objekt_id.' deleted');
        new Log(array('action' => 'delete', 'component' => 'Recycle bin', 'objekt_id' => $objekt_id->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($object->all['klass'])), $object->pealkiri(), $object->objekt_id, ' removed from Recycle Bin ')));
    }
    new Log(array('action' => 'delete', 'component' => 'Recycle bin', 'message' => 'Recycle Bin emptied'));
}
$root = new Alamlist(array('parent' => $trash_id, 'klass' => $classes, 'order' => $sort_by . ' ' . $sort_dir));
$untraveled = array();
//stack
$periferal = array();
//misc data for other table cells
while ($item = $root->next()) {
    $untraveled[] = array('level' => 0, 'object' => $item);
    $periferal[] = $item;
}
$untraveled = array_reverse($untraveled);
$adminpage_names = get_adminpage_name(array('script_name' => $site->script_name));
?>
function smarty_function_init_files($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    $files = array();
    ##############
    # default values
    extract($params);
    $folder = false;
    if (isset($parent)) {
        $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE objekt_id=?", $parent);
        $sth = new SQL($sql);
        $folder = $sth->fetch();
    } elseif (isset($parent_dir)) {
        # get parent folder info
        $parent_dir = preg_replace('#^/#', '', $parent_dir);
        $parent_dir = preg_replace('#/$#', '', $parent_dir);
        //parent dir must start with "public" or "shared"
        if (strpos($parent_dir, 'public') === 0 || strpos($parent_dir, 'shared') === 0) {
            $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE relative_path = ?", '/' . $parent_dir);
            $sth = new SQL($sql);
            $folder = $sth->fetch();
            $parent = $folder['objekt_id'];
        }
    }
    if (!$folder) {
        # default parent for file (folder "public/"): get folder ID of "public/"
        $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE relative_path = ? LIMIT 1", $site->CONF['file_path']);
        $sth = new SQL($sql);
        $folder = $sth->fetch();
        $parent = $folder['objekt_id'];
    }
    if (!isset($name)) {
        $name = "files";
    }
    switch ($on_create) {
        case 'publish':
            $publish = 1;
            break;
        case 'hide':
            $publish = 0;
            break;
        default:
            $publish = 1;
    }
    #  kui pole profile parameetrit, siis kasuta default profiili
    if (!$profile) {
        $default_profile_def = $site->get_profile(array(id => $site->get_default_profile_id(array(source_table => 'obj_file'))));
        # get profile name
        $profile = $default_profile_def['name'];
        unset($default_profile_def);
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array('new', 'edit', 'delete');
    } else {
        $buttons = split(',', $buttons);
    }
    ###############
    # order, parent
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    $where = preg_replace('#\\btitle\\b#i', "pealkiri", $where);
    $where = preg_replace('#\\bdate\\b#i', "aeg", $where);
    ######## where: profile, replace technical name with field name
    if (trim($where) != '') {
        $where = " (" . $where . ") ";
    }
    ##############
    # put all profile names into arr
    if ($profile) {
        $profile_names = split(",", $profile);
    } else {
        $profile_names = array();
        $profile_ids = array();
    }
    # get all profile data from cash
    foreach ($profile_names as $profile_name) {
        # profile name is case insensitive
        $profile_name = strtolower($profile_name);
        $profile_def = $site->get_profile(array(name => $profile_name));
        # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade ja vļæ½ljuda:
        if (!$profile_def[profile_id]) {
            if ($site->admin) {
                print "<font color=red><b>Profile '" . $profile_name . "' not found!</b></font>";
            }
            return;
        }
        $profile_ids[] = $profile_def[profile_id];
        $profile_arr[$profile_def[profile_id]] = $profile_def;
    }
    ############# parent
    $parent_id = trim($parent);
    #Bug #2803: Tagil {init_files} ei saanud ette anda mitud parent ID väärtust
    if ($parent_id) {
        ##############
        # create SQL
        $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "file", order => $order));
        $alamlistSQL->add_select("obj_file.profile_id, obj_file.relative_path, obj_file.filename, obj_file.mimetype, obj_file.size");
        if (sizeof($profile_ids) > 0) {
            $alamlistSQL->add_select("obj_file.*");
        }
        if (isset($select)) {
            $alamlistSQL->add_select($select);
        }
        if (sizeof($select_sql) > 0) {
            $alamlistSQL->add_select(join(", ", $select_sql));
        }
        $alamlistSQL->add_from("LEFT JOIN obj_file ON objekt.objekt_id=obj_file.objekt_id");
        if ($where) {
            $alamlistSQL->add_where($where);
        }
        $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => $start, limit => $limit));
        $alamlist->debug->print_msg();
        $alamlist_count = new Alamlist(array(alamlistSQL => $alamlistSQL, on_counter => 1));
        ##############
        # load variables
        $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => "21", profile_id => join(",", $profile_ids), publish => $publish));
        while ($obj = $alamlist->next()) {
            $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => "21", profile_id => join(",", $profile_ids), nupud => $buttons, publish => $publish));
            $obj->id = $obj->objekt_id;
            $obj->parent = $obj->parent_id;
            $obj->folder_fullpath = $site->absolute_path . $folder['relative_path'];
            $obj->href = $site->CONF['wwwroot'] . '/file.php?' . $obj->objekt_id;
            # Bug #2317
            $obj->title = $obj->all['pealkiri'];
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $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'];
            $pathinfo = pathinfo($site->absolute_path . $obj->all['relative_path']);
            $obj->fullpath = $site->absolute_path . $obj->all['relative_path'];
            $obj->filename = $obj->all['filename'];
            $obj->mimetype = $obj->all['mimetype'];
            # size is set later: after profiles
            $obj->profile_id = $obj->all['profile_id'];
            $obj->extension = strtolower($pathinfo["extension"]);
            if ($icons) {
                if (!preg_match("/\\/\$/", $icons)) {
                    $icons .= '/';
                }
                if (file_exists($site->absolute_path . $icons . $obj->extension . '.gif')) {
                    $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . $obj->extension . '.gif';
                } elseif (file_exists($site->absolute_path . $icons . 'unknown.gif')) {
                    $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . 'unknown.gif';
                }
            }
            $obj->class = translate_en($obj->all[klass]);
            # translate it to english
            $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'];
            ########## KUI PROFIIL on parameetrina kaasas JA failil on Mļæ½ļæ½RATUD mļæ½ni PROFIIL, siis korja andmed "->" omadustena kokku
            if (sizeof($profile_ids) > 0) {
                ###### load object. #### NB! actually should be: profile_id is in "objekt" tabel. then we don't have to entire object
                #			$obj->load_sisu();
                ###### loop over profiles
                foreach ($profile_ids as $profile_id) {
                    #printr($obj->objekt_id.' PROFILE_ID: '.$obj->all['profile_id']);
                    include_once $class_path . 'profile.class.php';
                    $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
                    #### 1. set profile fields as object attributes
                    $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
                    ###################
                    # get selectlist values - 1 extra sql per function; sql is fast
                    if (is_array($obj_profile->selectlist)) {
                        $obj_profile->selectlist = array_unique($obj_profile->selectlist);
                        #printr($obj_profile->selectlist);
                    }
                    # go on if object values needs changing:
                    if (sizeof($obj_profile->selectlist) > 0) {
                        #### 2. save array "->asset_names"  human readable NAME-s:
                        $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
                        #printr($obj_profile->asset_names);
                        #printr($obj_profile->change_fields);
                        ### 3. save object rest of attributes
                        #print "<br>muuta ID: ".$obj->id;
                        $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
                    }
                    # if any selectvalue exist & need to change
                    # / get selectlist values
                    ###################
                }
                ###### / loop over profiles
            }
            ####### / profile is set
            $obj->size = print_filesize($obj->all['size']);
            array_push($files, $obj);
        }
        ###### / loop over objects
    }
    $count = sizeof($files);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $files, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
     # 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
 ###########################
 ###########################
function smarty_function_init_object($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "object";
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    ##############
    # luua objekt & load sisu
    $obj = new Objekt(array(objekt_id => $id));
    $obj->load_sisu();
    ################
    # object GENERAL parameters
    $obj->id = $obj->objekt_id;
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    # kui link
    if ($obj->all[klass] == "link") {
        $objektUrl = $obj->all['url'];
        // replace index.php?id=xxx or ?id=xxx style local url with its alias
        if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
            $objektUrl = convert_local_link_to_alias($objektUrl);
        }
        $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
    } else {
        $obj->get_object_href();
    }
    $obj->title = $obj->pealkiri;
    $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $obj->all['tyyp_id'], publish => $publish));
    $obj->fdate = $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->details_link = $obj->href;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    $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'];
    ################
    # ALL values, set as attributes
    foreach ($obj->all as $fieldname => $value) {
        $obj->{$fieldname} = $value;
    }
    ###############
    # profile values, set as attributes
    $profile_def = $site->get_profile(array(id => $obj->all['profile_id']));
    if ($profile_def[profile_id]) {
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ################
    # object CLASS specific parameters
    ########## ARTICLE
    if ($obj->class == 'article') {
        //$obj = init_article(array("id"=>$obj->id), &$smarty);
        if (!function_exists('smarty_function_init_article')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_article');
        }
        smarty_function_init_article(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'document') {
        if (!function_exists('smarty_function_init_document')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_document');
        }
        $obj = smarty_function_init_document(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'image') {
        if (!function_exists('smarty_function_init_picture')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_picture');
        }
        $obj = smarty_function_init_picture(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'section') {
        $obj->show_toolicons = $obj->all['on_printlink'];
        $obj->is_mailinglist = $obj->all['on_meilinglist'];
        $obj->show_subarticles = $obj->all['on_alamartiklid'];
        $obj->hide_in_menu = $obj->all['on_peida_vmenyy'];
        $obj->show_date = $obj->all['on_kp_nahtav'];
    } elseif ($obj->class == 'poll') {
        $obj->is_open = $obj->all['on_avatud'];
        $obj->expires = $obj->all['expires'] ? $site->db->MySQL_ee($obj->all['expires']) : '';
        $obj->fexpires = $obj->all['expires'] ? $obj->all['expires'] : '';
        $obj->is_expired = $obj->all['expires'] && (strtotime($obj->all['expires']) > 0 && strtotime($obj->all['expires']) < time()) ? 1 : 0;
        #printr(strtotime($obj->all['expires']));
        ######### CHECK voting
        # 1) IP-based gallup
        if ($site->CONF[gallup_ip_check] == 1) {
            $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND ip LIKE ?", $obj->id, $_SERVER["REMOTE_ADDR"]);
            $sth = new SQL($sql);
            $count = $sth->fetchsingle();
        } else {
            if ($site->CONF[gallup_ip_check] == 2 && $site->cookie["gallup"][$obj->id] == 1) {
                $count = 1;
            } else {
                if ($site->CONF[gallup_ip_check] == 3) {
                    $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND user_id=?", $obj->id, $site->user->user_id);
                    $sth = new SQL($sql);
                    # count=1: not logged in users are not allowed to vote:
                    $count = $site->user->user_id ? $sth->fetchsingle() : 1;
                } else {
                    $count = 0;
                }
            }
        }
        ######### / CHECK voting
        ### is_voted: if user is voted this poll or not, 1/0
        $obj->is_voted = $count;
        # not voted
        ### answers
        $sql = $site->db->prepare("SELECT * FROM gallup_vastus WHERE objekt_id=?", $obj->id);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        $obj->answers = array();
        $obj->answers_count = 0;
        while ($vastus = $sth->fetch()) {
            unset($tmp);
            $tmp = new stdClass();
            $tmp->id = $vastus[gv_id];
            $tmp->answer = $vastus[vastus];
            $tmp->title = $vastus[vastus];
            $tmp->count = $vastus[count];
            $obj->answers[$vastus[gv_id]] = $tmp;
            $obj->answers_count += $vastus[count];
        }
        ### / answers
        ### voters (if not anonymous poll)
        if (!$obj->is_anonymous) {
            $sql = $site->db->prepare("SELECT gallup_ip.*, users.firstname, users.lastname\r\n\t\t\t\tFROM gallup_ip\r\n\t\t\t\t\tLEFT JOIN users ON users.user_id = gallup_ip.user_id\r\n\t\t\t\tWHERE objekt_id=?", $obj->id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $obj->voters = array();
            while ($vastus = $sth->fetch()) {
                unset($tmp);
                $tmp->id = $vastus[gi_id];
                $tmp->answer_id = $vastus[gv_id];
                $tmp->ip = $vastus[ip];
                $tmp->user_id = $vastus[user_id];
                $tmp->user_firstname = $vastus[firstname];
                $tmp->user_lastname = $vastus[lastname];
                $tmp->time = $site->db->MySQL_ee($vastus[vote_time]);
                $tmp->ftime = $vastus[vote_time];
                $obj->voters[$vastus[gi_id]] = $tmp;
            }
        }
        # if not anonymous poll
        ### / voters
    } elseif ($obj->class == 'album') {
        // add album config atributes
        $conf = new CONFIG($obj->all['ttyyp_params']);
        $obj->description = $conf->get('desc');
        $obj->thumbnail_size = $conf->get('tn_size');
        # in pixels
        $obj->image_size = $conf->get('pic_size');
        # in pixels
        $obj->folder_id = $conf->get('folder_id');
        # source folder ID
        $obj->folder_path = $conf->get('path');
        # source folder path, eg "public/images"
    }
    ########## / ALBUM
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
}
/**
* 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
    ###################
}
function smarty_function_init_document($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 = "document";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    if (!isset($ttyyp_id)) {
        $ttyyp_id = 0;
    }
    ##############
    # luua objekt
    $obj = new Objekt(array(objekt_id => $id));
    ##############
    # load variables
    $obj->load_sisu();
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 7, asukoht => $position, publish => $publish));
    $obj->id = $obj->objekt_id;
    $obj->href = $site->self . '?id=' . $obj->objekt_id;
    $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
    $obj->title = $obj->pealkiri;
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $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->file = $obj->filename = $obj->all['fail'];
    $obj->description = $obj->all['kirjeldus'];
    $obj->size = $obj->all['size'];
    $obj->size_formated = print_filesize($obj->all['size']);
    $obj->author = $obj->all['author'] ? $obj->all['author'] : $obj->all['autor'];
    $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
    $obj->download_link = 'doc.php?' . $obj->objekt_id;
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    $obj->hit_count = $obj->all['count'];
    # added 15.12.2004:
    $obj->comment_link = $site->self . '?id=' . $obj->objekt_id . '#comm';
    $obj->comment_title = $site->sys_sona(array(sona => "Kommentaarid", tyyp => "kujundus"));
    $obj->add_comment_link = $site->self . '?id=' . $obj->objekt_id . '#cbox';
    $obj->add_comment_title = $site->sys_sona(array(sona => "Lisa kommentaar", tyyp => "kujundus"));
    #no UI for this:	$obj->forum_allowed = $obj->all[on_foorum];
    $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'];
    $smarty->assign($name, $obj);
    //return $obj; # bug #1921 for {init_object} tag
}