function uploadImage($inputName, $uploadDir)
{
    $image = $_FILES[$inputName];
    $imagePath = '';
    // if a file is given
    if (trim($image['tmp_name']) != '') {
        // get the image extension
        $ext = substr(strrchr($image['name'], "."), 1);
        // generate a random new file name to avoid name conflict
        $imagePath = md5(rand() * time()) . ".{$ext}";
        // check the image width. if it exceed the maximum
        // width we must resize it
        $size = getimagesize($image['tmp_name']);
        if ($size[0] > MAX_CATEGORY_IMAGE_WIDTH) {
            $imagePath = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_CATEGORY_IMAGE_WIDTH);
        } else {
            // move the image to category image directory
            // if fail set $imagePath to empty string
            if (!move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath)) {
                $imagePath = '';
            }
        }
    }
    return $imagePath;
}
Esempio n. 2
0
function createImages($origFile, $id)
{
    global $portfolioFolder;
    list($origWidth, $origHeight, $origType) = getimagesize($origFile);
    ini_set("memory_limit", "128M");
    $origImage = $origType == 2 ? imagecreatefromjpeg($origFile) : imagecreatefrompng($origFile);
    $aspectRatio = $origWidth / $origHeight;
    createThumbnail($origImage, $origWidth, $origHeight, "{$portfolioFolder}/{$id}-small.png");
    createFullImage($origImage, $origWidth, $origHeight, "{$portfolioFolder}/{$id}-large.jpg");
    imagedestroy($origImage);
    logEvent("create-images", $origFile, $id, $aspectRatio);
}
function uploadProductImage($inputName, $uploadDir)
{
    $image = $_FILES[$inputName];
    $imagePath = '';
    $thumbnailPath = '';
    // if a file is given
    if (trim($image['tmp_name']) != '') {
        $ext = substr(strrchr($image['name'], "."), 1);
        //$extensions[$image['type']];
        // generate a random new file name to avoid name conflict
        $imagePath = md5(rand() * time()) . ".{$ext}";
        list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
        // make sure the image width does not exceed the
        // maximum allowed width
        if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
            $result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
            $imagePath = $result;
        } else {
            $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
        }
        if ($result) {
            // create thumbnail
            $thumbnailPath = md5(rand() * time()) . ".{$ext}";
            $result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);
            // create thumbnail failed, delete the image
            if (!$result) {
                unlink($uploadDir . $imagePath);
                $imagePath = $thumbnailPath = '';
            } else {
                $thumbnailPath = $result;
            }
        } else {
            // the product cannot be upload / resized
            $imagePath = $thumbnailPath = '';
        }
    }
    return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
