function execSearch()
 {
     global $site;
     if ($this->ok) {
         $this->show_exec_times = $_COOKIE['debug'] ? true : false;
         // bug #2477, hidden objects must be excluded
         $this->query_sql->add_where("objekt.is_hided_in_menu = '0'");
         if ($this->show_exec_times) {
             printr($site->timer->get_aeg() . ' - alamlist');
         }
         $query_result = new Alamlist(array('alamlistSQL' => $this->query_sql));
         if ($this->show_exec_times) {
             $query_result->debug->print_msg();
         }
         if ($this->show_exec_times) {
             printr($site->timer->get_aeg() . ' - done, get tree');
         }
         $object_parent_array = array();
         $sql = 'select objekt_id, parent_id from objekt_objekt;';
         $result = new SQL($sql);
         while ($row = $result->fetch('ASSOC')) {
             $object_parent_array[] = $row;
         }
         $objArray = new ObjectParentArray($object_parent_array);
         if ($this->show_exec_times) {
             printr($site->timer->get_aeg() . ' - done, start exclude all but homesection');
         }
         while ($object = $query_result->next()) {
             $parent_id = $objArray->find_parent((string) $object->objekt_id);
             $loop_guard = 0;
             $loop_ids = array();
             while ($parent_id) {
                 $loop_guard++;
                 if (!in_array($parent_id, $loop_ids)) {
                     $loop_ids[] = $parent_id;
                 }
                 if ($loop_guard > 100) {
                     new Log(array('component' => 'Search', 'type' => 'ERROR', 'message' => 'Neverending loop! ID list: ' . implode(',', $loop_ids), 'user_id' => 0));
                     exit;
                 }
                 if (in_array($parent_id, $this->section_id)) {
                     $this->result_objects[$object->all['klass']][] = $object;
                     $this->search_count++;
                     break;
                 }
                 $parent_id = $objArray->find_parent($parent_id);
             }
         }
         if ($this->show_exec_times) {
             printr($site->timer->get_aeg() . ' - done, ');
         }
     }
 }
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)));
}
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));
}
}
$parent_id = (int) $_GET['parent_id'];
$language_id = (int) $_GET['lang'];
// object classes
$classes = (array) $_SESSION[$swk_setup]['classes'];
if (empty($classes)) {
    $classes = array('rubriik', 'artikkel');
}
// fields to pull from db
$fields = $_SESSION[$swk_setup]['db_fields'];
if (empty($fields)) {
    $fields = array('select_checkbox', 'objekt_id', 'pealkiri', 'tyyp_id');
}
if (isset($parent_id)) {
    $objects_sql = new AlamlistSQL(array('parent' => $parent_id, 'klass' => implode(',', $classes), 'where' => 'keel = ' . $language_id));
    $objects_list = new Alamlist(array('alamlistSQL' => $objects_sql));
    $objects = array();
    while ($object = $objects_list->next()) {
        // translations
        if ($object->all['klass']) {
            $object->all['klass'] = strtolower($site->sys_sona(array('sona' => 'tyyp_' . $object->all['klass'], 'tyyp' => 'System')));
        }
        //convert dates
        if ($object->all['aeg']) {
            $object->all['aeg'] = $site->db->MySQL_ee($object->all['aeg']);
        }
        $objects[] = $object->all;
    }
    //printr($objects);
    if (count($objects)) {
        //this header makes prototype.js eval() the response
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));
}
/**
 * creates a array of files for filemanager from objekt list
 *
 * @param Alamlist $list
 * @return array
 */
