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';
    }
}
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");
    }
}