Esempio n. 4
0
function loadAttachmentContext($ID_MSG)
{
    global $attachments, $modSettings, $txt, $scripturl, $topic, $db_prefix, $sourcedir;
    // Set up the attachment info - based on code by Meriadoc.
    $attachmentData = array();
    if (isset($attachments[$ID_MSG]) && !empty($modSettings['attachmentEnable'])) {
        foreach ($attachments[$ID_MSG] as $i => $attachment) {
            $attachmentData[$i] = array('id' => $attachment['ID_ATTACH'], 'name' => htmlspecialchars($attachment['filename']), 'downloads' => $attachment['downloads'], 'size' => round($attachment['filesize'] / 1024, 2) . ' ' . $txt['smf211'], 'byte_size' => $attachment['filesize'], 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['ID_ATTACH'], 'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['ID_ATTACH'] . '">' . htmlspecialchars($attachment['filename']) . '</a>', 'is_image' => !empty($attachment['width']) && !empty($attachment['height']) && !empty($modSettings['attachmentShowImages']));
            if (!$attachmentData[$i]['is_image']) {
                continue;
            }
            $attachmentData[$i]['real_width'] = $attachment['width'];
            $attachmentData[$i]['width'] = $attachment['width'];
            $attachmentData[$i]['real_height'] = $attachment['height'];
            $attachmentData[$i]['height'] = $attachment['height'];
            // Let's see, do we want thumbs?
            if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachment['width'] > $modSettings['attachmentThumbWidth'] || $attachment['height'] > $modSettings['attachmentThumbHeight']) && strlen($attachment['filename']) < 249) {
                // A proper thumb doesn't exist yet? Create one!
                if (empty($attachment['ID_THUMB']) || $attachment['thumb_width'] > $modSettings['attachmentThumbWidth'] || $attachment['thumb_height'] > $modSettings['attachmentThumbHeight'] || $attachment['thumb_width'] < $modSettings['attachmentThumbWidth'] && $attachment['thumb_height'] < $modSettings['attachmentThumbHeight']) {
                    $filename = getAttachmentFilename($attachment['filename'], $attachment['ID_ATTACH']);
                    require_once $sourcedir . '/Subs-Graphics.php';
                    if (createThumbnail($filename, $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight'])) {
                        // Calculate the size of the created thumbnail.
                        list($attachment['thumb_width'], $attachment['thumb_height']) = @getimagesize($filename . '_thumb');
                        $thumb_size = filesize($filename . '_thumb');
                        $thumb_filename = addslashes($attachment['filename'] . '_thumb');
                        // Add this beauty to the database.
                        db_query("\n\t\t\t\t\t\t\tINSERT INTO {$db_prefix}attachments\n\t\t\t\t\t\t\t\t(ID_MSG, attachmentType, filename, size, width, height)\n\t\t\t\t\t\t\tVALUES ({$ID_MSG}, 3, '{$thumb_filename}', " . (int) $thumb_size . ", " . (int) $attachment['thumb_width'] . ", " . (int) $attachment['thumb_height'] . ")", __FILE__, __LINE__);
                        $attachment['ID_THUMB'] = db_insert_id();
                        if (!empty($attachment['ID_THUMB'])) {
                            db_query("\n\t\t\t\t\t\t\t\tUPDATE {$db_prefix}attachments\n\t\t\t\t\t\t\t\tSET ID_THUMB = {$attachment['ID_THUMB']}\n\t\t\t\t\t\t\t\tWHERE ID_ATTACH = {$attachment['ID_ATTACH']}\n\t\t\t\t\t\t\t\tLIMIT 1", __FILE__, __LINE__);
                            $thumb_realname = getAttachmentFilename($thumb_filename, $attachment['ID_THUMB'], true);
                            rename($filename . '_thumb', $modSettings['attachmentUploadDir'] . '/' . $thumb_realname);
                        }
                    }
                }
                $attachmentData[$i]['width'] = $attachment['thumb_width'];
                $attachmentData[$i]['height'] = $attachment['thumb_height'];
            }
            if (!empty($attachment['ID_THUMB'])) {
                $attachmentData[$i]['thumbnail'] = array('id' => $attachment['ID_THUMB'], 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['ID_THUMB'] . ';image');
            }
            $attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['ID_THUMB']);
            // If thumbnails are disabled, check the maximum size of the image.
            if (!$attachmentData[$i]['thumbnail']['has_thumb'] && (!empty($modSettings['max_image_width']) && $attachment['width'] > $modSettings['max_image_width'] || !empty($modSettings['max_image_height']) && $attachment['height'] > $modSettings['max_image_height'])) {
                if (!empty($modSettings['max_image_width']) && (empty($modSettings['max_image_height']) || $attachment['height'] * $modSettings['max_image_width'] / $attachment['width'] <= $modSettings['max_image_height'])) {
                    $attachmentData[$i]['width'] = $modSettings['max_image_width'];
                    $attachmentData[$i]['height'] = floor($attachment['height'] * $modSettings['max_image_width'] / $attachment['width']);
                } elseif (!empty($modSettings['max_image_width'])) {
                    $attachmentData[$i]['width'] = floor($attachment['width'] * $modSettings['max_image_height'] / $attachment['height']);
                    $attachmentData[$i]['height'] = $modSettings['max_image_height'];
                }
            } elseif ($attachmentData[$i]['thumbnail']['has_thumb']) {
                // If the image is too large to show inline, make it a popup.
                if (!empty($modSettings['max_image_width']) && $attachmentData[$i]['real_width'] > $modSettings['max_image_width'] || !empty($modSettings['max_image_height']) && $attachmentData[$i]['real_height'] > $modSettings['max_image_height']) {
                    $attachmentData[$i]['thumbnail']['javascript'] = "return reqWin('" . $attachmentData[$i]['href'] . ";image', " . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
                } else {
                    $attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['ID_ATTACH'] . ');';
                }
            }
            if (!$attachmentData[$i]['thumbnail']['has_thumb']) {
                $attachmentData[$i]['downloads']++;
            }
        }
    }
    return $attachmentData;
}
Esempio n. 5
0
function employees_update($selected_id)
{
    global $Translation;
    if ($_GET['update_x'] != '') {
        $_POST = $_GET;
    }
    // mm: can member edit record?
    $arrPerm = getTablePermissions('employees');
    $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='employees' and pkValue='" . makeSafe($selected_id) . "'");
    $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='employees' and pkValue='" . makeSafe($selected_id) . "'");
    if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
        // allow update?
        // update allowed, so continue ...
    } else {
        return false;
    }
    $data['TitleOfCourtesy'] = makeSafe($_POST['TitleOfCourtesy']);
    if ($data['TitleOfCourtesy'] == empty_lookup_value) {
        $data['TitleOfCourtesy'] = '';
    }
    $data['LastName'] = makeSafe($_POST['LastName']);
    if ($data['LastName'] == empty_lookup_value) {
        $data['LastName'] = '';
    }
    $data['FirstName'] = makeSafe($_POST['FirstName']);
    if ($data['FirstName'] == empty_lookup_value) {
        $data['FirstName'] = '';
    }
    $data['Title'] = makeSafe($_POST['Title']);
    if ($data['Title'] == empty_lookup_value) {
        $data['Title'] = '';
    }
    $data['BirthDate'] = intval($_POST['BirthDateYear']) . '-' . intval($_POST['BirthDateMonth']) . '-' . intval($_POST['BirthDateDay']);
    $data['BirthDate'] = parseMySQLDate($data['BirthDate'], '');
    $data['HireDate'] = intval($_POST['HireDateYear']) . '-' . intval($_POST['HireDateMonth']) . '-' . intval($_POST['HireDateDay']);
    $data['HireDate'] = parseMySQLDate($data['HireDate'], '1');
    $data['Address'] = br2nl(makeSafe($_POST['Address']));
    $data['City'] = makeSafe($_POST['City']);
    if ($data['City'] == empty_lookup_value) {
        $data['City'] = '';
    }
    $data['Region'] = makeSafe($_POST['Region']);
    if ($data['Region'] == empty_lookup_value) {
        $data['Region'] = '';
    }
    $data['PostalCode'] = makeSafe($_POST['PostalCode']);
    if ($data['PostalCode'] == empty_lookup_value) {
        $data['PostalCode'] = '';
    }
    $data['Country'] = makeSafe($_POST['Country']);
    if ($data['Country'] == empty_lookup_value) {
        $data['Country'] = '';
    }
    $data['HomePhone'] = makeSafe($_POST['HomePhone']);
    if ($data['HomePhone'] == empty_lookup_value) {
        $data['HomePhone'] = '';
    }
    $data['Extension'] = makeSafe($_POST['Extension']);
    if ($data['Extension'] == empty_lookup_value) {
        $data['Extension'] = '';
    }
    $data['Notes'] = makeSafe($_POST['Notes']);
    if ($data['Notes'] == empty_lookup_value) {
        $data['Notes'] = '';
    }
    $data['ReportsTo'] = makeSafe($_POST['ReportsTo']);
    if ($data['ReportsTo'] == empty_lookup_value) {
        $data['ReportsTo'] = '';
    }
    $data['selectedID'] = makeSafe($selected_id);
    if ($_POST['Photo_remove'] == 1) {
        $data['Photo'] = '';
        // delete file from server
        $res = sql("select `Photo` from `employees` where `EmployeeID`='" . makeSafe($selected_id) . "'", $eo);
        if ($row = @db_fetch_row($res)) {
            if ($row[0] != '') {
                @unlink(getUploadDir('') . $row[0]);
                preg_match('/^[a-z0-9_]+\\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
                $thumbDV = str_replace(".{$m['1']}ffffgggg", "_dv.{$m['1']}", $row[0] . 'ffffgggg');
                $thumbTV = str_replace(".{$m['1']}ffffgggg", "_tv.{$m['1']}", $row[0] . 'ffffgggg');
                @unlink(getUploadDir('') . $thumbTV);
                @unlink(getUploadDir('') . $thumbDV);
            }
        }
    } else {
        $data['Photo'] = PrepareUploadedFile('Photo', 153600, 'jpg|jpeg|gif|png', false, "");
        if ($data['Photo']) {
            createThumbnail($data['Photo'], getThumbnailSpecs('employees', 'Photo', 'tv'));
        }
        // delete file from server
        if ($data['Photo'] != '') {
            $res = sql("select `Photo` from `employees` where `EmployeeID`='" . makeSafe($selected_id) . "'", $eo);
            if ($row = @db_fetch_row($res)) {
                if ($row[0] != '') {
                    @unlink(getUploadDir('') . $row[0]);
                    preg_match('/^[a-z0-9_]+\\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
                    $thumbDV = str_replace(".{$m['1']}ffffgggg", "_dv.{$m['1']}", $row[0] . 'ffffgggg');
                    $thumbTV = str_replace(".{$m['1']}ffffgggg", "_tv.{$m['1']}", $row[0] . 'ffffgggg');
                    @unlink(getUploadDir('') . $thumbTV);
                    @unlink(getUploadDir('') . $thumbDV);
                }
            }
        }
    }
    // hook: employees_before_update
    if (function_exists('employees_before_update')) {
        $args = array();
        if (!employees_before_update($data, getMemberInfo(), $args)) {
            return false;
        }
    }
    $o = array('silentErrors' => true);
    sql('update `employees` set       `TitleOfCourtesy`=' . ($data['TitleOfCourtesy'] !== '' && $data['TitleOfCourtesy'] !== NULL ? "'{$data['TitleOfCourtesy']}'" : 'NULL') . ', ' . ($data['Photo'] != '' ? "`Photo`='{$data['Photo']}'" : ($_POST['Photo_remove'] != 1 ? '`Photo`=`Photo`' : '`Photo`=NULL')) . ', `LastName`=' . ($data['LastName'] !== '' && $data['LastName'] !== NULL ? "'{$data['LastName']}'" : 'NULL') . ', `FirstName`=' . ($data['FirstName'] !== '' && $data['FirstName'] !== NULL ? "'{$data['FirstName']}'" : 'NULL') . ', `Title`=' . ($data['Title'] !== '' && $data['Title'] !== NULL ? "'{$data['Title']}'" : 'NULL') . ', `BirthDate`=' . ($data['BirthDate'] !== '' && $data['BirthDate'] !== NULL ? "'{$data['BirthDate']}'" : 'NULL') . ', `HireDate`=' . ($data['HireDate'] !== '' && $data['HireDate'] !== NULL ? "'{$data['HireDate']}'" : 'NULL') . ', `Address`=' . ($data['Address'] !== '' && $data['Address'] !== NULL ? "'{$data['Address']}'" : 'NULL') . ', `City`=' . ($data['City'] !== '' && $data['City'] !== NULL ? "'{$data['City']}'" : 'NULL') . ', `Region`=' . ($data['Region'] !== '' && $data['Region'] !== NULL ? "'{$data['Region']}'" : 'NULL') . ', `PostalCode`=' . ($data['PostalCode'] !== '' && $data['PostalCode'] !== NULL ? "'{$data['PostalCode']}'" : 'NULL') . ', `Country`=' . ($data['Country'] !== '' && $data['Country'] !== NULL ? "'{$data['Country']}'" : 'NULL') . ', `HomePhone`=' . ($data['HomePhone'] !== '' && $data['HomePhone'] !== NULL ? "'{$data['HomePhone']}'" : 'NULL') . ', `Extension`=' . ($data['Extension'] !== '' && $data['Extension'] !== NULL ? "'{$data['Extension']}'" : 'NULL') . ', `Notes`=' . ($data['Notes'] !== '' && $data['Notes'] !== NULL ? "'{$data['Notes']}'" : 'NULL') . ', `ReportsTo`=' . ($data['ReportsTo'] !== '' && $data['ReportsTo'] !== NULL ? "'{$data['ReportsTo']}'" : 'NULL') . " where `EmployeeID`='" . makeSafe($selected_id) . "'", $o);
    if ($o['error'] != '') {
        echo $o['error'];
        echo '<a href="employees_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
        exit;
    }
    // hook: employees_after_update
    if (function_exists('employees_after_update')) {
        $res = sql("SELECT * FROM `employees` WHERE `EmployeeID`='{$data['selectedID']}' LIMIT 1", $eo);
        if ($row = db_fetch_assoc($res)) {
            $data = array_map('makeSafe', $row);
        }
        $data['selectedID'] = $data['EmployeeID'];
        $args = array();
        if (!employees_after_update($data, getMemberInfo(), $args)) {
            return;
        }
    }
    // mm: update ownership data
    sql("update membership_userrecords set dateUpdated='" . time() . "' where tableName='employees' and pkValue='" . makeSafe($selected_id) . "'", $eo);
}
Esempio n. 6
0
 $i = 1;
 $pieces = explode('.', $name);
 $filename = $pieces[0];
 if (in_array($extension, $allowed)) {
     if ($file_error === 0) {
         $file_dir = "images/" . $filename . "." . $pieces[1];
         while (file_exists("../images/" . $filename . "." . $pieces[1])) {
             $filename = $name_ext["filename"] . "_" . $i++;
             //$filename = $pieces[0] . "_" . $i++;
         }
         $file_dir = "images/" . $filename . "." . $pieces[1];
         $uploaded[$position] = $file_dir;
         if (move_uploaded_file($file_tmp, "../" . $file_dir)) {
             $metaSystem = new Metaclass($file_dir);
             $currentMeta = $metaSystem->getMeta();
             createThumbnail($filename . "." . $pieces[1]);
             $uploaded[$position] = $file_dir;
         } else {
             $failed[$position] = "[{$filename}] failed to upload.";
         }
     } else {
         $failed[$position] = "[{$filename}] errored with code {$file_error}.";
     }
 } else {
     $failed[$position] = "[{$filename}] file extension '{$extension}' is not allowed.";
 }
 if (!empty($uploaded)) {
     echo "{$filename} has been successfully uploaded!.";
     echo $filename;
     $picture->addPicture($filename, $extension, $file_dir);
     // set proper permissions on the new file
Esempio n. 7
0
function loadAttachmentContext($id_msg)
{
    global $attachments, $modSettings, $txt, $scripturl, $topic, $sourcedir, $smcFunc;
    // Set up the attachment info - based on code by Meriadoc.
    $attachmentData = array();
    $have_unapproved = false;
    if (isset($attachments[$id_msg]) && !empty($modSettings['attachmentEnable'])) {
        foreach ($attachments[$id_msg] as $i => $attachment) {
            $attachmentData[$i] = array('id' => $attachment['id_attach'], 'name' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($attachment['filename'])), 'downloads' => $attachment['downloads'], 'size' => round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'], 'byte_size' => $attachment['filesize'], 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_attach'], 'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_attach'] . '">' . htmlspecialchars($attachment['filename']) . '</a>', 'is_image' => !empty($attachment['width']) && !empty($attachment['height']) && !empty($modSettings['attachmentShowImages']), 'is_approved' => $attachment['approved']);
            // If something is unapproved we'll note it so we can sort them.
            if (!$attachment['approved']) {
                $have_unapproved = true;
            }
            if (!$attachmentData[$i]['is_image']) {
                continue;
            }
            $attachmentData[$i]['real_width'] = $attachment['width'];
            $attachmentData[$i]['width'] = $attachment['width'];
            $attachmentData[$i]['real_height'] = $attachment['height'];
            $attachmentData[$i]['height'] = $attachment['height'];
            // Let's see, do we want thumbs?
            if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachment['width'] > $modSettings['attachmentThumbWidth'] || $attachment['height'] > $modSettings['attachmentThumbHeight']) && strlen($attachment['filename']) < 249) {
                // A proper thumb doesn't exist yet? Create one!
                if (empty($attachment['id_thumb']) || $attachment['thumb_width'] > $modSettings['attachmentThumbWidth'] || $attachment['thumb_height'] > $modSettings['attachmentThumbHeight'] || $attachment['thumb_width'] < $modSettings['attachmentThumbWidth'] && $attachment['thumb_height'] < $modSettings['attachmentThumbHeight']) {
                    $filename = getAttachmentFilename($attachment['filename'], $attachment['id_attach'], $attachment['id_folder']);
                    require_once $sourcedir . '/Subs-Graphics.php';
                    if (createThumbnail($filename, $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight'])) {
                        // So what folder are we putting this image in?
                        if (!empty($modSettings['currentAttachmentUploadDir'])) {
                            if (!is_array($modSettings['attachmentUploadDir'])) {
                                $modSettings['attachmentUploadDir'] = @unserialize($modSettings['attachmentUploadDir']);
                            }
                            $path = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
                            $id_folder_thumb = $modSettings['currentAttachmentUploadDir'];
                        } else {
                            $path = $modSettings['attachmentUploadDir'];
                            $id_folder_thumb = 1;
                        }
                        // Calculate the size of the created thumbnail.
                        $size = @getimagesize($filename . '_thumb');
                        list($attachment['thumb_width'], $attachment['thumb_height']) = $size;
                        $thumb_size = filesize($filename . '_thumb');
                        // These are the only valid image types for SMF.
                        $validImageTypes = array(1 => 'gif', 2 => 'jpeg', 3 => 'png', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpeg', 14 => 'iff');
                        // What about the extension?
                        $thumb_ext = isset($validImageTypes[$size[2]]) ? $validImageTypes[$size[2]] : '';
                        // Figure out the mime type.
                        if (!empty($size['mime'])) {
                            $thumb_mime = $size['mime'];
                        } else {
                            $thumb_mime = 'image/' . $thumb_ext;
                        }
                        $thumb_filename = $attachment['filename'] . '_thumb';
                        $thumb_hash = getAttachmentFilename($thumb_filename, false, null, true);
                        // Add this beauty to the database.
                        $smcFunc['db_insert']('', '{db_prefix}attachments', array('id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'fileext' => 'string', 'mime_type' => 'string'), array($id_folder_thumb, $id_msg, 3, $thumb_filename, $thumb_hash, (int) $thumb_size, (int) $attachment['thumb_width'], (int) $attachment['thumb_height'], $thumb_ext, $thumb_mime), array('id_attach'));
                        $old_id_thumb = $attachment['id_thumb'];
                        $attachment['id_thumb'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
                        if (!empty($attachment['id_thumb'])) {
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}attachments
								SET id_thumb = {int:id_thumb}
								WHERE id_attach = {int:id_attach}', array('id_thumb' => $attachment['id_thumb'], 'id_attach' => $attachment['id_attach']));
                            $thumb_realname = getAttachmentFilename($thumb_filename, $attachment['id_thumb'], $id_folder_thumb, false, $thumb_hash);
                            rename($filename . '_thumb', $thumb_realname);
                            // Do we need to remove an old thumbnail?
                            if (!empty($old_id_thumb)) {
                                require_once $sourcedir . '/ManageAttachments.php';
                                removeAttachments(array('id_attach' => $old_id_thumb), '', false, false);
                            }
                        }
                    }
                }
                // Only adjust dimensions on successful thumbnail creation.
                if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height'])) {
                    $attachmentData[$i]['width'] = $attachment['thumb_width'];
                    $attachmentData[$i]['height'] = $attachment['thumb_height'];
                }
            }
            if (!empty($attachment['id_thumb'])) {
                $attachmentData[$i]['thumbnail'] = array('id' => $attachment['id_thumb'], 'href' => $scripturl . '?action=dlattach;topic=' . $topic . '.0;attach=' . $attachment['id_thumb'] . ';image');
            }
            $attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['id_thumb']);
            // If thumbnails are disabled, check the maximum size of the image.
            if (!$attachmentData[$i]['thumbnail']['has_thumb'] && (!empty($modSettings['max_image_width']) && $attachment['width'] > $modSettings['max_image_width'] || !empty($modSettings['max_image_height']) && $attachment['height'] > $modSettings['max_image_height'])) {
                if (!empty($modSettings['max_image_width']) && (empty($modSettings['max_image_height']) || $attachment['height'] * $modSettings['max_image_width'] / $attachment['width'] <= $modSettings['max_image_height'])) {
                    $attachmentData[$i]['width'] = $modSettings['max_image_width'];
                    $attachmentData[$i]['height'] = floor($attachment['height'] * $modSettings['max_image_width'] / $attachment['width']);
                } elseif (!empty($modSettings['max_image_width'])) {
                    $attachmentData[$i]['width'] = floor($attachment['width'] * $modSettings['max_image_height'] / $attachment['height']);
                    $attachmentData[$i]['height'] = $modSettings['max_image_height'];
                }
            } elseif ($attachmentData[$i]['thumbnail']['has_thumb']) {
                // If the image is too large to show inline, make it a popup.
                if (!empty($modSettings['max_image_width']) && $attachmentData[$i]['real_width'] > $modSettings['max_image_width'] || !empty($modSettings['max_image_height']) && $attachmentData[$i]['real_height'] > $modSettings['max_image_height']) {
                    $attachmentData[$i]['thumbnail']['javascript'] = 'return reqWin(\'' . $attachmentData[$i]['href'] . ';image\', ' . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
                } else {
                    $attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['id_attach'] . ');';
                }
            }
            if (!$attachmentData[$i]['thumbnail']['has_thumb']) {
                $attachmentData[$i]['downloads']++;
            }
        }
    }
    // Do we need to instigate a sort?
    if ($have_unapproved) {
        usort($attachmentData, 'approved_attach_sort');
    }
    return $attachmentData;
}
Esempio n. 8
0
}
// upload file
if ($allowuploads && $_FILES['file']) {
    $upload = true;
    if (!$overwrite) {
        if (file_exists($leadon . $_FILES['file']['name'])) {
            $upload = false;
        }
    }
    $ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.') + 1));
    if (!in_array($ext, $supportedextentions)) {
        $upload = false;
    }
    if ($upload) {
        move_uploaded_file($_FILES['file']['tmp_name'], $leadon . $_FILES['file']['name']);
        createThumbnail($leadon, $_FILES['file']['name'], $thumbs_directory, '120');
    }
}
if ($allowuploads) {
    $phpallowuploads = (bool) ini_get('file_uploads');
    $phpmaxsize = ini_get('upload_max_filesize');
    $phpmaxsize = trim($phpmaxsize);
    $last = strtolower($phpmaxsize[strlen($phpmaxsize) - 1]);
    switch ($last) {
        case 'g':
            $phpmaxsize *= 1024;
        case 'm':
            $phpmaxsize *= 1024;
    }
}
?>
Esempio n. 9
0
function createAttachment(&$attachmentOptions)
{
    global $db_prefix, $modSettings, $sourcedir;
    $attachmentOptions['errors'] = array();
    if (!isset($attachmentOptions['post'])) {
        $attachmentOptions['post'] = 0;
    }
    $already_uploaded = preg_match('~^post_tmp_' . $attachmentOptions['poster'] . '_\\d+$~', $attachmentOptions['tmp_name']) != 0;
    $file_restricted = @ini_get('open_basedir') != '' && !$already_uploaded;
    if ($already_uploaded) {
        $attachmentOptions['tmp_name'] = $modSettings['attachmentUploadDir'] . '/' . $attachmentOptions['tmp_name'];
    }
    // Make sure the file actually exists... sometimes it doesn't.
    if (!$file_restricted && !file_exists($attachmentOptions['tmp_name']) || !$already_uploaded && !is_uploaded_file($attachmentOptions['tmp_name'])) {
        $attachmentOptions['errors'] = array('could_not_upload');
        return false;
    }
    if (!$file_restricted || $already_uploaded) {
        list($attachmentOptions['width'], $attachmentOptions['height']) = @getimagesize($attachmentOptions['tmp_name']);
    }
    // Get the hash if no hash has been given yet.
    if (empty($attachmentOptions['file_hash'])) {
        $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, true);
    }
    // Is the file too big?
    if (!empty($modSettings['attachmentSizeLimit']) && $attachmentOptions['size'] > $modSettings['attachmentSizeLimit'] * 1024) {
        $attachmentOptions['errors'][] = 'too_large';
    }
    if (!empty($modSettings['attachmentCheckExtensions'])) {
        $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
        foreach ($allowed as $k => $dummy) {
            $allowed[$k] = trim($dummy);
        }
        if (!in_array(strtolower(substr(strrchr($attachmentOptions['name'], '.'), 1)), $allowed)) {
            $attachmentOptions['errors'][] = 'bad_extension';
        }
    }
    if (!empty($modSettings['attachmentDirSizeLimit'])) {
        // Make sure the directory isn't full.
        $dirSize = 0;
        $dir = @opendir($modSettings['attachmentUploadDir']) or fatal_lang_error('smf115b');
        while ($file = readdir($dir)) {
            if (substr($file, 0, -1) == '.') {
                continue;
            }
            if (preg_match('~^post_tmp_\\d+_\\d+$~', $file) != 0) {
                // Temp file is more than 5 hours old!
                if (filemtime($modSettings['attachmentUploadDir'] . '/' . $file) < time() - 18000) {
                    @unlink($modSettings['attachmentUploadDir'] . '/' . $file);
                }
                continue;
            }
            $dirSize += filesize($modSettings['attachmentUploadDir'] . '/' . $file);
        }
        closedir($dir);
        // Too big!  Maybe you could zip it or something...
        if ($attachmentOptions['size'] + $dirSize > $modSettings['attachmentDirSizeLimit'] * 1024) {
            $attachmentOptions['errors'][] = 'directory_full';
        }
    }
    // Check if the file already exists.... (for those who do not encrypt their filenames...)
    if (empty($modSettings['attachmentEncryptFilenames'])) {
        // Make sure they aren't trying to upload a nasty file.
        $disabledFiles = array('con', 'com1', 'com2', 'com3', 'com4', 'prn', 'aux', 'lpt1', '.htaccess', 'index.php');
        if (in_array(strtolower(basename($attachmentOptions['name'])), $disabledFiles)) {
            $attachmentOptions['errors'][] = 'bad_filename';
        }
        // Check if there's another file with that name...
        $request = db_query("\n\t\t\tSELECT ID_ATTACH\n\t\t\tFROM {$db_prefix}attachments\n\t\t\tWHERE filename = '" . strtolower($attachmentOptions['name']) . "'\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        if (mysql_num_rows($request) > 0) {
            $attachmentOptions['errors'][] = 'taken_filename';
        }
        mysql_free_result($request);
    }
    if (!empty($attachmentOptions['errors'])) {
        return false;
    }
    if (!is_writable($modSettings['attachmentUploadDir'])) {
        fatal_lang_error('attachments_no_write');
    }
    db_query("\n\t\tINSERT INTO {$db_prefix}attachments\n\t\t\t(ID_MSG, filename, file_hash, size, width, height)\n\t\tVALUES (" . (int) $attachmentOptions['post'] . ", SUBSTRING('" . $attachmentOptions['name'] . "', 1, 255), '{$attachmentOptions['file_hash']}', " . (int) $attachmentOptions['size'] . ', ' . (empty($attachmentOptions['width']) ? '0' : (int) $attachmentOptions['width']) . ', ' . (empty($attachmentOptions['height']) ? '0' : (int) $attachmentOptions['height']) . ')', __FILE__, __LINE__);
    $attachmentOptions['id'] = db_insert_id();
    if (empty($attachmentOptions['id'])) {
        return false;
    }
    $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], false, $attachmentOptions['file_hash']);
    if ($already_uploaded) {
        rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
    } elseif (!move_uploaded_file($attachmentOptions['tmp_name'], $attachmentOptions['destination'])) {
        fatal_lang_error('smf124');
    } elseif ($file_restricted) {
        list($attachmentOptions['width'], $attachmentOptions['height']) = @getimagesize($attachmentOptions['destination']);
        if (!empty($attachmentOptions['width']) && !empty($attachmentOptions['height'])) {
            db_query("\n\t\t\t\tUPDATE {$db_prefix}attachments\n\t\t\t\tSET\n\t\t\t\t\twidth = " . (int) $attachmentOptions['width'] . ",\n\t\t\t\t\theight = " . (int) $attachmentOptions['height'] . "\n\t\t\t\tWHERE ID_ATTACH = {$attachmentOptions['id']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
        }
    }
    // Attempt to chmod it.
    @chmod($attachmentOptions['destination'], 0644);
    if (!empty($attachmentOptions['skip_thumbnail']) || empty($attachmentOptions['width']) && empty($attachmentOptions['height'])) {
        return true;
    }
    // Like thumbnails, do we?
    if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight'])) {
        require_once $sourcedir . '/Subs-Graphics.php';
        if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight'])) {
            // Figure out how big we actually made it.
            list($thumb_width, $thumb_height) = @getimagesize($attachmentOptions['destination'] . '_thumb');
            $thumb_filename = addslashes($attachmentOptions['name'] . '_thumb');
            $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
            // To the database we go!
            $thumb_file_hash = getAttachmentFilename($thumb_filename, false, true);
            db_query("\n\t\t\t\tINSERT INTO {$db_prefix}attachments\n\t\t\t\t\t(ID_MSG, attachmentType, filename, file_hash, size, width, height)\n\t\t\t\tVALUES (" . (int) $attachmentOptions['post'] . ", 3, SUBSTRING('{$thumb_filename}', 1, 255), '{$thumb_file_hash}', " . (int) $thumb_size . ", " . (int) $thumb_width . ", " . (int) $thumb_height . ")", __FILE__, __LINE__);
            $attachmentOptions['thumb'] = db_insert_id();
            if (!empty($attachmentOptions['thumb'])) {
                db_query("\n\t\t\t\t\tUPDATE {$db_prefix}attachments\n\t\t\t\t\tSET ID_THUMB = {$attachmentOptions['thumb']}\n\t\t\t\t\tWHERE ID_ATTACH = {$attachmentOptions['id']}\n\t\t\t\t\tLIMIT 1", __FILE__, __LINE__);
                rename($attachmentOptions['destination'] . '_thumb', getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], false, $thumb_file_hash));
            }
        }
    }
    return true;
}
    getImage();
}
if (!preg_match('/^[a-z0-9_]+\\.(gif|png|jpg|jpeg|jpe)$/i', $i, $m)) {
    getImage();
}
if ($v != 'tv' && $v != 'dv') {
    getImage();
}
$img = $p[$t][$f] . $i;
$thumb = str_replace(".{$m['1']}ffffgggg", "_{$v}.{$m['1']}", $img . 'ffffgggg');
// if thumbnail exists and the user is not admin, output it without rebuilding the thumbnail
if (getImage($thumb) && !getLoggedAdmin()) {
    exit;
}
// otherwise, try to create the thumbnail and output it
if (!createThumbnail($img, getThumbnailSpecs($t, $f, $v))) {
    getImage();
}
if (!getImage($thumb)) {
    getImage();
}
function getImage($img = '')
{
    if (!$img) {
        // default image to return
        $img = './photo.gif';
        $exit = TRUE;
    }
    $thumbInfo = @getimagesize($img);
    $fp = @fopen($img, 'rb');
    if ($thumbInfo && $fp) {
Esempio n. 11
0
    $src = $filename;
    $tn_src = $filename;
    // Validates the form input
    //if(strlen($_POST['description']) < 4)
    //$error['description'] = '<p class="alert">Please enter a description for your photo. </p>';
    if ($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename)) {
        $error['no_file'] = '<p class="alert">กรุณาเลือกรูปภาพเพื่ออัพโหลด! </p>';
    }
    if (!$error) {
        move_uploaded_file($source, $target);
        $q = "INSERT into gs_photo(description, src, tn_src ,album_id) VALUES('{$description}', '{$src}', '{$tn_src}', '{$id}')";
        $result = $mysqli->query($q) or die(mysqli_error($mysqli));
        if ($result) {
            //echo "Success! Your file has been uploaded";
        }
        createThumbnail($filename);
        header("location: index.php?album_id=" . $id);
    }
    // end preg_match
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	<link rel="stylesheet" href="css/default.css" />
	<title>My Photos</title>
	<script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script>
	<script type="text/javascript">
	$(function() {
Esempio n. 12
0
             //一意のファイルネーム
             $uqFileName = uniqid('p') . '.' . getExt($fileName);
             $tmpName = $_FILES['addPhoto']['tmp_name'][$key];
             if (is_uploaded_file($tmpName)) {
                 if (move_uploaded_file($tmpName, "photo/" . $uqFileName)) {
                     chmod("photo/" . $uqFileName, 0644);
                     //                $stmt = $pdo->prepare("INSERT INTO photo (p_id, p_fileName, p_date, p_resistDate, p_title, p_koujiName, p_koujiShu,p_class,p_subClass,p_koushuYobi,p_place,p_period,p_infoYobi,p_photographer,p_company,p_description,p_floor,p_xStreet,p_yStreet,p_starFlg,p_blackBoardFlg)VALUES(NULL, :p_fileName, sysdate(), sysdate(), NULL , NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,:p_photographer,NULL ,NULL ,NULL ,NULL ,NULL ,0,0)");
                     $stmt = $pdo->prepare("INSERT INTO photo (p_id, p_fileName, p_date ,p_resistDate,p_photographer,p_starFlg,p_blackBoardFlg )VALUES(NULL, :p_fileName, sysdate(), sysdate(),:p_photographer,0,0)");
                     $stmt->bindValue(':p_fileName', $uqFileName);
                     $stmt->bindValue(':p_photographer', '中島貴春');
                     $status = $stmt->execute();
                     if ($status == false) {
                         echo "SQLエラー";
                         exit;
                     }
                     createThumbnail($uqFileName);
                 }
             }
         }
     }
     header("Location:main.php");
     //------------------------写真削除------------------------
 } else {
     if ($_POST["post_flg"] == 2) {
         if (isset($_POST['selectedNo'])) {
             $queryStr = 'DELETE FROM photo WHERE p_id IN(';
             //クエリ分に選択されたIDを足していく
             foreach ($_POST['selectedNo'] as $val) {
                 $queryStr .= $val . ',';
             }
             //最後にいらない,を削除
Esempio n. 13
0
$filename = filter_var($title . generateRandomString(5) . "." . $nameExif, FILTER_SANITIZE_SPECIAL_CHARS);
// Make sure description, set or not, is properly set
$desc = '';
if ($_POST['imageDesc']) {
    $desc = filter_var($_POST['imageDesc'], FILTER_SANITIZE_SPECIAL_CHARS);
    if ($_POST['imageDesc'] == 'undefined') {
        $desc = '';
    }
}
// Make the user's folder if it's their first upload.
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, '0755', true);
}
// Save the image to disk in folder with user's id
if (move_uploaded_file($_FILES['uploadfile']["tmp_name"], $upload_dir . $filename)) {
    $tempVar = createThumbnail(file_get_contents($upload_dir . $filename));
    if ($tempVar) {
        $stm->bindParam(":thumbnail", $tempVar, PDO::PARAM_LOB);
        $stm->bindParam(":userID", $_SESSION['userID'], PDO::PARAM_STR);
        $stm->bindParam(":imageTitle", $title, PDO::PARAM_STR);
        $stm->bindParam(":imageName", $filename, PDO::PARAM_STR);
        $stm->bindParam(":imageDesc", $desc, PDO::PARAM_STR);
        $stm->bindParam(":inFolderID", $_POST['folderID'], PDO::PARAM_INT);
        if (!$stm->execute()) {
            die("Failed: Unable to upload image to database.");
        } else {
            $lastID = $db->lastInsertId();
            // Add tags
            if ($_POST['tags'] != '') {
                $tags = explode(',', $_POST['tags']);
                foreach ($tags as $tag) {
Esempio n. 14
0
 public function uploadFiles1($conn, $files, $kde)
 {
     $fileCount = count($files["name"]);
     if ($fileCount + count($this->attachments) > 100) {
         echoError("err-too-many-attachments");
         return;
     }
     for ($i = 0; $i < $fileCount; $i++) {
         $subor = $files["name"][$i];
         $ext = pathinfo($subor, PATHINFO_EXTENSION);
         if (checkUploadFile($ext, $files["size"][$i])) {
             $typ = "program";
             if (isSupportedImageFormat($ext)) {
                 $typ = "image";
             }
             if (mysqli_query($conn, "INSERT INTO " . $typ . "s (context_id, original_name) VALUES (" . $this->id . ",\"" . $subor . "\")")) {
                 $new_name = mysqli_insert_id($conn) . "." . $ext;
                 if ($typ == "image") {
                     $target_file = $kde . $typ . "s/big/" . $new_name;
                     $target_file2 = $kde . $typ . "s/small/" . $new_name;
                     if (!file_exists($kde . $typ . "s/big")) {
                         mkdir($kde . $typ . "s/big", 0777, true);
                     }
                     if (!file_exists($kde . $typ . "s/small")) {
                         mkdir($kde . $typ . "s/small", 0777, true);
                     }
                 } else {
                     $target_file = $kde . $typ . "s/" . $new_name;
                     if (!file_exists($kde . $typ . "s")) {
                         mkdir($kde . $typ . "s", 0777, true);
                     }
                 }
                 if (move_uploaded_file($files["tmp_name"][$i], $target_file)) {
                     if ($typ == "image") {
                         createThumbnail($new_name, 250, 250, $kde . $typ . "s/big", $kde . $typ . "s/small/");
                     }
                     echoMessage("m-file-uploaded", $subor);
                 } else {
                     mysqli_query($conn, "DELETE FROM " . $typ . "s WHERE " . $typ . "_id = " . mysqli_insert_id($conn));
                     echoError("err-file-upload", $subor);
                 }
             } else {
                 echoError("err-file-upload-db", $subor . ": " . mysqli_error($conn));
             }
         } else {
             echoError("err-file-too-big", $subor);
         }
     }
 }
Esempio n. 15
0
 public function createNewHomePageImage($img_name, $href, $caption, $size)
 {
     if (isset($_FILES[$img_name])) {
         $target_dir = "/uploads/news/";
         switch ($_FILES[$img_name]["type"]) {
             case "image/gif":
                 $file_ext = ".gif";
                 break;
             case "image/jpeg":
                 $file_ext = ".jpeg";
                 break;
             case "image/jpg":
                 $file_ext = ".jpg";
                 break;
             case "image/pjpeg":
                 $file_ext = ".jpeg";
                 break;
             case "image/png":
                 $file_ext = ".png";
                 break;
             default:
                 $file_ext = "";
                 break;
         }
         if (empty($file_ext)) {
             throw new Exception("Unknown file format");
         }
         $img_url = $target_dir . uniqid("img_") . $file_ext;
         $target_file = ROOT . $img_url;
     } else {
         throw new Exception("No image set");
     }
     $link = AdminUtility::getDefaultDBConnection();
     //Check if exists
     $check_query = "select * from home_page_images where img_url='" . mysqli_escape_string($link, $img_url) . "' " . "and caption = '" . mysqli_escape_string($link, $caption) . "'";
     $check_result = mysqli_query($link, $check_query);
     if (!$check_result) {
         //Log error
         AdminUtility::logMySQLError($link);
         throw new Exception("Oops! Something went wrong");
     } elseif (mysqli_num_rows($check_result) > 0) {
         throw new Exception("Image already exists");
     }
     //Validate news
     if (empty($href) || empty($caption)) {
         throw new Exception("Link or caption is empty");
     }
     //upload
     if (isset($_FILES[$img_name])) {
         if (!move_uploaded_file($_FILES[$img_name]["tmp_name"], $target_file)) {
             throw new Exception("Upload failed");
         }
     } else {
         throw new Exception("Upload empty");
     }
     //Check image dimension
     try {
         checkDimension($target_file, $size);
     } catch (Exception $exc) {
         unlink($target_file);
         throw new Exception($exc->getMessage());
     }
     //Create thumbnail
     $thumb_url = createThumbnail($target_file);
     $query = "insert into home_page_images set " . "img_url='" . mysqli_escape_string($link, $img_url) . "', " . "href='" . mysqli_escape_string($link, $href) . "', " . "thumb_url='" . mysqli_escape_string($link, $thumb_url) . "', " . "caption='" . mysqli_escape_string($link, $caption) . "', " . "size='" . mysqli_escape_string($link, $size) . "'";
     $result = mysqli_query($link, $query);
     //Log error
     AdminUtility::logMySQLError($link);
     return $result;
 }
Esempio n. 16
0
function generateThumb()
{
    require '../../init.php';
    $img = scandir($_SESSION['rootDir'] . '/images/trip/');
    foreach ($img as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        } else {
            $imgData[] = $file;
        }
    }
    $files = scandir($_SESSION['rootDir'] . '/images/thumb/');
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        } else {
            $thumbData[] = $file;
        }
    }
    if (!empty($thumbData)) {
        $data = array_diff($imgData, $thumbData);
        foreach ($data as $thumbImg) {
            createThumbnail($_SESSION['rootDir'] . '/images/trip/' . $thumbImg);
        }
    } else {
        foreach ($imgData as $thumbImg) {
            createThumbnail($_SESSION['rootDir'] . '/images/trip/' . $thumbImg);
        }
    }
    echo 'Icons generated successfully!';
}
    $isJPEG = in_array(strtolower($ext), $display);
    $isThumb = False;
    $aSize = count($parts);
    if ($aSize > 0) {
        $isThumb = $parts[$aSize - 1] == 'thumb';
    }
    return $isJPEG && !$isThumb;
}
set_time_limit(0);
$watermark = imagecreatefrompng('../images/watermark.png');
$it = new RecursiveDirectoryIterator("../images");
foreach (new RecursiveIteratorIterator($it) as $file) {
    if (isTargetImage($file)) {
        setImageCopyright($file, 'Copyright 2014 Emel Hamlet');
        $image = imagecreatefromjpeg($file);
        if (strpos($file, '../images/current') === 0 || strpos($file, '../images/past') === 0) {
            $parts = explode('.', $file);
            $ext = array_pop($parts);
            array_push($parts, 'thumb', $ext);
            $thumbnail = implode('.', $parts);
            resizeImage($image, NULL, 500);
            watermarkImage($image, $watermark);
            createThumbnail($image, $thumbnail, NULL, 150);
        } else {
            watermarkImage($image, $watermark);
        }
        imagejpeg($image, getcwd() . '/' . $file);
        imagedestroy($image);
    }
}
imagedestroy($watermark);
function properties_update($selected_id)
{
    global $Translation;
    if ($_GET['update_x'] != '') {
        $_POST = $_GET;
    }
    // mm: can member edit record?
    $arrPerm = getTablePermissions('properties');
    $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
    $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
    if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
        // allow update?
        // update allowed, so continue ...
    } else {
        return false;
    }
    $data['property_name'] = makeSafe($_POST['property_name']);
    if ($data['property_name'] == empty_lookup_value) {
        $data['property_name'] = '';
    }
    if ($data['property_name'] == '') {
        echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Property Name': {$Translation['field not null']}<br><br>";
        echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
        exit;
    }
    $data['type'] = makeSafe($_POST['type']);
    if ($data['type'] == empty_lookup_value) {
        $data['type'] = '';
    }
    if ($data['type'] == '') {
        echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Type': {$Translation['field not null']}<br><br>";
        echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
        exit;
    }
    $data['number_of_units'] = makeSafe($_POST['number_of_units']);
    if ($data['number_of_units'] == empty_lookup_value) {
        $data['number_of_units'] = '';
    }
    $data['owner'] = makeSafe($_POST['owner']);
    if ($data['owner'] == empty_lookup_value) {
        $data['owner'] = '';
    }
    $data['operating_account'] = makeSafe($_POST['operating_account']);
    if ($data['operating_account'] == empty_lookup_value) {
        $data['operating_account'] = '';
    }
    $data['property_reserve'] = makeSafe($_POST['property_reserve']);
    if ($data['property_reserve'] == empty_lookup_value) {
        $data['property_reserve'] = '';
    }
    $data['lease_term'] = makeSafe($_POST['lease_term']);
    if ($data['lease_term'] == empty_lookup_value) {
        $data['lease_term'] = '';
    }
    $data['country'] = makeSafe($_POST['country']);
    if ($data['country'] == empty_lookup_value) {
        $data['country'] = '';
    }
    $data['street'] = makeSafe($_POST['street']);
    if ($data['street'] == empty_lookup_value) {
        $data['street'] = '';
    }
    $data['City'] = makeSafe($_POST['City']);
    if ($data['City'] == empty_lookup_value) {
        $data['City'] = '';
    }
    $data['State'] = makeSafe($_POST['State']);
    if ($data['State'] == empty_lookup_value) {
        $data['State'] = '';
    }
    $data['ZIP'] = makeSafe($_POST['ZIP']);
    if ($data['ZIP'] == empty_lookup_value) {
        $data['ZIP'] = '';
    }
    $data['selectedID'] = makeSafe($selected_id);
    if ($_POST['photo_remove'] == 1) {
        $data['photo'] = '';
    } else {
        $data['photo'] = PrepareUploadedFile('photo', 1024000, 'jpg|jpeg|gif|png', false, "");
        if ($data['photo']) {
            createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'tv'));
        }
        if ($data['photo']) {
            createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'dv'));
        }
    }
    // hook: properties_before_update
    if (function_exists('properties_before_update')) {
        $args = array();
        if (!properties_before_update($data, getMemberInfo(), $args)) {
            return false;
        }
    }
    $o = array('silentErrors' => true);
    sql('update `properties` set       `property_name`=' . ($data['property_name'] !== '' && $data['property_name'] !== NULL ? "'{$data['property_name']}'" : 'NULL') . ', `type`=' . ($data['type'] !== '' && $data['type'] !== NULL ? "'{$data['type']}'" : 'NULL') . ', `number_of_units`=' . ($data['number_of_units'] !== '' && $data['number_of_units'] !== NULL ? "'{$data['number_of_units']}'" : 'NULL') . ', ' . ($data['photo'] != '' ? "`photo`='{$data['photo']}'" : ($_POST['photo_remove'] != 1 ? '`photo`=`photo`' : '`photo`=NULL')) . ', `owner`=' . ($data['owner'] !== '' && $data['owner'] !== NULL ? "'{$data['owner']}'" : 'NULL') . ', `country`=' . ($data['country'] !== '' && $data['country'] !== NULL ? "'{$data['country']}'" : 'NULL') . ', `street`=' . ($data['street'] !== '' && $data['street'] !== NULL ? "'{$data['street']}'" : 'NULL') . ', `City`=' . ($data['City'] !== '' && $data['City'] !== NULL ? "'{$data['City']}'" : 'NULL') . ', `State`=' . ($data['State'] !== '' && $data['State'] !== NULL ? "'{$data['State']}'" : 'NULL') . ', `ZIP`=' . ($data['ZIP'] !== '' && $data['ZIP'] !== NULL ? "'{$data['ZIP']}'" : 'NULL') . " where `id`='" . makeSafe($selected_id) . "'", $o);
    if ($o['error'] != '') {
        echo $o['error'];
        echo '<a href="properties_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
        exit;
    }
    // hook: properties_after_update
    if (function_exists('properties_after_update')) {
        $res = sql("SELECT * FROM `properties` WHERE `id`='{$data['selectedID']}' LIMIT 1", $eo);
        if ($row = db_fetch_assoc($res)) {
            $data = array_map('makeSafe', $row);
        }
        $data['selectedID'] = $data['id'];
        $args = array();
        if (!properties_after_update($data, getMemberInfo(), $args)) {
            return;
        }
    }
    // mm: update ownership data
    sql("update membership_userrecords set dateUpdated='" . time() . "' where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'", $eo);
}
Esempio n. 19
0
function createAttachment(&$attachmentOptions)
{
    global $modSettings, $sourcedir, $backend_subdir;
    require_once $sourcedir . '/lib/Subs-Graphics.php';
    // We need to know where this thing is going.
    if (!empty($modSettings['currentAttachmentUploadDir'])) {
        if (!is_array($modSettings['attachmentUploadDir'])) {
            $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
        }
        // Just use the current path for temp files.
        $attach_dir = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
        $id_folder = $modSettings['currentAttachmentUploadDir'];
    } else {
        $attach_dir = $modSettings['attachmentUploadDir'];
        $id_folder = 1;
    }
    $attachmentOptions['errors'] = array();
    if (!isset($attachmentOptions['post'])) {
        $attachmentOptions['post'] = 0;
    }
    if (!isset($attachmentOptions['approved'])) {
        $attachmentOptions['approved'] = 1;
    }
    $already_uploaded = preg_match('~^post_tmp_' . $attachmentOptions['poster'] . '_\\d+$~', $attachmentOptions['tmp_name']) != 0;
    $file_restricted = @ini_get('open_basedir') != '' && !$already_uploaded;
    if ($already_uploaded) {
        $attachmentOptions['tmp_name'] = $attach_dir . '/' . $attachmentOptions['tmp_name'];
    }
    // Make sure the file actually exists... sometimes it doesn't.
    if (!$file_restricted && !file_exists($attachmentOptions['tmp_name']) || !$already_uploaded && !is_uploaded_file($attachmentOptions['tmp_name'])) {
        $attachmentOptions['errors'] = array('could_not_upload');
        return false;
    }
    // These are the only valid image types for SMF.
    $validImageTypes = array(1 => 'gif', 2 => 'jpeg', 3 => 'png', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpeg', 14 => 'iff');
    if (!$file_restricted || $already_uploaded) {
        $size = @getimagesize($attachmentOptions['tmp_name']);
        list($attachmentOptions['width'], $attachmentOptions['height']) = $size;
        // If it's an image get the mime type right.
        if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width']) {
            // Got a proper mime type?
            if (!empty($size['mime'])) {
                $attachmentOptions['mime_type'] = $size['mime'];
            } elseif (isset($validImageTypes[$size[2]])) {
                $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
            }
        }
    }
    // Get the hash if no hash has been given yet.
    if (empty($attachmentOptions['file_hash'])) {
        $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);
    }
    // Is the file too big?
    if (!empty($modSettings['attachmentSizeLimit']) && $attachmentOptions['size'] > $modSettings['attachmentSizeLimit'] * 1024) {
        $attachmentOptions['errors'][] = 'too_large';
    }
    if (!empty($modSettings['attachmentCheckExtensions'])) {
        $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
        foreach ($allowed as $k => $dummy) {
            $allowed[$k] = trim($dummy);
        }
        if (!in_array(strtolower(substr(strrchr($attachmentOptions['name'], '.'), 1)), $allowed)) {
            $attachmentOptions['errors'][] = 'bad_extension';
        }
    }
    if (!empty($modSettings['attachmentDirSizeLimit'])) {
        // This is a really expensive operation for big numbers of
        // attachments, which is also very easy to cache. Only do it
        // every ten minutes.
        if (empty($modSettings['attachment_dirsize']) || empty($modSettings['attachment_dirsize_time']) || $modSettings['attachment_dirsize_time'] < time() - 600) {
            // It has been cached - just work with this value for now!
            $dirSize = $modSettings['attachment_dirsize'];
        } else {
            // Make sure the directory isn't full.
            $dirSize = 0;
            $dir = @opendir($attach_dir) or fatal_lang_error('cant_access_upload_path', 'critical');
            while ($file = readdir($dir)) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                if (preg_match('~^post_tmp_\\d+_\\d+$~', $file) != 0) {
                    // Temp file is more than 5 hours old!
                    if (filemtime($attach_dir . '/' . $file) < time() - 18000) {
                        @unlink($attach_dir . '/' . $file);
                    }
                    continue;
                }
                $dirSize += filesize($attach_dir . '/' . $file);
            }
            closedir($dir);
            updateSettings(array('attachment_dirsize' => $dirSize, 'attachment_dirsize_time' => time()));
        }
        // Too big!  Maybe you could zip it or something...
        if ($attachmentOptions['size'] + $dirSize > $modSettings['attachmentDirSizeLimit'] * 1024) {
            $attachmentOptions['errors'][] = 'directory_full';
        } elseif (!isset($modSettings['attachment_full_notified']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $attachmentOptions['size'] + $dirSize > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024) {
            require_once $sourcedir . '/lib/Subs-Admin.php';
            emailAdmins('admin_attachments_full');
            updateSettings(array('attachment_full_notified' => 1));
        }
    }
    // Check if the file already exists.... (for those who do not encrypt their filenames...)
    if (empty($modSettings['attachmentEncryptFilenames'])) {
        // Make sure they aren't trying to upload a nasty file.
        $disabledFiles = array('con', 'com1', 'com2', 'com3', 'com4', 'prn', 'aux', 'lpt1', '.htaccess', 'index.php');
        if (in_array(strtolower(basename($attachmentOptions['name'])), $disabledFiles)) {
            $attachmentOptions['errors'][] = 'bad_filename';
        }
        // Check if there's another file with that name...
        $request = smf_db_query('
			SELECT id_attach
			FROM {db_prefix}attachments
			WHERE filename = {string:filename}
			LIMIT 1', array('filename' => strtolower($attachmentOptions['name'])));
        if (mysql_num_rows($request) > 0) {
            $attachmentOptions['errors'][] = 'taken_filename';
        }
        mysql_free_result($request);
    }
    if (!empty($attachmentOptions['errors'])) {
        return false;
    }
    if (!is_writable($attach_dir)) {
        fatal_lang_error('attachments_no_write', 'critical');
    }
    // Assuming no-one set the extension let's take a look at it.
    if (empty($attachmentOptions['fileext'])) {
        $attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
        if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name']) {
            $attachmentOptions['fileext'] = '';
        }
    }
    smf_db_insert('', '{db_prefix}attachments', array('id_folder' => 'int', 'id_msg' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int'), array($id_folder, (int) $attachmentOptions['post'], $attachmentOptions['name'], $attachmentOptions['file_hash'], $attachmentOptions['fileext'], (int) $attachmentOptions['size'], empty($attachmentOptions['width']) ? 0 : (int) $attachmentOptions['width'], empty($attachmentOptions['height']) ? '0' : (int) $attachmentOptions['height'], !empty($attachmentOptions['mime_type']) ? $attachmentOptions['mime_type'] : '', (int) $attachmentOptions['approved']), array('id_attach'));
    $attachmentOptions['id'] = smf_db_insert_id('{db_prefix}attachments', 'id_attach');
    if (empty($attachmentOptions['id'])) {
        return false;
    }
    // If it's not approved add to the approval queue.
    if (!$attachmentOptions['approved']) {
        smf_db_insert('', '{db_prefix}approval_queue', array('id_attach' => 'int', 'id_msg' => 'int'), array($attachmentOptions['id'], (int) $attachmentOptions['post']), array());
    }
    $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $id_folder, false, $attachmentOptions['file_hash']);
    if ($already_uploaded) {
        rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
    } elseif (!move_uploaded_file($attachmentOptions['tmp_name'], $attachmentOptions['destination'])) {
        fatal_lang_error('attach_timeout', 'critical');
    }
    // Udate the cached directory size, if we care for it.
    if (!empty($modSettings['attachmentDirSizeLimit'])) {
        updateSettings(array('attachment_dirsize' => $modSettings['attachment_dirsize'] + $attachmentOptions['size'], 'attachment_dirsize_time' => time()));
    }
    // Attempt to chmod it.
    @chmod($attachmentOptions['destination'], 0644);
    $size = @getimagesize($attachmentOptions['destination']);
    list($attachmentOptions['width'], $attachmentOptions['height']) = empty($size) ? array(null, null, null) : $size;
    // We couldn't access the file before...
    if ($file_restricted) {
        // Have a go at getting the right mime type.
        if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width']) {
            if (!empty($size['mime'])) {
                $attachmentOptions['mime_type'] = $size['mime'];
            } elseif (isset($validImageTypes[$size[2]])) {
                $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
            }
        }
        if (!empty($attachmentOptions['width']) && !empty($attachmentOptions['height'])) {
            smf_db_query('
				UPDATE {db_prefix}attachments
				SET
					width = {int:width},
					height = {int:height},
					mime_type = {string:mime_type}
				WHERE id_attach = {int:id_attach}', array('width' => (int) $attachmentOptions['width'], 'height' => (int) $attachmentOptions['height'], 'id_attach' => $attachmentOptions['id'], 'mime_type' => empty($attachmentOptions['mime_type']) ? '' : $attachmentOptions['mime_type']));
        }
    }
    // Security checks for images
    // Do we have an image? If yes, we need to check it out!
    if (isset($validImageTypes[$size[2]])) {
        if (!checkImageContents($attachmentOptions['destination'], !empty($modSettings['attachment_image_paranoid']))) {
            // It's bad. Last chance, maybe we can re-encode it?
            if (empty($modSettings['attachment_image_reencode']) || !reencodeImage($attachmentOptions['destination'], $size[2])) {
                // Nothing to do: not allowed or not successful re-encoding it.
                require_once $sourcedir . '/lib/Subs-ManageAttachments.php';
                removeAttachments(array('id_attach' => $attachmentOptions['id']));
                $attachmentOptions['id'] = null;
                $attachmentOptions['errors'][] = 'bad_attachment';
                return false;
            }
            // Success! However, successes usually come for a price:
            // we might get a new format for our image...
            $old_format = $size[2];
            $size = @getimagesize($attachmentOptions['destination']);
            if (!empty($size) && $size[2] != $old_format) {
                // Let's update the image information
                // !!! This is becoming a mess: we keep coming back and update the database,
                //  instead of getting it right the first time.
                if (isset($validImageTypes[$size[2]])) {
                    $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
                    smf_db_query('
						UPDATE {db_prefix}attachments
						SET
							mime_type = {string:mime_type}
						WHERE id_attach = {int:id_attach}', array('id_attach' => $attachmentOptions['id'], 'mime_type' => $attachmentOptions['mime_type']));
                }
            }
        }
    }
    if (!empty($attachmentOptions['skip_thumbnail']) || empty($attachmentOptions['width']) && empty($attachmentOptions['height'])) {
        return true;
    }
    // Like thumbnails, do we?
    if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight'])) {
        if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight'])) {
            // Figure out how big we actually made it.
            $size = @getimagesize($attachmentOptions['destination'] . '_thumb');
            list($thumb_width, $thumb_height) = $size;
            if (!empty($size['mime'])) {
                $thumb_mime = $size['mime'];
            } elseif (isset($validImageTypes[$size[2]])) {
                $thumb_mime = 'image/' . $validImageTypes[$size[2]];
            } else {
                $thumb_mime = '';
            }
            $thumb_filename = $attachmentOptions['name'] . '_thumb';
            $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
            $thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
            // To the database we go!
            smf_db_insert('', '{db_prefix}attachments', array('id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int'), array($id_folder, (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'], $thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved']), array('id_attach'));
            $attachmentOptions['thumb'] = smf_db_insert_id('{db_prefix}attachments', 'id_attach');
            if (!empty($attachmentOptions['thumb'])) {
                smf_db_query('
					UPDATE {db_prefix}attachments
					SET id_thumb = {int:id_thumb}
					WHERE id_attach = {int:id_attach}', array('id_thumb' => $attachmentOptions['thumb'], 'id_attach' => $attachmentOptions['id']));
                rename($attachmentOptions['destination'] . '_thumb', getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $id_folder, false, $thumb_file_hash));
            }
        }
    }
    return true;
}
function modifythumbnails()
{
    $sql = "SELECT pd_image, pd_thumbnail FROM tbl_Course where (pd_image!='')";
    $result = dbQuery($sql) or die('Cannot get Course. ' . mysql_error());
    while ($row = dbFetchArray($result)) {
        list($bigimage, $thumbimage) = $row;
        if ($thumbimage != '') {
            rename(SRV_ROOT . 'images/Course/' . $thumbimage, SRV_ROOT . 'images/Course/remainings/' . $thumbimage);
        }
        createThumbnail(SRV_ROOT . 'images/Course/' . $bigimage, SRV_ROOT . 'images/Course/' . $thumbimage, 100);
    }
    header("Location: index.php");
}
Esempio n. 21
0
     mkdir($path . "/images");
     mkdir($path . "/images/thumb/");
     mkdir($path . "/pdf");
     mkdir($path . "/videos");
 }
 switch ($type) {
     case 'link':
         $notes = $data;
         break;
     case 'image':
         $image_date_name = date('Y-m-d_H-i-s');
         $image_name = $image_date_name . "." . $ext;
         $image_path = $path . "/images/" . $image_name;
         file_put_contents($image_path, base64_decode($data));
         $thumb_path = $path . "/images/thumb/";
         createThumbnail($image_path, $image_date_name, 250, $thumb_path);
         $notes = $sitesUrl . "{$site}/documents/userdata/images/" . $image_name;
         break;
     case 'pdf':
         $pdf_name = date('Y-m-d_H-i-s') . "." . $ext;
         file_put_contents($path . "/pdf/" . $pdf_name, base64_decode($data));
         $notes = $sitesUrl . "{$site}/documents/userdata/pdf/" . $pdf_name;
         break;
     case 'video':
         $video_name = date('Y-m-d_H-i-s') . "." . $ext;
         file_put_contents($path . "/videos/" . $video_name, base64_decode($data));
         $notes = $sitesUrl . "{$site}/documents/userdata/videos/" . $video_name;
         break;
 }
 $select_query = "SELECT *  FROM `list_options` \n        WHERE `list_id` LIKE 'lists' AND `option_id` LIKE '" . add_escape_custom($list_id) . "' AND `title` LIKE '" . add_escape_custom($list_id) . "'";
 $result_select = sqlQuery($select_query);
