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_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));
}
function smarty_function_init_objects($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $objects_arr = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent_system_alias) && !isset($parent)) {
        $parent_id = $leht->id;
    } elseif (isset($parent_system_alias)) {
        //$parent_id = $site->alias(array('key' => $parent_system_alias));
        $parent_id = $site->alias(array('key' => $parent_system_alias, 'keel' => $site->keel));
    } elseif (isset($parent)) {
        $parent_id = $parent;
    }
    // if parent_id not found
    if (!$parent_id) {
        $parent_id = $leht->id;
    }
    if (!isset($name)) {
        $name = "objects";
    }
    $classes = trim($classes);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    ##################
    # classes
    if ($classes) {
        ######### translate classes: change class values for language compability
        $transl_class_arr = array();
        foreach (split(",", $classes) as $class) {
            if (trim($class) != '') {
                $transl_class_arr[] = translate_ee($class);
                # translate it to estonian
            }
        }
        #		echo printr($transl_class_arr);
        $classes = join(",", $transl_class_arr);
        ######## gather tyyp ID values => to array
        $tyyp_id_arr = array();
        $sql = "SELECT tyyp_id, klass FROM tyyp";
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        while ($tmp = $sth->fetch()) {
            # if ID found in classes array, then add it:
            if (in_array($tmp['klass'], $transl_class_arr)) {
                $tyyp_id_arr[] = $tmp['tyyp_id'];
            }
        }
        #		echo printr($tyyp_id_arr);
        # tyyp_idlist ID numeric values for buttons:
        $tyyp_idlist = join(",", $tyyp_id_arr);
    }
    # if classes parameter provided
    # / classes
    ##################
    ##############
    # alamlist
    $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => $classes, asukoht => $position, order => $order));
    if ($select) {
        $alamlistSQL->add_select($select);
    }
    if ($where) {
        $alamlistSQL->add_where($where);
    }
    if ($group) {
        $alamlistSQL->add_group($site->db->prepare('group by ' . $group));
    }
    $alamlist = new Alamlist(array('alamlistSQL' => $alamlistSQL, start => $start, limit => $limit));
    $alamlist->debug->print_msg();
    # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
    if (isset($limit)) {
        $alamlist_count = new Alamlist(array(parent => $parent_id, klass => $classes, asukoht => $position, on_counter => 1));
    }
    ##############
    # load variables
    $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => $tyyp_idlist, publish => $publish));
    while ($obj = $alamlist->next()) {
        ################
        # object parameters
        $obj->id = $obj->objekt_id;
        # kui link
        if ($obj->all[klass] == "link") {
            # load sisu, et saada vļæ½ļæ½rtused "url" ja "on_uusaken"
            $obj->load_sisu();
            $objektUrl = $obj->all['url'];
            // replace index.php?id=xxx or ?id=xxx style local url with its alias
            if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
                $objektUrl = convert_local_link_to_alias($objektUrl);
            }
            $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
        } else {
            $obj->get_object_href();
        }
        $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
        $obj->title = $obj->pealkiri;
        $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $tyyp_idlist, publish => $publish));
        $obj->fdate = $obj->all[aeg];
        $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
        ## crap data
        $obj->flast_modified = $obj->all['last_modified'];
        $obj->author = $obj->all[author];
        $obj->class = translate_en($obj->all[klass]);
        # translate it to english
        $obj->details_link = $obj->href;
        $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
        $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
        $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
        $obj->created_user_id = $obj->all['created_user_id'];
        $obj->created_user_name = $obj->all['created_user_name'];
        $obj->changed_user_id = $obj->all['changed_user_id'];
        $obj->changed_user_name = $obj->all['changed_user_name'];
        $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
        $obj->fcreated_time = $obj->all['created_time'];
        $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
        $obj->fchanged_time = $obj->all['changed_time'];
        $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
        $obj->comment_count = $obj->all['comment_count'];
        ###############
        # push array, in case we don't have "peida menuus" turned on (section objects)
        if (!$obj->all[is_hided_in_menu] || $site->in_editor) {
            array_push($objects_arr, $obj);
        }
    }
    $count = sizeof($objects_arr);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $objects_arr, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
