/**
* save object info to database
*
* Uses sub-scripts to save different data for different object types.
* No parameters used, only globals, it is included script.
*
* @package CMS
*
* Call:
*		include_once("edit_object.php");
*		save_object();
*/
function save_object()
{
    global $site;
    global $objekt;
    global $class_path;
    global $keel;
    global $tyyp;
    verify_form_token();
    ###################
    # 1. special case: if object is NEW picture
    if ($tyyp['klass'] == "pilt" && !$objekt->objekt_id) {
        include_once "edit_" . $tyyp['klass'] . ".php";
        if (function_exists("save_objekts")) {
            save_objekts(array(tyyp_id => $tyyp[tyyp_id], keel => $keel));
        }
    } else {
        # pealkiri peab olema!
        if ($site->fdat[pealkiri] == '' && $tyyp['klass'] != "kommentaar") {
            $errors .= $site->sys_sona(array(sona => "maaratud pealkiri", tyyp => "editor")) . "<br>";
        }
        ###################
        # Salvestame tyybi parameetrid
        if (file_exists("edit_" . $tyyp['klass'] . ".php")) {
            include_once "edit_" . $tyyp['klass'] . ".php";
            if (function_exists("save_tyyp_params")) {
                $templ_params = save_tyyp_params(array(objekt => $objekt));
            }
        }
        ###################
        # Salvestame malli parameetrid - old ver3 style
        # arvestame, et malli parameetrid k�ivad ainult sisumalli kohta
        $sql = $site->db->prepare("SELECT ttyyp_id, templ_fail FROM templ_tyyp WHERE ttyyp_id = ?", $site->fdat['ttyyp_id']);
        $sth = new SQL($sql);
        $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
        $temp_ttyyp = $sth->fetch();
        if ($temp_ttyyp['templ_fail'] && strpos($temp_ttyyp['templ_fail'], '../') !== 0 && file_exists("../" . $temp_ttyyp['templ_fail'])) {
            include_once "../" . $temp_ttyyp['templ_fail'];
        }
        if (function_exists("save_params")) {
            $templ_params = save_params(array(objekt => $objekt));
        }
        ### ttyyp_params - ver3 style vs ver4. Bug #2506
        if (!empty($templ_params)) {
            $oldstyle_tyyp_params = true;
            # if old-ver-style fixed params are used
        } else {
            # use new ver4 style custom conf save/load by default
            $oldstyle_tyyp_params = false;
        }
        ###################
        # if no errors occured , begin saving to database
        if (!$errors) {
            $site->debug->msg("EDIT: Objekti salvestamine");
            ###################
            # strip HTML tags from headline, lyhi, sisu for strip-fields
            // folder title is folder filesystem name
            if ($site->fdat['tyyp_id'] == 22) {
                $site->fdat['pealkiri'] = safe_filename2($site->fdat['pealkiri']);
            }
            $pealkiri_strip = $site->fdat['pealkiri'];
            $sisu_strip = $site->fdat['scms_article_editor'] ? $site->fdat['scms_article_editor'] : ($site->fdat['sisu'] ? $site->fdat['sisu'] : $site->fdat['text']);
            # replace some tags with space before stripping tags (bug #1568 )
            $replace_tags_arr = array("<br>", "<BR>", "<br />", "<BR />", "&nbsp;");
            $pealkiri_strip = str_replace($replace_tags_arr, " ", $pealkiri_strip);
            $sisu_strip = str_replace($replace_tags_arr, " ", $sisu_strip);
            $replace_tags_arr = array("&amp;");
            $pealkiri_strip = str_replace($replace_tags_arr, "&", $pealkiri_strip);
            $sisu_strip = str_replace($replace_tags_arr, "&", $sisu_strip);
            $pealkiri_strip = strip_tags($pealkiri_strip);
            $sisu_strip = strip_tags($sisu_strip);
            // remove excess spaces
            $sisu_strip = preg_replace('/\\s+/', ' ', $sisu_strip);
            // overwrite catch for files, this is here so when a new file is being uploaded but
            // a file with a same name already exists
            // there wouldn't be double objects
            // instead use the existing object and move on as that objects update
            if ($site->fdat['tyyp_id'] == 21 && $_FILES['fileupload']['name']) {
                $parent_folder = new Objekt(array('objekt_id' => $objekt->parent_id, 'on_sisu' => 1));
                $parent_folder_path = preg_replace('#/$#', '', $site->absolute_path) . $parent_folder->all['relative_path'];
                // delete file
                if (file_exists($parent_folder_path . '/' . safe_filename2($_FILES['fileupload']['name']))) {
                    unlink($parent_folder_path . '/' . safe_filename2($_FILES['fileupload']['name']));
                }
                $file_path = preg_replace('#/$#', '', $site->absolute_path) . $objekt->all['relative_path'];
                // delete the file itself (bug #2586)
                if ($objekt->objekt_id && file_exists($file_path)) {
                    unlink($file_path);
                }
                $sql = $site->db->prepare('select objekt_id from obj_file where relative_path = ?', $parent_folder->all['relative_path'] . '/' . safe_filename2($_FILES['fileupload']['name']));
                $result = new SQL($sql);
                if ($result->rows && ($existing_id = $result->fetchsingle())) {
                    // delete the object used to overwrite
                    // don't delete if it's the same object (bug # 2576)
                    if ($objekt->objekt_id && $objekt->objekt_id != $existing_id) {
                        $objekt->del();
                    }
                    $objekt = new Objekt(array('objekt_id' => $existing_id, 'on_sisu' => 1, 'no_cache' => 1));
                }
            }
            // / overwrite catch
            ###################
            # UPDATE
            if ($objekt->objekt_id) {
                /* Check if avaldamise_algus & avaldamise_lopp has the right format
                			   if not fix it.
                			*/
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat[avaldamise_algus], $aa_reg)) {
                    if (!$aa_reg[2] && !$aa_reg[3]) {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " 00:00:00";
                    } else {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " " . $aa_reg[2] . ":" . $aa_reg[3] . ":00";
                    }
                }
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_lopp'], $al_reg)) {
                    if (!$al_reg[2] && !$al_reg[3]) {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " 23:59:59";
                    } else {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " " . $al_reg[2] . ":" . $al_reg[3] . ":59";
                    }
                }
                /* End of check */
                $sql = $site->db->prepare("UPDATE objekt SET pealkiri=?, on_pealkiri=?, on_foorum=?, on_saadetud=?, ttyyp_id=?, page_ttyyp_id=?, pealkiri_strip=?, sisu_strip=?, aeg=?, avaldamisaeg_algus=?, avaldamisaeg_lopp=?, last_modified=" . time() . ", author=?, friendly_url=?, is_hided_in_menu=?, kesk=?, check_in=?, changed_user_id=?, changed_user_name=?, changed_time=?, on_avaldatud = ? WHERE objekt_id=?", $site->fdat['pealkiri'], $site->fdat['on_pealkiri'], $site->fdat['on_foorum'] ? 1 : 0, $site->fdat['on_saadetud'] ? 0 : 1, $site->fdat['ttyyp_id'], $site->fdat['page_ttyyp_id'], $pealkiri_strip, $sisu_strip, $site->db->ee_MySQL($site->fdat['aeg']), $site->db->ee_MySQL_long($site->fdat['avaldamise_algus']), $site->db->ee_MySQL_long($site->fdat['avaldamise_lopp']), $site->fdat['author'], $site->fdat['friendly_url'], $site->fdat['is_hided_in_menu'] ? 1 : 0, $site->fdat['kesk'], 0, $site->user->id, $site->user->name, date("Y-m-d H:i:s"), isset($site->fdat['publish']) && is_numeric($site->fdat['publish']) ? (int) $site->fdat['publish'] : $objekt->all['on_avaldatud'], $objekt->objekt_id);
                $sth = new SQL($sql);
                $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                # save old-ver3-style tyyp_params. Bug #2506
                # this SQL should happen only as exception and not by default
                if ($oldstyle_tyyp_params === true) {
                    $sql = $site->db->prepare("UPDATE objekt SET ttyyp_params = ? WHERE objekt_id=?", $templ_params ? $templ_params : 'ttyyp_params', $objekt->objekt_id);
                    $sth = new SQL($sql);
                    $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                }
                # ------------------------
                # Kustutame chache-ist ka
                # ------------------------
                clear_cache("ALL");
                new Log(array('action' => 'update', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id, "changed")));
            } else {
                /* Check if avaldamise_algus & avaldamise_lopp has the right format
                			   if not fix it.
                			*/
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_algus'], $aa_reg)) {
                    if (!$aa_reg[2] && !$aa_reg[3]) {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " 00:00:00";
                    } else {
                        $site->fdat['avaldamise_algus'] = $aa_reg[1] . " " . $aa_reg[2] . ":" . $aa_reg[3] . ":00";
                    }
                }
                if (preg_match("/(\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d[\\:\\\\.\\/\\-]\\d?\\d?\\d\\d)\\s?(\\d?\\d?)[\\:\\\\.\\/\\-]?(\\d?\\d?)/", $site->fdat['avaldamise_lopp'], $al_reg)) {
                    if (!$al_reg[2] && !$al_reg[3]) {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " 23:59:59";
                    } else {
                        $site->fdat['avaldamise_lopp'] = $al_reg[1] . " " . $al_reg[2] . ":" . $al_reg[3] . ":59";
                    }
                }
                /* End of check */
                $sql = $site->db->prepare("INSERT INTO objekt (pealkiri, on_pealkiri, on_foorum, on_saadetud, tyyp_id, author, on_avaldatud, keel, kesk, ttyyp_id, page_ttyyp_id, pealkiri_strip, sisu_strip, aeg, sys_alias, ttyyp_params, avaldamisaeg_algus, avaldamisaeg_lopp, last_modified, friendly_url, is_hided_in_menu, check_in, check_in_admin_id, created_user_id, created_user_name, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $site->fdat['pealkiri'], $site->fdat['on_pealkiri'], $site->fdat['on_foorum'], $site->fdat['on_saadetud'] ? 0 : 1, $tyyp['tyyp_id'], $site->fdat['author'], $site->fdat['sys_alias'] || $site->fdat['publish'] ? 1 : 0, $tyyp['tyyp_id'] == 21 || $tyyp['tyyp_id'] == 22 ? 1 : $keel, $site->fdat['kesk'], $site->fdat['ttyyp_id'], $site->fdat['page_ttyyp_id'], $pealkiri_strip, $sisu_strip, $site->db->ee_MySQL($site->fdat['aeg']), $site->fdat['sys_alias'], $templ_params, $site->db->ee_MySQL_long($site->fdat['avaldamise_algus']), $site->db->ee_MySQL_long($site->fdat['avaldamise_lopp']), time(), $site->fdat['friendly_url'], $site->fdat['is_hided_in_menu'] ? 1 : 0, 0, $site->user->id, $site->user->id, $site->user->name, date("Y-m-d H:i:s"));
                $sth = new SQL($sql);
                $site->debug->msg("EDIT: " . $sth->debug->get_msgs());
                $obj_insert_id = $sth->insert_id;
                # ------------------------
                # Kustutame chache-ist ka
                # ------------------------
                clear_cache("ALL");
                $objekt = new Objekt(array(objekt_id => $obj_insert_id, no_cache => 1, creating => 1));
                if (!is_numeric($objekt->objekt_id)) {
                    $objekt->objekt_id = $obj_insert_id;
                }
                $site->fdat['id'] = $objekt->objekt_id;
                new Log(array('action' => 'create', 'objekt_id' => $objekt->objekt_id, 'message' => sprintf("%s '%s' (ID = %s) %s", ucfirst(translate_en($objekt->all['klass'])), $objekt->pealkiri(), $objekt->objekt_id, "inserted")));
                $is_new = 1;
            }
            # / INSERT
            ###################
            ###################
            # WHAT IS THIS?
            $objekt->all["on_peida_vmenyy"] = $site->fdat["on_peida_vmenyy"] ? 1 : 0;
            ###################
            # SALVESTA t��bist s�ltuv osa
            #$fdat{objekt}->{klass} = "artikkel" if ($fdat{objekt}->{klass} eq "oigusakt");
            # INCLUDE t��bist s�ltuv fail
            include_once "edit_" . $tyyp['klass'] . ".php";
            # salvesta objekti t��bist s�ltuv osa
            salvesta_objekt();
            # save all profile fields:
            if ($site->fdat['profile_id']) {
                # if profile set
                save_obj_profile();
            }
            # / SALVESTA t��bist s�ltuv osa
            ###################
            ###################
            # PARENTS (tbl 'objekt_objekt')
            ###################
            $site->debug->msg("------------ PARENTS -------------");
            ###################
            #######################
            # 1. FIND NEW PARENTS
            $new_parents = array();
            # parentit on lubatud select-boxis muuta j�rgmistel objektidel:
            # artikkel, dokument, rubriik, album, asset, gallup, kommentaar
            # 1) kui tegu on lubatud objektiga JA vormis oli parent rubriik valitud,
            # siis
            if (($tyyp['klass'] == "artikkel" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "rubriik" || $tyyp['klass'] == "album" || $tyyp['klass'] == "asset" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "kommentaar" || $tyyp['klass'] == "link") && is_array($site->fdat['rubriik'])) {
                # salvesta k�ik vormis valitud rubriigid massiivi
                foreach ($site->fdat['rubriik'] as $value) {
                    $new_parents[$value] = 1;
                }
                # kui parenti ID oli 0, siis what the hell siin tehakse?
                /*
                if ($site->fdat['parent_id']==0) {
                	$new_parents[$site->fdat['parent_id']] = 1;
                }
                */
            } elseif ($site->fdat['parent_id']) {
                $new_parents[$site->fdat['parent_id']] = 1;
            }
            ######### get parent object
            if ($site->fdat['parent_id']) {
                $parent = new Objekt(array(objekt_id => $site->fdat['parent_id']));
            }
            # kui objektil leidub korrektne parent ja pole tegu rubriigiga,
            # siis pane parentiks 'parent_id' parameeter (eee, j�lle?)
            # Lauri: parent ise ei tohiks saada new_parentiks. seega kommentaari juures konkreetselt keelan ara
            if ($parent && $parent->all['klass'] != "rubriik" && $tyyp['klass'] != "kommentaar") {
                $new_parents[$site->fdat['parent_id']] = 1;
            }
            ######## gallupi erijuht
            if ($tyyp['klass'] == "gallup") {
                if ($site->fdat['on_avatud']) {
                    $objekt->load_sisu();
                    $site->debug->msg("EDIT: vana parent rullib!");
                    # removed by Bug #1896: gallupit ei saa teise rubriigi alla t�sta
                    # $new_parents = array($objekt->all["orig_parent_id"] => 1);
                } else {
                    # kui suletud gallup, siis liiguta gallupi arhiivi
                    $new_parents = array($site->alias("gallup_arhiiv") => 1);
                }
            }
            $site->debug->msg("EDIT: Selected new parents: " . join(",", array_keys($new_parents)));
            # 1. / FIND NEW PARENTS
            #######################
            #######################
            # 2. FIND CURRENT PARENTS
            $current_parents = array();
            ########### RUBRIIK V�I LINGIKAST
            if ($tyyp['klass'] == "rubriik") {
                ######## Otsime, kas rubriik kuulub ka m�ne uudistekogu alla - need on vaja uutele parentitele vaikselt lisada
                $sql = $site->db->prepare("SELECT objekt_objekt.parent_id FROM objekt_objekt LEFT JOIN objekt ON objekt.objekt_id=objekt_objekt.parent_id WHERE objekt_objekt.objekt_id=? and objekt.tyyp_id=9", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetchsingle()) {
                    $newslist_parents[$tmp_data] = 1;
                    # lisa salaja uudistekogu ID samuti uute parentite massiivile
                    $new_parents[$tmp_data] = 1;
                }
                unset($tmp_data);
                if ($sth->rows) {
                    $site->debug->msg("EDIT: Parent news lists: " . join(",", array_keys($newslist_parents)));
                }
                ########## leia rubriigi praegused parentid
                $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=?", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetch()) {
                    $parent_id = $tmp_data['parent_id'];
                    $current_parents[$parent_id] = 1;
                }
                ######### K�IK �LEJ��NUD objektid v.a rubriik ja lingikast
            } else {
                # -----------------------------------
                # siin on need objektid mille jaoks
                # on lubatud rohkem kui 1 �lema omama
                # -----------------------------------
                $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=?", $objekt->objekt_id);
                $sth = new SQL($sql);
                while ($tmp_data = $sth->fetch()) {
                    $parent_id = $tmp_data['parent_id'];
                    $current_parents[$parent_id] = 1;
                }
                # mis siin tehakse?
                # Lauri: oeldakse jargmise IF-i jaoks, et ara sinna sisse mine. vaata 10 rida allapoole
                if ($current_parents[0]) {
                    $new_parents[0] = 1;
                }
            }
            $site->debug->msg("EDIT: Current parents: " . join(",", array_keys($current_parents)));
            # / 2. FIND CURRENT PARENTS
            #######################
            # kui uute parentite massiiv on t�hi, siis kasuta vormis alati kaasas olnud
            # peidetud v��rtust 'permanent_parent_id'
            if ($site->fdat['permanent_parent_id'] != "" && !count(array_keys($new_parents))) {
                $new_parents[$site->fdat['permanent_parent_id']] = 1;
            }
            $site->debug->msg("EDIT: Final parents: " . join(",", array_keys($new_parents)));
            #######################
            # 3. CHECK NEW PARENTS PERMISSIONS
            foreach (array_keys($new_parents) as $parent_id) {
                if ($parent_id) {
                    # kui uus �lem (varem polnud), siis kontrolli �iguseid
                    if (!$current_parents[$parent_id]) {
                        ####### check permissions
                        $perm = get_obj_permission(array("objekt_id" => $parent_id));
                        # kui uuel parentil on CREATE �igus, siis luba lisada objekt selle parenti alla,
                        # muidu mitte
                        if ($perm['C']) {
                            $site->debug->msg("EDIT: New parent " . $parent_id . " permissions " . $perm['mask'] . " allow to create object under it => OK");
                        } else {
                            $site->debug->msg("EDIT: New parent " . $parent_id . " permissions " . $perm['mask'] . " don't allow to create object under it => FORBIDDEN");
                            # v�ta see parent maha uute parentite massiivist
                            unset($new_parents[$parent_id]);
                        }
                        # new parent permissions
                    }
                }
                # if parent_id
            }
            $site->debug->msg("EDIT: Final parents after permission check: " . join(",", array_keys($new_parents)));
            # / 3. CHECK NEW PARENTS PERMISSIONS
            #######################
            # kui uute parentite arv on 0 st objekti ei tohi uue parenti alla lisada,
            # siis �ra tee �ldse midagi
            if (!count(array_keys($new_parents))) {
                $site->debug->msg("EDIT: Can't move under new parent => don't do anything at all");
                $fatal_parent_error = 1;
            }
            # kui uued parentid on ainult uudistekogud (samad mis enne), siis �ra tee �ldse midagi
            if (sizeof($newslist_parents) > 0) {
                $result = array_diff(array_keys($new_parents), array_keys($newslist_parents));
                if (sizeof($result) <= 0) {
                    # kui massiivid pole erinevad
                    $site->debug->msg("EDIT: New parents are equal to existing newslist parents => don't do anything at all");
                    $fatal_parent_error = 1;
                }
            } else {
                if (!$fatal_parent_error) {
                    # if not fatal parent error
                    #######################
                    # 4. INSERT NEW PARENTS (siin on juba ainult need parentid, mille alla v�ib objekti lisada)
                    foreach (array_keys($new_parents) as $parent_id) {
                        if ($parent_id) {
                            # �lem on olemas, siis pole vaja midagi teha
                            if ($current_parents[$parent_id]) {
                                $current_parents[$parent_id] = 0;
                                $site->debug->msg("EDIT: Parent {$parent_id} j��b nagu oli");
                            } else {
                                if ($site->fdat["sorting"]) {
                                    $sorteering = $site->fdat["sorting"];
                                } else {
                                    $sql = "SELECT max(sorteering) FROM objekt_objekt";
                                    $sth = new SQL($sql);
                                    $sorteering = $sth->fetchsingle();
                                }
                                #move objects forward so new object can be inserted in the middle
                                $sql = $site->db->prepare("UPDATE objekt_objekt SET sorteering=sorteering+1 WHERE sorteering>?", $sorteering);
                                $sth = new SQL($sql);
                                $site->debug->msg("EDIT: " . $sql);
                                ################ INSERT
                                $sql = $site->db->prepare("INSERT INTO objekt_objekt (objekt_id, parent_id, sorteering) VALUES (?,?,?)", $objekt->objekt_id, $parent_id, $sorteering + 1);
                                $sth = new SQL($sql);
                                $site->debug->msg("EDIT: " . $sql);
                                if ($tyyp['klass'] == 'kommentaar') {
                                    $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count+1 WHERE objekt_id=?", $parent_id);
                                    $sth = new SQL($sql);
                                    $site->debug->msg("EDIT: " . $sql);
                                }
                            }
                            # uus �lem, lisa
                        }
                        # if parent_id
                    }
                    # / 4. INSERT NEW PARENTS
                    #######################
                    #######################
                    # 5. DELETE OLD PARENTS
                    function notnull($a)
                    {
                        return $a > 0;
                    }
                    $to_delete = join(",", array_keys(array_filter($current_parents, "notnull")));
                    $site->debug->msg("EDIT: Current Parents, allowed to delete: " . $to_delete);
                    # kui vormis oli valitud m�ni parent rubriik JA objekt on lubatud t��pi (tal v�ib parentit muuta),
                    # siis... mis tehakse?
                    if (sizeof($site->fdat['rubriik']) > 0 && ($tyyp['klass'] == "artikkel" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "rubriik" || $tyyp['klass'] == "album" || $tyyp['klass'] == "asset" || $tyyp['klass'] == "dokument" || $tyyp['klass'] == "gallup" || $tyyp['klass'] == "kommentaar" || $tyyp['klass'] == "link")) {
                        $parent_ids = array();
                        foreach (array_unique(array_merge($site->fdat['rubriik'], array_keys($new_parents))) as $tmp_id) {
                            if ((int) $tmp_id) {
                                $parent_ids[] = (int) $tmp_id;
                            }
                        }
                        ########### Lauri 04092009: store parents that will be deleted so we can reduce their comment_count
                        $sql = $site->db->prepare("SELECT parent_id FROM objekt_objekt WHERE objekt_id=? AND parent_id NOT IN(" . implode(',', $parent_ids) . ")", $objekt->objekt_id);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        $parents_to_delete = array();
                        while ($return_row = $sth->fetch()) {
                            $parents_to_delete[] = $return_row['parent_id'];
                        }
                        ############ DELETE
                        $sql = $site->db->prepare("DELETE FROM objekt_objekt WHERE objekt_id=? AND parent_id NOT IN(" . implode(',', $parent_ids) . ")", $objekt->objekt_id);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        ########## Lauri 04092009: reduce comment count for parents from which kommentaar was deleted
                        if ($tyyp['klass'] == 'kommentaar') {
                            $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count-1 WHERE objekt_id IN(" . implode(',', $parents_to_delete) . ")");
                            $sth = new SQL($sql);
                            $site->debug->msg("EDIT: " . $sql);
                        }
                    }
                    ############ DELETE
                    # kui on parenteid, mida kustutada:
                    if ($to_delete) {
                        $sql = $site->db->prepare("DELETE FROM objekt_objekt WHERE objekt_id=? AND parent_id IN(?)", $objekt->objekt_id, $to_delete);
                        $sth = new SQL($sql);
                        $site->debug->msg("EDIT: " . $sql);
                        ############ Lauri 04092009: if some more parents got removed, reduce comment_count on them too. have to make sure not to do it twice tho
                        $comments_to_substract = array_diff((array) $to_delete, $parents_to_delete);
                        if ($tyyp['klass'] == 'kommentaar' && count($comments_to_substract)) {
                            $sql = $site->db->prepare("UPDATE objekt SET comment_count = comment_count-1 WHERE objekt_id IN (" . implode(',', $comments_to_substract) . ")");
                            $sth = new SQL($sql);
                            $site->debug->msg("EDIT: " . $sql);
                        }
                    }
                    # / 5. DELETE OLD PARENTS
                    #######################
                }
            }
            # if not fatal parent error (new parent permissions)
            ################################## / DATABASE SQL-s ##################################
            $site->debug->msg("------------ PARENTS END -------------");
            # / PARENTS
            ###################
            ########################
            # INSERT PERMISSIONS
            # lisame uuele objektile t�pselt samad �igused nagu on tema parent objektile.
            # OBJ class check: save permissions only for objects having class "rubriik" (1) or "folder" (22).
            # NB! if you change class conditions here, be sure to change them in Repair database script also!
            # (see also bug #1545)
            if ($tyyp[tyyp_id] == 1 || $tyyp[tyyp_id] == 22) {
                # if object is section or folder
                if ($is_new) {
                    # leia k�ik parenti �igused userite/gruppide kohta:
                    $sql = $site->db->prepare("SELECT * FROM permissions WHERE type=? AND source_id=?", 'OBJ', $parent->objekt_id);
                    $sth = new SQL($sql);
                    # ts�kkel �le parenti �iguste
                    while ($perm = $sth->fetch()) {
                        # lisa �igus uuele objektile
                        $sql2 = $site->db->prepare("INSERT INTO permissions (type,source_id,role_id,group_id,user_id,C,R,U,P,D) VALUES (?,?,?,?,?,?,?,?,?,?)", 'OBJ', $objekt->objekt_id, $perm['role_id'], $perm['group_id'], $perm['user_id'], $perm['C'], $perm['R'], $perm['U'], $perm['P'], $perm['D']);
                        $sth2 = new SQL($sql2);
                    }
                    # ts�kkel �le parenti �iguste
                    // reload permissions for user
                    if (!$site->user->is_superuser) {
                        if ($site->user) {
                            $site->user->permissions = $site->user->load_objpermissions();
                        } elseif ($site->guest) {
                            $site->guest->permissions = $site->guest->load_objpermissions();
                        }
                    }
                }
                # if new, just created object
            }
            # if object is section or folder
            # / INSERT PERMISSIONS
            ########################
            return 1;
        } else {
            ?>
	<center><font class=txt>
		<br>
		<font color=red>&nbsp;<?php 
            echo $errors;
            ?>
</font>
		<br>
		<a href="javascript:history.back();"><?php 
            echo $site->sys_sona(array(sona => "Tagasi", tyyp => "editor"));
            ?>
</a>
	</font></center>
<?php 
        }
        # / print errors
        ###################
    }
    # / 2. usual case
    ###################
}
function synchronise_folder($folder_id)
{
    global $site;
    $folder_id = (int) $folder_id;
    $objekt = new Objekt(array('objekt_id' => $folder_id));
    if ($objekt->objekt_id == $folder_id && $objekt->all['tyyp_id'] == 22) {
        $objekt->load_sisu();
        $folder_path = preg_replace('#/$#', '', $site->absolute_path) . $objekt->all['relative_path'];
        // get folder & file count in this from database
        $sql = 'select count(objekt_id) from objekt_objekt where parent_id = ' . $folder_id;
        $result = new SQL($sql);
        $db_object_count = $result->fetchsingle();
        // check if folder & file count from db matches count in file system
        $fs_object_count = 0;
        if ($dir = opendir($folder_path)) {
            while (false !== ($file = readdir($dir))) {
                if (strpos($file, '.') !== 0) {
                    $fs_object_count++;
                    // break counting if there are more files, syncro is needed
                    if ($fs_object_count > $db_object_count) {
                        break;
                    }
                }
            }
            closedir($dir);
        } else {
            // not a folder ... TODO
        }
        //if the fs and db object count do not match syncronise folder contents
        if ($fs_object_count != $db_object_count) {
            // collect files and folder from fs
            $fs_files = array();
            $fs_folders = array();
            $dir = opendir($folder_path);
            while (false !== ($file = readdir($dir))) {
                if (strpos($file, '.') !== 0) {
                    if (is_dir($folder_path . '/' . $file)) {
                        $fs_folders[$file] = $file;
                    } else {
                        $fs_files[$file] = array('filename' => $file, 'size' => @filesize($folder_path . '/' . $file), 'mimetype' => get_file_mime_content_type($folder_path . '/' . $file));
                    }
                }
            }
            closedir($dir);
            // files first
            $sql = 'select obj_file.objekt_id, filename, mimetype, size from obj_file left join objekt_objekt on obj_file.objekt_id = objekt_objekt.objekt_id where parent_id = ' . $folder_id;
            $result = new SQL($sql);
            $files_to_delete = array();
            while ($row = $result->fetch('ASSOC')) {
                // mark files not found in fs for deletion
                if (!$fs_files[$row['filename']]) {
                    $files_to_delete[] = $row['objekt_id'];
                } else {
                    // update file size, mimetype if needed
                    if ($fs_files[$row['filename']]['size'] != $row['size'] || $fs_files[$row['filename']]['mimetype'] != $row['mimetype']) {
                        $sql = $site->db->prepare("update obj_file set size = ?, mimetype = ? where objekt_id = ?", $fs_files[$row['filename']]['size'], $fs_files[$row['filename']]['mimetype'], $row['objekt_id']);
                        new SQL($sql);
                        // set
                        $sql = $site->db->prepare("update objekt set changed_time = now(), changed_user_id = ?, changed_user_name = ? where objekt_id = ?", $site->user->user_id, $site->user->name, $row['objekt_id']);
                        new SQL($sql);
                    }
                    // check for thumbnail
                    if (!file_exists($folder_path . '/.thumbnails/' . $row['filename'])) {
                        // create thumbnail
                        create_file_thumbnail($folder_path . '/' . $row['filename']);
                    }
                    // remove from fs object array
                    unset($fs_files[$row['filename']]);
                }
            }
            // delete files not in fs TODO: catch errors from file delete
            delete_files($files_to_delete);
            // left over files are new, create them
            foreach ($fs_files as $filename => $file) {
                $safe_filename = safe_filename2($filename);
                if ($safe_filename != $filename) {
                    if (rename($folder_path . '/' . $filename, $folder_path . '/' . $safe_filename)) {
                    } else {
                        // log unable to rename, skip
                        new Log(array('action' => 'create', 'component' => 'Files', 'type' => 'ERROR', 'message' => "Could not rename '" . $objekt->all['relative_path'] . '/' . $filename . "' to '" . $objekt->all['relative_path'] . '/' . $safe_filename . "', file system error."));
                        continue;
                    }
                }
                // objekt
                insert_new_file_object($objekt, $filename, $file['size'], $file['mimetype']);
                // create thumbnail
                create_file_thumbnail($folder_path . '/' . $safe_filename);
            }
            // folders next
            $sql = 'select obj_folder.objekt_id, relative_path from obj_folder left join objekt_objekt on obj_folder.objekt_id = objekt_objekt.objekt_id where parent_id = ' . $folder_id;
            $result = new SQL($sql);
            $folders_to_delete = array();
            while ($row = $result->fetch('ASSOC')) {
                $folder_name = str_replace($objekt->all['relative_path'] . '/', '', $row['relative_path']);
                // mark folders not found in fs for deletion
                if (!$fs_folders[$folder_name]) {
                    $folders_to_delete[] = $row['objekt_id'];
                } else {
                    // remove from fs object array
                    unset($fs_folders[$folder_name]);
                }
            }
            // delete folders present in db but not present in fs
            foreach ($folders_to_delete as $folder_id) {
                // TODO: error catching from folder deleting
                delete_folder($folder_id);
            }
            // create new folders
            foreach ($fs_folders as $folder_name) {
                create_folder($folder_name, $objekt->objekt_id);
            }
            new Log(array('action' => 'sync', 'component' => 'Files', 'objekt_id' => $objekt->objekt_id, 'message' => "Folder '" . $objekt->all['relative_path'] . "' (ID = " . $objekt->objekt_id . ") synchronised."));
            // recurse?
            return true;
        } else {
            // nothing to syncro
            return true;
        }
    } else {
        return 'no_such_folder_object';
    }
}
# sql
	echo "
	<tr> 	
	<td><b>permissions: public/ folders to CRUPD=11111</b><br></td>
	</tr>
	";