function get_files_list($list)
{
    global $site;
    $files = array();
    while ($file = $list->next()) {
        if (strpos($file->all['relative_path'], $site->CONF['file_path']) === 0 || strpos($file->all['relative_path'], $site->CONF['secure_file_path']) === 0) {
            $thumbnail_file = str_replace($file->all['filename'], '.thumbnails/' . $file->all['filename'], $file->all['relative_path']);
            $thumbnail_path = preg_replace('#/$#', '', $site->absolute_path) . $thumbnail_file;
            $pathinfo = pathinfo($file->all['relative_path']);
            $pathinfo['extension'] = strtolower($pathinfo['extension']);
            if (file_exists($thumbnail_path)) {
                $thumbnail_url = $site->CONF['wwwroot'] . $thumbnail_file;
            } else {
                $thumbnail_path = $site->absolute_path . $site->CONF['styles_path'] . '/gfx/icons/48x48/mime/' . $pathinfo['extension'] . '.png';
                if (file_exists($thumbnail_path)) {
                    $thumbnail_url = $site->CONF['wwwroot'] . $site->CONF['styles_path'] . '/gfx/icons/48x48/mime/' . $pathinfo['extension'] . '.png';
                } else {
                    $thumbnail_url = $site->CONF['wwwroot'] . $site->CONF['styles_path'] . '/gfx/icons/48x48/mime/unknown.png';
                }
            }
            $files[$file->objekt_id] = array('title' => $file->all['pealkiri'], 'objekt_id' => $file->objekt_id, 'thumbnail' => $thumbnail_url, 'size' => $file->all['size'], 'hr_size' => human_readable_file_size($file->all['size']), 'mimetype' => $file->all['mimetype'], 'filename' => $file->all['filename'], 'extension' => $pathinfo['extension'], 'folder' => str_replace('/' . $file->all['filename'], '', $file->all['relative_path']), 'parent_id' => $file->parent_id, 'date' => $file->all['aeg'], 'hr_date' => $site->db->MySQL_ee($file->all['aeg']), 'permissions' => $file->permission);
        }
    }
    return $files;
}
function print_kast($kast, $is_custom = 0, $archive_link_on = 1)
{
    #Muutujad mis hoiab custom stringid
    $custom_buttons = '';
    $custom_title = '';
    $custom_contents = '';
    if (get_class($kast) == "Objekt" || is_subclass_of($kast, "Objekt")) {
        # ----------------------------
        # Uudiste kogumik
        # ----------------------------
        if ($kast->all[klass] == "kogumik") {
            $kast->load_sisu();
            if (!$is_custom) {
                ?>
				<table width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" border="0" cellspacing="0" cellpadding="1">
				  <tr> 
					<td width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" class="boxhead" height="24">
					&nbsp;&nbsp;<?php 
                echo $kast->pealkiri();
                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                ?>
</td>
				  </tr>
				  <tr> 
					<td width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout");
                ?>
" bgcolor="<?php 
                echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                ?>
"> 
					  <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="<?php 
                echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                ?>
">
						<tr> 
						  <td align="right" valign="top"><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="20" height="10"></td>
						  <td><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="<?php 
                echo $kast->site->dbstyle("menyy_laius", "layout") - 42;
                ?>
" height="10"></td>
						  <td><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="20" height="10"></td>
						</tr>
<?php 
            } else {
                //Custom print out
                ob_start();
                $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                $custom_buttons .= ob_get_contents();
                ob_end_clean();
                $custom_title .= $kast->pealkiri();
                $custom_contents .= "<ul class=\"boxlist\">";
            }
            //if is_custom
            # rubriigid kus uudised otsida
            $sql = "SELECT objekt.objekt_id FROM objekt LEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id WHERE objekt_objekt.parent_id=" . $kast->objekt_id . " AND (objekt.kesk = 0 or objekt.kesk = 5 or objekt.kesk = 9) AND objekt.tyyp_id=1";
            ####### POOLELI
            if (!$kast->site->in_editor) {
                $sql .= " AND objekt.on_avaldatud=1";
            }
            if (!$kast->site->in_editor) {
                $sql .= " AND !FIND_IN_SET(objekt.objekt_id, '" . join(",", $kast->site->noaccess_hash) . "')";
            }
            $sth = new SQL($sql);
            while ($rid = $sth->fetchsingle()) {
                $news_rubrics .= "," . $rid;
            }
            $kast->debug->msg($sth->debug->get_msgs());
            $kast->debug->msg("Rubriigid: {$news_rubrics}");
            $sql = "\r\n\t\t\t\t\t\t\tSELECT objekt.objekt_id, objekt.pealkiri, objekt.aeg, objekt.on_avaldatud, objekt_objekt.parent_id \r\n\t\t\t\t\t\t\tFROM objekt \r\n\t\t\t\t\t\t\tLEFT JOIN objekt_objekt ON objekt_objekt.objekt_id=objekt.objekt_id \r\n\t\t\t\t\t\t\tWHERE find_in_set(objekt_objekt.parent_id,'{$news_rubrics}') AND (objekt.kesk=0 OR objekt.kesk=6) AND (objekt.tyyp_id=2 OR objekt.tyyp_id=15)";
            if (!$kast->site->in_editor) {
                $sql .= " AND objekt.on_avaldatud=1  ";
            }
            $sql .= " ORDER BY objekt.aeg DESC, objekt_objekt.sorteering DESC limit 0," . ($kast->all[art_arv] ? $kast->all[art_arv] : 5);
            $kast->debug->msg($sth->debug->get_msgs());
            $sth = new SQL($sql);
            $kast->debug->msg("Leitud " . $sth->rows . " alamobjekte");
            $esimene = 1;
            while ($ary = $sth->fetch()) {
                $kast->debug->msg("Objekt leitud: {$ary['objekt_id']}. " . $ary[pealkiri]);
                $obj = new Objekt(array(ary => $ary));
                if (!$is_custom) {
                    if (!$esimene) {
                        # eraldaja
                        ?>
								<tr valign="top"> 
								  <td align="right" valign="top"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="20" height="10"></td>
								  <td background="<?php 
                        echo $kast->site->img_path;
                        ?>
/stripe1.gif"><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="1" height="10"></td>
								  <td><img src="<?php 
                        echo $kast->site->img_path;
                        ?>
/px.gif" width="20" height="10"></td>
								</tr>
<?php 
                    }
                    if ($obj->site->in_editor) {
                        ?>
								
								<!--tr valign="top"> 
									<td colspan="3" align=left>&nbsp; &nbsp;
									
									</td>
								</tr-->
<?php 
                    }
                    # if in_editor
                    ?>
								<tr valign="top"> 
								  <td align="right" valign="top"><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/nupp1.gif" width="10" height="10" align="texttop"></td>
								  <td><a href="<?php 
                    echo $kast->site->self;
                    ?>
?id=<?php 
                    echo $obj->objekt_id;
                    ?>
" class="navi2_on"><?php 
                    echo $obj->pealkiri();
                    ?>
</a><?php 
                    echo $kast->all[on_kp_nahtav] ? "<br><font class=txt><font class=date>" . $obj->aeg() . "</font></font>" : "";
                    $obj->edit_buttons(array(tyyp_idlist => 3, only_edit => 1));
                    ?>
</td>
								  <td><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="20" height="10"></td>
								</tr>
<?php 
                    $esimene = 0;
                } else {
                    //Custom print out
                    if ($obj->site->in_editor) {
                        ob_start();
                        $obj->edit_buttons(array(tyyp_idlist => 3, only_edit => 1));
                        $custom_contents .= ob_get_contents();
                        ob_end_clean();
                    }
                    if ($kast->all[on_kp_nahtav]) {
                        $cu_date = '&nbsp;&nbsp;<font class=date>' . $obj->aeg() . ' </font>';
                    } else {
                        $cu_date = '';
                    }
                    $custom_contents .= '<li class="list"><a href="' . $kast->site->self . '?id=' . $obj->objekt_id . '" class="navi2_on">' . $obj->pealkiri() . $cu_date . '</a>' . '</li>' . ($obj->site->in_editor ? "<br clear=all>" : "");
                }
                //if is_custom
            }
            # while
            if (!$is_custom) {
                ?>
						<tr> 
						  <td colspan="3"><img src="<?php 
                echo $kast->site->img_path;
                ?>
/px.gif" width="1" height="10"></td>
						</tr>
					  </table>
					</td>
				  </tr>
				</table>
							  <br>
<?php 
            } else {
                $custom_contents .= "</ul>";
            }
            //if is_custom
        } else {
            if ($kast->all[klass] == "rubriik") {
                # ----------------------------
                # Lingide kast
                # ----------------------------
                if (!$is_custom) {
                    ?>
        <table width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" border="0" cellspacing="0" cellpadding="1">
          <tr> 
            <td width="100%" class="boxhead" height="24">
		&nbsp;&nbsp;<?php 
                    echo $kast->pealkiri();
                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17"));
                    ?>
</td>
          </tr>
          <tr> 
            <td width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout");
                    ?>
" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_border", "color") ? $kast->site->dbstyle("menyy_border", "color") : "#CCCCCC";
                    ?>
"> 
              <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="<?php 
                    echo $kast->site->dbstyle("menyy_taust", "color") ? $kast->site->dbstyle("menyy_taust", "color") : "#FAFAFA";
                    ?>
">
				<tr> 
                  <td align="right" valign="top"><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="20" height="10"></td>
                  <td><img src="<?php 
                    echo $kast->site->img_path;
                    ?>
/px.gif" width="<?php 
                    echo $kast->site->dbstyle("menyy_laius", "layout") - 52;
                    ?>
" height="10" border=0></td>

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

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

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

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

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

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


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

 </td>
 </tr>        
 </table>
	 <br>
<?php 
                } else {
                    //Custom print out
                    ob_start();
                    $kast->edit_buttons(array(tyyp_idlist => "8,2,6,9,13,17", no_br => 1));
                    $custom_buttons .= ob_get_contents();
                    ob_end_clean();
                    $custom_title .= $kast->site->sys_sona(array(sona => 'new', tyyp => "editor"));
                }
                //if is_custom
            }
            # if ! size > 0
        } else {
            $GLOBALS[site]->debug->msg("print_kast() argument \"kast\" on vale");
        }
    }
    #print "<br>";
    return array('buttons' => $custom_buttons, 'title' => $custom_title, 'contents' => $custom_contents);
}
 function InitTree(&$opArray, $open_objects, $load_object_fields, $classes, $language_id = 0)
 {
     global $site;
     //global $timer;
     //echo '<!-- start InitTree: '.$timer->get_aeg().' -->';
     $this->opArray =& $opArray;
     $this->open_objects = (array) $open_objects;
     $this->load_object_fields = (array) $load_object_fields;
     $this->classes = (array) $classes;
     $this->language_id = $language_id;
     $langs = array();
     if (count($this->load_object_fields) == 0) {
         $this->load_object_fields = array('objekt_id', 'pealkiri', 'on_avaldatud', 'tyyp_id');
     }
     //echo '<!-- start load open objects: '.$timer->get_aeg().' -->';
     //init open objects
     foreach ($this->open_objects as $i => $object_id) {
         if ($object_id) {
             $object = new Objekt(array('objekt_id' => $object_id));
             //not an object or no permissions
             if ($object->objekt_id && $object->all['keel'] == $this->language_id) {
                 $this->addObject($object->all);
                 $this->objects[$object->objekt_id]['select_checkbox'] = 0;
             } else {
                 unset($this->open_objects[$i]);
             }
         }
     }
     //set open object id's into cookie
     setcookie('swk_unfolded_ids', implode(',', $this->open_objects));
     //echo '<!-- end load open objects: '.$timer->get_aeg().' -->';
     // /init open objects
     //printr($this->objects);
     // init open objects children
     //echo '<!-- start load open objects children: '.$timer->get_aeg().' -->';
     foreach ($this->open_objects as $object_id) {
         $objects_sql = new AlamlistSQL(array('parent' => $object_id, 'klass' => implode(',', $this->classes), 'where' => 'keel = ' . mysql_escape_string($language_id)));
         //$objects_sql->add_select('objekt.pealkiri');
         $objects_list = new Alamlist(array('alamlistSQL' => $objects_sql));
         $objects = array();
         while ($object = $objects_list->next()) {
             $this->addObject($object->all);
             $this->objects[$object->objekt_id]['select_checkbox'] = 0;
         }
     }
     // /init open objects children
     //echo '<!-- end InitTree: '.$timer->get_aeg().' -->';
 }
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));
}
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_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 Parents()
 {
     $args = func_get_arg(0);
     $this->ObjektArray();
     $this->meta = array();
     if (is_object($args['parent']) && !strcasecmp(get_class($args['parent']), 'Objekt')) {
         # parent on objekt
         $this->parent_id = $args["parent"]->objekt_id;
         $this->debug->msg("Parents. Antud on objekt: parent_id = " . $this->parent_id);
     } elseif (preg_match("/^\\d+\$/", $args["parent"])) {
         # parent on objekti ID
         $this->parent_id = $args["parent"];
         $this->debug->msg("Parents. Antud on objekti ID: parent_id = " . $this->parent_id);
     } else {
         # parent on vigane
         $this->debug->msg("vigased algandmed: \"{$args['parent']}\" pole objekt ega objekti ID");
     }
     # merle h�mar kommentaar "lisa_objekt"-ile: mulle tundub, et see on vajalik situatsioonis,
     # kus URL-i peal id puudub JA tegu on vana fiks. op-malliga: siis "on meil eriobjekt"
     # ja oleks vaja seda op-malli n�idata HOME rubriigi all ja seep�rast lisatakse parentsi l�ppu objekt HOME.
     if ($args["lisa_objekt"]) {
         $this->add($args["lisa_objekt"]);
     }
     if ($this->parent_id) {
         $id = $this->parent_id;
         $this->debug->msg("Parents. Alguses parent_id = " . $this->parent_id);
         $idid = array();
         # juhul kui HOME, on vaja �he sammu v�rra alla minna
         if ($args["on_esileht"]) {
             $this->debug->msg("Antud HOME rubriik, h�ppame �he taseme v�rra alla");
             $alamlist = new Alamlist(array("parent" => $id, "start" => 0, "limit" => 1, "klass" => 'rubriik', "order" => "objekt.kesk asc, sorteering DESC"));
             $this->debug->msg($alamlist->debug->get_msgs());
             if ($alamlist->size) {
                 $obj = $alamlist->get(0);
                 $id = $obj->objekt_id;
                 $this->debug->msg("Uus ID = {$id}");
             } else {
                 $this->debug->msg("Kahjuks alla h�pata ei saa... Pole sobivat kohta");
             }
         }
         $this->aktiivne_id = $id;
         #############################
         # allah�ppamine
         $this->debug->msg("JUMP: ================START================");
         $this->debug->msg("Jump down? " . ($this->site->in_editor || $this->site->in_admin ? "We are in editor-area or admin-area => abort mission" : "We are in public area => start mission"));
         # We are in public area => start missio:
         if (!($this->site->in_editor || $this->site->in_admin)) {
             do {
                 $last_id = $id;
                 $obj = new Objekt(array("objekt_id" => $id));
                 $this->debug->msg($obj->debug->get_msgs());
                 #####################
                 # kui objekt on rubriik JA talle pole ei lehe- ega sisumalli m��ratud
                 # siis tuleb objekti auto avanemine ise otsustada.
                 # variante on 2:
                 if ($obj->all[klass] == "rubriik" && !$obj->all["page_ttyyp_id"] && !$obj->all["ttyyp_id"]) {
                     $obj->all["on_auto_avanev"] = $this->site->master_tpl["on_auto_avanev"];
                     $this->debug->msg("JUMP: Auto avanemise m��rab saidi p�himall (ID=" . $this->site->master_tpl[ttyyp_id] . ")" . $this->site->master_tpl["on_auto_avanev"]);
                 } elseif ($obj->all["page_ttyyp_id"] && !$obj->all["ttyyp_id"]) {
                     $sql = $this->site->db->prepare("SELECT on_auto_avanev FROM templ_tyyp WHERE ttyyp_id=?", $obj->all["page_ttyyp_id"]);
                     $sth = new SQL($sql);
                     $obj->all["on_auto_avanev"] = $sth->fetchsingle();
                 }
                 $this->debug->msg("JUMP: Tulemus: objekt " . $obj->objekt_id . " " . ($obj->all["on_auto_avanev"] ? "ON" : "EI OLE") . " auto avanev ");
                 # juhul, kui malli on_auto_avanev = 1,
                 # siis hakka pihta
                 if ($obj->all["on_auto_avanev"]) {
                     # kontrollime objektide olemasolu
                     $alamlist = new Alamlist(array("parent" => $obj->objekt_id, "on_counter" => 1, "not_klass" => "rubriik,loginkast,kogumik,link", "order" => "sorteering DESC"));
                     $this->debug->msg($alamlist->debug->get_msgs());
                     # alamlist on tyhi
                     if ($alamlist->rows == 0) {
                         $this->debug->msg("JUMP: Otsime esimest alamrubriiki, kuhu v�iks h�pata");
                         $alamlist = new Alamlist(array("parent" => $obj->objekt_id, "start" => 0, "klass" => "rubriik", "not_tyyp_nimi" => "Lingikast"));
                         $this->debug->msg($alamlist->debug->get_msgs());
                         # kui leiti alamrubriik vaata talle otsa ja p��a teda lisada
                         if ($alamlist->rows > 0) {
                             $obj = $alamlist->next();
                             $this->debug->msg($alamlist->debug->get_msgs());
                             # kui ei �nnestunud objekti korralikult k�tte saada (polnud �iguseid)
                             # siis nendi fakti ja �ra h�ppa alla
                             if (!$obj->objekt_id) {
                                 $this->debug->msg("JUMP: Objekti ei tehtud, ei h�ppa alla");
                             } else {
                                 # JUMP REALLY DOWN here:
                                 $this->debug->msg("JUMP: H�ppasime alla ja n��d on aktiivne id = " . $obj->objekt_id);
                                 $id = $obj->objekt_id;
                             }
                             # kas objekt on vaatamiseks tibens
                         } else {
                             $this->debug->msg("JUMP: Ei h�ppa alla, sest polnud rubriiki, kuhu h�pata");
                         }
                     } else {
                         $this->debug->msg("JUMP: Ei h�ppa alla, sest leiti alamobjekte!");
                     }
                 }
             } while ($last_id !== $id);
         }
         # to jump or not to jump
         $this->aktiivne_id = $id;
         $this->debug->msg("JUMP: ================END================");
         # / allah�ppamine
         #############################
         #############################
         # loop over parents
         $first = 1;
         $i = 0;
         while ($id) {
             # hakkame antud objektist �lesse minna
             #######################
             # if current object, do extra checks:
             # 1) decide which parent to use from now on
             # 2) check if object's language matches with site language
             if ($first || $i == 1) {
                 # if first or second (if we have sub-article as current object, Bug #1955)
                 $obj_parent = "";
                 # 1. ja 2. objekti p�ritakse 2 korda (pole ilus lahendus, hetkel h�davajadus):
                 # 1. kord selleks, et teada saada tema klass
                 $obj = new Objekt(array("objekt_id" => $id, "no_cache" => 1));
                 #################
                 # 1) if current object is article, then start searching parents (we have to find correct parent)
                 if ($obj->all["klass"] == "artikkel") {
                     $this->debug->msg("Current object" . ($i == 1 ? "'s parent" : "") . " is article. Start doing extra check.");
                     # find all parent id-s of this object
                     #####################
                     # 1a. if found more than 1 parent => go on and find right parent
                     if ($obj->all['parents_count'] > 1) {
                         $all_parents = $obj->get_obj_all_parents($obj->objekt_id);
                         # v6ttame maha prygikasti rubriik parenti listist:
                         if ($this->site->alias("trash")) {
                             if (in_array($this->site->alias("trash"), $all_parents)) {
                                 $all_parents = array_diff($all_parents, array($this->site->alias("trash")));
                             }
                         }
                         $this->debug->msg("Object " . $obj->objekt_id . " has " . sizeof($all_parents) . " parents: " . join(",", $all_parents));
                         # get cookie with previous page current section value
                         #$cookie_parent = $this->site->sess_get("current_section");
                         $cookie_parent = $_COOKIE["current_section"];
                         ###################
                         # parent_id in URL (Bug #538)
                         # new feature: parameter "parent_id" in URL, it overrides "current_section" cookie settings
                         if ($this->site->fdat['parent_id']) {
                             $obj_parent = $this->site->fdat['parent_id'];
                             $this->debug->msg("Parent found in URL. Parent set to: " . $obj_parent);
                         } elseif (is_array($_SESSION['alias'])) {
                             #Alias being used and a direct path to the object is being shown.
                             foreach ($_SESSION['alias'] as $cuuki) {
                                 if ($cuuki['objekt_id'] == $obj->objekt_id) {
                                     $obj_parent = $cuuki['parent_id'];
                                 }
                             }
                         }
                         ###################
                         # if cookie has value, go on
                         if ($cookie_parent && $obj_parent == "") {
                             $this->debug->msg("Found current_section cookie: " . $cookie_parent);
                             # if 1 object parent is same as cookie, take this for parent
                             if (in_array($cookie_parent, $all_parents)) {
                                 $obj_parent = $cookie_parent;
                                 $this->debug->msg("Parent set to:" . $obj_parent);
                             } else {
                                 $this->debug->msg("Cookie doesn't match. Searching match from parents...");
                                 foreach ($all_parents as $par) {
                                     # find all parents for parent
                                     $all_parents = $obj->get_obj_all_parents($par);
                                     # if 1 object parent is same as cookie, take this for parent
                                     if (in_array($cookie_parent, $all_parents)) {
                                         $obj_parent = $par;
                                         $this->debug->msg("Parent set to:" . $obj_parent);
                                         break;
                                     }
                                 }
                                 # foreach
                                 if (!$obj_parent) {
                                     $this->debug->msg("No match found in parents. Parent not set.");
                                 }
                             }
                             # if not match
                         } else {
                             $this->debug->msg("I have no idea, which parent to prefer => choosing just the first one");
                         }
                         # / just pick first parent - we have no info which one to prefer
                         ###################
                     }
                     # / if found more than 1 parent, go on
                     #####################
                 }
                 # / if current object is article, then start searching parents
                 #################
                 # 2) check if object's language matches with site language
                 # bug #2398 : skip language check and automatic langchange for folders, files.
                 # bug #2661 : Sisuobjekti detailvaate lingile lisatud ?lang=en parameeter peab alati m�juma (site classis v�etakse fdat->keel m�lemast parameetrist juba)
                 if ($obj->objekt_id && !in_array($obj->all['tyyp_id'], array(21, 22)) && !isset($this->site->fdat['keel'])) {
                     $this->debug->msg("Language check: current object (ID=" . $obj->objekt_id . ") language is: " . $obj->all[keel] . "; site language is: " . $this->site->keel);
                     # if they differ, change site language
                     if ($obj->all[keel] != $this->site->keel) {
                         $this->site->change_keel($obj->all[keel]);
                         $this->debug->msg("Site language set to: " . $obj->all[keel]);
                     }
                 }
                 $no_cache = 1;
             } else {
                 $obj_parent = "";
                 $no_cache = 0;
             }
             # / if current object, decide which parent to use from now on
             #######################
             ###################
             # create object
             $obj = new Objekt(array("objekt_id" => $id, "parent_id" => $obj_parent, "no_cache" => $no_cache));
             $this->debug->msg($obj->debug->get_msgs());
             # if creating object fails (because of wrong parent), do it without parent
             if (!$obj->objekt_id) {
                 $obj = new Objekt(array("objekt_id" => $id, "no_cache" => 1));
                 $this->debug->msg($obj->debug->get_msgs());
             }
             ############# if creating object still fails then QUIT because PARENT IS FORBIDDEN
             if (!$obj->objekt_id) {
                 $this->debug->msg("PARENTS: Kuna �ks parentitest on keelatud siis l�peta kogu t�� ja reseti parents");
                 $this->list = array();
                 $this->objekts = array();
                 $this->set_size();
                 $this->index = -1;
                 return;
             } elseif (!$idid["id" . $id]) {
                 # viimases rubriigis vaatame on_peida_vmenyy v��rtus
                 if ($obj->all["klass"] == "rubriik" && !isset($on_peida_vmenyy)) {
                     $obj->load_sisu();
                     $on_peida_vmenyy = $obj->all["on_peida_vmenyy"];
                     $this->debug->msg("Aktiivse rubriigi on_peida_vmenyy is: " . $obj->all["on_peida_vmenyy"]);
                 }
                 # lisame objekt
                 $this->add($obj);
                 # meta
                 if ($this->meta["keywords"] == "" && $obj->all["meta_keywords"] != "") {
                     $this->meta["keywords"] = $obj->all["meta_keywords"];
                     $this->debug->msg("meta keyword = " . $this->meta["keywords"]);
                 }
                 if ($this->meta["description"] == "" && $obj->all["meta_description"] != "") {
                     $this->meta["description"] = $obj->all["meta_description"];
                     $this->debug->msg("meta description = " . $this->meta["description"]);
                 }
                 if ($this->meta["title"] == "" && $obj->all["meta_title"] != "") {
                     $this->meta["title"] = $obj->all["meta_title"];
                     $this->debug->msg("meta title = " . $this->meta["title"]);
                 }
                 $idid["id" . $id] = 1;
                 ############################
                 # set next ID
                 $id = $obj->parent_id;
                 ############################
                 # set next ID exception: 18.05.03 by merle
                 # force another parent for system article:
                 # if object is system article, then dont proceed with its real parent (system section)
                 # but force its parent to be first page in the site
                 if ($first && $obj->parent_id == $this->site->alias("system") && $obj->all["klass"] == "artikkel") {
                     $this->debug->msg("Current object is system article: " . $obj->all[sys_alias]);
                     $home_alamlist = new Alamlist(array("parent" => $this->site->alias("rub_home_id"), "start" => 0, "limit" => 1, "tyyp" => 'rubriik'));
                     if ($home_alamlist->size) {
                         $home_obj = $home_alamlist->get(0);
                         $id = $home_obj->objekt_id;
                         $this->debug->msg("Because its system article, parent is forced to be: {$id}");
                     } else {
                         $this->debug->msg("Setting new parent for system article failed - not found any section");
                     }
                 }
                 # force another parent for system article:
                 ############################
             } else {
                 $idid["id" . $id] = 1;
                 $id = '';
             }
             $i++;
             $first = 0;
         }
         # while obj
         # / loop over parents
         ####################
         $this->on_peida_vmenyy = $on_peida_vmenyy;
         #defined("on_peida_vmenyy") ? constant("on_peida_vmenyy"):0;
     }
     # if parent
 }
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));
}
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));
}
						# 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()) {	

						?>
							<tr> 
							  <td nowrap>
							<?
							$obj->edit_buttons(array(
								nupud => array("new","edit","hide","delete"),
								tyyp_idlist => "2",
								keel => $keel_id
							));
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));
}
/**
 * Used by {print_box} API function
 *
 */