function AddPicture2($allowed_add)
{
    global $txt, $smcFunc, $sourcedir, $modSettings, $context;
    $memID = $context['member']['id'];
    checkSession('post');
    if (!$allowed_add) {
        fatal_error($txt['Maximum_pictures_add_not'], false);
    }
    if (!isset($_POST['title']) || !isset($_POST['description']) || !isset($_FILES['picture']) || !isset($_POST['album_id'])) {
        fatal_error($txt['Maximum_pictures_fields'], false);
    }
    if ($_POST['album_id'] > 0) {
        $request = $smcFunc['db_query']('', '
			SELECT pictures 
			FROM {db_prefix}Maximum_albums 
			WHERE id_album = {int:id_album}', array('id_album' => (int) $_POST['album_id']));
        if ($smcFunc['db_num_rows']($request) < 1) {
            fatal_error($txt['Maximum_albums_parent_not'], false);
        }
    }
    // Are there any errors during upload?
    if (!($_FILES['picture']['error'] == '0') || !file_exists($_FILES['picture']['tmp_name']) || !is_uploaded_file($_FILES['picture']['tmp_name'])) {
        fatal_error($txt['Maximum_pictures_upload_fail'], false);
    }
    // Is this file a picture or something else?
    $picture = getimagesize($_FILES['picture']['tmp_name']);
    if ($picture == NULL) {
        fatal_error($txt['Maximum_pictures_pic_not'], false);
    }
    $time = time();
    $filename = $memID . '_' . $time . '.' . get_extension($_FILES['picture']['name']);
    $thumb_filename = $memID . '_' . $time . '_thumb.' . get_extension($_FILES['picture']['name']);
    move_uploaded_file($_FILES['picture']['tmp_name'], $modSettings['Maximum_pictures_path'] . '/tmp_' . $memID);
    // Let's make thumbnails :).
    unset($modSettings['avatar_download_png']);
    // Delete this line if you want PNG thumbnails (better quality (lossless), much bigger files).
    require_once $sourcedir . '/Subs-Graphics.php';
    createThumbnail($modSettings['Maximum_pictures_path'] . '/tmp_' . $memID, 400, 400);
    rename($modSettings['Maximum_pictures_path'] . '/tmp_' . $memID . '_thumb', $modSettings['Maximum_pictures_path'] . '/' . $thumb_filename);
    createThumbnail($modSettings['Maximum_pictures_path'] . '/tmp_' . $memID, $modSettings['Maximum_pictures_width'], '');
    rename($modSettings['Maximum_pictures_path'] . '/tmp_' . $memID . '_thumb', $modSettings['Maximum_pictures_path'] . '/' . $filename);
    @unlink($modSettings['Maximum_pictures_path'] . '/tmp_' . $memID);
    $smcFunc['db_insert']('normal', '{db_prefix}Maximum_pictures', array('id_member' => 'int', 'time' => 'int', 'title' => 'text', 'description' => 'text', 'filename' => 'text', 'id_album' => 'int'), array('id_member' => $memID, 'time' => $time, 'title' => htmlspecialchars($_POST['title']), 'description' => htmlspecialchars($_POST['description']), 'filename' => htmlspecialchars($_FILES['picture']['name']), 'id_album' => (int) $_POST['album_id']), array('id_picture'));
    if ($_POST['album_id'] > 0) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}Maximum_albums SET 
			pictures = pictures + 1 
			WHERE id_album = {int:id_album}', array('id_album' => (int) $_POST['album_id']));
    }
    redirectexit('action=profile;area=pictures;u=' . $memID . ';album=' . $_POST['album_id']);
}
Esempio n. 23
0
function categories_update($selected_id)
{
    global $Translation;
    if ($_GET['update_x'] != '') {
        $_POST = $_GET;
    }
    // mm: can member edit record?
    $arrPerm = getTablePermissions('categories');
    $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='categories' and pkValue='" . makeSafe($selected_id) . "'");
    $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='categories' and pkValue='" . makeSafe($selected_id) . "'");
    if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
        // allow update?
        // update allowed, so continue ...
    } else {
        return false;
    }
    $data['CategoryName'] = makeSafe($_POST['CategoryName']);
    if ($data['CategoryName'] == empty_lookup_value) {
        $data['CategoryName'] = '';
    }
    $data['Description'] = makeSafe($_POST['Description']);
    if ($data['Description'] == empty_lookup_value) {
        $data['Description'] = '';
    }
    $data['selectedID'] = makeSafe($selected_id);
    if ($_POST['Picture_remove'] == 1) {
        $data['Picture'] = '';
        // delete file from server
        $res = sql("select `Picture` from `categories` where `CategoryID`='" . makeSafe($selected_id) . "'", $eo);
        if ($row = @db_fetch_row($res)) {
            if ($row[0] != '') {
                @unlink(getUploadDir('') . $row[0]);
                preg_match('/^[a-z0-9_]+\\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
                $thumbDV = str_replace(".{$m['1']}ffffgggg", "_dv.{$m['1']}", $row[0] . 'ffffgggg');
                $thumbTV = str_replace(".{$m['1']}ffffgggg", "_tv.{$m['1']}", $row[0] . 'ffffgggg');
                @unlink(getUploadDir('') . $thumbTV);
                @unlink(getUploadDir('') . $thumbDV);
            }
        }
    } else {
        $data['Picture'] = PrepareUploadedFile('Picture', 204800, 'jpg|jpeg|gif|png', false, "");
        if ($data['Picture']) {
            createThumbnail($data['Picture'], getThumbnailSpecs('categories', 'Picture', 'tv'));
        }
        if ($data['Picture']) {
            createThumbnail($data['Picture'], getThumbnailSpecs('categories', 'Picture', 'dv'));
        }
        // delete file from server
        if ($data['Picture'] != '') {
            $res = sql("select `Picture` from `categories` where `CategoryID`='" . makeSafe($selected_id) . "'", $eo);
            if ($row = @db_fetch_row($res)) {
                if ($row[0] != '') {
                    @unlink(getUploadDir('') . $row[0]);
                    preg_match('/^[a-z0-9_]+\\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
                    $thumbDV = str_replace(".{$m['1']}ffffgggg", "_dv.{$m['1']}", $row[0] . 'ffffgggg');
                    $thumbTV = str_replace(".{$m['1']}ffffgggg", "_tv.{$m['1']}", $row[0] . 'ffffgggg');
                    @unlink(getUploadDir('') . $thumbTV);
                    @unlink(getUploadDir('') . $thumbDV);
                }
            }
        }
    }
    // hook: categories_before_update
    if (function_exists('categories_before_update')) {
        $args = array();
        if (!categories_before_update($data, getMemberInfo(), $args)) {
            return false;
        }
    }
    $o = array('silentErrors' => true);
    sql('update `categories` set       ' . ($data['Picture'] != '' ? "`Picture`='{$data['Picture']}'" : ($_POST['Picture_remove'] != 1 ? '`Picture`=`Picture`' : '`Picture`=NULL')) . ', `CategoryName`=' . ($data['CategoryName'] !== '' && $data['CategoryName'] !== NULL ? "'{$data['CategoryName']}'" : 'NULL') . ', `Description`=' . ($data['Description'] !== '' && $data['Description'] !== NULL ? "'{$data['Description']}'" : 'NULL') . " where `CategoryID`='" . makeSafe($selected_id) . "'", $o);
    if ($o['error'] != '') {
        echo $o['error'];
        echo '<a href="categories_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
        exit;
    }
    // hook: categories_after_update
    if (function_exists('categories_after_update')) {
        $res = sql("SELECT * FROM `categories` WHERE `CategoryID`='{$data['selectedID']}' LIMIT 1", $eo);
        if ($row = db_fetch_assoc($res)) {
            $data = array_map('makeSafe', $row);
        }
        $data['selectedID'] = $data['CategoryID'];
        $args = array();
        if (!categories_after_update($data, getMemberInfo(), $args)) {
            return;
        }
    }
    // mm: update ownership data
    sql("update membership_userrecords set dateUpdated='" . time() . "' where tableName='categories' and pkValue='" . makeSafe($selected_id) . "'", $eo);
}
Esempio n. 24
0
function update_file($id, $file)
{
    global $mysql, $msg, $log;
    $id = intval($id);
    if (!$id) {
        return;
    }
    $qPicture = $mysql->query("SELECT * FROM " . _PREFIX_ . "images WHERE id = '" . $id . "'");
    $oPicture = mysql_fetch_object($qPicture);
    if (is_uploaded_file($file['tmp_name']) && !@move_uploaded_file($file['tmp_name'], IMAGE_DIR . $oPicture->file)) {
        $msg->error("Fehler beim Dateiupload.");
        return;
    }
    /**
     * Thumbnail erstellen
     */
    createThumbnail(IMAGE_DIR . $oPicture->file, IMAGE_DIR . $oPicture->file_t);
    $msg->success("Upload erfolgreich.");
    $log->add("Dateiupload Update", "<id>" . $id . "</id><file>" . $safe_filename . "</file>");
}
Esempio n. 25
0
                 $mins = floor(round($duration / 1000) / 60);
                 $secs = str_pad(floor(round($duration / 1000) % 60), 2, "0", STR_PAD_LEFT);
                 $post['file_original'] = "{$mins}:{$secs}" . ($post['file_original'] != '' ? ', ' . $post['file_original'] : '');
             } else {
                 $file_info = getimagesize($file_location);
                 $post['image_width'] = $file_info[0];
                 $post['image_height'] = $file_info[1];
                 if ($file_mime == "application/x-shockwave-flash") {
                     if (!copy('swf_thumbnail.png', $thumb_location)) {
                         @unlink($file_location);
                         fancyDie("Could not create thumbnail.");
                     }
                     addVideoOverlay($thumb_location);
                 } else {
                     list($thumb_maxwidth, $thumb_maxheight) = thumbnailDimensions($post);
                     if (!createThumbnail($file_location, $thumb_location, $thumb_maxwidth, $thumb_maxheight)) {
                         @unlink($file_location);
                         fancyDie("Could not create thumbnail.");
                     }
                 }
             }
             $thumb_info = getimagesize($thumb_location);
             $post['thumb_width'] = $thumb_info[0];
             $post['thumb_height'] = $thumb_info[1];
         }
     }
 }
 if ($post['file'] == '') {
     // No file uploaded
     $allowed = "";
     if (TINYIB_PIC || TINYIB_SWF || TINYIB_WEBM) {
Esempio n. 26
0
        //if error, retrieve the error using the oci_error() function & output an error
        if (!$res) {
            $err = oci_error($stid);
            echo htmlentities($err['message']);
        }
        $row = oci_fetch_array($stid, OCI_ASSOC);
        if (!$row['SENSOR_ID']) {
            echo 'The sensor with the sensor id: ' . $_POST['sensor_id'] . ' does not exist. <br/>';
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
        } else {
            //Create Thumbnail
            $thumb = createThumbnail($image_dir, $image_dir . '_thumb.jpg', 50, 50);
            if (!$thumb) {
                echo "Sorry, an error has occurred while creating thumbnail";
                $uploadOk = 0;
            }
            //Attempt to put image into database
            //Code stolen and adapted from https://stackoverflow.com/questions/11970258/upload-images-as-blobs-in-oracle-using-php
            $conn = connect();
            //RECOREDED DATA VS. RECOREDED DATA!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            $sql = 'INSERT INTO images(image_id, sensor_id, date_created, description, thumbnail, recorded_data)
			VALUES (\'' . $_POST['image_id'] . '\', \'' . $_POST['sensor_id'] . '\', to_date(\'' . $_POST['date_created'] . '\',
			\'dd/mm/yyyy HH24:Mi:SS\'), \'' . $_POST['description'] . '\', empty_blob(), empty_blob()) 
			RETURNING thumbnail, recorded_data INTO :thumbnail, :recorded_data';
            $stid = oci_parse($conn, $sql);
            $tblob = oci_new_descriptor($conn, OCI_D_LOB);
            $iblob = oci_new_descriptor($conn, OCI_D_LOB);
Esempio n. 27
0
             unlink($unlinktumb);
         }
         $ext = explode('.', $_FILES['file']['name']);
         $extension = $ext[1];
         if ($extension == 'jpg' || $extension == 'png' || $extension == 'JPG' || $extension == 'jpeg' || $extension == 'gif' || $extension == 'pjpeg' || $extension == 'x-png') {
             $extension = $extension;
         } else {
             echo 1;
             die;
         }
         $count = rand(0, 99999999);
         $file_name = "{$username}" . "{$count}" . "." . "{$extension}";
         $file_name = str_replace('php', '', $file_name);
         move_uploaded_file(preg_replace('/\\s+/', '', $_FILES["file"]["tmp_name"]), "../avatar/" . "{$file_name}");
         $path = "../avatar/{$file_name}";
         createThumbnail($path);
         $tumb_new = str_replace(array('.jpg', '.JPG', '.jpeg', '.png', '.gif', '.php'), array('_tumb.jpg', '_tumb.JPG', '_tumb.jpeg', '_tumb.png', '_tumb.gif', ' '), $file_name);
         $filename = "../avatar/{$tumb_new}";
         if (file_exists($filename)) {
             $tumb_new = $mysqli->real_escape_string($tumb_new);
         } else {
             $tumb_new = "default_avatar_tumb.png";
         }
         $mysqli->query("UPDATE `users` SET `user_avatar` = '{$file_name}', `user_tumb` = '{$tumb_new}'  WHERE `user_id` = '{$user["user_id"]}'");
         $mysqli->query("UPDATE `chat` SET `avatar` = '{$tumb_new}'  WHERE `post_user` = '{$user["user_name"]}'");
         $mysqli->query("UPDATE `private` SET `avatar` = '{$tumb_new}'  WHERE `hunter` = '{$user["user_name"]}'");
         echo 5;
     } else {
         echo 2909457;
     }
 }
Esempio n. 28
0
        height:100px;
        margin-top:2px;
    }
        </style>
        <?php 