######### loop
foreach($puu->objektid as $folder_id){

	## create folder object
	$objekt = new Objekt(array(
		objekt_id => $folder_id,
		no_cache => 1,
		skip_sanity_check => 1,
	));
	$objekt->load_sisu();

	### get this folder object permission mask directly from database
	$sql2 = $site->db->prepare("SELECT * FROM permissions  WHERE group_id=? AND source_id = ?", 1, $folder_id);
	$sth2 = new SQL($sql2);
	$tmp = $sth2->fetch();
	$perm_mask = $tmp['C'].$tmp['R'].$tmp['U'].$tmp['P'].$tmp['D'];

#		echo "<tr bgcolor=\"FFFFFF\"><td>"; 	
#printr($perm_mask);
#	echo "</td></tr>"; 	
#printr($objekt->all['pealkiri']. ' => '.$perm_mask.' (ID: '.$folder_id.')');

	if($perm_mask != '11111') { # wrong perm mask

	#####################
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);
}
/**
 * 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_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_message($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "message";
    }
    switch ($on_create) {
        case "publish":
            $publish = 1;
            break;
        case "hide":
            $publish = 0;
            break;
        default:
            $publish = 0;
    }
    ##############
    # luua objekt
    $obj = new Objekt(array(objekt_id => $id));
    ##############
    # minna edasi vaid siis kui tegemist on kommentaariga/kirjaga
    if (!$obj->all[klass] == "kommentaar") {
        # error pealkirja or smth
        # assign
        # exit;
    }
    ##############
    # load variables
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 14, publish => $publish));
    $obj->id = $obj->objekt_id;
    $obj->parent_href = $site->self . '?id=' . $obj->parent_id;
    $obj->title = $obj->pealkiri();
    $obj->load_sisu();
    $obj->body = nl2br(htmlspecialchars($obj->all[text]));
    $obj->author = $obj->all[nimi];
    $obj->author_email = $obj->all[email];
    $obj->hide_email = $obj->all[on_peida_email];
    $obj->started = $site->db->MySQL_ee_short($obj->all[aeg]);
    $obj->date = $obj->started;
    # alternative name
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->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
    # parent subject
    $obj->parent_subject = $leht->parents->get(1);
    $obj->parent_subject_id = $obj->parent_subject->objekt_id;
    $obj->parent_subject_title = $obj->parent_subject->pealkiri;
    # parent section
    $obj->parent_section = $leht->parents->get(2);
    $obj->parent_section_id = $obj->parent_section->objekt_id;
    $obj->parent_section_title = $obj->parent_section->pealkiri;
    #	$obj->parent_section_href = $obj->parent_section->objekt_id;
    $obj->hit_count = $obj->all['count'];
    $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'];
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
}
function smarty_function_init_article($params, &$smarty)
{
    global $site, $leht, $template, $class_path;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if ($system_message || $system_alias) {
        $system_message = $system_alias ? $system_alias : $system_message;
        $id = $site->alias(array('key' => translate_ee($system_message), 'keel' => $site->keel));
    }
    if (!isset($name)) {
        $name = "article";
    }
    // on_create statements:
    $on_create = explode(',', $on_create);
    // default on_create statements:
    $publish = 0;
    $allow_comments = $site->CONF['default_comments'];
    // cycle statements
    foreach ($on_create as $on_create_statement) {
        $on_create_statement = trim($on_create_statement);
        switch ($on_create_statement) {
            case 'publish':
                $publish = 1;
                break;
            case 'hide':
                $publish = 0;
                break;
            case 'allow_comments':
                $allow_comments = 1;
                break;
        }
    }
    # if parameter "get_object_fields" is given (may be comma sep.list), then split it to array
    if (isset($get_object_fields)) {
        $get_object_fields_arr = split(",", $get_object_fields);
        $i = 0;
        foreach ($get_object_fields_arr as $tmp) {
            $get_object_fields_arr[$i] = trim($tmp);
            $i++;
        }
    }
    ###############
    # action-buttons
    # by default show all
    if (!isset($buttons)) {
        $buttons = array("new", "edit", "hide", "move", "delete");
    } else {
        $buttons = split(",", $buttons);
    }
    if (!isset($ttyyp_id)) {
        $ttyyp_id = 0;
    }
    // system alias given but no such article, can be created under system section
    if (!$id) {
        $parent_id = $site->alias('system');
        $alamlist = new Alamlist(array('parent' => $parent_id, 'klass' => 'artikkel', 'asukoht' => $position, 'start' => 0, 'limit' => 1));
        $new_button = $alamlist->get_edit_buttons(array('tyyp_idlist' => 2, 'publish' => $publish, 'allow_comments' => $allow_comments, 'sys_alias' => $system_message));
        $smarty->assign($name . '_newbutton', $new_button);
        return;
    }
    ##############
    # luua objekt
    $objSettings = array();
    $objSettings['objekt_id'] = $id;
    $obj = new Objekt($objSettings);
    $allObjParents = $obj->get_obj_all_parents($objSettings['objekt_id']);
    if (in_array($leht->parents->list[0]->parent_id, $allObjParents)) {
        $objSettings['parent_id'] = $leht->parents->list[0]->parent_id;
        $obj = new Objekt($objSettings);
    }
    ##############
    # minna edasi vaid siis kui tegemist on artikliga
    if (!$obj->all[klass] == "artikkel") {
        # error pealkirja or smth
        # assign
        # exit;
    }
    ##############
    # load variables
    #PREVIOUS ARTICLE
    $alamlistSQL = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0, order => "objekt_objekt.sorteering ASC"));
    $alamlistSQL->add_where("sorteering>'" . $obj->all['sorteering'] . "'");
    $alamlist = new Alamlist(array(alamlistSQL => $alamlistSQL, start => 0, limit => 1));
    #NEXT ARTICLE
    $alamlistSQL2 = new AlamlistSQL(array(parent => $obj->parent_id, klass => "artikkel", asukoht => 0));
    $alamlistSQL2->add_where("sorteering<'" . $obj->all['sorteering'] . "'");
    $alamlist2 = new Alamlist(array(alamlistSQL => $alamlistSQL2, start => 0, limit => 1));
    $prev_art = $alamlist->next();
    $next_art = $alamlist2->next();
    $obj->id = $obj->objekt_id;
    $obj->get_object_href();
    $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
    $obj->title = $obj->pealkiri;
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->show_headline = $obj->all['on_pealkiri'];
    $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
    $obj->details_title = $site->sys_sona(array(sona => "loe edasi", tyyp => "kujundus"));
    $obj->printgif = '<a href="' . $obj->href . '&op=print" onClick="avaprintaken(this.href, 600, 400, \'print\'); return false;" target=_blank><img src="' . $site->img_path . '/print_it.gif" border=0 width=19 height=18></a>';
    $obj->printlink = $site->self . '?id=' . $obj->objekt_id . '&op=print';
    # added 08.11.2002:
    $obj->comment_link = $site->self . '?id=' . $obj->objekt_id . '#comm';
    $obj->comment_title = $site->sys_sona(array(sona => "Kommentaarid", tyyp => "kujundus"));
    $obj->add_comment_link = $site->self . '?id=' . $obj->objekt_id . '#cbox';
    $obj->add_comment_title = $site->sys_sona(array(sona => "Add", tyyp => "kujundus"));
    # existing already by default: $obj->comment_count
    $obj->forum_allowed = $obj->all[on_foorum];
    $obj->last_commented_time = $site->db->MySQL_ee($obj->all['last_commented_time']);
    $obj->comment_count = $obj->all['comment_count'];
    # added 21.01.2003:
    $obj->author = $obj->all[author];
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    $obj->next_id = $next_art->objekt_id;
    $obj->prev_id = $prev_art->objekt_id;
    $obj->hit_count = $obj->all['count'];
    ##############
    # load sisu
    $obj->load_sisu();
    if (0 && $context_start) {
        $obj->lead = $context_start . $obj->lyhi->get_text() . '</editor:context>';
        $obj->body = $context_start . $obj->sisu->get_text() . '</editor:context>';
    } else {
        $obj->lead = $obj->lyhi->get_text();
        $obj->body = $obj->sisu->get_text();
    }
    if (!$site->in_editor && $site->CONF['use_aliases'] && $site->CONF['replace_links_with_alias']) {
        $hostUrl = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $site->wwwroot . '/';
        //body urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->body, $searchResults, PREG_SET_ORDER);
        //body urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed body urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->body, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with "
        preg_match_all('{<a[^>]+href="((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))"[^>]*>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //lead urls enclosed with '
        preg_match_all("{<a[^>]+href='((" . str_replace('.', '\\.', $hostUrl) . "[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>0-9]*))'[^>]*>.+</a>}Ui", $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        //non-enclosed lead urls
        preg_match_all('{<a[^>]+href=((' . str_replace('.', '\\.', $hostUrl) . '[^>]*|/[^>]*|index.php|)\\?([^>]*id=([0-9]+)[^>\\s0-9]*))(\\s+[^>]*|)>.+</a>}Ui', $obj->lead, $searchResults2, PREG_SET_ORDER);
        $searchResults = array_merge($searchResults, $searchResults2);
        foreach ($searchResults as $key => $value) {
            //create an object with the id found in url
            $linkObj = new Objekt(array(objekt_id => $value[4]));
            $variables = array();
            $separator = strpos($value[3], '&amp;') !== false ? '&amp;' : '&';
            foreach (explode($separator, $value[3]) as $param) {
                $paramArray = explode('=', $param);
                if ($paramArray[0] != 'id') {
                    $variables[] = $param;
                }
            }
            if (count($variables) > 0) {
                $param = '?' . implode('&amp;', $variables);
            } else {
                $param = '';
            }
            $replaceValue = str_replace($value[1], (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $linkObj->get_object_href() . $param, $value[0]);
            $obj->lead = str_replace($value[0], $replaceValue, $obj->lead);
            $obj->body = str_replace($value[0], $replaceValue, $obj->body);
        }
    }
    #############
    # buttons (must be after load_sisu(), Bug #1963)
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => $obj->all['tyyp_id'], nupud => $buttons, ttyyp_id => $ttyyp_id, profile_id => $obj->all['profile_id'], publish => $publish, 'allow_comments' => $allow_comments));
    ########## KUI artiklil on Mļæ½ļæ½RATUD mļæ½ni PROFIIL, siis korja andmed "->" omadustena kokku
    if ($obj->all['profile_id']) {
        #printr($obj->objekt_id.' PROFILE_ID: '.$obj->all['profile_id']);
        include_once $class_path . 'profile.class.php';
        $obj_profile = new Profile(array("id" => $obj->all['profile_id']));
        #### 1. set profile fields as object attributes
        $obj_profile->set_obj_general_fields(array("obj" => &$obj, "get_object_fields" => $get_object_fields));
        ###################
        # get selectlist values - 1 extra sql per function; sql is fast
        if (is_array($obj_profile->selectlist)) {
            $obj_profile->selectlist = array_unique($obj_profile->selectlist);
            #printr($obj_profile->selectlist);
        }
        # go on if object values needs changing:
        if (sizeof($obj_profile->selectlist) > 0) {
            #### 2. save array "->asset_names"  human readable NAME-s:
            $obj_profile->get_asset_names(array("selectlist" => $obj_profile->selectlist));
            #printr($obj_profile->asset_names);
            #printr($obj_profile->change_fields);
            ### 3. save object rest of attributes
            #print "<br>muuta ID: ".$obj->id;
            $obj_profile->set_obj_selectlist_fields(array("obj" => &$obj, "change_fields" => $obj_profile->change_fields));
        }
        # if any selectvalue exist & need to change
        # / get selectlist values
        ###################
    }
    ####### / profile is set
    $obj->created_user_id = $obj->all['created_user_id'];
    $obj->created_user_name = $obj->all['created_user_name'];
    $obj->changed_user_id = $obj->all['changed_user_id'];
    $obj->changed_user_name = $obj->all['changed_user_name'];
    $obj->created_time = $site->db->MySQL_ee($obj->all['created_time']);
    $obj->fcreated_time = $obj->all['created_time'];
    $obj->changed_time = $site->db->MySQL_ee($obj->all['changed_time']);
    $obj->fchanged_time = $obj->all['changed_time'];
    ##############
    # assign to template variables
    $smarty->assign($name, $obj);
    //return $obj; # bug #1921 # for {init_object} tag
}
 function Parents()
 {
     $args = func_get_arg(0);
     $this->ObjektArray();
     $this->meta = array();
     if (is_object($args['parent']) && !strcasecmp(get_class($args['parent']), 'Objekt')) {
         # parent on objekt
         $this->parent_id = $args["parent"]->objekt_id;
         $this->debug->msg("Parents. Antud on objekt: parent_id = " . $this->parent_id);
     } elseif (preg_match("/^\\d+\$/", $args["parent"])) {
         # parent on objekti ID
         $this->parent_id = $args["parent"];
         $this->debug->msg("Parents. Antud on objekti ID: parent_id = " . $this->parent_id);
     } else {
         # parent on vigane
         $this->debug->msg("vigased algandmed: \"{$args['parent']}\" pole objekt ega objekti ID");
     }
     # merle h�mar kommentaar "lisa_objekt"-ile: mulle tundub, et see on vajalik situatsioonis,
     # kus URL-i peal id puudub JA tegu on vana fiks. op-malliga: siis "on meil eriobjekt"
     # ja oleks vaja seda op-malli n�idata HOME rubriigi all ja seep�rast lisatakse parentsi l�ppu objekt HOME.
     if ($args["lisa_objekt"]) {
         $this->add($args["lisa_objekt"]);
     }
     if ($this->parent_id) {
         $id = $this->parent_id;
         $this->debug->msg("Parents. Alguses parent_id = " . $this->parent_id);
         $idid = array();
         # juhul kui HOME, on vaja �he sammu v�rra alla minna
         if ($args["on_esileht"]) {
             $this->debug->msg("Antud HOME rubriik, h�ppame �he taseme v�rra alla");
             $alamlist = new Alamlist(array("parent" => $id, "start" => 0, "limit" => 1, "klass" => 'rubriik', "order" => "objekt.kesk asc, sorteering DESC"));
             $this->debug->msg($alamlist->debug->get_msgs());
             if ($alamlist->size) {
                 $obj = $alamlist->get(0);
                 $id = $obj->objekt_id;
                 $this->debug->msg("Uus ID = {$id}");
             } else {
                 $this->debug->msg("Kahjuks alla h�pata ei saa... Pole sobivat kohta");
             }
         }
         $this->aktiivne_id = $id;
         #############################
         # allah�ppamine
         $this->debug->msg("JUMP: ================START================");
         $this->debug->msg("Jump down? " . ($this->site->in_editor || $this->site->in_admin ? "We are in editor-area or admin-area => abort mission" : "We are in public area => start mission"));
         # We are in public area => start missio:
         if (!($this->site->in_editor || $this->site->in_admin)) {
             do {
                 $last_id = $id;
                 $obj = new Objekt(array("objekt_id" => $id));
                 $this->debug->msg($obj->debug->get_msgs());
                 #####################
                 # kui objekt on rubriik JA talle pole ei lehe- ega sisumalli m��ratud
                 # siis tuleb objekti auto avanemine ise otsustada.
                 # variante on 2:
                 if ($obj->all[klass] == "rubriik" && !$obj->all["page_ttyyp_id"] && !$obj->all["ttyyp_id"]) {
                     $obj->all["on_auto_avanev"] = $this->site->master_tpl["on_auto_avanev"];
                     $this->debug->msg("JUMP: Auto avanemise m��rab saidi p�himall (ID=" . $this->site->master_tpl[ttyyp_id] . ")" . $this->site->master_tpl["on_auto_avanev"]);
                 } elseif ($obj->all["page_ttyyp_id"] && !$obj->all["ttyyp_id"]) {
                     $sql = $this->site->db->prepare("SELECT on_auto_avanev FROM templ_tyyp WHERE ttyyp_id=?", $obj->all["page_ttyyp_id"]);
                     $sth = new SQL($sql);
                     $obj->all["on_auto_avanev"] = $sth->fetchsingle();
                 }
                 $this->debug->msg("JUMP: Tulemus: objekt " . $obj->objekt_id . " " . ($obj->all["on_auto_avanev"] ? "ON" : "EI OLE") . " auto avanev ");
                 # juhul, kui malli on_auto_avanev = 1,
                 # siis hakka pihta
                 if ($obj->all["on_auto_avanev"]) {
                     # kontrollime objektide olemasolu
                     $alamlist = new Alamlist(array("parent" => $obj->objekt_id, "on_counter" => 1, "not_klass" => "rubriik,loginkast,kogumik,link", "order" => "sorteering DESC"));
                     $this->debug->msg($alamlist->debug->get_msgs());
                     # alamlist on tyhi
                     if ($alamlist->rows == 0) {
                         $this->debug->msg("JUMP: Otsime esimest alamrubriiki, kuhu v�iks h�pata");
                         $alamlist = new Alamlist(array("parent" => $obj->objekt_id, "start" => 0, "klass" => "rubriik", "not_tyyp_nimi" => "Lingikast"));
                         $this->debug->msg($alamlist->debug->get_msgs());
                         # kui leiti alamrubriik vaata talle otsa ja p��a teda lisada
                         if ($alamlist->rows > 0) {
                             $obj = $alamlist->next();
                             $this->debug->msg($alamlist->debug->get_msgs());
                             # kui ei �nnestunud objekti korralikult k�tte saada (polnud �iguseid)
                             # siis nendi fakti ja �ra h�ppa alla
                             if (!$obj->objekt_id) {
                                 $this->debug->msg("JUMP: Objekti ei tehtud, ei h�ppa alla");
                             } else {
                                 # JUMP REALLY DOWN here:
                                 $this->debug->msg("JUMP: H�ppasime alla ja n��d on aktiivne id = " . $obj->objekt_id);
                                 $id = $obj->objekt_id;
                             }
                             # kas objekt on vaatamiseks tibens
                         } else {
                             $this->debug->msg("JUMP: Ei h�ppa alla, sest polnud rubriiki, kuhu h�pata");
                         }
                     } else {
                         $this->debug->msg("JUMP: Ei h�ppa alla, sest leiti alamobjekte!");
                     }
                 }
             } while ($last_id !== $id);
         }
         # to jump or not to jump
         $this->aktiivne_id = $id;
         $this->debug->msg("JUMP: ================END================");
         # / allah�ppamine
         #############################
         #############################
         # loop over parents
         $first = 1;
         $i = 0;
         while ($id) {
             # hakkame antud objektist �lesse minna
             #######################
             # if current object, do extra checks:
             # 1) decide which parent to use from now on
             # 2) check if object's language matches with site language
             if ($first || $i == 1) {
                 # if first or second (if we have sub-article as current object, Bug #1955)
                 $obj_parent = "";
                 # 1. ja 2. objekti p�ritakse 2 korda (pole ilus lahendus, hetkel h�davajadus):
                 # 1. kord selleks, et teada saada tema klass
                 $obj = new Objekt(array("objekt_id" => $id, "no_cache" => 1));
                 #################
                 # 1) if current object is article, then start searching parents (we have to find correct parent)
                 if ($obj->all["klass"] == "artikkel") {
                     $this->debug->msg("Current object" . ($i == 1 ? "'s parent" : "") . " is article. Start doing extra check.");
                     # find all parent id-s of this object
                     #####################
                     # 1a. if found more than 1 parent => go on and find right parent
                     if ($obj->all['parents_count'] > 1) {
                         $all_parents = $obj->get_obj_all_parents($obj->objekt_id);
                         # v6ttame maha prygikasti rubriik parenti listist:
                         if ($this->site->alias("trash")) {
                             if (in_array($this->site->alias("trash"), $all_parents)) {
                                 $all_parents = array_diff($all_parents, array($this->site->alias("trash")));
                             }
                         }
                         $this->debug->msg("Object " . $obj->objekt_id . " has " . sizeof($all_parents) . " parents: " . join(",", $all_parents));
                         # get cookie with previous page current section value
                         #$cookie_parent = $this->site->sess_get("current_section");
                         $cookie_parent = $_COOKIE["current_section"];
                         ###################
                         # parent_id in URL (Bug #538)
                         # new feature: parameter "parent_id" in URL, it overrides "current_section" cookie settings
                         if ($this->site->fdat['parent_id']) {
                             $obj_parent = $this->site->fdat['parent_id'];
                             $this->debug->msg("Parent found in URL. Parent set to: " . $obj_parent);
                         } elseif (is_array($_SESSION['alias'])) {
                             #Alias being used and a direct path to the object is being shown.
                             foreach ($_SESSION['alias'] as $cuuki) {
                                 if ($cuuki['objekt_id'] == $obj->objekt_id) {
                                     $obj_parent = $cuuki['parent_id'];
                                 }
                             }
                         }
                         ###################
                         # if cookie has value, go on
                         if ($cookie_parent && $obj_parent == "") {
                             $this->debug->msg("Found current_section cookie: " . $cookie_parent);
                             # if 1 object parent is same as cookie, take this for parent
                             if (in_array($cookie_parent, $all_parents)) {
                                 $obj_parent = $cookie_parent;
                                 $this->debug->msg("Parent set to:" . $obj_parent);
                             } else {
                                 $this->debug->msg("Cookie doesn't match. Searching match from parents...");
                                 foreach ($all_parents as $par) {
                                     # find all parents for parent
                                     $all_parents = $obj->get_obj_all_parents($par);
                                     # if 1 object parent is same as cookie, take this for parent
                                     if (in_array($cookie_parent, $all_parents)) {
                                         $obj_parent = $par;
                                         $this->debug->msg("Parent set to:" . $obj_parent);
                                         break;
                                     }
                                 }
                                 # foreach
                                 if (!$obj_parent) {
                                     $this->debug->msg("No match found in parents. Parent not set.");
                                 }
                             }
                             # if not match
                         } else {
                             $this->debug->msg("I have no idea, which parent to prefer => choosing just the first one");
                         }
                         # / just pick first parent - we have no info which one to prefer
                         ###################
                     }
                     # / if found more than 1 parent, go on
                     #####################
                 }
                 # / if current object is article, then start searching parents
                 #################
                 # 2) check if object's language matches with site language
                 # bug #2398 : skip language check and automatic langchange for folders, files.
                 # bug #2661 : Sisuobjekti detailvaate lingile lisatud ?lang=en parameeter peab alati m�juma (site classis v�etakse fdat->keel m�lemast parameetrist juba)
                 if ($obj->objekt_id && !in_array($obj->all['tyyp_id'], array(21, 22)) && !isset($this->site->fdat['keel'])) {
                     $this->debug->msg("Language check: current object (ID=" . $obj->objekt_id . ") language is: " . $obj->all[keel] . "; site language is: " . $this->site->keel);
                     # if they differ, change site language
                     if ($obj->all[keel] != $this->site->keel) {
                         $this->site->change_keel($obj->all[keel]);
                         $this->debug->msg("Site language set to: " . $obj->all[keel]);
                     }
                 }
                 $no_cache = 1;
             } else {
                 $obj_parent = "";
                 $no_cache = 0;
             }
             # / if current object, decide which parent to use from now on
             #######################
             ###################
             # create object
             $obj = new Objekt(array("objekt_id" => $id, "parent_id" => $obj_parent, "no_cache" => $no_cache));
             $this->debug->msg($obj->debug->get_msgs());
             # if creating object fails (because of wrong parent), do it without parent
             if (!$obj->objekt_id) {
                 $obj = new Objekt(array("objekt_id" => $id, "no_cache" => 1));
                 $this->debug->msg($obj->debug->get_msgs());
             }
             ############# if creating object still fails then QUIT because PARENT IS FORBIDDEN
             if (!$obj->objekt_id) {
                 $this->debug->msg("PARENTS: Kuna �ks parentitest on keelatud siis l�peta kogu t�� ja reseti parents");
                 $this->list = array();
                 $this->objekts = array();
                 $this->set_size();
                 $this->index = -1;
                 return;
             } elseif (!$idid["id" . $id]) {
                 # viimases rubriigis vaatame on_peida_vmenyy v��rtus
                 if ($obj->all["klass"] == "rubriik" && !isset($on_peida_vmenyy)) {
                     $obj->load_sisu();
                     $on_peida_vmenyy = $obj->all["on_peida_vmenyy"];
                     $this->debug->msg("Aktiivse rubriigi on_peida_vmenyy is: " . $obj->all["on_peida_vmenyy"]);
                 }
                 # lisame objekt
                 $this->add($obj);
                 # meta
                 if ($this->meta["keywords"] == "" && $obj->all["meta_keywords"] != "") {
                     $this->meta["keywords"] = $obj->all["meta_keywords"];
                     $this->debug->msg("meta keyword = " . $this->meta["keywords"]);
                 }
                 if ($this->meta["description"] == "" && $obj->all["meta_description"] != "") {
                     $this->meta["description"] = $obj->all["meta_description"];
                     $this->debug->msg("meta description = " . $this->meta["description"]);
                 }
                 if ($this->meta["title"] == "" && $obj->all["meta_title"] != "") {
                     $this->meta["title"] = $obj->all["meta_title"];
                     $this->debug->msg("meta title = " . $this->meta["title"]);
                 }
                 $idid["id" . $id] = 1;
                 ############################
                 # set next ID
                 $id = $obj->parent_id;
                 ############################
                 # set next ID exception: 18.05.03 by merle
                 # force another parent for system article:
                 # if object is system article, then dont proceed with its real parent (system section)
                 # but force its parent to be first page in the site
                 if ($first && $obj->parent_id == $this->site->alias("system") && $obj->all["klass"] == "artikkel") {
                     $this->debug->msg("Current object is system article: " . $obj->all[sys_alias]);
                     $home_alamlist = new Alamlist(array("parent" => $this->site->alias("rub_home_id"), "start" => 0, "limit" => 1, "tyyp" => 'rubriik'));
                     if ($home_alamlist->size) {
                         $home_obj = $home_alamlist->get(0);
                         $id = $home_obj->objekt_id;
                         $this->debug->msg("Because its system article, parent is forced to be: {$id}");
                     } else {
                         $this->debug->msg("Setting new parent for system article failed - not found any section");
                     }
                 }
                 # force another parent for system article:
                 ############################
             } else {
                 $idid["id" . $id] = 1;
                 $id = '';
             }
             $i++;
             $first = 0;
         }
         # while obj
         # / loop over parents
         ####################
         $this->on_peida_vmenyy = $on_peida_vmenyy;
         #defined("on_peida_vmenyy") ? constant("on_peida_vmenyy"):0;
     }
     # if parent
 }
function smarty_function_init_document($params, &$smarty)
{
    global $site, $leht, $template;
    $content_template =& $leht->content_template;
    ##############
    # default values
    extract($params);
    if (!isset($id)) {
        $id = $leht->id;
    }
    if (!isset($name)) {
        $name = "document";
    }
    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);
    }
    if (!isset($ttyyp_id)) {
        $ttyyp_id = 0;
    }
    ##############
    # luua objekt
    $obj = new Objekt(array(objekt_id => $id));
    ##############
    # load variables
    $obj->load_sisu();
    $obj->buttons = $obj->get_edit_buttons(array(tyyp_idlist => 7, asukoht => $position, publish => $publish));
    $obj->id = $obj->objekt_id;
    $obj->href = $site->self . '?id=' . $obj->objekt_id;
    $obj->is_selected = $leht->parents->on_parent($obj->objekt_id);
    $obj->title = $obj->pealkiri;
    $obj->date = $site->db->MySQL_ee_short($obj->all['aeg']);
    $obj->datetime = $site->db->MySQL_ee($obj->all['aeg']);
    $obj->fdate = substr($obj->all['aeg'], 0, strpos($obj->all['aeg'], ' '));
    $obj->fdatetime = $obj->all['aeg'];
    $obj->last_modified = date('Y', $obj->all['last_modified']) > 1970 ? date('d.m.Y H:i', $obj->all['last_modified']) : '';
    ## crap data
    $obj->flast_modified = $obj->all['last_modified'];
    $obj->file = $obj->filename = $obj->all['fail'];
    $obj->description = $obj->all['kirjeldus'];
    $obj->size = $obj->all['size'];
    $obj->size_formated = print_filesize($obj->all['size']);
    $obj->author = $obj->all['author'] ? $obj->all['author'] : $obj->all['autor'];
    $obj->details_link = $site->self . '?id=' . $obj->objekt_id;
    $obj->download_link = 'doc.php?' . $obj->objekt_id;
    $obj->class = translate_en($obj->all[klass]);
    # translate it to english
    $obj->hit_count = $obj->all['count'];
    # added 15.12.2004:
    $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 => "Lisa kommentaar", tyyp => "kujundus"));
    #no UI for this:	$obj->forum_allowed = $obj->all[on_foorum];
    $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'];
    $smarty->assign($name, $obj);
    //return $obj; # bug #1921 for {init_object} tag
}