Beispiel #1
0
 /**
  * Show the contact page
  * @param string $lang
  */
 public function index($lang = "")
 {
     // https://css-tricks.com/serious-form-security/
     $this->to_tpl['errors'] = array();
     $this->to_tpl['success'] = false;
     $this->set_language($lang);
     if ($lang == "sr") {
         $this->template = "contact-sr";
     } else {
         $this->template = "contact-en";
     }
     $this->set_page_name($this->language_titles["contact"][$lang]);
     if (isset($_POST['submit'])) {
         if (verify_form_token('contact')) {
             // Building a whitelist array with keys which will send through the form,
             // no others would be accepted later on
             $whitelist = array('token', 'name', 'email', 'message', 'submit');
             // Building an array with the $_POST-superglobal
             foreach ($_POST as $key => $item) {
                 // Check if the value $key (fieldname from $_POST)
                 // can be found in the whitelisting array,
                 // if not, die with a short message to the hacker
                 if (!in_array($key, $whitelist)) {
                     write_log('Unknown form fields');
                     die("Hack-Attempt detected. Please use only the fields in the form.");
                 }
             }
             // if pass, send email
             $from_name = stripcleantohtml($_POST['name']);
             $from_email = stripcleantohtml($_POST['email']);
             $message = cleantohtml($_POST['message']);
             $errors = $this->check_input($from_name, $from_email, $message);
             if (!empty($errors)) {
                 $this->to_tpl['errors'] = $errors;
                 $this->to_tpl['token'] = $_POST['token'];
                 return;
             }
             $send = $this->phpmailer($from_name, $from_email, $message);
             if ($send === true) {
                 $this->to_tpl['success'] = true;
             } else {
                 var_dump($send);
                 die;
                 //write_log('PHP Mailer error: ' . $send);
             }
         } else {
             write_log('Formtoken');
             die("Hack-Attempt detected.");
         }
         return;
     }
     // Generate a new token for the $_SESSION superglobal
     // and put them in a hidden field
     $this->to_tpl['token'] = generate_form_token('contact');
     return;
 }