require_once 'createthumb.php';
if (isset($_POST['upload_image'])) {
    $target = "../uploads/images/";
    $image = $_FILES["file"]["name"];
    $filename = stripslashes($image);
    $target = $target . basename($_FILES["file"]["name"]);
    //Writes the photo to the server
    if ($_FILES["file"]["type"] == "image/jpeg" && $_FILES["file"]["size"] < 10000000) {
        copy($_FILES["file"]["tmp_name"], $target);
        // create a thumbnail version of the image as well
        createThumbnail("file", 100, 100, "../uploads/images/.thumbs/");
    }
    // TODO - put img in DB ???
}
if ($filename) {
    //echo "<img src='../uploads/images/event_imgs/{$filename}' style='display:block;'/>\n";
    echo "<script>\n    \n    \$(function(){\n    \n    \n    \$('#image', parent.document).val('{$filename}');\n    \$(parent.document).contents().find('#short_desc_ifr').contents().find('#tinymce').css({'background': 'url(/uploads/images/" . rawurlencode($filename) . ") no-repeat #dcd4c7'});\n\n\n    });\n    </script>";
}
?>
       
        <form method='post' enctype='multipart/form-data' action='' id="upload_image_form">
            <label class="cabinet"> <input type="file" name="file" class="file" id="event_image"/>
            <input type="submit" name="upload_image" value="upload" id="upload_image"/><br/><br/>
            </label>
        </form>
        
