/**
* 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 upload_to_folder($file, $folder_id)
{
    global $site;
    $folder_id = (int) $folder_id;
    $objekt = new Objekt(array('objekt_id' => $folder_id, 'on_sisu' => 1));
    if ($objekt->objekt_id == $folder_id && $objekt->all['tyyp_id'] == 22) {
        // check for Create permission
        if (!$objekt->permission['U']) {
            new Log(array('action' => 'create', 'type' => 'WARNING', 'component' => 'Files', 'objekt_id' => $objekt->objekt_id, 'message' => "Attempt to create file under '" . $objekt->all['relative_path'] . "' (ID = " . $objekt->objekt_id . ") with no create permission."));
            return 'no_permissions_to_create_file';
        }
        $folder_path = preg_replace('#/$#', '', $site->absolute_path) . $objekt->all['relative_path'];
        $filename = $file['name'];
        $filename_parts = explode('.', $file['name']);
        if (sizeof($filename_parts) > 1) {
            $file_extension = array_pop($filename_parts);
            $file_basename = implode('.', $filename_parts);
        } else {
            $file_extension = '';
            $file_basename = $filename;
        }
        $i = 0;
        while (file_exists($folder_path . '/' . $filename)) {
            $filename = $file_basename . '_' . ++$i . ($file_extension ? '.' . $file_extension : '');
            // loop guard
            if ($i > 1000) {
                return 'file_already_exists';
            }
        }
        $file['name'] = $filename;
        $upload_result = upload_file_to_folder($file, $folder_path);
        if ($upload_result === true) {
            $file_id = insert_new_file_object($objekt, $file['name'], $file['size'], $file['type']);
            // thumbnail?
            create_file_thumbnail($folder_path . '/' . safe_filename2($file['name']));
            return (int) $file_id;
        } else {
            new Log(array('action' => 'update', 'component' => 'Files', 'type' => 'ERROR', 'message' => "Could not create file in '" . $objekt->all['relative_path'] . "', file system error."));
            return $upload_result;
        }
    } else {
        return 'no_such_folder_object';
    }
}
        $response = array('error' => 0);
    } else {
        $response = array('error' => 1, 'error_message' => $delete_message);
    }
    echo $json_encoder->encode($response);
    exit;
}
// edit folder
if ($site->user->user_id && $site->fdat['op'] == 'edit_folder' && (int) $site->fdat['folder_id'] && $site->fdat['name']) {
    verify_form_token();
    include_once $class_path . 'adminpage.inc.php';
    include_once $class_path . 'custom.inc.php';
    include_once $class_path . 'lgpl/Services_JSON.class.php';
    $json_encoder = new Services_JSON();
    $folder_id = (int) $site->fdat['folder_id'];
    $name = safe_filename2($site->fdat['name']);
    $rename_message = rename_folder($name, $folder_id);
    if ($rename_message === true) {
        $objekt = new Objekt(array('objekt_id' => $folder_id));
        $folders = get_subfolders($objekt->parent_id);
        // dont send the parent itself
        reset($folders);
        unset($folders[key($folders)]);
        $response = array('error' => 0, 'folder_id' => $folder_id, 'folders' => $folders);
    } else {
        $response = array('error' => 1, 'error_message' => $rename_message);
    }
    echo $json_encoder->encode($response);
    exit;
}
// get folder files
function safe_filename($name)
{
    /*
    $name = preg_replace("/[^\w\.]/","_",$name);
    $name = str_replace(array('�','�','�','�','�','�','�','�'), array('O','o','A','a','O','o','U','u'), $name);
    */
    return safe_filename2($name);
}
 if (!empty($site->CONF['documents_in_filesystem']) && !empty($site->CONF['documents_directory']) && file_exists(str_replace('//', '/', $site->absolute_path . $site->CONF['documents_directory']))) {
     $download_filename = '';
     if (!empty($_GET['filename']) && $_GET['filename'] == 'original' && !empty($result['fail'])) {
         $download_filename = preg_replace(array("/[<>:\"\\/\\\\?\\|\\*]+/", "/^[\\s\\.]+/", "/[\\s\\.]+\$/"), '', $result['fail']);
     } else {
         if (!empty($objekt->all['pealkiri'])) {
             $download_filename = preg_replace(array("/[<>:\"\\/\\\\?\\|\\*]+/", "/^[\\s\\.]+/", "/[\\s\\.]+\$/"), '', $objekt->all['pealkiri']);
         }
         if (!empty($result['tyyp'])) {
             $download_filename .= '.' . preg_replace(array("/[<>:\"\\/\\\\?\\|\\*]+/", "/^[\\s\\.]+/", "/[\\s\\.]+\$/"), '', $result['tyyp']);
         }
         if (!preg_replace("/\\." . $result['tyyp'] . "\$/", '', $download_filename) && !empty($result['fail'])) {
             $download_filename = preg_replace(array("/[<>:\"\\/\\\\?\\|\\*]+/", "/^[\\s\\.]+/", "/[\\s\\.]+\$/"), '', $result['fail']);
         }
     }
     header("Content-Disposition: " . (!empty($_GET['disposition']) && $_GET['disposition'] == 'inline' ? 'inline' : 'attachment') . "; filename=\"" . safe_filename2($download_filename) . "\"; filename*=UTF-8''" . rawurlencode($download_filename) . "");
 } else {
     header("Content-Disposition: attachment; filename=\"" . $result['fail'] . "\"");
 }
 header("Content-Type: {$ctype}");
 header("Cache-control: private");
 header("Pragma: public");
 if ($result['download_type']) {
     if (!empty($site->CONF['documents_in_filesystem']) && !empty($site->CONF['documents_directory']) && file_exists(str_replace('//', '/', $site->absolute_path . $site->CONF['documents_directory']))) {
         $doc_name = md5($result['objekt_id']);
         $doc_full_path = str_replace('//', '/', $site->absolute_path . $site->CONF['documents_directory'] . '/' . $doc_name[0] . '/' . $doc_name);
         if (!empty($site->CONF['documents_mod_xsendfile']) && in_array('mod_xsendfile', apache_get_modules())) {
             header('X-Sendfile: ' . $doc_full_path);
             exit;
         }
     } else {
function salvesta_objekt()
{
    global $site;
    global $objekt;
    global $class_path;
    if ($objekt->objekt_id) {
        if ($objekt->on_sisu_olemas) {
            # -------------------------------
            # Objekti uuendamine andmebaasis
            # -------------------------------
            $parent_folder = new Objekt(array('objekt_id' => $objekt->parent_id, 'on_sisu' => 1));
            $fileupload = $_FILES['fileupload'];
            if ($fileupload['name'] && $parent_folder->all['relative_path']) {
                $fileupload['name'] = safe_filename2($fileupload['name']);
                $upload_path = preg_replace('#/$#', '', $site->absolute_path) . $parent_folder->all['relative_path'];
                $upload = upload_file_to_folder($fileupload, $upload_path);
                if ($upload === true) {
                    create_file_thumbnail($upload_path . '/' . $fileupload['name']);
                    $pealkiri = $site->fdat['pealkiri'] ? $site->fdat['pealkiri'] : $fileupload['name'];
                    $mimetype = get_file_mime_content_type($upload_path . '/' . $fileupload['name']);
                    $pathinfo = pathinfo($upload_path . '/' . $fileupload['name']);
                    ############ 1) update record in object content table:
                    $sql = $site->db->prepare("update obj_file set relative_path = ?, filename = ?, mimetype = ?, size = ? where objekt_id = ?;", $parent_folder->all['relative_path'] . '/' . $fileupload['name'], $pathinfo['basename'], $mimetype, filesize($upload_path . '/' . $fileupload['name']), $objekt->objekt_id);
                    $sth = new SQL($sql);
                    //if($site->fdat['dir']) refresh_gallery_images($objekt, $site->fdat['dir']);
                }
                //if fullpath
            }
            //if file size
            ############ 1) create always record in object content table:
            $sql = $site->db->prepare("UPDATE obj_file SET profile_id=? WHERE objekt_id=?", $site->fdat['profile_id'], $objekt->objekt_id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            if ($site->fdat['in_wysiwyg'] == 1) {
                $objekt->all['in_wysiwyg_filename'] = $pathinfo['basename'];
                // very ugly workaround for bug #2269
                //printr($objekt->all['in_wysiwyg_filename']);
            }
        } else {
            # -------------------------------
            # Objekti loomine andmebaasis
            # -------------------------------
            /*
             * Upload file data and make thumbnail
             */
            /*
            # old usage of "dir" - when files where not content objects as should,
            # find "dir" value from "parent_id" (parent_id overrules any "dir" value):
            if($site->fdat['parent_id']){
            	$sql = $site->db->prepare("SELECT * FROM obj_folder  WHERE objekt_id = ?", $site->fdat['parent_id']);
            	$sth = new SQL($sql);
            	$parent_folder = $sth->fetch();
            }
            */
            if ($objekt->parent_id) {
                $parent_folder = new Objekt(array('objekt_id' => $objekt->parent_id, 'on_sisu' => 1));
            } elseif ($site->fdat['parent_id']) {
                $parent_folder = new Objekt(array('objekt_id' => $site->fdat['parent_id'], 'on_sisu' => 1));
            } elseif ($site->fdat['dir']) {
                $sql = $site->db->prepare('select objekt_id from obj_folder where relative_path = ?', '/' . $site->fdat['dir']);
                $result = new SQL($sql);
                $parent_folder = new Objekt(array('objekt_id' => $result->fetchsingle(), 'on_sisu' => 1));
            } else {
                //screwed, dont know where to put the object
                exit;
            }
            $site->fdat['dir'] = preg_replace('#^/#', '', $parent_folder->all['relative_path']);
            $fileupload = $_FILES['fileupload'];
            if ($fileupload['name'] && $parent_folder->all['relative_path']) {
                $fileupload['name'] = safe_filename2($fileupload['name']);
                $upload_path = preg_replace('#/$#', '', $site->absolute_path) . $parent_folder->all['relative_path'];
                $upload = upload_file_to_folder($fileupload, $upload_path);
                $fullpath = $upload_path . '/' . $fileupload['name'];
                if ($upload === true) {
                    create_file_thumbnail($fullpath);
                    $pealkiri = $site->fdat['pealkiri'] ? $site->fdat['pealkiri'] : $fileupload['name'];
                    $mimetype = get_file_mime_content_type($fullpath);
                    $pathinfo = pathinfo($fullpath);
                    ############ 1) create always record in object content table:
                    $sql = $site->db->prepare("INSERT INTO obj_file (objekt_id, relative_path, filename, mimetype, size, profile_id) VALUES (?,?,?,?,?,?)", $objekt->objekt_id, $parent_folder->all['relative_path'] . '/' . $pathinfo['basename'], $pathinfo['basename'], $mimetype, filesize($fullpath), $site->fdat['profile_id']);
                    #print $sql."<hr>";
                    $sth = new SQL($sql);
                    if ($site->fdat['in_wysiwyg'] == 1) {
                        $objekt->all['in_wysiwyg_filename'] = $pathinfo['basename'];
                        // very ugly workaround for bug #2269
                    }
                    if ($site->fdat['dir']) {
                        refresh_gallery_images($objekt, $site->fdat['dir']);
                    }
                }
                //if fullpath
            }
            //if file size
        }
        //if update or insert
    } else {
        $site->debug->msg("sisu pole salvestatud kuna objekt_id puudub");
    }
}