function smarty_function_init_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_files($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    $files = array();
    ##############
    # default values
    extract($params);
    $folder = false;
    if (isset($parent)) {
        $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE objekt_id=?", $parent);
        $sth = new SQL($sql);
        $folder = $sth->fetch();
    } elseif (isset($parent_dir)) {
        # get parent folder info
        $parent_dir = preg_replace('#^/#', '', $parent_dir);
        $parent_dir = preg_replace('#/$#', '', $parent_dir);
        //parent dir must start with "public" or "shared"
        if (strpos($parent_dir, 'public') === 0 || strpos($parent_dir, 'shared') === 0) {
            $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE relative_path = ?", '/' . $parent_dir);
            $sth = new SQL($sql);
            $folder = $sth->fetch();
            $parent = $folder['objekt_id'];
        }
    }
    if (!$folder) {
        # default parent for file (folder "public/"): get folder ID of "public/"
        $sql = $site->db->prepare("SELECT objekt_id, relative_path FROM obj_folder WHERE relative_path = ? LIMIT 1", $site->CONF['file_path']);
        $sth = new SQL($sql);
        $folder = $sth->fetch();
        $parent = $folder['objekt_id'];
    }
    if (!isset($name)) {
        $name = "files";
    }
    switch ($on_create) {
        case 'publish':
            $publish = 1;
            break;
        case 'hide':
            $publish = 0;
            break;
        default:
            $publish = 1;
    }
    #  kui pole profile parameetrit, siis kasuta default profiili
    if (!$profile) {
        $default_profile_def = $site->get_profile(array(id => $site->get_default_profile_id(array(source_table => 'obj_file'))));
        # get profile name
        $profile = $default_profile_def['name'];
        unset($default_profile_def);
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array('new', 'edit', 'delete');
    } else {
        $buttons = split(',', $buttons);
    }
    ###############
    # order, parent
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    $where = preg_replace('#\\btitle\\b#i', "pealkiri", $where);
    $where = preg_replace('#\\bdate\\b#i', "aeg", $where);
    ######## where: profile, replace technical name with field name
    if (trim($where) != '') {
        $where = " (" . $where . ") ";
    }
    ##############
    # put all profile names into arr
    if ($profile) {
        $profile_names = split(",", $profile);
    } else {
        $profile_names = array();
        $profile_ids = array();
    }
    # get all profile data from cash
    foreach ($profile_names as $profile_name) {
        # profile name is case insensitive
        $profile_name = strtolower($profile_name);
        $profile_def = $site->get_profile(array(name => $profile_name));
        # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade ja vļæ½ljuda:
        if (!$profile_def[profile_id]) {
            if ($site->admin) {
                print "<font color=red><b>Profile '" . $profile_name . "' not found!</b></font>";
            }
            return;
        }
        $profile_ids[] = $profile_def[profile_id];
        $profile_arr[$profile_def[profile_id]] = $profile_def;
    }
    ############# parent
    $parent_id = trim($parent);
    #Bug #2803: Tagil {init_files} ei saanud ette anda mitud parent ID väärtust
    if ($parent_id) {
        ##############
        # create SQL
        $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "file", order => $order));
        $alamlistSQL->add_select("obj_file.profile_id, obj_file.relative_path, obj_file.filename, obj_file.mimetype, obj_file.size");
        if (sizeof($profile_ids) > 0) {
            $alamlistSQL->add_select("obj_file.*");
        }
        if (isset($select)) {
            $alamlistSQL->add_select($select);
        }
        if (sizeof($select_sql) > 0) {
            $alamlistSQL->add_select(join(", ", $select_sql));
        }
        $alamlistSQL->add_from("LEFT JOIN obj_file ON objekt.objekt_id=obj_file.objekt_id");
        if ($where) {
            $alamlistSQL->add_where($where);
        }
        $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => $start, limit => $limit));
        $alamlist->debug->print_msg();
        $alamlist_count = new Alamlist(array(alamlistSQL => $alamlistSQL, on_counter => 1));
        ##############
        # load variables
        $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => "21", profile_id => join(",", $profile_ids), publish => $publish));
        while ($obj = $alamlist->next()) {
            $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => "21", profile_id => join(",", $profile_ids), nupud => $buttons, publish => $publish));
            $obj->id = $obj->objekt_id;
            $obj->parent = $obj->parent_id;
            $obj->folder_fullpath = $site->absolute_path . $folder['relative_path'];
            $obj->href = $site->CONF['wwwroot'] . '/file.php?' . $obj->objekt_id;
            # Bug #2317
            $obj->title = $obj->all['pealkiri'];
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
            $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
            $obj->fdatetime = $obj->all['aeg'];
            $pathinfo = pathinfo($site->absolute_path . $obj->all['relative_path']);
            $obj->fullpath = $site->absolute_path . $obj->all['relative_path'];
            $obj->filename = $obj->all['filename'];
            $obj->mimetype = $obj->all['mimetype'];
            # size is set later: after profiles
            $obj->profile_id = $obj->all['profile_id'];
            $obj->extension = strtolower($pathinfo["extension"]);
            if ($icons) {
                if (!preg_match("/\\/\$/", $icons)) {
                    $icons .= '/';
                }
                if (file_exists($site->absolute_path . $icons . $obj->extension . '.gif')) {
                    $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . $obj->extension . '.gif';
                } elseif (file_exists($site->absolute_path . $icons . 'unknown.gif')) {
                    $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . 'unknown.gif';
                }
            }
            $obj->class = translate_en($obj->all[klass]);
            # translate it to english
            $obj->created_user_id = $obj->all['created_user_id'];
            $obj->created_user_name = $obj->all['created_user_name'];
            $obj->changed_user_id = $obj->all['changed_user_id'];
            $obj->changed_user_name = $obj->all['changed_user_name'];
            $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
            $obj->fcreated_time = $obj->all['created_time'];
            $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
            $obj->fchanged_time = $obj->all['changed_time'];
            $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
            $obj->comment_count = $obj->all['comment_count'];
            ########## KUI PROFIIL on parameetrina kaasas JA failil on Mļæ½ļæ½RATUD mļæ½ni PROFIIL, siis korja andmed "->" omadustena kokku
            if (sizeof($profile_ids) > 0) {
                ###### load object. #### NB! actually should be: profile_id is in "objekt" tabel. then we don't have to entire object
                #			$obj->load_sisu();
                ###### loop over profiles
                foreach ($profile_ids as $profile_id) {
                    #printr($obj->objekt_id.' PROFILE_ID: '.$obj->all['profile_id']);
                    include_once $class_path . 'profile.class.php';
                    $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
                    #### 1. set profile fields as object attributes
                    $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
                    ###################
                    # get selectlist values - 1 extra sql per function; sql is fast
                    if (is_array($obj_profile->selectlist)) {
                        $obj_profile->selectlist = array_unique($obj_profile->selectlist);
                        #printr($obj_profile->selectlist);
                    }
                    # go on if object values needs changing:
                    if (sizeof($obj_profile->selectlist) > 0) {
                        #### 2. save array "->asset_names"  human readable NAME-s:
                        $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
                        #printr($obj_profile->asset_names);
                        #printr($obj_profile->change_fields);
                        ### 3. save object rest of attributes
                        #print "<br>muuta ID: ".$obj->id;
                        $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
                    }
                    # if any selectvalue exist & need to change
                    # / get selectlist values
                    ###################
                }
                ###### / loop over profiles
            }
            ####### / profile is set
            $obj->size = print_filesize($obj->all['size']);
            array_push($files, $obj);
        }
        ###### / loop over objects
    }
    $count = sizeof($files);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $files, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