Esempio n. 29
0
 }
 //echo "<h1 class='baex_title' style='color:#e3e3e3;'>".$title."</h1>";
 $tweet_bae = urlencode("#FLMAG:\n\n" . $title . "\n\n--> FREELABEL.net/images/" . $id . "\n" . $twitpic);
 $embed_code = '<img src="' . $image . '">';
 // Detect File Type
 if (strpos($image, 'mp4') or strpos($image, 'm4v') or strpos($image, 'mov')) {
     $type = 'video';
 } else {
     $type = 'image';
 }
 switch ($type) {
     case 'image':
         //echo 'THISIMAGE '.$image;
         if ($image != '') {
             include_once ROOT . 'submit/views/db/thumbnail.php';
             $tnl = createThumbnail($image);
             $embed_code = "<img id='main_image_showcase' src='" . $tnl . "' alt='" . $tnl . "'>";
         }
         //echo 'THIS '.$tnl;
         break;
     case 'video':
         //include_once(ROOT.'submit/views/db/thumbnail.php');
         if ($image != '') {
             $tnl = $image;
             $embed_code = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<video id='main_image_showcase' controls autoplay='1' loop=1 preload='metadata' alt='" . $tnl . "'>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<source src='" . $tnl . "'>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t</video>";
         }
         break;
     default:
         echo 'File type not recognized!';
         break;
 }