/**
* 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
    ###################
}
        $site->guest->debug->print_msg();
    }
    $site->debug->print_msg();
    ########### EXIT
    exit;
}
# / ACCESS allowed/denied
###########################
# / PERMISSIONS CHECK
####################################
######### GO ON WITH REAL WORK
#################
# STEP2: SAVE DATA
if ($op2 && !$site->fdat['refresh']) {
    $form_error = array();
    verify_form_token();
    ##############
    # SAVE GROUP TAB
    if ($site->fdat['tab'] == 'group') {
        ################## GET profile
        $profile_def = $site->get_profile(array("id" => $site->fdat['profile_id']));
        ################## CHECK & CHANGE profile values (required, date formats, arrays, etc)
        $sql_field_values = check_profile_values(array("profile_def" => &$profile_def, "skip_fields" => "group_id,name,parent_group_id"));
        #printr($sql_field_values);
        ############ NEW OR COPY
        if ($op == 'new' || $op == 'copy') {
            $parent_id = $site->fdat['group_id'];
            $sql = $site->db->prepare("INSERT INTO groups (profile_id, name, parent_group_id, auth_type " . (count($update_fields) ? ',' . join(",", array_keys($sql_field_values)) : '') . ") VALUES (?,?,?,? " . (count($update_fields) ? ",'" . join("','", array_values($sql_field_values)) . "'" : "") . " )", $site->fdat['profile_id'] ? $site->fdat['profile_id'] : 0, trim($site->fdat['name']) == '' ? 'undefined' : $site->fdat['name'], $site->fdat['parent_group_id'], $site->fdat['auth_type']);
            #print $sql;
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
function salvesta_objekt()
{
    global $site;
    global $objekt;
    $class_path = "../classes/";
    verify_form_token();
    if ($objekt->objekt_id) {
        if ($objekt->on_sisu_olemas) {
            # -------------------------------
            # Objekti uuendamine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("update obj_rubriik set on_peida_vmenyy=?, on_printlink=?, on_meilinglist=?, on_alamartiklid=? WHERE objekt_id=?", $objekt->all[on_peida_vmenyy], $site->fdat[on_printlink] ? 1 : 0, $site->fdat[on_meilinglist] ? 1 : 0, $site->fdat[on_alamartiklid] ? 1 : 0, $objekt->objekt_id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
        } else {
            # -------------------------------
            # Objekti loomine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("insert into obj_rubriik (objekt_id,on_peida_vmenyy, on_printlink, on_meilinglist, on_alamartiklid) values (?,?,?,?,?)", $objekt->objekt_id, $objekt->all[on_peida_vmenyy], $site->fdat[on_printlink] ? 1 : 0, $site->fdat[on_meilinglist] ? 1 : 0, $site->fdat[on_alamartiklid] ? 1 : 0);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
        }
        $site->debug->msg("sisu on salvestatud, objekt_id = " . $objekt->objekt_id);
    } else {
        $site->debug->msg("sisu pole salvestatud kuna objekt_id puudub");
    }
}
/**
* save permissions to database
*
* Deletes all old values and inserts new ones.
* NB! Used some global variables (doesn't have to be this way later... only for development convienence now)
* 
* @package CMS
* 
* @param string type - permission type (OBJ/ADMIN/ACL/..)
*
* Call:
*		save_permissions(array(
*			"type" => 'OBJ'	
*		));
*/
function save_permissions($args)
{
    global $site;
    global $objekt;
    global $class_path;
    global $keel;
    verify_form_token();
    # if objekt is not created (probably error situation), try to create it again
    if (!$objekt->objekt_id) {
        $objekt = new Objekt(array(objekt_id => $site->fdat['id']));
    }
    if ($args['type']) {
        ############ 1. DELETE ALL OLD PERMISSIONS for object
        $sql = $site->db->prepare("DELETE FROM permissions WHERE type=? AND source_id=?", $args['type'], $site->fdat['id']);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
        #		print "<br>".$sql;
        ############
        # loop over permission rows
        foreach ($site->fdat as $field => $value) {
            if (substr($field, 0, strlen('permission')) == 'permission') {
                # get type (role/group/user) and ID (role_id or group_id or user_id) from fieldname
                list($name, $type, $id) = split("_", $field);
                #print "<br>".$field." => ".$acl. ", ".$type. ", ". $id. " => C:".$site->fdat[$type.'_C_'.$id]." R:".$site->fdat[$type.'_R_'.$id];
                #echo " U:".$site->fdat[$type.'_U_'.$id]; echo " P:".$site->fdat[$type.'_P_'.$id]; echo " D:".$site->fdat[$type.'_D_'.$id];
                #echo " subtree:".$site->fdat[$type.'_S_'.$id];
                ############ 2. INSERT NEW PERMISSIONS for object
                $sql = $site->db->prepare("INSERT INTO permissions (type,source_id,role_id,group_id,user_id,C,R,U,P,D) VALUES (?,?,?,?,?,?,?,?,?,?)", $args['type'], $site->fdat['id'], $type == 'role' ? $id : 0, $type == 'group' ? $id : 0, $type == 'user' ? $id : 0, $site->fdat[$type . '_C_' . $id] ? $site->fdat[$type . '_C_' . $id] : 0, $site->fdat[$type . '_R_' . $id] ? $site->fdat[$type . '_R_' . $id] : 0, $site->fdat[$type . '_U_' . $id] ? $site->fdat[$type . '_U_' . $id] : 0, $site->fdat[$type . '_P_' . $id] ? $site->fdat[$type . '_P_' . $id] : 0, $site->fdat[$type . '_D_' . $id] ? $site->fdat[$type . '_D_' . $id] : 0);
                $sth = new SQL($sql);
                $site->debug->msg($sth->debug->get_msgs());
                #print "<br>".$sql;
            }
            # if permission field
        }
        # / loop over permission rows
        ############
        ############
        # write log
        # type= OBJ
        if ($args['type'] == 'OBJ') {
            new Log(array('action' => 'update', 'component' => 'ACL', 'objekt_id' => $objekt->objekt_id, 'message' => "Object '" . $objekt->all['pealkiri'] . "' (ID=" . $site->fdat['id'] . ") permissions updated"));
        } elseif ($args['type'] == 'ADMIN') {
            #USE FUNCTIONN! POOELLI
            ####### get adminpage name
            $sql = $site->db->prepare("SELECT eng_nimetus FROM admin_osa WHERE id=?", $site->fdat['id']);
            $sth = new SQL($sql);
            $pagename = $sth->fetchsingle();
            $site->debug->msg($sth->debug->get_msgs());
            ####### write log
            new Log(array('action' => 'update', 'component' => 'ACL', 'message' => "Adminpage '" . $pagename . "' permissions updated"));
        }
        # if permission type
        # / write log
        ############
    }
    # if permission type provided
}
function salvesta_objekt_metadata()
{
    global $site;
    verify_form_token();
    $class_path = "../classes/";
    $objekt = new Objekt(array('objekt_id' => $site->fdat['id']));
    if ($objekt->all['objekt_id']) {
        # -------------------------------
        # Objekti uuendamine andmebaasis
        # -------------------------------
        $sql = $site->db->prepare("update objekt set meta_title=?, meta_keywords=?, meta_description=? WHERE objekt_id=?", $site->fdat['meta_title'], $site->fdat['meta_keywords'], $site->fdat['meta_description'], $objekt->objekt_id);
        $sth = new SQL($sql);
        $site->debug->msg($sth->debug->get_msgs());
    } else {
        $site->debug->msg("sisu pole salvestatud kuna objekt_id puudub");
    }
}
function salvesta_objekt()
{
    global $site;
    global $objekt;
    verify_form_token();
    if ($objekt->objekt_id) {
        if ($objekt->on_sisu_olemas) {
            # -------------------------------
            # Objekti uuendamine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("update obj_rubriik set on_peida_vmenyy=?, on_printlink=?, on_meilinglist=? WHERE objekt_id=?", $objekt->all[on_peida_vmenyy], $site->fdat[on_printlink] ? 1 : 0, $site->fdat[on_meilinglist] ? 1 : 0, $objekt->objekt_id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
        } else {
            # -------------------------------
            # Objekti loomine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("insert into obj_rubriik (objekt_id,on_peida_vmenyy, on_printlink, on_meilinglist) values (?,?,?,?)", $objekt->objekt_id, $objekt->all[on_peida_vmenyy], $site->fdat[on_printlink] ? 1 : 0, $site->fdat[on_meilinglist] ? 1 : 0);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
            // Here we make objekt_id like current id (in main window)
            ?>
			<script language=javascript><!--		
				variableFromEditRubriik_id='<?php 
            echo $objekt->objekt_id;
            ?>
';
			//--></script>
<?php 
        }
        $site->debug->msg("sisu on salvestatud, objekt_id = " . $objekt->objekt_id);
        #$site->debug->print_hash($site->fdat,1,"FDAT");
    } else {
        $site->debug->msg("sisu pole salvestatud kuna objekt_id puudub");
    }
    ############################
    ### image and thumb generation
    if ($site->fdat['old_tn_size'] != $site->fdat['tn_size'] || $site->fdat['old_path'] != $site->fdat['path'] || $site->fdat['old_pic_size'] != $site->fdat['pic_size'] || $site->fdat['op2'] == 'save') {
        if ($site->fdat['path']) {
            global $class_path;
            include_once $class_path . 'picture.inc.php';
            generate_images($site->absolute_path . $site->fdat['path'], $site->fdat['tn_size'], $site->fdat['pic_size']);
        }
    }
    ### end image and thumb generation
    ############################
}
function salvesta_objekt()
{
    global $site;
    global $objekt;
    $class_path = "../classes/";
    verify_form_token();
    # -----------------------------
    # lyhi ja sisu koristamine
    # -----------------------------
    # ------
    # SISU
    # ------
    $sisu = $site->fdat['scms_article_editor'];
    //printr(htmlspecialchars($site->fdat['scms_article_editor']));
    //$hostname = ($site->CONF['protocol'] ? $site->CONF['protocol'] : "http://").$site->CONF['hostname'].$site->CONF['wwwroot'].$site->CONF['file_path'].'/';
    $hostname = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $site->CONF['hostname'] . $site->CONF['wwwroot'] . '/';
    # asendada piltidel abosluutne tee  koodiga "##saurus649code##"
    $pattern1 = "|" . '(src\\s*=\\s*[\\"\']?)' . $hostname . "|i";
    $pattern2 = "|" . '(background\\s*=\\s*[\\"\']?)' . $hostname . "|i";
    # asendada failidel abosluutne tee  koodiga "##saurus649code##"
    $pattern3 = "|" . '(href\\s*=\\s*[\\"\']?)' . $hostname . "|i";
    $sisu = preg_replace($pattern1, "\\1" . "##saurus649code##" . '/', $sisu);
    $sisu = preg_replace($pattern2, "\\1" . "##saurus649code##" . '/', $sisu);
    $sisu = preg_replace($pattern3, "\\1" . "##saurus649code##" . '/', $sisu);
    $lyhi = '';
    ## search for LEAD tag and divide content into 2 fields in teh database: lyhi and sisu
    if (strpos($sisu, '<hr class="scms_lead_body_separator" />') !== false) {
        $sisu = explode('<hr class="scms_lead_body_separator" />', $sisu);
        $lyhi = $sisu[0];
        $sisu = $sisu[1];
    }
    if (strpos($sisu, '<hr class="scms_lead_body_separator">') !== false) {
        $sisu = explode('<hr class="scms_lead_body_separator">', $sisu);
        $lyhi = $sisu[0];
        $sisu = $sisu[1];
    }
    //Sisu
    $site->debug->msg('sisu: ' . $sisu);
    $site->debug->msg('pattern: ' . $pattern1);
    $site->debug->msg('pattern: ' . $pattern2);
    $site->debug->msg('pattern: ' . $pattern3);
    $site->debug->msg('sisu: ' . $sisu);
    if ($objekt->objekt_id) {
        // form allowed mails check/insert bug #2277
        // teststring: value="merle@saurus.ee|||index.php?id=26675|||index.php?id=26674|||midagimidagi
        if (preg_match_all('/<input(.*?)>/', $lyhi . $sisu, $matches)) {
            $systemfields = array();
            foreach ($matches[0] as $match) {
                if (strpos($match, 'type="hidden"') && strpos($match, 'name="systemfield"')) {
                    $systemfields[] = $match;
                }
            }
            foreach ($systemfields as $key => $systemfield) {
                if (preg_match('/value="(.*?)\\|\\|\\|(.*?)\\|\\|\\|(.*?)\\|\\|\\|/', $systemfield, $matches)) {
                    // delete form id from objekt_id_list
                    $sql = "select id, objekt_id_list from allowed_mails where objekt_id_list like '%" . $objekt->objekt_id . '_' . $key . "%';";
                    $result = new SQL($sql);
                    while ($row = $result->fetch('ASSOC')) {
                        if ($row['objekt_id_list']) {
                            $row['objekt_id_list'] = explode(',', $row['objekt_id_list']);
                        } else {
                            $row['objekt_id_list'] = array();
                        }
                        if ($row['id']) {
                            unset($row['objekt_id_list'][array_search($objekt->objekt_id . '_' . $key, $row['objekt_id_list'])]);
                            $sql = $site->db->prepare('update allowed_mails set objekt_id_list = ? where id = ?;', implode(',', $row['objekt_id_list']), $row['id']);
                            new SQL($sql);
                        }
                    }
                    // /delete form id from objekt_id_list
                    $sql = $site->db->prepare('select id, objekt_id_list from allowed_mails where mail = ?;', trim($matches[1]));
                    $result = new SQL($sql);
                    $result = $result->fetch('ASSOC');
                    $mail_id = $result['id'];
                    if ($result['objekt_id_list']) {
                        $objekt_id_list = explode(',', $result['objekt_id_list']);
                    } else {
                        $objekt_id_list = array();
                    }
                    // insert id
                    if (!$mail_id) {
                        $sql = $site->db->prepare('insert into allowed_mails (mail, objekt_id_list) values (?, ?);', trim($matches[1]), $objekt->objekt_id . '_' . $key);
                        $result = new SQL($sql);
                        $mail_id = $result->insert_id;
                    }
                    //insert objekt_id, in obj_id_list
                    $objekt_id_list[] = $objekt->objekt_id . '_' . $key;
                    $sql = $site->db->prepare('update allowed_mails set objekt_id_list = ? where id = ?;', implode(',', $objekt_id_list), $mail_id);
                    new SQL($sql);
                    //replace mail address with allowed mails row id
                    $lyhi = str_replace('value="' . $matches[1] . '|||', 'value="' . $mail_id . '|||', $lyhi);
                    $sisu = str_replace('value="' . $matches[1] . '|||', 'value="' . $mail_id . '|||', $sisu);
                }
            }
        }
        // /form allowed mails check/insert
        if ($objekt->on_sisu_olemas) {
            # -------------------------------
            # Objekti uuendamine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("update obj_artikkel set lyhi=?, sisu=?, profile_id=?  WHERE objekt_id=?", $lyhi, $sisu, $site->fdat['profile_id'], $objekt->objekt_id);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
        } else {
            # -------------------------------
            # Objekti loomine andmebaasis
            # -------------------------------
            $sql = $site->db->prepare("insert into obj_artikkel (objekt_id, lyhi, sisu, profile_id) values (?,?,?,?)", $objekt->objekt_id, $lyhi, $sisu, $site->fdat['profile_id']);
            $sth = new SQL($sql);
            $site->debug->msg($sth->debug->get_msgs());
        }
        $site->debug->msg("sisu on salvestatud, objekt_id = " . $objekt->objekt_id);
    } else {
        $site->debug->msg("sisu pole salvestatud kuna objekt_id puudub");
    }
}
/**
 * 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_verify_form_token($params, &$smarty)
{
    verify_form_token();
}