function get_files_from_folder($folder_id, $sorting = 'objekt.pealkiri asc', $page = 1)
{
    global $site;
    $objekt = new Objekt(array('objekt_id' => $folder_id));
    if ($objekt->objekt_id == $folder_id && $objekt->all['tyyp_id'] == 22) {
        $list_sql = new AlamlistSQL(array('parent' => $folder_id, 'klass' => 'file', 'order' => $sorting));
        $list_sql->add_select("obj_file.profile_id, obj_file.relative_path, obj_file.filename, obj_file.mimetype, obj_file.size");
        $list_sql->add_from("LEFT JOIN obj_file ON objekt.objekt_id=obj_file.objekt_id");
        $list = new Alamlist(array('alamlistSQL' => $list_sql, 'start' => ($page - 1) * 100, 'limit' => 100));
        $count_sql = new AlamlistSQL(array('parent' => $folder_id, 'klass' => 'file'));
        $count = new Alamlist(array('alamlistSQL' => $count_sql, 'on_counter' => 1));
        return array('total_files' => (int) $count->rows, 'files' => get_files_list($list));
    } else {
        return 'no_such_folder_object';
    }
}
function print_me($template)
{
    $leht =& $template->leht;
    #$curr_rub_id = $leht->id;
    $args[tulemuste_arv] = 10;
    $curr_rub_id = $leht->site->alias("gallup_arhiiv");
    $template->debug->msg("Rubriik: {$curr_rub_id}");
    ?>

<table width="<?php 
    echo $template->site->dbstyle("sisu_tabeli_laius", "layout");
    ?>
" height="<?php 
    echo $template->site->dbstyle("sisu_tabeli_korgus", "layout");
    ?>
"  border="0" cellspacing="<?php 
    echo $template->site->dbstyle("sisu_tabeli_cellspacing", "layout");
    ?>
" cellpadding="0">
    <tr valign="top"> 

<?php 
    $leht->debug->msg($leht->site->dbstyle("menyy", "layout"));
    ?>
<td width="100%">
	<h1 class="pealkiri"><?php 
    echo $template->site->sys_sona(array("sona" => $template->all["nimi"], "tyyp" => "kujundus"));
    ?>
</h1><br><hr noshade size="1" style="color:#dddddd;">

<?php 
    # ---------------------------
    # Gallup on siin
    # ---------------------------
    $alamlist_count = new Alamlist(array(parent => $curr_rub_id, klass => "gallup", on_counter => 1));
    ########## 1. ONE GALLUP
    if ($leht->site->fdat["gallup_id"]) {
        $obj = new Objekt(array(objekt_id => $leht->site->fdat["gallup_id"]));
    }
    if (!$obj) {
        $alamlist = new Alamlist(array(parent => $curr_rub_id, klass => "gallup", start => 0, limit => 1));
        $obj = $alamlist->next();
    }
    if ($obj->on_404) {
        header('Location: ' . $site->CONF['wwwroot'] . '/?id=' . $obj->objekt_id);
        exit;
    } elseif ($obj) {
        printf("<font class=sub_pealkiri>%s</font><br>", $obj->get_edit_buttons(array(tyyp_idlist => "6", nupud => array("edit", "delete"))) . $obj->pealkiri);
        $sql = $leht->site->db->prepare("SELECT * FROM gallup_vastus WHERE objekt_id=?", $obj->objekt_id);
        $sth = new SQL($sql);
        # tulemused
        #### 1. for MSSQL
        if (strtoupper($leht->site->CONF["dbtype"]) == 'MSSQL') {
            $sql = $leht->site->db->prepare("SELECT SUM([count]) AS kokku, MAX([count]) AS maksi FROM gallup_vastus WHERE objekt_id=?", $obj->objekt_id);
        } else {
            $sql = $leht->site->db->prepare("SELECT SUM(count) AS kokku, MAX(count) AS maksi FROM gallup_vastus WHERE objekt_id=?", $obj->objekt_id);
        }
        $sth_c = new SQL($sql);
        $stat = $sth_c->fetch();
        $obj->debug->msg("kokku = {$stat['kokku']}, maks = {$stat['maksi']}");
        $obj->debug->msg($sth_c->debug->get_msgs());
        ?>
		<table border=0>
			 <tr>
				 <td valign="top"><img src="<?php 
        echo $obj->site->img_path;
        ?>
/px.gif" width="300" height="3"></td>
			 </tr>
<?php 
        while ($vastus = $sth->fetch()) {
            $percent = $stat[kokku] ? sprintf('%2.0f', 100 * $vastus[count] / $stat[kokku]) : 0;
            ?>
					
			 <tr>
				 <td valign="top" class="<?php 
            echo $obj->site->agent ? "txt" : "txt1";
            ?>
"><?php 
            echo $vastus[vastus];
            ?>
</td>
			 </tr>
			 <tr>
				 <td valign="top"><b><font class="<?php 
            echo $obj->site->agent ? "txt" : "txt1";
            ?>
">- <?php 
            echo $percent;
            ?>
%</font></b> <img src="<?php 
            echo $obj->site->img_path;
            ?>
/gallup_bar<?php 
            echo $stat[maksi] == $vastus[count] && $vastus[count] ? "2" : "1";
            ?>
.gif" width="<?php 
            echo 0.01 * 250 * $percent;
            ?>
" height=8 border="1"></td>
			 </tr>
<?php 
        }
        # while vastus
        ?>
			 <tr>
				 <td valign="top" class="<?php 
        echo $obj->site->agent ? "txt" : "txt1";
        ?>
"><?php 
        echo $leht->site->sys_sona(array(sona => "vastajaid", tyyp => "kujundus"));
        ?>
: <b><?php 
        echo $stat[kokku];
        ?>
</b></td>
			 </tr>
		 </table>
		 <br><br>
<?php 
    }
    ########## 2. GALLUP LIST
    $alamlistSQL = new AlamlistSQL(array("parent" => $curr_rub_id, "klass" => "gallup"));
    $alamlistSQL->add_select(" DATE_FORMAT(objekt.aeg, '%d.%m.%y') as faeg ");
    $alamlistSQL->debug->print_msg();
    $template->debug->msg("SQL: " . $alamlistSQL->make_sql());
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL));
    $alamlist->debug->print_msg();
    ?>

	<table>