Esempio n. 30
0
        if (!mysql_select_db(VIVVO_DB_DATABASE, $connection)) {
            die("Error while connection to database. " . mysql_error());
        }
        $size = preg_replace('/[^a-zA-Z0-9\\-\\_]/', '', $_GET['size']);
        $res = mysql_query('SELECT * FROM ' . VIVVO_DB_PREFIX . 'configuration WHERE variable_name LIKE \'VIVVO_' . strtoupper($size) . '_IMAGE_%\'');
        while ($row = mysql_fetch_assoc($res)) {
            @define($row['variable_name'], $row['variable_value']);
        }
        if (defined('VIVVO_' . strtoupper($size) . '_IMAGE_HEIGHT') && defined('VIVVO_' . strtoupper($size) . '_IMAGE_WIDTH')) {
            $file_thumbnail = VIVVO_FS_ROOT . 'cache/thumbnail/' . $size . '/' . $file_thumb_name;
            $thumb_width = constant('VIVVO_' . strtoupper($size) . '_IMAGE_WIDTH');
            $thumb_height = constant('VIVVO_' . strtoupper($size) . '_IMAGE_HEIGHT');
        }
    }
    mysql_close($connection);
    createThumbnail($file, $file_thumbnail, $thumb_width, $thumb_height);
}
if (file_exists($file_thumbnail) && !is_link($file_thumbnail) && !is_dir($file_thumbnail)) {
    $file_split = explode('.', $file_thumbnail);
    $ext = end($file_split);
    $sendbody = true;
    $expires = 60 * 60 * 24 * 10;
    $exp_gmt = gmdate("D, d M Y H:i:s", VIVVO_START_TIME + $expires) . " GMT";
    $lastmod = @filemtime($file_thumbnail);
    $mod_gmt = gmdate("D, d M Y H:i:s", $lastmod) . " GMT";
    # get file content
    $etag = '"' . md5($file_thumbnail . $lastmod) . '"';
    # check 'If-Modified-Since' header
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && gmdate('D, d M Y H:i:s', $lastmod) . " GMT" == trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        header("HTTP/1.0 304 Not Modified");
        header("ETag: {$etag}");