function smarty_function_init_favorites($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    $objects_arr = array();
    ##############
    # default values
    extract($params);
    if (!isset($name)) {
        $name = "favorites";
    }
    ##################
    # classes
    $tyyp_idlist = null;
    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
    ##################
    ##############
    # Get data
    $raw_favorites = $site->user->get_favorites(array(tyyp_id => $tyyp_idlist, order => $order));
    $favorites = array();
    $i = 0;
    if (is_array($raw_favorites)) {
        foreach ($raw_favorites as $raw_fav) {
            $favorites[$i]->all = $raw_fav;
            $favorites[$i]->id = $raw_fav['objekt_id_r'];
            $favorites[$i]->title = $raw_fav['pealkiri'];
            $favorites[$i]->href = $site->self . '?id=' . $raw_fav['objekt_id_r'];
            if (0 && $raw_fav['tyyp_id'] == 21) {
                /* Special case */
                /* I'm not sure this has worked before
                			if (!function_exists ("objManagement")) {
                				include_once($class_path."objectmanager.class.php");
                			}
                			$manager = new objManagement();
                			$favorites[$i]->icon = $manager->getThumbnail(array(
                						fullpath => $raw_fav['fullpath'],
                						size => '16x16',
                						show_icons => 1
                						));
                			unset($manager);
                			*/
            } else {
                if ($raw_fav['tyyp_id'] == 22) {
                    /* Special case 2 */
                    $favorites[$i]->icon = $leht->site->CONF['wwwroot'] . $leht->site->CONF['styles_path'] . '/gfx/icons/16x16/mime/folder_open.png';
                } else {
                    $favorites[$i]->icon = $leht->site->CONF['wwwroot'] . $leht->site->CONF['styles_path'] . "/gfx/icons/16x16/mime/knode.png";
                }
            }
            $i++;
        }
    }
    unset($raw_favorites);
    ##############
    # assign to template variables
    $smarty->assign(array($name => $favorites, $name . '_count' => $i));
}
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));
}
 if (!$error) {
     $site->fdat["templ_content"] = eregi_replace('<#textarea', '<textarea', $site->fdat["templ_content"]);
     $site->fdat["templ_content"] = eregi_replace('<#/textarea', '</textarea', $site->fdat["templ_content"]);
     $out = fopen($templ_path . $filename, "wb");
     fputs($out, $site->fdat["templ_content"]);
     if (!$out) {
         $error = $site->sys_sona(array(sona => "Faili salvestamisel tekkis viga", tyyp => "editor")) . $templ_path . $filename;
     }
     fclose($out);
 }
 # / MALLI SISU: textarea sisu faili
 ###############################
 ###############################
 # salvesta baasi
 /* translate op into estonian */
 $site->fdat['op_value'] = translate_ee($site->fdat['op_value']);
 if (1) {
     # --------------------------
     # INSERT INTO - UUS MALL
     # --------------------------
     if (!$error && $site->fdat['op'] == "new") {
         #######
         # find new id
         # allowed are: 1000..1999, 2100..N/A
         $sql = $site->db->prepare("SELECT max(ttyyp_id) FROM templ_tyyp WHERE ttyyp_id >= 1000 AND ttyyp_id < 2000 \r\n\t\t\t\tOR ttyyp_id >= 2100");
         $sth = new SQL($sql);
         $site->debug->msg($sth->debug->get_msgs());
         $max_id = $sth->fetchsingle();
         if ($max_id) {
             $max_id++;
         } else {
/**
 * changes the op template
 *
 * @param string $op
 * @param integer $template_id
 */
function change_op_template($op, $template_id)
{
    global $site;
    $template_id = (int) $template_id;
    if ($op && $template_id) {
        $op = translate_ee($op);
        $sql = $site->db->prepare("update templ_tyyp set op = NULL where op = ?", $op);
        new SQL($sql);
        $sql = $site->db->prepare("update templ_tyyp set op = ? where ttyyp_id = ?", $op, $template_id);
        new SQL($sql);
    }
}
/**
* sync_extensions (public)
* 
* 1) Reads directory "extensions/" and adds new record into table 'extension' for each found directory
* 2) searches for file "extension.config.php" and reads the values in that file into the extension record
*   - add new admin-pages automatically, if needed
*   - add new templates automatically, if needed
*	- add new system word group, if needed
*   - import dictionary from language files
*   - run install/update SQL files
*   - check dependencies
* 
* @package CMS
* 
*/
function sync_extensions()
{
    global $site, $class_path;
    include_once $class_path . 'lang_functions.inc.php';
    include_once $class_path . 'install.inc.php';
    $ext_path = $site->absolute_path . 'extensions/';
    $handle = opendir($ext_path);
    while (false !== ($dir = readdir($handle))) {
        if (is_dir($ext_path . $dir) && $dir != '.' && $dir != '..' && $dir != 'CVS') {
            $dirlist[] = $dir . "/";
        }
        # if
    }
    # while
    closedir($handle);
    # if no dirs found => do nothing & return
    if (!count($dirlist)) {
        return;
    }
    sort($dirlist);
    ############ loop over extension directories
    foreach ($dirlist as $dir) {
        $is_install = false;
        # true, if found new extension
        $dir_absolute_path = $ext_path . $dir;
        $dir_relative_path = 'extensions/' . $dir;
        $dir_name = substr($dir, 0, -1);
        #		printr($dir_absolute_path);
        #		printr($dir_relative_path);
        ####### check if extension exists
        $extension = new extension(array(name => $dir_name));
        ###### 1. extension not found in database => INSERT it
        if (!$extension->name) {
            $is_install = true;
            $sql = $site->db->prepare("INSERT INTO extensions (name,path,is_active) VALUES (?,?,?)", $dir_name, $dir_relative_path, '0');
            $sth = new SQL($sql);
            #print($sql);
            $site->debug->msg($sth->debug->get_msgs());
            ####### write log
            new Log(array('action' => 'create', 'component' => 'Extensions', 'message' => "New extension '" . $dir_name . "' inserted. (sync)"));
            # reload extension:
            $extension = new extension(array(name => $dir_name));
            $no_delete_extension[] = $extension->id;
        } else {
            $no_delete_extension[] = $extension->id;
            ####### WRITE LOG
            new Log(array('action' => 'update', 'component' => 'Extensions', 'message' => "New extension '" . $dir_name . "' updated. (sync)"));
        }
        ####### 2. search for CONFIG FILE
        $conf_found = $extension->load_extension_config();
        # now all config variables are in array $extension->CONF
        #printr($conf_found);
        ####### 3. UPDATE extension record
        # 3.A config file found => we have official ext, overwrite all record values with config file values
        if ($conf_found) {
            $sql = $site->db->prepare("UPDATE extensions SET path=?, is_official=?, title=?, description=?, author=?, version=?, version_date=?, icon_path=?, min_saurus_version=?, min_saurus_modules=?, is_downloadable=? WHERE name=?", $dir_relative_path, '1', $extension->CONF['title'], $extension->CONF['description'], $extension->CONF['author'], $extension->CONF['version'], $extension->CONF['version_date'], $extension->CONF['icon_path'], $extension->CONF['min_saurus_version'], $extension->CONF['min_saurus_modules'], $extension->CONF['is_downloadable'] == '1' ? '1' : '0', $extension->name);
        } else {
            $sql = $site->db->prepare("UPDATE extensions SET path=?, is_official=? WHERE name=?", $dir_relative_path, '0', $extension->name);
        }
        # official or custom ext
        $sth = new SQL($sql);
        #print($sql);
        $site->debug->msg($sth->debug->get_msgs());
        ####### 4. CREATE ADMIN-PAGES
        if (count($extension->CONF['adminpages']) > 0) {
            #printr($extension->CONF['adminpages']);
            ## get minimum sorteering from main menu "Extensions"
            $sql = $site->db->prepare("SELECT MIN(sorteering) AS min_sorteering FROM admin_osa WHERE parent_id=?", '86');
            $sth = new SQL($sql);
            #print($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $min_sorteering = $sth->fetchsingle();
            $min_sorteering = intval($min_sorteering) - 1;
            ## find new ID, must be 1000...->
            $sql = $site->db->prepare("SELECT MAX(id) FROM admin_osa WHERE id >= 1000");
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $max_id = $sth->fetchsingle();
            if ($max_id) {
                $max_id++;
            } else {
                $max_id = 1000;
            }
            foreach ($extension->CONF['adminpages'] as $adminpage) {
                ## parent ID is hardcoded "86": Extensions
                #check if adminpage exists:
                $sql = $site->db->prepare("SELECT id FROM admin_osa WHERE eng_nimetus=? AND parent_id=? AND extension=?", $adminpage["name"], '86', $extension->name);
                $sth = new SQL($sql);
                $adminpage_id = $sth->fetchsingle();
                ## if not found => INSERT
                if (!$adminpage_id) {
                    $sql = $site->db->prepare("INSERT INTO admin_osa (id, parent_id, sorteering, eng_nimetus, fail, moodul_id, extension) VALUES (?, ?, ?, ?, ?, ?, ?)", $max_id, 86, $min_sorteering, $adminpage["name"], $site->CONF['wwwroot'] . '/' . $extension->path . $adminpage["file"], 0, $extension->name);
                    $max_id++;
                    #######write log
                    new Log(array('action' => 'create', 'component' => 'Extensions', 'message' => "Extension '" . $extension->name . "': new admin-page '" . $adminpage["name"] . "' inserted (sync)"));
                } else {
                    $sql = $site->db->prepare("UPDATE admin_osa SET eng_nimetus=?, fail=?, extension=?  WHERE id=?", $adminpage["name"], $site->CONF['wwwroot'] . '/' . $extension->path . $adminpage["file"], $extension->name, $adminpage_id);
                    $no_delete_list[] = $adminpage_id;
                }
                $sth = new SQL($sql);
                if (!$adminpage_id) {
                    $no_delete_list[] = $sth->insert_id;
                }
                #print($sql);
                $site->debug->msg($sth->debug->get_msgs());
                #######################
                # save system word to group "admin":
                include_once $class_path . 'adminpage.inc.php';
                // get admin section key (should always be 12, but in any case)
                $sql = "select sst_id from sys_sona_tyyp where voti = 'admin'";
                $result = new SQL($sql);
                $sst_id = $result->fetchsingle();
                // insert the same translation for every active language
                $sql = 'select distinct glossary_id as keel_id from keel where on_kasutusel = 1';
                $result = new SQL($sql);
                while ($row = $result->fetch('ASSOC')) {
                    save_systemword(array('sysword' => $adminpage['name'], 'translation' => $adminpage['name'], 'lang_id' => $row['keel_id'], 'sst_id' => $sst_id));
                }
            }
            # loop over adminpages
            if (!empty($extension->name)) {
                new sql("delete from admin_osa where extension='" . $extension->name . "' and id not in (" . implode(",", $no_delete_list) . ")");
            }
        }
        # if adminpages found
        ####### 5. CREATE TEMPLATES
        if (count($extension->CONF['templates']) > 0) {
            #printr($extension->CONF['templates']);
            $sql = $site->db->prepare("SELECT max(ttyyp_id) FROM templ_tyyp WHERE ttyyp_id >= 1000 AND ttyyp_id < 2000 OR ttyyp_id >= 2100");
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $max_id = $sth->fetchsingle();
            if ($max_id) {
                $max_id++;
            } else {
                $max_id = 1000;
            }
            ############## loop over templates
            foreach ($extension->CONF['templates'] as $template) {
                #check if template exists:
                $template['op'] = translate_ee($template['op']);
                /* get op: dont overwrite existing values */
                $sql = $site->db->prepare("SELECT op FROM templ_tyyp WHERE op=? AND nimi<>?;", $template['op'], $template['name']);
                $sth = new SQL($sql);
                $op_found = $sth->fetchsingle();
                if ($op_found) {
                    $template['op'] = '';
                    # dont overwrite
                }
                $sql = $site->db->prepare("SELECT ttyyp_id FROM templ_tyyp WHERE nimi=? AND extension=?", $template["name"], $extension->name);
                $sth = new SQL($sql);
                $template_id = $sth->fetchsingle();
                ## if not found => INSERT
                if (!$template_id) {
                    $sql = $site->db->prepare("INSERT INTO templ_tyyp (ttyyp_id, nimi, templ_fail, on_page_templ, on_nahtav, extension, op, is_readonly, is_default, preview, preview_thumb) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $max_id, $template['name'], '../../../' . $extension->path . $template['file'], $template['is_page'] ? 1 : 0, $template['is_visible'] ? 1 : 0, $extension->name, $template['op'], $template['is_readonly'] ? 1 : 0, $template['is_default'] ? 1 : 0, $template['preview'], $template['preview_thumb']);
                    $max_id++;
                    #######write log
                    new Log(array('action' => 'create', 'component' => 'Extensions', 'message' => "Extension '" . $extension->name . "': new template '" . $template["name"] . "' inserted (sync)"));
                } else {
                    $sql = $site->db->prepare("UPDATE templ_tyyp SET nimi=?, templ_fail=?, on_page_templ=?, on_nahtav=?, extension=?, op=" . ($template['op'] ? "'" . mysql_real_escape_string($template['op']) . "'" : 'op') . ", is_readonly=?, is_default = ?, preview = ?, preview_thumb = ? WHERE ttyyp_id=?", $template['name'], '../../../' . $extension->path . $template['file'], $template['is_page'] ? 1 : 0, $template['is_visible'] ? 1 : 0, $extension->name, $template['is_readonly'] ? 1 : 0, $template['is_default'] ? 1 : 0, $template['preview'], $template['preview_thumb'], $template_id);
                }
                $sth = new SQL($sql);
                #print($sql.'<br />');
                $site->debug->msg($sth->debug->get_msgs());
            }
            # loop over templates
        }
        # if templates found
        ####### 6. CREATE SYSTEMWORD GROUP in GLOSSARY
        # check if systemword group with that name exists
        $sql = $site->db->prepare("SELECT sst_id FROM sys_sona_tyyp WHERE voti=?", $extension->name);
        $sth = new SQL($sql);
        $sst_id = $sth->fetchsingle();
        # UPDATE glossary group name
        if ($sst_id) {
            $sql = $site->db->prepare("UPDATE sys_sona_tyyp SET voti=?, nimi=?, extension=? WHERE sst_id=?", $extension->name, $extension->CONF['title'] ? $extension->CONF['title'] : $extension->name, $extension->name, $sst_id);
            $sth = new SQL($sql);
        } else {
            # find new sst ID (must be >= 100; 0...100 are reserved for Saurus internal use)
            $sql = $site->db->prepare("SELECT MAX(sst_id) FROM sys_sona_tyyp");
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            $max_id = $sth->fetchsingle();
            if ($max_id >= 100) {
                $max_id++;
            } else {
                $max_id = 100;
            }
            $sql = $site->db->prepare("INSERT INTO sys_sona_tyyp (sst_id, voti, nimi, extension) VALUES (?,?,?,?)", $max_id, $extension->name, $extension->CONF['title'] ? $extension->CONF['title'] : $extension->name, $extension->name);
            $sth = new SQL($sql);
            ####### write log
            new Log(array('action' => 'create', 'component' => 'Extensions', 'message' => "Extension '" . $extension->name . "': new glossary group '" . $extension->CONF['title'] . "' inserted (sync)"));
        }
        ########## 7. import dictionary from language files
        if ($extension->name) {
            /* get site's languages and encodings */
            $languages = array();
            $sql = 'select distinct glossary_id as keel_id, encoding from keel where on_kasutusel = 1;';
            $result = new SQL($sql);
            while ($lang = $result->fetch('ASSOC')) {
                if (file_exists($site->absolute_path . 'extensions/' . $extension->name . '/lang/' . $lang['encoding'] . '/language' . $lang['keel_id'] . '.csv')) {
                    import_dict_from_file($site->absolute_path . 'extensions/' . $extension->name . '/lang/' . $lang['encoding'] . '/language' . $lang['keel_id'] . '.csv');
                }
            }
        }
        ####### 4. RUN INSTALL/UPDATE SQL FILES
        # 8A. if INSTALLING new extension then run all *.sql files in extension folder "install/"
        if ($is_install) {
            $ext_install_path = $dir_absolute_path . 'install/';
            if (is_dir($ext_install_path)) {
                # if install/ exists, Bug #2442
                $handle = opendir($ext_install_path);
                while (false !== ($dir = readdir($handle))) {
                    if (is_file($file = $ext_install_path . $dir) && $dir != '.' && $dir != '..' && $dir != 'CVS') {
                        $tmp_parts = pathinfo($ext_install_path . $dir);
                        ## if file extension is "sql" (case insensitive) => run sql files
                        if (strtoupper($tmp_parts['extension']) == 'SQL') {
                            #
                            if ($fd = fopen($file, "r")) {
                                $sql = fread($fd, filesize($file));
                                fclose($fd);
                                # if there is smth in file
                                if ($sql) {
                                    $pieces = split_sql_file($sql, ';');
                                    // now $pieces is an array of all sql directives to launch
                                    foreach ($pieces as $query) {
                                        $sth = new SQL($query);
                                        if ($sth->error) {
                                            print "<font color=red>Error: " . $sth->error . "</font><br />";
                                        }
                                        $i++;
                                    }
                                }
                                # data found
                            } else {
                                echo "<font color=red>Can't open data file \"<b>" . $filename . "</b>\" - access denied</font><br />";
                            }
                            # cant open sql file
                        }
                        # if sql file
                    }
                    # file
                }
                # while
                closedir($handle);
            }
            # if dir exists
        } else {
        }
        # is update
        ############# 9. CHECK DEPENDENCIES
        $extension->check_dependencies();
    }
    // Delete non-existing extensions
    if (is_array($no_delete_extension)) {
        $sth = new SQL("select name from extensions where extension_id not in (" . implode(",", $no_delete_extension) . ")");
        while ($r = $sth->fetch("ASSOC")) {
            $extension = new extension(array(name => $r['name']));
            $extension->uninstall();
        }
    }
    ############ / loop over extension directories
}
 function Site()
 {
     global $class_path;
     $args = func_get_arg(0);
     $this->args =& $args;
     $this->timer = new Timer();
     $this->cash = array();
     $this->rub_loetelu = array();
     $this->noaccess_hash = array();
     $this->fatal_error = '';
     $this->script_version = '4.7.FINAL';
     $this->site_poll_url = "http://extranet.saurus.ee/register/cms_site_polling.php";
     // auth is register:register
     ######################
     # this->fdat
     $this->fdat = array();
     $this->fdat = sizeof($_POST) > 0 ? $_POST : $_GET;
     ## set magic_quotes_gpc to OFF using transcribe() function
     $this->fdat = $this->transcribe($this->fdat);
     ######################
     # alternatiiv "?id" muutujale: t��tab ka "pg"
     $this->fdat['id'] = $this->fdat['id'] ? $this->fdat['id'] : $this->fdat['pg'];
     ######################
     # this->cookie
     $this->cookie = array();
     if (sizeof($_COOKIE) > 0) {
         while (list($name, $value) = each($_COOKIE)) {
             if (is_array($value)) {
                 while (list($arrname, $arrvalue) = each($value)) {
                     $this->cookie[$name][$arrname] = $arrvalue;
                 }
             } else {
                 $this->cookie[$name] = $value;
             }
         }
     }
     ######################
     # alias translation are in custom.inc.php
     $this->fdat['op'] = translate_ee($this->fdat['op']);
     if (isset($this->fdat['query'])) {
         $this->fdat['otsi'] =& $this->fdat['query'];
     }
     ######################
     # this->self: URL koos scriptinimega, nt /port/index.php
     # lets check if web server is Apache or not
     if (preg_match("/apache/i", $_SERVER["SERVER_SOFTWARE"]) || preg_match("/apache/i", $_SERVER["SERVER_SOFTWARE"])) {
         $this->self = $_SERVER["REQUEST_URI"];
         # kui apache
     } else {
         $this->self = $_SERVER["SCRIPT_NAME"];
         # kui muu (nt IIS)
     }
     #echo "<font color=red>test=".$this->self."</font></br>";
     #$this->self = "/index.php";
     $this->fullself = $this->self;
     # failinimi l�pust maha
     if (preg_match("/^[^\\?]*\\//", $this->self, $matches)) {
         $path = $matches[0];
     } else {
         $path = $this->self;
     }
     # slash l�ppu!
     if (!preg_match("/\\/\$/", $path)) {
         $path .= "/";
     }
     $this->self = $path;
     # this->self
     ######################
     ######################
     # find hostname & wwwroot from url
     #
     # this->hostname: serveri nimi, nt dino.saurus.ee
     # this->wwwroot: URL ilma scriptinimega, nt /port
     #    on t�histring kui saidil oma virtuaalhost ja dns-kirje.
     $this->wwwroot = $path;
     # v�ta l�pust "/extensions/<MY_EXTENSION_NAME>/admin/" maha kui on (Bug #2190)
     $this->wwwroot = preg_replace("/\\/extensions\\/(.*)\\/admin\\/\$/i", "", $this->wwwroot);
     # v�tame admin/ ja editor/ osa maha
     $re = '/' . preg_replace("/\\//", "\\\\/", '(editor|admin|classes|temp)/.*$') . '/i';
     $this->wwwroot = preg_replace($re, "", $this->wwwroot);
     # slash l�pust maha!
     $this->wwwroot = preg_replace("/\\/\$/", "", $this->wwwroot);
     # find hostname from url
     $this->hostname = $_SERVER["HTTP_HOST"];
     # / find hostname & this->wwwroot from url
     ####################
     ######################
     # $this->script_name - ainult scriptinimi, nt index.php. Bug #2690: $site->script_name leitakse valesti kui url-is esineb kaldkriips
     $this->script_name = $_SERVER["SCRIPT_NAME"];
     $break = explode('/', $this->script_name);
     $this->script_name = $break[count($break) - 1];
     # $this->script_name
     ######################
     # self = url + failinimi
     $this->self .= $this->script_name;
     ######################
     # $this->URI - $site->self + ? + $_SERVER["QUERY_STRING"], nt /port/index.php?id=666
     # Kui asi seotud aliastega, siis tyhjendame query_string:
     $ENV_QUERY_STRING = $_SERVER["QUERY_STRING"];
     # bug #791
     if (substr_count($ENV_QUERY_STRING, 'mod_rewrite') || substr_count($this->self, "/map/")) {
         $this->URI = $this->self;
         if (count($this->fdat > 1)) {
             $this->URI .= "?";
             foreach ($this->fdat as $key => $value) {
                 if ($value && $key != 'keel' && $key != 'mod_rewrite' && $key != 'cmd') {
                     $this->URI .= $key . "=" . $value . "&";
                 }
             }
         }
     } else {
         $this->URI = $this->self . ($ENV_QUERY_STRING ? "?" . $ENV_QUERY_STRING : "");
     }
     #$this->URI = $this->self."?".(substr_count($ENV_QUERY_STRING,'mod_rewrite') ? "":$ENV_QUERY_STRING);
     $this->safeURI = urlencode($this->URI);
     ######################
     # $this->absolute_path - absolute path of website root
     $this->absolute_path = getcwd() . '/';
     # l�pust /admin|editor|classes/ maha
     if (preg_match("/(.*)\\/(admin|editor|classes|temp)\\/\$/", $this->absolute_path, $matches) || preg_match("/(.*)\\\\(admin|editor|classes|temp)\\/\$/", $this->absolute_path, $matches)) {
         $this->absolute_path = $matches[1];
     }
     # slash l�ppu!
     if (!preg_match("/\\/\$/", $this->absolute_path)) {
         $this->absolute_path .= "/";
     }
     # windows compatible
     $this->absolute_path = str_replace('\\', '/', $this->absolute_path);
     ######################
     # $this->on_debug
     $this->on_debug = $args["on_debug"];
     $this->agent = 1;
     # defineerime debug classi s�ltuvalt selles,
     # kas on_debug = 1 v�i 0
     if ($this->on_debug) {
         include_once $class_path . "debug.inc.php";
     } else {
         include_once $class_path . "nodebug.inc.php";
     }
     $this->debug = new Debug();
     $this->editor_debug = new Debug();
     $this->debug->msg("Site->hostname: " . $this->hostname);
     $this->debug->msg("Site->wwwroot: " . $this->wwwroot);
     $this->debug->msg("Site->self: " . $this->self);
     $this->debug->msg("Site->script_name: " . $this->script_name);
     $this->debug->msg("Site->URI: " . $this->URI);
     ######################
     # $this->CONF: values from file 'config.php'
     $this->CONF = $this->ReadConf();
     $this->dbstyles = array();
     ######################
     # $this->db
     # andmebaasist s�ltumatu API
     include_once $class_path . $this->CONF["dbtype"] . ".inc.php";
     $this->db = new DB(array("host" => $this->CONF["dbhost"], "port" => $this->CONF["dbport"], "dbname" => $this->CONF["db"], "user" => $this->CONF["user"], "pass" => $this->CONF["passwd"], 'mysql_set_names' => $this->CONF["mysql_set_names"]));
     if ($this->db->error) {
         print "<font face=\"arial, verdana\" color=red>Error! Can't connect to database!</font>";
         exit;
     }
     # OMG, php OO sakib nii kohutavalt, seep???rast tuleb kasutada globaalset muutujat site instance-i k???tte saamiseks kui see pole veel l???puni valmis looddud. seda on vaja SQL classis.
     global $site;
     $site = $this;
     ######################
     # $this->CONF: merge values from file and database
     $this->CONF = array_merge($this->CONF, $this->ReadConfDB());
     ######################
     # hostname & wwwroot
     /* save old values */
     $this->db_hostname = $this->CONF['hostname'];
     $this->db_wwwroot = $this->CONF['wwwroot'];
     ## 1. CRON: if hostname is still empty => we may have cron-job running here,
     # in that case: get hostname and wwwroot from database conf variables (Bug #1903)
     if (trim($this->hostname) == '') {
         $this->hostname = $this->CONF['hostname'];
         $this->wwwroot = $this->CONF['wwwroot'];
     } else {
         # arvesta tegelikke v��rtuseid ja mitte andmebaasi kirjutatud v��rtuseid (Bug #1439):
         $this->CONF["hostname"] = $this->hostname;
         # Bug #2319. �rme kirjuta �le CONF['wwwroot'] v��rtust, sest aliaste puhul kui meil on nt URL
         # www.site.com/aliaste/rodu/ on suht v�imatu v�lja peilida, mis siis ikkagi on
         # TEGELIK wwwroot. Seep�rast kasutame andmebaasi v��rtust.
         # old: $this->CONF["wwwroot"] = $this->wwwroot;
         #$this->wwwroot = $this->CONF['wwwroot']; # new. no �kki peaks tegema
     }
     ######################
     # $this->img_path
     $this->img_path = $this->CONF["wwwroot"] . $this->CONF["img_path"];
     ######################
     # current version nr in database
     $sql = "SELECT version_nr FROM version ORDER BY release_date DESC LIMIT 1";
     $sth = new SQL($sql);
     $this->cms_version = $sth->fetchsingle();
     $this->debug->msg("Site CMS version: " . $this->cms_version);
     ######################
     # minimum (install) version nr in database
     $sql = "SELECT version_nr FROM version ORDER BY release_date ASC LIMIT 1";
     $sth = new SQL($sql);
     $this->cms_min_version = $sth->fetchsingle();
     $this->debug->msg("Site CMS minimum (install) version: " . $this->cms_min_version);
     ######################
     # current version nr in script
     $this->debug->msg("Site->script version: " . $this->script_version);
     ######################
     # lang/keel in URL
     $this->fdat['keel'] = isset($this->fdat['lang']) ? $this->fdat['lang'] : $this->fdat['keel'];
     # $this->keel
     # $this->encoding
     # $this->extension
     # $this->locale
     $tmp_arr = $this->get_keel(array("on_admin_keel" => $args["on_admin_keel"]));
     $this->keel = $tmp_arr['keel_id'];
     $this->encoding = $tmp_arr['encoding'];
     $this->extension = $tmp_arr['extension'];
     $this->locale = $tmp_arr['locale'];
     $this->glossary_id = $tmp_arr['glossary_id'];
     ############### aliases
     $this->load_aliases();
     $this->license = 'Saurus CMS Community Edition';
     $this->title = 'Saurus CMS Community Edition';
     ######################
     # $this->admin
     # "in_editor" on true juhul kui ollakse toimetaja keskkonnas:
     # kui URLis leidub editor/
     $pattern = "/^" . preg_replace("/\\//", "\\\\/", $this->CONF['wwwroot']) . "\\/(editor)\\//";
     if (preg_match($pattern, $this->URI)) {
         $this->in_editor = 1;
     } else {
         $this->in_editor = 0;
     }
     # "in_admin" on true juhul kui ollakse admin keskkonnas:
     # kui URLis leidub admin/
     $pattern = "/^" . preg_replace("/\\//", "\\\\/", $this->CONF['wwwroot']) . "\\/(admin)\\//";
     if (preg_match($pattern, $this->URI)) {
         $this->in_admin = 1;
     } else {
         $this->in_admin = 0;
     }
     # for compability with old ver 3: is_admin = treu if we are in admin/ or editor/ area
     if ($this->in_editor || $this->in_admin) {
         $this->admin = 1;
     } else {
         $this->admin = 0;
     }
     #################################################
     # force HTTPS for editor
     if ($this->in_editor && $this->CONF['force_https_for_editing'] && empty($_SERVER['HTTPS'])) {
         header('Location: https://' . $this->CONF['hostname'] . $this->CONF['wwwroot'] . '/editor/index.php');
         exit;
     }
     # / force HTTPS for editor
     #################################################
     #################################################
     # force HTTPS for admin
     if ($this->in_admin && $this->CONF['force_https_for_admin'] && empty($_SERVER['HTTPS'])) {
         header('Location: https://' . $this->CONF['hostname'] . $_SERVER['REQUEST_URI']);
         exit;
     }
     # / force HTTPS for editor
     #################################################
     $this->debug->msg("MC RUNTIME " . get_magic_quotes_runtime());
     $this->debug->msg("MC CONF " . get_magic_quotes_gpc());
     $this->debug->msg("Session id = " . session_id());
     #####################
     # $this->user
     $this->create_user();
     //$this->update_wwwroot();
     ##############################
     # get object classes
     $result = new SQL('select * from tyyp order by tyyp_id');
     while ($row = $result->fetch('ASSOC')) {
         $this->object_classes[$row['tyyp_id']] = $row;
         $this->object_tyyp_id_klass[$row['tyyp_id']] =& $this->object_classes[$row['tyyp_id']]['klass'];
         $this->object_tyyp_id_nimi[$row['tyyp_id']] =& $this->object_classes[$row['tyyp_id']]['nimi'];
     }
     # / get object classes
     ##############################
     #####################
     # global cookies (used through the site)
     # 1) save cookie
     if ($this->fdat['group_id']) {
         setcookie("scms_group_id", $this->fdat['group_id']);
     } else {
         $this->fdat['group_id'] = $_COOKIE["scms_group_id"];
     }
     # 3) if group_id is still empty then get  top parent group id (Everybody)
     if (!$this->fdat['group_id']) {
         $this->fdat['group_id'] = get_topparent_group(array("site" => $this));
     }
     # Kalendri kuup???eva "meelde j???tmine"
     if ($this->fdat['start_date'] && $this->fdat['end_date']) {
         $scms_calendar_date[] = "start_date=" . $this->fdat['start_date'] . "&end_date=" . $this->fdat['end_date'];
     }
     if ($this->fdat['week']) {
         $scms_calendar_date[] = "week=" . $this->fdat['week'];
     }
     if ($this->fdat['day'] && $this->fdat['month'] && $this->fdat['year']) {
         $scms_calendar_date[] = "day=" . $this->fdat['day'] . "&month=" . $this->fdat['month'] . "&year=" . $this->fdat['year'];
     }
     if (is_array($scms_calendar_date)) {
         $_COOKIE['scms_calendar_date'] = htmlentities(urlencode(join("&", $scms_calendar_date)));
         setcookie("scms_calendar_date", $_COOKIE['scms_calendar_date']);
     }
     # Get calendar date cookie
     if ($_COOKIE['scms_calendar_date']) {
         $calendar_date = urldecode($_COOKIE['scms_calendar_date']);
         $calendar_date = split("&", $calendar_date);
         foreach ($calendar_date as $value) {
             $result = split("=", $value);
             $cookie_calendar_date[$result[0]] = $result[1];
         }
     }
     if ($cookie_calendar_date && !$this->fdat['start_date'] && !$this->fdat['end_date']) {
         $this->fdat['start_date'] = $cookie_calendar_date['start_date'];
         $this->fdat['end_date'] = $cookie_calendar_date['end_date'];
     }
     if ($cookie_calendar_date && !$this->fdat['week']) {
         $this->fdat['week'] = $cookie_calendar_date['week'];
     }
     if ($cookie_calendar_date && !$this->fdat['day'] && !$this->fdat['month'] && !$this->fdat['year']) {
         $this->fdat['day'] = $cookie_calendar_date['day'];
         $this->fdat['month'] = $cookie_calendar_date['month'];
         $this->fdat['year'] = $cookie_calendar_date['year'];
     }
     # // Get calendar date cookie
     # / global cookies (used through the site)
     #####################
     #######################
     # leia saidi p???himallid - lehemall ja sisumall
     $this->get_master_tpl();
     # leitakse $this->master_tpl, $this->master_cont_tpl
     #######################
     # leia k???igi objektit??????pide p???himallid
     $this->get_objtype_tpl();
     # leitakse $this->objtype_tpl
 }
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_search_results($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    //translate url params
    foreach ($site->fdat as $key => $value) {
        if (!array_key_exists($site->fdat[translate_en($key)], $site->fdat)) {
            $site->fdat[translate_en($key)] =& $site->fdat[$key];
        }
    }
    extract($params);
    if (!isset($name)) {
        $name = 'search';
    }
    if (!isset($query)) {
        $query = $site->fdat['query'];
    }
    if (!isset($sites)) {
        $sites = $site->fdat['sites'];
    }
    if (!empty($sites)) {
        if (strtolower($sites) == "all") {
            $sql_keel = "SELECT keel_id FROM keel WHERE on_kasutusel=1";
        } else {
            $pre_search_explode = explode(",", strtolower(trim($sites)));
            foreach ($pre_search_explode as $k => $v) {
                $pre_search_explode[$k] = $site->db->prepare('?', trim($v));
            }
            $sql_keel = 'SELECT keel_id FROM keel WHERE on_kasutusel=1 AND extension IN (' . implode(',', $pre_search_explode) . ')';
        }
        $sth = new SQL($sql_keel);
        while ($r = $sth->fetch("ASSOC")) {
            $keeled[] = $r['keel_id'];
        }
        $keel = implode(",", (array) $keeled);
    } else {
        $keel = $site->keel;
    }
    if (!isset($search_type)) {
        $search_type = $site->fdat['bool'];
    }
    $bool_array = array("or", "and", "phrase");
    if (!in_array(strtolower($search_type), $bool_array)) {
        $search_type = "or";
    }
    if (!isset($exclude)) {
        $exclude = $site->fdat['exclude'];
    }
    if (!isset($section)) {
        $section = $site->fdat['section'];
    }
    if (!isset($last_changed)) {
        $last_changed = $site->fdat['time'];
    }
    if ($last_changed != "") {
        if (is_numeric($last_changed) && $last_changed >= 1 && $last_changed <= 6) {
        } elseif (!is_numeric($last_changed)) {
            $time_array = array("1 DAY", "7 DAY", "1 MONTH", "3 MONTH", "6 MONTH", "1 YEAR");
            foreach ($time_array as $k => $v) {
                if (strtoupper(trim($last_changed)) == $v) {
                    $last_changed = $k + 1;
                }
            }
            if (!is_numeric($last_changed)) {
                $last_changed = "0";
            }
        } else {
            $last_changed = "0";
        }
    }
    if (!isset($order)) {
        $order = $site->fdat['order'];
    }
    if (!isset($name)) {
        $name = 'search';
    }
    if (!isset($classes)) {
        foreach ($site->object_classes as $class_def) {
            if ($class_def['on_otsingus']) {
                $classes[] = $class_def['klass'];
            }
        }
    } else {
        $classes = explode(',', trim($classes));
        foreach ($classes as $i => $class) {
            $classes[$i] = translate_ee(trim($class));
        }
    }
    /*
    if(!isset($buttons))
    	$buttons = array('new', 'edit', 'hide', 'move', 'delete');
    else
    	$buttons = split(',', $buttons);
    */
    //check cache
    if (is_array($site->cash(array('klass' => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS')))) {
        //read from cache
        $search = $site->cash(array('klass' => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS'));
    } else {
        include_once $class_path . 'FulltextSearch.class.php';
        $do_boolean = false;
        foreach (explode(' ', $query) as $query_word) {
            if (preg_match('/\\*$/', $query_word)) {
                $do_boolean = true;
                break;
            }
        }
        if (strtolower($search_type) != 'or') {
            $do_boolean = true;
        }
        if ($do_boolean || $exclude || $section || $last_changed) {
            //boolean search
            if ($use_fulltext) {
                $search = new FulltextSearchBoolean($query, $exclude, $search_type, $last_changed, $order, $section, $classes, $keel);
            } else {
                $search = new AdvancedSearch($query, $exclude, $search_type, $last_changed, $order, $section, $classes, $keel);
            }
        } else {
            //simple search
            $search = new FulltextSearch($query, 0, $classes, $use_fulltext ? true : false, $keel);
        }
        if ($keel != "") {
            $search->execSearch();
        }
        //write to cache
        $site->cash(array(klass => 'GET_SEARCH_RESULTS', 'kood' => 'GET_SEARCH_RESULTS', 'sisu' => $search));
    }
    $labels = array();
    $k = 0;
    foreach ($search->getResults() as $class_name => $objects) {
        if (in_array($class_name, $classes)) {
            $labels[$k]->title = $site->sys_sona(array('sona' => 'lipik ' . $class_name, 'tyyp' => 'otsing'));
            $labels[$k]->name = translate_en($class_name);
            $labels[$k]->counttotal = count($objects);
            $labels[$k]->results = isset($start) && $limit ? array_slice($objects, $start, $limit) : $objects;
            $labels[$k]->count = count($labels[$k]->results);
            foreach ($labels[$k]->results as $i => $obj) {
                /* @var $labels[$k]->results[$i] Objekt */
                // copy-paste from init_object
                $labels[$k]->results[$i]->id =& $labels[$k]->results[$i]->objekt_id;
                # kui link
                if ($labels[$k]->results[$i]->all['klass'] == 'link') {
                    # load sisu, et saada vļæ½ļæ½rtused "url" ja "on_uusaken"
                    $labels[$k]->results[$i]->load_sisu();
                    $labels[$k]->results[$i]->all['url'] && $labels[$k]->results[$i]->all['on_uusaken'] ? $labels[$k]->results[$i]->href = $labels[$k]->results[$i]->all['url'] . '" target="_blank' : ($labels[$k]->results[$i]->href = $labels[$k]->results[$i]->all['url']);
                } else {
                    $labels[$k]->results[$i]->href = $site->self . '?id=' . $labels[$k]->results[$i]->objekt_id;
                }
                // if an article mark for excerpt loading
                if ($labels[$k]->results[$i]->all['klass'] == 'artikkel') {
                    $sql = "select substring(sisu_strip, if(locate('" . $search->search_words[0] . "', sisu_strip) < (" . floor($site->CONF['search_result_excerpt_length'] / 2) . "), 1, if(locate('" . $search->search_words[0] . "', sisu_strip) + (" . floor($site->CONF['search_result_excerpt_length'] / 2) . ") > char_length(sisu_strip), char_length(sisu_strip) - " . $site->CONF['search_result_excerpt_length'] . ", locate('" . $search->search_words[0] . "', sisu_strip) - (" . floor($site->CONF['search_result_excerpt_length'] / 2) . "))), " . $site->CONF['search_result_excerpt_length'] . ") as excerpt from objekt where objekt_id = " . $labels[$k]->results[$i]->all['objekt_id'];
                    $result = new SQL($sql);
                    $labels[$k]->results[$i]->excerpt = $result->fetchsingle();
                } else {
                    $labels[$k]->results[$i]->excerpt = '';
                }
                $labels[$k]->results[$i]->score =& $labels[$k]->results[$i]->all['fulltext_score'];
                $labels[$k]->results[$i]->title =& $labels[$k]->results[$i]->pealkiri;
                $labels[$k]->results[$i]->fdate =& $labels[$k]->results[$i]->all['aeg'];
                $labels[$k]->results[$i]->author =& $labels[$k]->results[$i]->all['author'];
                $labels[$k]->results[$i]->class = translate_en($labels[$k]->results[$i]->all['klass']);
                # translate it to english
                /* maybe fields
                			$labels[$k]->results[$i]->is_selected = $leht->parents->on_parent($labels[$k]->results[$i]->objekt_id);
                			$labels[$k]->results[$i]->buttons = $labels[$k]->results[$i]->get_edit_buttons(array(
                				'nupud' => $buttons,
                				//'tyyp_idlist' => $tyyp_idlist,//???
                			));
                			$labels[$k]->results[$i]->created_user_id =& $labels[$k]->results[$i]->all['created_user_id'];
                			$labels[$k]->results[$i]->created_user_name =& $labels[$k]->results[$i]->all['created_user_name'];
                			$labels[$k]->results[$i]->changed_user_id =& $labels[$k]->results[$i]->all['changed_user_id'];
                			$labels[$k]->results[$i]->changed_user_name =& $labels[$k]->results[$i]->all['changed_user_name'];
                			$labels[$k]->results[$i]->created_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['created_time']);
                			$labels[$k]->results[$i]->fcreated_time =& $labels[$k]->results[$i]->all['created_time'];
                			$labels[$k]->results[$i]->changed_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['changed_time']);
                			$labels[$k]->results[$i]->fchanged_time =& $labels[$k]->results[$i]->all['changed_time'];
                			$labels[$k]->results[$i]->last_commented_time =& $site->db->MySQL_ee($labels[$k]->results[$i]->all['last_commented_time']);;
                			$labels[$k]->results[$i]->comment_count =& $labels[$k]->results[$i]->all['comment_count'];
                			*/
            }
            //$labels[] = $label;
            $k++;
        }
    }
    $smarty->assign(array($name => $labels, $name . '_counttotal' => $search->search_count));
}
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
}