<?php 
    while ($obj = $alamlist->next()) {
        ?>
	<tr>
	<td class=date><?php 
        echo $obj->all['faeg'];
        ?>
</td>
	<td><a href="?op=gallup_arhiiv&page=<?php 
        echo $site->fdat['page'];
        ?>
&gallup_id=<?php 
        echo $obj->objekt_id;
        ?>
"><?php 
        echo $obj->get_edit_buttons(array("tyyp_idlist" => 6, "nupud" => array("edit", "delete")));
        echo $obj->all['pealkiri'];
        ?>
</a></td>

	</tr>
<?php 
    }
    ?>
	</table>



</td>
</tr>
</table>
<?php 
}
function smarty_function_init_images($params, &$smarty)
{
    if (!function_exists('search_obj_array')) {
        function search_obj_array($needle, $field, $array = array())
        {
            if ($array) {
                foreach ($array as $key => $data) {
                    if ($data->all[$field] == $needle) {
                        return $key;
                    }
                }
            }
            return false;
        }
    }
    global $class_path, $site, $leht;
    extract($params);
    if (!isset($name)) {
        $name = 'images';
    }
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    $album = new Objekt(array('objekt_id' => $parent));
    $conf = new CONFIG($album->all['ttyyp_params']);
    //$alamlist->debug->print_msg();
    $files = array();
    if ($conf->get('path')) {
        $path = (string) $conf->get('path');
        $path = preg_replace('#^/#', '', $path);
        $path = preg_replace('#/$#', '', $path);
        $sql = $site->db->prepare('select objekt_id from obj_folder where relative_path = ?', '/' . $path);
        $result = new SQL($sql);
        $folder_id = $result->fetchsingle();
        if ($folder_id) {
            $alamlistSQL = new AlamlistSQL(array('parent' => $folder_id, 'klass' => 'file', 'order' => ' filename ', 'where' => $where));
            $alamlistSQL->add_select(" obj_file.filename, obj_file.size, obj_file.kirjeldus ");
            $alamlistSQL->add_from("LEFT JOIN obj_file ON objekt.objekt_id=obj_file.objekt_id");
            $alamlist = new Alamlist(array('alamlistSQL' => $alamlistSQL));
            $files = array();
            $new_button = $alamlist->get_edit_buttons(array('tyyp_idlist' => '21', 'publish' => 1));
            while ($obj = $alamlist->next()) {
                $obj->buttons = $obj->get_edit_buttons(array('tyyp_idlist' => 21, 'nupud' => array('edit', 'delete', 'new')));
                $files[] = $obj;
            }
        }
        $path = $site->absolute_path . $path;
        include_once $class_path . 'picture.inc.php';
        $imgs = get_images($path, $conf->get('path'));
    } else {
        //veateade et path pole paika pandud or something ...
    }
    $start_from = 0;
    if ($limit) {
        $end_at = $limit;
    } else {
        $end_at = sizeof($imgs);
    }
    if ($start) {
        $total_pages = ceil(sizeof($imgs) / $limit);
        $start_from = $start;
        $end_at = $start_from + $limit;
    }
    if ($end_at > sizeof($imgs)) {
        $end_at = sizeof($imgs);
    }
    $j = 0;
    $images = array();
    for ($i = $start_from; $i < $end_at; $i++) {
        $images[$j]->thumb_path = $site->CONF['wwwroot'] . '/' . $imgs[$i]['thumb'];
        # relative path
        $images[$j]->thumb_height = $imgs[$i]['thumb_height'];
        # in pixels
        $images[$j]->thumb_width = $imgs[$i]['thumb_width'];
        $images[$j]->image_path = $site->CONF['wwwroot'] . '/' . $imgs[$i]['image'];
        $images[$j]->image_height = $imgs[$i]['image_height'];
        $images[$j]->image_width = $imgs[$i]['image_width'];
        $images[$j]->actual_image_path = $site->CONF['wwwroot'] . '/' . $imgs[$i]['actual_image'];
        $images[$j]->actual_image_height = $imgs[$i]['actual_image_height'];
        $images[$j]->actual_image_width = $imgs[$i]['actual_image_width'];
        $images[$j]->actual_image_size =& $images[$j]->size;
        # original
        $images[$j]->filename = $imgs[$i]['filename'];
        $key = search_obj_array($imgs[$i]['filename'], 'filename', $files);
        if ($key !== false) {
            $images[$j]->id = $files[$key]->all['objekt_id'];
            $images[$j]->title = $files[$key]->pealkiri;
            $images[$j]->description = $files[$key]->all['kirjeldus'];
            $images[$j]->size = $files[$key]->all['size'];
            # final display
            $images[$j]->buttons = $files[$key]->buttons;
        }
        $j++;
    }
    //printr($images);
    $smarty->assign(array($name => $images, $name . '_newbutton' => $new_button, $name . '_title' => $album->pealkiri, $name . '_first_image' => $images[0]->image_path, $name . '_last_image' => $images[sizeof($images) - 1]->image_path, $name . '_count' => sizeof($images), $name . '_counttotal' => sizeof($imgs)));
}
?>
</td>
							</tr>
				<?
							$i++;
						} 
						# / 1. loop over sys_aliases
						######################

						######################
						# 2. loop over user_defined system articles

						if($group_name == 'user_defined_messages') {
							$alamlistSQL = new AlamlistSQL(array(
								parent => $leitud_aliased["system"]->objekt_id,
								klass	=> "artikkel",
								asukoht	=> 0,
								order => "aeg",
							));
							# User defined articles: show also articles having non-empty "sys_alias" field value:
							$alamlistSQL->add_where("objekt.sys_alias NOT IN ('".join("','",array_merge($sysalias_groups["system_messages"],$sysalias_groups["form_messages"]))."')");

							$alamlistSQL->add_where($site->db->prepare("objekt.keel=?",$keel_id));

							$alamlist = new Alamlist(array(
								alamlistSQL => $alamlistSQL,
							));

							$alamlist->debug->print_msg();

							while ($obj = $alamlist->next()) {	
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_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));
}
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));
}
function smarty_function_init_assets($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    include_once $class_path . 'profile.class.php';
    $assets = array();
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "assets";
    }
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    $parent_id = trim($parent);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    # NB! kui t��p on asset, siis PEAB alati kaasas olema ka profiili ID
    # (muidu ei oma custom asset m�tet);
    # kui pole profile parameetrit, anda toimetajale veateade ja v�ljuda:
    if (!$profile) {
        if ($site->admin) {
            print "<font color=red><b>Profile parameter is required!</b></font>";
        }
        exit;
    }
    # for language compatibility, replace order with existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    ##############
    ## deprecated parameter "fields"
    if (isset($fields)) {
        $get_object_fields .= "," . $fields;
    }
    # put all fields filter into arr
    $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++;
    }
    ##############
    # put all profile names into arr
    $profile_names = split(",", $profile);
    ##############
    # 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>";
            }
            exit;
        }
        $profile_ids[] = $profile_def[profile_id];
        $profile_arr[$profile_def[profile_id]] = $profile_def;
    }
    if (($id || $parent_id) && sizeof($profile_ids) > 0) {
        # one object
        if ($id) {
            ##############
            # luua objekt
            $obj = new Objekt(array(objekt_id => $id));
            $obj->load_sisu();
            $obj->hit_count = $obj->all['count'];
            $alamlist = new ObjektArray();
            $alamlist->add($obj);
        } elseif ($parent_id) {
            # loop over profile ID-s
            foreach ($profile_ids as $profile_id) {
                $where_sql[] = "obj_asset.profile_id = '" . $profile_id . "'";
                $profile_def = unserialize($profile_arr[$profile_id]['data']);
                if (!is_array($profile_def)) {
                    $profile_def = array();
                }
                # loop over one profile fields
                foreach ($profile_def as $key => $data) {
                    if (!$get_object_fields || sizeof($get_object_fields_arr) > 0 && in_array($data[name], $get_object_fields_arr)) {
                        $select_sql[] = ($data['is_predefined'] ? 'objekt' : 'obj_asset') . "." . $key;
                        if ($contains) {
                            $contains_sql[] = ($where ? " AND " : "") . $key . $site->db->prepare(" LIKE ?", '%' . $contains . '%');
                        }
                    }
                    if ($where) {
                        # replace technical name with field name
                        $where = str_replace($data['name'], $key, $where);
                    }
                    if ($order) {
                        $order = str_replace($data['name'], $key, $order);
                    }
                    if ($select) {
                        $select = str_replace($data['name'], $key, $select);
                    }
                }
                # / loop over one profile fields
            }
            # / loop over profile ID-s
            ##############
            # create SQL
            $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "asset", order => $order, asukoht => $position));
            $alamlistSQL->add_select("obj_asset.profile_id");
            if (isset($select)) {
                $alamlistSQL->add_select($select);
            }
            if (sizeof($select_sql) > 0) {
                $alamlistSQL->add_select(join(", ", $select_sql));
            }
            $alamlistSQL->add_from("LEFT JOIN obj_asset ON objekt.objekt_id=obj_asset.objekt_id");
            $alamlistSQL->add_where("(" . join(" OR ", $where_sql) . ")");
            if ($where) {
                $alamlistSQL->add_where($where);
            }
            if (sizeof($contains_sql) > 0) {
                $alamlistSQL->add_where(join(" OR ", $contains_sql));
            }
            $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 => "20", profile_id => join(",", $profile_ids), asukoht => $position, publish => $publish));
        }
        # id or list
        $all_change_fields = array();
        $all_selectlist = array();
        # array of ID-s which need additional steps to convert ID-s to human readable NAME-s (assets or users/groups)
        if (!isset($buttons)) {
            $buttons = array('new', 'edit', 'hide', 'move', 'delete');
        } else {
            $buttons = split(',', $buttons);
        }
        while ($obj = $alamlist->next()) {
            $obj->id =& $obj->objekt_id;
            $obj->class = $obj->all[klass];
            # translate it to english
            $obj->buttons = $obj->get_edit_buttons(array('nupud' => $buttons, tyyp_idlist => "20", profile_id => join(",", $profile_ids), publish => $publish));
            $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('d.m.Y H:i', $obj->all['last_modified']);
            $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->title = $obj->pealkiri;
            $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
            // bug #2455
            if (is_array($obj_profile->data)) {
                foreach ($obj_profile->data as $profile_key => $profile_data) {
                    if ($profile_key != $profile_data['name'] && !isset($obj->all[$profile_data['name']])) {
                        $obj->all[$profile_data['name']] =& $obj->all[$profile_key];
                    }
                }
            }
            // / bug #2455
            $obj->profile = $obj_profile->name;
            # name
            #### 1. set profile fields as object attributes
            $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
            ## gather all selectlist values into one array:
            if (sizeof($obj_profile->selectlist) > 0) {
                $all_selectlist = array_merge($obj_profile->selectlist, $all_selectlist);
            }
            ## gather all need_change_obj values into one array:
            # that means object attributes has to be cahnged later. remeMber fields for each obj.
            if (sizeof($obj_profile->change_fields) > 0) {
                $all_change_fields[$obj->id] = $obj_profile->change_fields;
            }
            #printr($obj_profile->change_fields);
            $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'];
            ### push
            array_push($assets, $obj);
        }
        //printr($all_selectlist);
        ###################
        # get selectlist values - 1 (or 2, if system tables involved) extra sql per function; sql is fast
        if (sizeof($all_selectlist) > 0) {
            # 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $all_selectlist));
            #printr($obj_profile->asset_names);
            #printr($all_change_fields);
            ###############
            # assign names to attributes
            #echo printr($asset_names);
            ###############
            # loop over asset objects and changes attributes values correct
            $i = 0;
            foreach ($assets as $tmp) {
                # pointer to array element:
                $obj =& $assets[$i];
                # go on if object values needs changing:
                if (in_array($obj->id, array_keys($all_change_fields))) {
                    #print "<br>muuta ID: ".$obj->id;
                    ### 3. save object rest of attributes
                    $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $all_change_fields[$obj->id]));
                }
                # if need to change
                $i++;
            }
        }
        # if any selectvalue is to get
        # / get selectlist values
        ###################
    }
    # if parameters are OK
    $count = $alamlist->rows;
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $assets, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_rows' => $counttotal, $name . '_count' => $count));
}
function smarty_function_init_calendar($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    if ($site->fdat['year'] < 100 && $site->fdat['year']) {
        $site->fdat['year'] += 2000;
    }
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "cal";
    }
    if (!isset($object_class)) {
        $object_class = "artikkel";
    }
    if (!isset($hide_selectboxes)) {
        $hide_selectboxes = 0;
    }
    if (!isset($hide_weeknumbers)) {
        $hide_weeknumbers = 0;
    }
    if (!isset($hide_month_link)) {
        $hide_month_link = 0;
    }
    if (!isset($hide_today_link)) {
        $hide_today_link = 0;
    }
    if (!isset($parent)) {
        $url_id = $leht->id;
    } else {
        $url_id = $parent;
    }
    # Generate hidden fields & url-parameters from $fdat :
    if ($send_variables == 1) {
        $skip_arr = array('month', 'year', 'week', 'day', 'start_date', 'end_date', 'id');
        if (is_array($site->fdat)) {
            foreach ($site->fdat as $key => $val) {
                if (!in_array($key, $skip_arr) && $val) {
                    if (is_array($val)) {
                        $val2 = array_unique($val);
                        foreach ($val2 as $tmpval) {
                            $hid_var .= "<input type=hidden name=\"" . $key . "[]\" value=\"" . $tmpval . "\">\n";
                            $link_var .= "&" . $key . "[]=" . $tmpval;
                        }
                    } else {
                        $hid_var .= "<input type=hidden name=\"" . $key . "\" value=\"" . $val . "\">\n";
                        $link_var .= "&" . $key . "=" . $val;
                    }
                }
            }
        }
    }
    $img_path = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $site->CONF[hostname] . $site->CONF[wwwroot] . $site->CONF[img_path];
    #################
    # start_date, end_date
    # if parameter is given to function then change month and year values to correct ones
    if (isset($start_date)) {
        $isset_start_date = 1;
    }
    if (isset($site->fdat[start_date])) {
        $isset_url = 1;
    }
    # if start date or end date is not given by parameter in URL, take it from function parameter
    $start_date = $site->fdat[start_date] ? $site->fdat[start_date] : $start_date;
    $end_date = $site->fdat[end_date] ? $site->fdat[end_date] : $end_date;
    # take dd.mm.yyyy and split it
    list($sday, $smonth, $syear) = split('\\.', $start_date);
    $sday = intval($sday);
    $smonth = intval($smonth);
    $syear = intval($syear);
    if ($syear < 100 && $syear) {
        $syear += 2000;
    }
    list($eday, $emonth, $eyear) = split('\\.', $end_date);
    $eday = intval($eday);
    $emonth = intval($emonth);
    $eyear = intval($eyear);
    if ($eyear < 100 && $eyear) {
        $eyear += 2000;
    }
    ##################
    # find values in such priority order:
    # 1.parameters from URL
    # 2.parameters from function
    # 3.today values
    $month = $site->fdat['month'] ? $site->fdat['month'] : ($isset_start_date || $isset_url ? $smonth : date("n"));
    $year = $site->fdat['year'] ? $site->fdat['year'] : ($isset_start_date || $isset_url ? $syear : date("Y"));
    $day = $site->fdat['day'];
    $y = substr($year, 2);
    $selected_weeknumber = $site->fdat['week'];
    ##################
    # today values
    $cur_month = date("n");
    $cur_year = date("Y");
    $cur_day = date("j");
    ##################
    # find object counts foreach this month day
    $alamlistSQL = new AlamlistSQL(array(parent => $url_id, klass => $object_class, asukoht => 0));
    $first_day = mktime(0, 0, 0, $month, 1, $year);
    $last_day = mktime(0, 0, 0, $month + 1, 0, $year);
    if ($object_class == 'artikkel') {
        $alamlistSQL->add_select("DAYOFMONTH(obj_artikkel.starttime) AS start_day");
        $alamlistSQL->add_select("DAYOFMONTH(obj_artikkel.endtime) AS end_day");
        $alamlistSQL->add_from("LEFT JOIN obj_artikkel on objekt.objekt_id=obj_artikkel.objekt_id");
        $alamlistSQL->add_where("(MONTH(obj_artikkel.starttime) = '" . $month . "' OR MONTH(obj_artikkel.endtime) = '" . $month . "') AND (YEAR(obj_artikkel.starttime) = '" . $year . "' OR YEAR(obj_artikkel.endtime) = '" . $year . "') ");
    }
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL));
    $alamlist->debug->print_msg();
    $obj_exists = array();
    # loop this month events
    while ($obj = $alamlist->next()) {
        $i = 0;
        # if events start or end time matches with day
        # turn 'exists'-flag on for this day
        if ($object_class == 'artikkel') {
            for ($i = $obj->all[start_day]; $i <= $obj->all[end_day]; $i++) {
                $obj_exists[$i] = 1;
            }
        }
    }
    #################
    # javascript for changing month
    $html = '
	<SCRIPT LANGUAGE="JavaScript"><!--
	function prev() {
		if(document.cal.month.options.selectedIndex == 0) {
			document.cal.month.options.selectedIndex = 11;
			document.cal.year.options.selectedIndex = document.cal.year.options.selectedIndex-1;
		} else {
			document.cal.month.options.selectedIndex = document.cal.month.options.selectedIndex-1;
		}
		document.cal.submit();
		return false;
	}
	function next() {
		if(document.cal.month.options.selectedIndex == 11) {
			document.cal.month.options.selectedIndex = 0;
			document.cal.year.options.selectedIndex = document.cal.year.options.selectedIndex+1;
		} else {
			document.cal.month.options.selectedIndex = document.cal.month.options.selectedIndex+1;
		}
		document.cal.submit();
		return false;
	}
	//--></SCRIPT>
	';
    #################
    # form
    $html .= '
	<form name="cal" method="get" action="' . $site->self . '">
	' . $hid_var . '
	<input type=hidden name=id value="' . $url_id . '">
		  <table border="0" cellspacing="0" cellpadding="5" class="cal_maintable" width="170">';
    if ($hide_selectboxes != 1) {
        $html .= '<tr class="cal_selectbox_tr" align="center"> 
				<td style="padding-top: 5px; padding-bottom: 5px; padding-right: 3px; padding-left: 1px;"> 
				  <table border="0" cellspacing="0" cellpadding="0" width="100%">
					<tr> 
					  <td align="right" width="20"><a href="javascript:prev()"><img src="' . $img_path . '/cal_tagasi.gif" border="0"></a></td>
					  <td align="center" class="caltext" valign="top"> 
						<select class="drd" style="width: 90px" name="month" onChange="submit()">
	';
        ##### month select-box ######
        for ($i = 1; $i <= 12; $i++) {
            $html .= '<option value="' . $i . '"';
            if ($i == $month) {
                $html .= "selected";
            }
            $html .= '>' . $site->sys_sona(array(sona => "month" . $i, tyyp => "kalender")) . '</option>';
        }
        $html .= '
						</select>
					  </td>
					  <td width="20"><a href="javascript:next()"><img src="' . $img_path . '/cal_edasi.gif" border="0"></a></td>
					  <td class="caltext" valign="top" align="right"> 
						<select name="year" class="drd" onChange="submit()">
	';
        ##### year select-box ######
        for ($i = 2000; $i <= $cur_year + 3; $i++) {
            $html .= '<option value="' . $i . '"';
            if ($i == $year) {
                $html .= "selected";
            }
            $html .= '>' . $i . '</option>';
        }
        $html .= '
				</select>
			  </td>
			</tr>

		  </table>
		</td>
	  </tr>';
    }
    # if hide_selectboxes!=1
    $html .= '<tr align="center" class="cal_weekday_tr"> 
				<td class="caltext"> 
				  <table width="100%" border="0" cellpadding="0" cellspacing="2">
					<tr nowrap>';
    if ($hide_weeknumbers != 1) {
        $html .= '
					  <td align="right" class="caltext"><img src="' . $img_path . '/px.gif" width="20" height="1"> 
					  </td>';
    }
    $html .= '
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday1", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday2", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday3", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday4", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday5", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="13%"><b>' . $site->sys_sona(array(sona => "weekday6", tyyp => "kalender")) . '</b></td>
					  <td align="right" class="caltext" style="padding-bottom:3px; padding-right:6px;" width="14%"><b>' . $site->sys_sona(array(sona => "weekday7", tyyp => "kalender")) . '</b></td>
					</tr>
					<tr class="cal_spacer_tr" nowrap> 
					  <td colspan="';
    if ($hide_weeknumbers != 1) {
        $html .= '8';
    } else {
        $html .= '7';
    }
    $html .= '"><img src="' . $img_path . '/px.gif" width="1" height="1"></td>
					</tr>
	';
    $weekday = date("w", mktime(0, 0, 0, $month, 1, $year));
    $weeknumber = date("W", mktime(0, 0, 0, $month, 1, $year));
    if ($weekday == 0) {
        $weekday = $weekday + 7;
    }
    $daysnum = date("t", mktime(0, 0, 0, $month, 1, $year));
    ##################
    # 1st row start & weeknumber
    $weeklink = $site->self . "?id=" . $url_id . "&start_date=" . date("d.m.Y", get_monday($weeknumber, $year)) . "&end_date=" . date("d.m.Y", get_sunday($weeknumber, $year)) . "&week=" . $weeknumber . "&month=" . $month . "&year=" . $year . $link_var;
    $html .= '
		<tr align="center" nowrap>
		';
    if ($hide_weeknumbers != 1) {
        $html .= '<td align="right" class="cal"><a href="' . $weeklink . '" class="week">' . $weeknumber . '.</a></td>';
    }
    # empty spaces
    for ($j = 1; $j < $weekday; $j++) {
        $html .= '<td align="center" class="cal"></td>';
    }
    # paevade arv selles kuus:
    $days_qty = date("t", mktime(0, 0, 0, $month, 1, $year));
    ################
    # tsļæ½kkel ļæ½le pļæ½evade
    for ($i = 1; $i <= $daysnum; $i++) {
        $is_selected = 0;
        $is_between = 0;
        # link for 1 day
        $link = $site->self . "?id=" . $url_id . "&day=" . $i . "&month=" . $month . "&year=" . $year;
        $link .= "&start_date=" . date("d.m.Y", mktime(0, 0, 0, $month, $i, $year));
        $link .= "&end_date=" . date("d.m.Y", mktime(0, 0, 0, $month, $i, $year));
        $link .= $link_var;
        # current week number
        $weeknumber = date("W", mktime(0, 0, 0, $month, $i, $year));
        # set flag for convienence:
        # if current date is between startdate and endate
        if (mktime(0, 0, 0, $month, $i, $year) >= mktime(0, 0, 0, $smonth, $sday, $syear) && mktime(0, 0, 0, $month, $i, $year) <= mktime(0, 0, 0, $emonth, $eday, $eyear)) {
            $is_between = 1;
        }
        # RED: day is between start_date and end_date - make it red,
        # but if start/enddate is given as f-n parameter and some other selection is made, dont do so
        if ($is_between && !$day && !$selected_weeknumber) {
            $html .= '<td align="right" class="cal_actual"><a href="' . $link . '" class="today' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
            $is_selected = 1;
        } else {
            if ($i == $day) {
                $html .= '<td align="right" class="cal_actual"><a href="' . $link . '" class="today' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
                $is_selected = 1;
            } else {
                if (!$isset_start_date && !$day && !$selected_weeknumber && !$site->fdat[start_date] && !$site->fdat[end_date] && ($year == $cur_year && $month == $cur_month && $i == $cur_day)) {
                    $html .= '<td align="right" class="cal_actual"><a href="' . $link . '" class="today' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
                    $is_selected = 1;
                } else {
                    if ($weeknumber == $selected_weeknumber) {
                        $html .= '<td align="right" class="cal_actual"><a href="' . $link . '" class="today' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
                        $is_selected = 1;
                    } else {
                        if ($i == $cur_day && $year == $cur_year && $month == $cur_month) {
                            $html .= '<td align="right" class="cal_nottoday"><a href="' . $link . '" class="day' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
                        } else {
                            $html .= '<td align="right" class="cal"><a href="' . $link . '" class="day' . ($obj_exists[$i] ? "_bd" : "") . '">' . $i . '</a></td>';
                        }
                    }
                }
            }
        }
        #############
        # find selected start & end date
        if ($is_selected) {
            if (!$selected_start_date) {
                $selected_start_date = (strlen($i) == 1 ? "0" : "") . $i . "." . (strlen($month) == 1 ? "0" : "") . $month . "." . $year;
                #bugine					$selected_start_date =  $start_date;
                $selected_date = mktime(0, 0, 0, $month, $i, $year);
                $selection = 1;
            }
            # if selection goes on
            if ($selection) {
                $selected_end_date = (strlen($i) == 1 ? "0" : "") . $i . "." . (strlen($month) == 1 ? "0" : "") . $month . "." . $year;
                #					$selected_end_date = $end_date;
            }
        }
        # if not selected, but AFTER some selection, tehen interrupt selection flag
        if (!$is_selected && isset($selected_date) && mktime(0, 0, 0, $month, $i, $year) >= $selected_date) {
            $selection = 0;
        }
        #############
        # end of row, new start & week number
        if ($weekday++ % 7 == 0 && $i < $days_qty) {
            $weeknumber++;
            $weeklink = $site->self . "?id=" . $url_id . "&start_date=" . date("d.m.Y", get_monday($weeknumber + 1, $year)) . "&end_date=" . date("d.m.Y", get_sunday($weeknumber + 1, $year)) . "&week=" . $weeknumber . "&month=" . $month . "&year=" . $year . $link_var;
            $html .= '</tr>
				<tr align="center" nowrap>';
            if ($hide_weeknumbers != 1) {
                $html .= '<td align="right" class="cal"><a href="' . $weeklink . '" class="week">' . $weeknumber . '.</a></td>';
            }
        }
        # if
        # this month end date
        $month_end = $i . "." . ($month < 10 ? "0" . $month : $month) . "." . $year;
    }
    # empty spaces
    $last_weekday = date('w', mktime(0, 0, 0, $month, --$i, $year));
    if ($last_weekday) {
        # empty spaces
        for ($j = $last_weekday; $j < 7; $j++) {
            $html .= '<td align="center" class="cal"></td>';
        }
        //$html .= '</tr>'; // on seda vaja
    }
    # for ļæ½le pļæ½evade
    ####################
    # this month start date
    $month_start = "01." . ($month < 10 ? "0" . $month : $month) . "." . $year;
    ####################
    # links 'whole month', 'today'
    $html .= '</tr>';
    if (!($hide_month_link == 1 and $hide_today_link == 1)) {
        # in case we don't have both hidden
        $html .= '<tr class="cal_spacer_tr" nowrap> 
			  <td colspan="';
        if ($hide_weeknumbers != 1) {
            $html .= '8';
        } else {
            $html .= '7';
        }
        $html .= '"><img src="' . $img_path . '/px.gif" width="1" height="1"></td>
			</tr>';
        $html .= '
			<tr><td colspan="';
        if ($hide_weeknumbers != 1) {
            $html .= '8';
        } else {
            $html .= '7';
        }
        $html .= '">
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
			<tr nowrap> 
			  <td height="18" class="cal">';
        if ($hide_month_link != 1) {
            $html .= '<a class="day" href="' . $site->self . '?id=' . $url_id . '&month=' . $month . '&year=' . $year . '&start_date=' . $month_start . '&end_date=' . $month_end . $link_var . '">' . $site->sys_sona(array(sona => "whole month", tyyp => "kalender")) . '</a>';
        } else {
            $html .= '&nbsp;';
        }
        $html .= '
				</td>
			  <td align="right" class="cal" height="18">';
        if ($hide_today_link != 1) {
            $html .= '<a class="day" href="' . $site->self . '?id=' . $url_id . '&day=' . $cur_day . '&month=' . $cur_month . '&year=' . $cur_year . $link_var . '">' . $site->sys_sona(array(sona => "today", tyyp => "kalender")) . '</a>';
        } else {
            $html .= '&nbsp;';
        }
        $html .= '
			  </td>
			</tr>
		  </table>
			</td></tr>';
    }
    $html .= '</table>
		</td>
	  </tr>
	</table>
	</form>
	';
    ##############
    # assign to template variables
    $smarty->assign(array($name . '_html' => $html, $name . '_start_date' => $selected_start_date, $name . '_end_date' => $selected_end_date));
}
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
}
function smarty_function_init_picture($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "picture";
    }
    if (!isset($id)) {
        $id = $leht->id;
    }
    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);
    }
    $picture = new Objekt(array(objekt_id => $id));
    # we can have 2 object classes here: "pilt" and "file"
    # save class of the requested object for later
    $picture_class = $picture->all['klass'];
    ##############
    # load variables
    $picture->buttons = $picture->get_edit_buttons(array(tyyp_idlist => $picture->all['tyyp_id'], nupud => $buttons, publish => $publish));
    $picture->id = $picture->objekt_id;
    $picture->title = $picture->pealkiri;
    $picture->album_href = $picture->parent_id;
    $parent = $leht->parents->get(1);
    $alamlist_count = new Alamlist(array(parent => $picture->parent_id, klass => $picture_class, asukoht => 0, on_counter => 1));
    #PREVIOUS PICTURE
    $alamlistSQL = new AlamlistSQL(array(parent => $picture->parent_id, klass => $picture_class, asukoht => 0, order => "objekt_objekt.sorteering ASC"));
    $alamlistSQL->add_where("sorteering>'" . $picture->all['sorteering'] . "'");
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => 0, limit => 1));
    #NEXT PICTURE
    $alamlistSQL2 = new AlamlistSQL(array(parent => $picture->parent_id, klass => $picture_class, asukoht => 0));
    $alamlistSQL2->add_where("sorteering<'" . $picture->all['sorteering'] . "'");
    $alamlist2 = new Alamlist(array(alamlistSQL => $alamlistSQL2, start => 0, limit => 1));
    $prev_img = $alamlist->next();
    $next_img = $alamlist2->next();
    ## 1. img from filesystem (Bug #2316)
    if ($picture_class == 'file') {
        $sql = $site->db->prepare("SELECT * FROM obj_file WHERE objekt_id = ?", $picture->objekt_id);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        $result = $sth->fetch();
        $result['fullpath'] = preg_replace('#/$#', '', $site->absolute_path) . $result['relative_path'];
        //Find out if is picture or not
        if (preg_match("/(jpeg|png|gif)/", $result['mimetype'])) {
            /* is img */
            if (function_exists("getimagesize")) {
                list($i_width, $i_height, $i_type, $i_attr) = getimagesize($result['fullpath']);
            } else {
                $i_width = 720;
                $i_height = 470;
            }
            $picture->image_width = $i_width;
            $picture->image_height = $i_height;
            //Find out if we are in secure or public dir
            if (false !== strpos($result['fullpath'], $site->CONF['secure_file_path'])) {
                /* SECURE */
                $root_dir = $site->CONF['secure_file_path'];
            } else {
                /* PUBLIC */
                $root_dir = $site->CONF['file_path'];
            }
            if (preg_match("/^.*(" . str_replace('/', '\\/', $root_dir) . ".*)\$/", $result['fullpath'], $regs)) {
                $root_dir = preg_replace('/\\/[^\\/]+$/i', '', $regs[1]);
            } else {
                $root_dir = '..' . $root_dir;
            }
            $filepath = $site->CONF['wwwroot'] . $root_dir . '/' . $result['filename'];
            $source = "<img src=\"" . $filepath . "\" border=\"0\" />";
        }
        # if img type
    } elseif ($picture_class == 'pilt') {
        $source = "<img src=\"" . $site->CONF['wwwroot'] . ($site->admin ? "/editor" : "") . "/image.php?" . $picture->objekt_id . "\" border=\"0\" />";
        $thumbnail = "<img src=\"" . $site->CONF['wwwroot'] . ($site->admin ? "/editor" : "") . "/image.php?" . $picture->objekt_id . "t\" border=\"0\" alt =\"" . $picture->all['pealkiri'] . "\" />";
    }
    $picture->hit_count = $picture->all['count'];
    $picture->created_user_id = $picture->all['created_user_id'];
    $picture->created_user_name = $picture->all['created_user_name'];
    $picture->changed_user_id = $picture->all['changed_user_id'];
    $picture->changed_user_name = $picture->all['changed_user_name'];
    $picture->created_time = $site->db->MySQL_ee($picture->all['created_time']);
    $picture->fcreated_time = $picture->all['created_time'];
    $picture->changed_time = $site->db->MySQL_ee($picture->all['changed_time']);
    $picture->fchanged_time = $picture->all['changed_time'];
    $picture->last_commented_time = $site->db->MySQL_ee($picture->all['last_commented_time']);
    $picture->comment_count = $picture->all['comment_count'];
    $picture->show_headline = $picture->all['on_pealkiri'];
    ##############
    # assign to template variables
    $smarty->assign(array($name => $picture, $name . '_source' => $source, $name . '_thumbnail' => $thumbnail, $name . '_next' => $prev_img->objekt_id, $name . '_previous' => $next_img->objekt_id));
    $smarty->assign($name, $picture);
    //return $picture; Bug #1921 # for {init_object} tag
}