function print_kastid()
{
    # -------------------------------
    # kastid antud asukohaga
    # print_kastid (array(
    #	leht => $leht,
    #	template => $template, (kas leht v�i template peab olema)
    #	asukoht => 8,
    #	on_td	=> 0/1,
    # ))
    # -------------------------------
    $args = func_get_arg(0);
    $custom_objs = array();
    if ($args[template]) {
        $leht =& $args[template]->leht;
    } else {
        $leht =& $args[leht];
    }
    if ($args[parent_id]) {
        $parent_id = $args[parent_id];
    } elseif ($args[asukoht] == 8) {
        $parent_id = $leht->parents->get(0);
    } else {
        $parent_id = $leht->parents->get(-2);
    }
    if ($args[is_custom]) {
        $is_custom = $args[is_custom];
    } else {
        $is_custom = 0;
    }
    $leht->debug->msg("Kastid asukoht = {$args['asukoht']}, parent_id = " . (is_object($parent_id) ? $parent_id->objekt_id : $parent_id));
    $aken_alamlist = new Alamlist(array(parent => is_object($parent_id) ? $parent_id->objekt_id : $parent_id, asukoht => $args[asukoht]));
    if ($aken_alamlist->size || $leht->site->admin) {
        if ($args[on_td]) {
            ?>
<td width="<?php 
            echo $leht->site->dbstyle("menyy_laius", "layout");
            ?>
" align="center" class=box><?php 
        }
        # added 12.12.2003 by Dima Bug #744
        $sql = "SELECT COUNT(*) FROM obj_gallup WHERE on_avatud = '0'";
        $sth = new SQL($sql);
        $leht->site->debug->msg($sth->debug->get_msgs());
        $archive_link_on = $sth->fetchsingle() ? 1 : 0;
        # //
        include_once "kast.php";
        while ($kast = $aken_alamlist->next()) {
            $custom_objs[] = print_kast($kast, $is_custom, $archive_link_on);
            $was_printed = 1;
        }
        $is_not_empty = print_kast($aken_alamlist, $is_custom);
        if (!empty($is_not_empty[buttons])) {
            $custom_objs[] = $is_not_empty;
        }
    }
    if ($args[on_td]) {
        ?>
</td><?php 
    }
    if ($is_custom) {
        return $custom_objs;
    } else {
        return $was_printed;
    }
}
            $site->debug->msg($sth16->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, ($system_admin ? " removed from Recycle Bin " : "deleted") . $unlink_err)));
            ?>
		<script type="text/javascript">
			window.opener.location=mylocation;
			window.close();
		</script>