function smarty_function_init_documents($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    $documents = array();
    $parent_ary = array();
    ##############
    # default values
    extract($params);
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    if (!isset($name)) {
        $name = "documents";
    }
    # for language compatibility, replace with search string existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    $parent_id = trim($parent);
    if ($parent_id) {
        ##############
        # alamlist
        $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "dokument", asukoht => $position, order => $order, where => $where));
        $alamlistSQL->add_select(" obj_dokument.tyyp, obj_dokument.mime_tyyp, obj_dokument.fail, obj_dokument.kirjeldus, obj_dokument.autor, obj_dokument.size, obj_dokument.download_type");
        $alamlistSQL->add_from("LEFT JOIN obj_dokument ON objekt.objekt_id=obj_dokument.objekt_id");
        $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => $start, limit => $limit));
        #		$alamlist->debug->print_msg();
        #		$alamlist->sql->debug->print_msg();
        # if parameter "limit" is provided then "counttotal" element is needed (shows total rows)
        if (isset($limit)) {
            $alamlist_count = new Alamlist(array(alamlistSQL => $alamlistSQL, on_counter => 1));
        }
        ##############
        # load variables
        $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => 7, publish => $publish));
        while ($obj = $alamlist->next()) {
            $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 7, asukoht => $position, publish => $publish));
            $obj->id = $obj->objekt_id;
            $obj->href = $site->self . '?id=' . $obj->objekt_id;
            $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
            $obj->title = $obj->pealkiri;
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
            $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
            $obj->fdatetime = $obj->all['aeg'];
            $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
            ## crap data
            $obj->flast_modified = $obj->all['last_modified'];
            $obj->file = $obj->filename = $obj->all['fail'];
            $obj->description = $obj->all['kirjeldus'];
            $obj->size = $obj->all['size'];
            $obj->type = $obj->all['tyyp'];
            $obj->mime_type = $obj->all['mime_tyyp'];
            $obj->size_formated = print_filesize($obj->all['size']);
            $obj->author = $obj->all['author'] ? $obj->all['author'] : $obj->all['autor'];
            $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
            $obj->download_link = $site->wwwroot . '/doc.php?' . $obj->objekt_id;
            $obj->class = translate_en($obj->all[klass]);
            # translate it to english
            $obj->created_user_id = $obj->all['created_user_id'];
            $obj->created_user_name = $obj->all['created_user_name'];
            $obj->changed_user_id = $obj->all['changed_user_id'];
            $obj->changed_user_name = $obj->all['changed_user_name'];
            $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
            $obj->fcreated_time = $obj->all['created_time'];
            $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
            $obj->fchanged_time = $obj->all['changed_time'];
            $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
            $obj->comment_count = $obj->all['comment_count'];
            array_push($documents, $obj);
        }
    }
    # / loop over all parent id
    #######################
    ##################
    # fix objects order, if more than 1 parent_id was given
    # because database sort is not enough for this case
    if (sizeof($parent_ary) > 1) {
        list($order_field, $order_sort) = split(" ", $order);
        # exception for dates: for array sort rename db field date:
        $order_field = str_replace("aeg", "fdate", $order_field);
        # sort objects by required field
        if (trim($order_field)) {
            $documents = casort($documents, $order_field);
        }
        # if sortorder is 'desc', then reverse array
        if (strtolower(trim($order_sort)) == 'desc') {
            $documents = array_reverse($documents);
        }
    }
    # / fix objects order, if more than 1 parent_id was given
    ##################
    $count = sizeof($documents);
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $documents, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_count' => $count));
}
function smarty_function_init_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));
}
function smarty_function_init_assets($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    include_once $class_path . 'profile.class.php';
    $assets = array();
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "assets";
    }
    if (!isset($parent)) {
        $parent = $leht->id;
    }
    $parent_id = trim($parent);
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    # NB! kui t��p on asset, siis PEAB alati kaasas olema ka profiili ID
    # (muidu ei oma custom asset m�tet);
    # kui pole profile parameetrit, anda toimetajale veateade ja v�ljuda:
    if (!$profile) {
        if ($site->admin) {
            print "<font color=red><b>Profile parameter is required!</b></font>";
        }
        exit;
    }
    # for language compatibility, replace order with existing db field name
    $order = preg_replace('#\\btitle\\b#i', "pealkiri", $order);
    $order = preg_replace('#\\bdate\\b#i', "aeg", $order);
    ##############
    ## deprecated parameter "fields"
    if (isset($fields)) {
        $get_object_fields .= "," . $fields;
    }
    # put all fields filter into arr
    $get_object_fields_arr = split(",", $get_object_fields);
    $i = 0;
    foreach ($get_object_fields_arr as $tmp) {
        $get_object_fields_arr[$i] = trim($tmp);
        $i++;
    }
    ##############
    # put all profile names into arr
    $profile_names = split(",", $profile);
    ##############
    # get all profile data from cash
    foreach ($profile_names as $profile_name) {
        # profile name is case insensitive
        $profile_name = strtolower($profile_name);
        $profile_def = $site->get_profile(array(name => $profile_name));
        # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade ja v�ljuda:
        if (!$profile_def[profile_id]) {
            if ($site->admin) {
                print "<font color=red><b>Profile '" . $profile_name . "' not found!</b></font>";
            }
            exit;
        }
        $profile_ids[] = $profile_def[profile_id];
        $profile_arr[$profile_def[profile_id]] = $profile_def;
    }
    if (($id || $parent_id) && sizeof($profile_ids) > 0) {
        # one object
        if ($id) {
            ##############
            # luua objekt
            $obj = new Objekt(array(objekt_id => $id));
            $obj->load_sisu();
            $obj->hit_count = $obj->all['count'];
            $alamlist = new ObjektArray();
            $alamlist->add($obj);
        } elseif ($parent_id) {
            # loop over profile ID-s
            foreach ($profile_ids as $profile_id) {
                $where_sql[] = "obj_asset.profile_id = '" . $profile_id . "'";
                $profile_def = unserialize($profile_arr[$profile_id]['data']);
                if (!is_array($profile_def)) {
                    $profile_def = array();
                }
                # loop over one profile fields
                foreach ($profile_def as $key => $data) {
                    if (!$get_object_fields || sizeof($get_object_fields_arr) > 0 && in_array($data[name], $get_object_fields_arr)) {
                        $select_sql[] = ($data['is_predefined'] ? 'objekt' : 'obj_asset') . "." . $key;
                        if ($contains) {
                            $contains_sql[] = ($where ? " AND " : "") . $key . $site->db->prepare(" LIKE ?", '%' . $contains . '%');
                        }
                    }
                    if ($where) {
                        # replace technical name with field name
                        $where = str_replace($data['name'], $key, $where);
                    }
                    if ($order) {
                        $order = str_replace($data['name'], $key, $order);
                    }
                    if ($select) {
                        $select = str_replace($data['name'], $key, $select);
                    }
                }
                # / loop over one profile fields
            }
            # / loop over profile ID-s
            ##############
            # create SQL
            $alamlistSQL = new AlamlistSQL(array(parent => $parent_id, klass => "asset", order => $order, asukoht => $position));
            $alamlistSQL->add_select("obj_asset.profile_id");
            if (isset($select)) {
                $alamlistSQL->add_select($select);
            }
            if (sizeof($select_sql) > 0) {
                $alamlistSQL->add_select(join(", ", $select_sql));
            }
            $alamlistSQL->add_from("LEFT JOIN obj_asset ON objekt.objekt_id=obj_asset.objekt_id");
            $alamlistSQL->add_where("(" . join(" OR ", $where_sql) . ")");
            if ($where) {
                $alamlistSQL->add_where($where);
            }
            if (sizeof($contains_sql) > 0) {
                $alamlistSQL->add_where(join(" OR ", $contains_sql));
            }
            $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => $start, limit => $limit));
            $alamlist->debug->print_msg();
            $alamlist_count = new Alamlist(array(alamlistSQL => $alamlistSQL, on_counter => 1));
            ##############
            # load variables
            $new_button = $alamlist->get_edit_buttons(array(tyyp_idlist => "20", profile_id => join(",", $profile_ids), asukoht => $position, publish => $publish));
        }
        # id or list
        $all_change_fields = array();
        $all_selectlist = array();
        # array of ID-s which need additional steps to convert ID-s to human readable NAME-s (assets or users/groups)
        if (!isset($buttons)) {
            $buttons = array('new', 'edit', 'hide', 'move', 'delete');
        } else {
            $buttons = split(',', $buttons);
        }
        while ($obj = $alamlist->next()) {
            $obj->id =& $obj->objekt_id;
            $obj->class = $obj->all[klass];
            # translate it to english
            $obj->buttons = $obj->get_edit_buttons(array('nupud' => $buttons, tyyp_idlist => "20", profile_id => join(",", $profile_ids), publish => $publish));
            $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
            $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
            $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
            $obj->fdatetime = $obj->all['aeg'];
            $obj->last_modified = date('d.m.Y H:i', $obj->all['last_modified']);
            $obj->flast_modified = $obj->all['last_modified'];
            $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
            $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
            $obj->title = $obj->pealkiri;
            $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
            // bug #2455
            if (is_array($obj_profile->data)) {
                foreach ($obj_profile->data as $profile_key => $profile_data) {
                    if ($profile_key != $profile_data['name'] && !isset($obj->all[$profile_data['name']])) {
                        $obj->all[$profile_data['name']] =& $obj->all[$profile_key];
                    }
                }
            }
            // / bug #2455
            $obj->profile = $obj_profile->name;
            # name
            #### 1. set profile fields as object attributes
            $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
            ## gather all selectlist values into one array:
            if (sizeof($obj_profile->selectlist) > 0) {
                $all_selectlist = array_merge($obj_profile->selectlist, $all_selectlist);
            }
            ## gather all need_change_obj values into one array:
            # that means object attributes has to be cahnged later. remeMber fields for each obj.
            if (sizeof($obj_profile->change_fields) > 0) {
                $all_change_fields[$obj->id] = $obj_profile->change_fields;
            }
            #printr($obj_profile->change_fields);
            $obj->created_user_id = $obj->all['created_user_id'];
            $obj->created_user_name = $obj->all['created_user_name'];
            $obj->changed_user_id = $obj->all['changed_user_id'];
            $obj->changed_user_name = $obj->all['changed_user_name'];
            $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
            $obj->fcreated_time = $obj->all['created_time'];
            $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
            $obj->fchanged_time = $obj->all['changed_time'];
            ### push
            array_push($assets, $obj);
        }
        //printr($all_selectlist);
        ###################
        # get selectlist values - 1 (or 2, if system tables involved) extra sql per function; sql is fast
        if (sizeof($all_selectlist) > 0) {
            # 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $all_selectlist));
            #printr($obj_profile->asset_names);
            #printr($all_change_fields);
            ###############
            # assign names to attributes
            #echo printr($asset_names);
            ###############
            # loop over asset objects and changes attributes values correct
            $i = 0;
            foreach ($assets as $tmp) {
                # pointer to array element:
                $obj =& $assets[$i];
                # go on if object values needs changing:
                if (in_array($obj->id, array_keys($all_change_fields))) {
                    #print "<br>muuta ID: ".$obj->id;
                    ### 3. save object rest of attributes
                    $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $all_change_fields[$obj->id]));
                }
                # if need to change
                $i++;
            }
        }
        # if any selectvalue is to get
        # / get selectlist values
        ###################
    }
    # if parameters are OK
    $count = $alamlist->rows;
    $counttotal = isset($limit) ? $alamlist_count->rows : $count;
    ##############
    # assign to template variables
    $smarty->assign(array($name => $assets, $name . '_newbutton' => $new_button, $name . '_counttotal' => $counttotal, $name . '_rows' => $counttotal, $name . '_count' => $count));
}
function smarty_function_init_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_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));
}