/**
 * This source file is is part of Saurus CMS content management software.
 * It is licensed under MPL 1.1 (http://www.opensource.org/licenses/mozilla1.1.php).
 * Copyright (C) 2000-2010 Saurused Ltd (http://www.saurus.info/).
 * Redistribution of this file must retain the above copyright notice.
 * 
 * Please note that the original authors never thought this would turn out
 * such a great piece of software when the work started using Perl in year 2000.
 * Due to organic growth, you may find parts of the software being
 * a bit (well maybe more than a bit) old fashioned and here's where you can help.
 * Good luck and keep your open source minds open!
 * 
 * @package		SaurusCMS
 * @copyright	2000-2010 Saurused Ltd (http://www.saurus.info/)
 * @license		Mozilla Public License 1.1 (http://www.opensource.org/licenses/mozilla1.1.php)
 * 
 */
function smarty_function_init_file($params, &$smarty)
{
    global $site, $leht, $class_path;
    extract($params);
    $id = (int) $id;
    if (!$id) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = 'file';
    }
    if (!isset($buttons)) {
        $buttons = array('new', 'edit', 'hide', 'move', 'delete');
    } else {
        $buttons = split(',', $buttons);
    }
    $obj = new Objekt(array('objekt_id' => $id));
    $obj->load_sisu();
    $obj->id = $obj->objekt_id;
    $obj->parent = $obj->parent_id;
    $obj->title = $obj->pealkiri;
    $obj->class = translate_en($obj->all['klass']);
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    $obj->href = $site->CONF['wwwroot'] . '/file.php?' . $obj->objekt_id;
    $obj->fullpath = preg_replace('#/$#', '', $site->absolute_path) . $obj->all['relative_path'];
    unset($obj->all['fullpath']);
    $obj->filename = $obj->all['filename'];
    $obj->mimetype = $obj->all['mimetype'];
    $obj->profile_id = $obj->all['profile_id'];
    $obj->url = $site->CONF['wwwroot'] . $obj->all['relative_path'];
    $obj->size = print_filesize($obj->all['size']);
    $pathinfo = pathinfo($obj->fullpath);
    $obj->extension = strtolower($pathinfo['extension']);
    // for images give gallery thumbs and images
    if (strpos($obj->all['mimetype'], 'image/') === 0) {
        $folder = preg_replace('#/$#', '', $site->absolute_path) . str_replace($obj->all['filename'], '', $obj->all['relative_path']);
        $folder_url = $site->CONF['wwwroot'] . $folder;
        //thumbs
        if (file_exists($folder . '.gallery_thumbnails/' . $obj->all['filename']) && ($thumb_info = @getimagesize($folder . '.gallery_thumbnails/' . $obj->all['filename']))) {
            $obj->thumb_path = $folder_url . '.gallery_thumbnails/' . $obj->all['filename'];
            $obj->thumb_width = $thumb_info[0];
            $obj->thumb_height = $thumb_info[1];
        }
        //image
        if (file_exists($folder . '.gallery_pictures/' . $obj->all['filename']) && ($image_info = @getimagesize($folder . '.gallery_pictures/' . $obj->all['filename']))) {
            $obj->image_path = $folder_url . '.gallery_pictures/' . $obj->all['filename'];
            $obj->image_width = $image_info[0];
            $obj->image_height = $image_info[1];
        }
        //actual image
        if (file_exists($site->absolute_path . $obj->all['relative_path']) && ($actual_image_info = @getimagesize($site->absolute_path . $obj->all['relative_path']))) {
            $obj->actual_image_path = $obj->url;
            $obj->actual_image_width = $actual_image_info[0];
            $obj->actual_image_height = $actual_image_info[1];
        }
    }
    if ($icons) {
        if (!preg_match("/\\/\$/", $icons)) {
            $icons .= '/';
        }
        if (file_exists($site->absolute_path . $icons . $obj->extension . '.gif')) {
            $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . $obj->extension . '.gif';
        } elseif (file_exists($site->absolute_path . $icons . 'unknown.gif')) {
            $obj->icon = $site->CONF['wwwroot'] . '/' . $icons . 'unknown.gif';
        }
    }
    if (!$profile) {
        $default_profile_def = $site->get_profile(array('id' => $site->get_default_profile_id(array(source_table => 'obj_file'))));
        # get profile name
        $profile = $default_profile_def['name'];
        unset($default_profile_def);
    }
    ##############
    # put all profile names into arr
    if ($profile) {
        $profile_names = split(",", $profile);
    } else {
        $profile_names = array();
        $profile_ids = array();
    }
    # get all profile data from cash
    foreach ($profile_names as $profile_name) {
        # profile name is case insensitive
        $profile_name = strtolower($profile_name);
        $profile_def = $site->get_profile(array(name => $profile_name));
        # sanity check: kui ei leitud sellise nimega profiili, anda toimetajale veateade
        if (!$profile_def['profile_id']) {
            if ($site->admin) {
                print "<font color=red><b>Profile '" . $profile_name . "' not found!</b></font>";
            }
            return;
        }
        $profile_ids[] = $profile_def['profile_id'];
        $profile_arr[$profile_def['profile_id']] = $profile_def;
    }
    $obj->buttons = $obj->get_edit_buttons(array('nupud' => $buttons, 'tyyp_idlist' => 21, 'publish' => $publish, 'profile_id' => join(',', $profile_ids)));
    $profile_def = $site->get_profile(array('id' => $obj->all['profile_id']));
    if ($profile_def[profile_id]) {
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array('id' => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array('obj' => &$obj, 'get_object_fields' => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array('selectlist' => $obj_profile->selectlist));
            ### 3. save object rest of attributes
            $obj_profile->set_obj_selectlist_fields(array('obj' => &$obj, 'change_fields' => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    foreach ($obj->all as $fieldname => $value) {
        $obj->{$fieldname} = $value;
    }
    $smarty->assign($name, $obj);
}
function smarty_function_init_object($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "object";
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    ##############
    # luua objekt & load sisu
    $obj = new Objekt(array(objekt_id => $id));
    $obj->load_sisu();
    ################
    # object GENERAL parameters
    $obj->id = $obj->objekt_id;
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    # kui link
    if ($obj->all[klass] == "link") {
        $objektUrl = $obj->all['url'];
        // replace index.php?id=xxx or ?id=xxx style local url with its alias
        if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
            $objektUrl = convert_local_link_to_alias($objektUrl);
        }
        $objektUrl && $obj->all['on_uusaken'] ? $obj->href = $objektUrl . '" target="_blank' : ($obj->href = $objektUrl);
    } else {
        $obj->get_object_href();
    }
    $obj->title = $obj->pealkiri;
    $obj->buttons = $obj->get_edit_buttons(array(nupud => $buttons, tyyp_idlist => $obj->all['tyyp_id'], publish => $publish));
    $obj->fdate = $obj->all[aeg];
    $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
    ## crap data
    $obj->flast_modified = $obj->all['last_modified'];
    $obj->details_link = $obj->href;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    ################
    # ALL values, set as attributes
    foreach ($obj->all as $fieldname => $value) {
        $obj->{$fieldname} = $value;
    }
    ###############
    # profile values, set as attributes
    $profile_def = $site->get_profile(array(id => $obj->all['profile_id']));
    if ($profile_def[profile_id]) {
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ################
    # object CLASS specific parameters
    ########## ARTICLE
    if ($obj->class == 'article') {
        //$obj = init_article(array("id"=>$obj->id), &$smarty);
        if (!function_exists('smarty_function_init_article')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_article');
        }
        smarty_function_init_article(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'document') {
        if (!function_exists('smarty_function_init_document')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_document');
        }
        $obj = smarty_function_init_document(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'image') {
        if (!function_exists('smarty_function_init_picture')) {
            require_once $smarty->_get_plugin_filepath('function', 'init_picture');
        }
        $obj = smarty_function_init_picture(array("id" => $obj->id, 'name' => $name), $smarty);
        return;
    } elseif ($obj->class == 'section') {
        $obj->show_toolicons = $obj->all['on_printlink'];
        $obj->is_mailinglist = $obj->all['on_meilinglist'];
        $obj->show_subarticles = $obj->all['on_alamartiklid'];
        $obj->hide_in_menu = $obj->all['on_peida_vmenyy'];
        $obj->show_date = $obj->all['on_kp_nahtav'];
    } elseif ($obj->class == 'poll') {
        $obj->is_open = $obj->all['on_avatud'];
        $obj->expires = $obj->all['expires'] ? $site->db->MySQL_ee($obj->all['expires']) : '';
        $obj->fexpires = $obj->all['expires'] ? $obj->all['expires'] : '';
        $obj->is_expired = $obj->all['expires'] && (strtotime($obj->all['expires']) > 0 && strtotime($obj->all['expires']) < time()) ? 1 : 0;
        #printr(strtotime($obj->all['expires']));
        ######### CHECK voting
        # 1) IP-based gallup
        if ($site->CONF[gallup_ip_check] == 1) {
            $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND ip LIKE ?", $obj->id, $_SERVER["REMOTE_ADDR"]);
            $sth = new SQL($sql);
            $count = $sth->fetchsingle();
        } else {
            if ($site->CONF[gallup_ip_check] == 2 && $site->cookie["gallup"][$obj->id] == 1) {
                $count = 1;
            } else {
                if ($site->CONF[gallup_ip_check] == 3) {
                    $sql = $site->db->prepare("SELECT COUNT(gi_id) FROM gallup_ip WHERE objekt_id=? AND user_id=?", $obj->id, $site->user->user_id);
                    $sth = new SQL($sql);
                    # count=1: not logged in users are not allowed to vote:
                    $count = $site->user->user_id ? $sth->fetchsingle() : 1;
                } else {
                    $count = 0;
                }
            }
        }
        ######### / CHECK voting
        ### is_voted: if user is voted this poll or not, 1/0
        $obj->is_voted = $count;
        # not voted
        ### answers
        $sql = $site->db->prepare("SELECT * FROM gallup_vastus WHERE objekt_id=?", $obj->id);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        $obj->answers = array();
        $obj->answers_count = 0;
        while ($vastus = $sth->fetch()) {
            unset($tmp);
            $tmp = new stdClass();
            $tmp->id = $vastus[gv_id];
            $tmp->answer = $vastus[vastus];
            $tmp->title = $vastus[vastus];
            $tmp->count = $vastus[count];
            $obj->answers[$vastus[gv_id]] = $tmp;
            $obj->answers_count += $vastus[count];
        }
        ### / answers
        ### voters (if not anonymous poll)
        if (!$obj->is_anonymous) {
            $sql = $site->db->prepare("SELECT gallup_ip.*, users.firstname, users.lastname\r\n\t\t\t\tFROM gallup_ip\r\n\t\t\t\t\tLEFT JOIN users ON users.user_id = gallup_ip.user_id\r\n\t\t\t\tWHERE objekt_id=?", $obj->id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $obj->voters = array();
            while ($vastus = $sth->fetch()) {
                unset($tmp);
                $tmp->id = $vastus[gi_id];
                $tmp->answer_id = $vastus[gv_id];
                $tmp->ip = $vastus[ip];
                $tmp->user_id = $vastus[user_id];
                $tmp->user_firstname = $vastus[firstname];
                $tmp->user_lastname = $vastus[lastname];
                $tmp->time = $site->db->MySQL_ee($vastus[vote_time]);
                $tmp->ftime = $vastus[vote_time];
                $obj->voters[$vastus[gi_id]] = $tmp;
            }
        }
        # if not anonymous poll
        ### / voters
    } elseif ($obj->class == 'album') {
        // add album config atributes
        $conf = new CONFIG($obj->all['ttyyp_params']);
        $obj->description = $conf->get('desc');
        $obj->thumbnail_size = $conf->get('tn_size');
        # in pixels
        $obj->image_size = $conf->get('pic_size');
        # in pixels
        $obj->folder_id = $conf->get('folder_id');
        # source folder ID
        $obj->folder_path = $conf->get('path');
        # source folder path, eg "public/images"
    }
    ########## / ALBUM
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
}
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_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_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
}