<?php 
            exit;
        } else {
            # ------------------
            # K�sime kinnitust
            # ------------------
            $kinnitus = $site->sys_sona(array(sona => "tyyp_" . $tyyp['nimi'], tyyp => "System")) . ' "<b>' . $objekt->pealkiri . '</b>": ' . $site->sys_sona(array(sona => "do you want to permanently delete", tyyp => "editor"));
            if ($objekt->all[klass] == "rubriik") {
                $alam_list = new Alamlist(array(parent => $objekt, klass => 'rubriik'));
                $alamrubriigid = array();
                while ($rubriik = $alam_list->next()) {
                    array_push($alamrubriigid, $rubriik->pealkiri);
                }
            } elseif ($objekt->all[klass] == "artikkel") {
            }
            ##################### print permanent remove confirm
            if (!$hidden_output) {
                ?>
<form action="<?php 
                echo $site->self;
                ?>
" method=get>
<?php 
                create_form_token('delete-object');
	# $alamlist_count - kui palju üldse kommentaare on, parent jaoks

	$alamlist_count = new Alamlist(array(
		parent => $curr_obj->parent_id,
		klass	=> "kommentaar",
		asukoht	=> 0,
		on_counter => 1		
	));
	
	
	# Siin valime viimane kommentaar, parent jaoks
	
	$alamlist = new Alamlist(array(
		parent => $curr_obj->parent_id,
		klass	=> "kommentaar",
		start =>$alamlist_count->rows-1,
		limit =>1,
		asukoht	=> 0,
		order => " objekt.aeg, objekt.objekt_id ASC ",
	));

	# $alamlist_count - kui palju child kommentaare on, kui neid on, siis kustutada ei tohi

	$alamlist_count2 = new Alamlist(array(
		parent => $site->fdat['id'],
		klass	=> "kommentaar",
		asukoht	=> 0,
		on_counter => 1		
	));

	$obj_from_alamlist = $alamlist->next();
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));
}
                    $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));
?>
<html>
	<head> 	
		<title><?php 
echo $site->sys_sona(array('sona' => 'recycle bin', 'tyyp' => 'Admin'));
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 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_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
}