Beispiel #1
0
function process_album_upload($album_image, $width, $height)
{
    $temp_image_path = GALLERY_MAIN_UPLOAD_DIR . $album_image;
    $temp_image_name = $album_image;
    list(, , $temp_image_type) = getimagesize($temp_image_path);
    if ($temp_image_type === NULL) {
        return false;
    }
    $uploaded_image_path = GALLERY_MAIN_UPLOAD_DIR . $temp_image_name;
    move_uploaded_file($temp_image_path, $uploaded_image_path);
    $type = explode(".", $album_image);
    $thumbnail_image_path = GALLERY_MAIN_ALB_THUMB_DIR . preg_replace("{\\.[^\\.]+\$}", "." . $type[1], $temp_image_name);
    $result = generate_thumbnail($uploaded_image_path, $thumbnail_image_path, $width, $height);
    return $result ? array($uploaded_image_path, $thumbnail_image_path) : false;
}
/**
 * Upload an attachment in to the file system
 *
 * @param array $attachment Attachment data (as fed by PHPs $_FILE)
 * @param boolean $update_attachment Whether or not we are updating a current attachment or inserting a new one
 * @return array Array of attachment data if successful, otherwise array of error data
 */
function upload_attachment($attachment, $update_attachment = false)
{
    global $mybb, $db, $theme, $templates, $posthash, $pid, $tid, $forum, $mybb, $lang, $plugins, $cache;
    $posthash = $db->escape_string($mybb->get_input('posthash'));
    $pid = (int) $pid;
    if (isset($attachment['error']) && $attachment['error'] != 0) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail;
        switch ($attachment['error']) {
            case 1:
                // UPLOAD_ERR_INI_SIZE
                $ret['error'] .= $lang->error_uploadfailed_php1;
                break;
            case 2:
                // UPLOAD_ERR_FORM_SIZE
                $ret['error'] .= $lang->error_uploadfailed_php2;
                break;
            case 3:
                // UPLOAD_ERR_PARTIAL
                $ret['error'] .= $lang->error_uploadfailed_php3;
                break;
            case 4:
                // UPLOAD_ERR_NO_FILE
                $ret['error'] .= $lang->error_uploadfailed_php4;
                break;
            case 6:
                // UPLOAD_ERR_NO_TMP_DIR
                $ret['error'] .= $lang->error_uploadfailed_php6;
                break;
            case 7:
                // UPLOAD_ERR_CANT_WRITE
                $ret['error'] .= $lang->error_uploadfailed_php7;
                break;
            default:
                $ret['error'] .= $lang->sprintf($lang->error_uploadfailed_phpx, $attachment['error']);
                break;
        }
        return $ret;
    }
    if (!is_uploaded_file($attachment['tmp_name']) || empty($attachment['tmp_name'])) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_php4;
        return $ret;
    }
    $attachtypes = $cache->read('attachtypes');
    $attachment = $plugins->run_hooks("upload_attachment_start", $attachment);
    $ext = get_extension($attachment['name']);
    // Check if we have a valid extension
    if (!isset($attachtypes[$ext])) {
        $ret['error'] = $lang->error_attachtype;
        return $ret;
    } else {
        $attachtype = $attachtypes[$ext];
    }
    // Check the size
    if ($attachment['size'] > $attachtype['maxsize'] * 1024 && $attachtype['maxsize'] != "") {
        $ret['error'] = $lang->sprintf($lang->error_attachsize, $attachtype['maxsize']);
        return $ret;
    }
    // Double check attachment space usage
    if ($mybb->usergroup['attachquota'] > 0) {
        $query = $db->simple_select("attachments", "SUM(filesize) AS ausage", "uid='" . $mybb->user['uid'] . "'");
        $usage = $db->fetch_array($query);
        $usage = $usage['ausage'] + $attachment['size'];
        if ($usage > $mybb->usergroup['attachquota'] * 1024) {
            $friendlyquota = get_friendly_size($mybb->usergroup['attachquota'] * 1024);
            $ret['error'] = $lang->sprintf($lang->error_reachedattachquota, $friendlyquota);
            return $ret;
        }
    }
    // Gather forum permissions
    $forumpermissions = forum_permissions($forum['fid']);
    // Check if an attachment with this name is already in the post
    if ($pid != 0) {
        $uploaded_query = "pid='{$pid}'";
    } else {
        $uploaded_query = "posthash='{$posthash}'";
    }
    $query = $db->simple_select("attachments", "*", "filename='" . $db->escape_string($attachment['name']) . "' AND " . $uploaded_query);
    $prevattach = $db->fetch_array($query);
    if ($prevattach['aid'] && $update_attachment == false) {
        if (!$mybb->usergroup['caneditattachments'] && !$forumpermissions['caneditattachments']) {
            $ret['error'] = $lang->error_alreadyuploaded_perm;
            return $ret;
        }
        $ret['error'] = $lang->error_alreadyuploaded;
        return $ret;
    }
    // Check to see how many attachments exist for this post already
    if ($mybb->settings['maxattachments'] > 0 && $update_attachment == false) {
        $query = $db->simple_select("attachments", "COUNT(aid) AS numattachs", $uploaded_query);
        $attachcount = $db->fetch_field($query, "numattachs");
        if ($attachcount >= $mybb->settings['maxattachments']) {
            $ret['error'] = $lang->sprintf($lang->error_maxattachpost, $mybb->settings['maxattachments']);
            return $ret;
        }
    }
    $month_dir = '';
    if ($mybb->safemode == false) {
        // Check if the attachment directory (YYYYMM) exists, if not, create it
        $month_dir = gmdate("Ym");
        if (!@is_dir($mybb->settings['uploadspath'] . "/" . $month_dir)) {
            @mkdir($mybb->settings['uploadspath'] . "/" . $month_dir);
            // Still doesn't exist - oh well, throw it in the main directory
            if (!@is_dir($mybb->settings['uploadspath'] . "/" . $month_dir)) {
                $month_dir = '';
            }
        }
    }
    // All seems to be good, lets move the attachment!
    $filename = "post_" . $mybb->user['uid'] . "_" . TIME_NOW . "_" . md5(random_str()) . ".attach";
    $file = upload_file($attachment, $mybb->settings['uploadspath'] . "/" . $month_dir, $filename);
    // Failed to create the attachment in the monthly directory, just throw it in the main directory
    if (!empty($file['error']) && $month_dir) {
        $file = upload_file($attachment, $mybb->settings['uploadspath'] . '/', $filename);
    } elseif ($month_dir) {
        $filename = $month_dir . "/" . $filename;
    }
    if (!empty($file['error'])) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail;
        switch ($file['error']) {
            case 1:
                $ret['error'] .= $lang->error_uploadfailed_nothingtomove;
                break;
            case 2:
                $ret['error'] .= $lang->error_uploadfailed_movefailed;
                break;
        }
        return $ret;
    }
    // Lets just double check that it exists
    if (!file_exists($mybb->settings['uploadspath'] . "/" . $filename)) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail . $lang->error_uploadfailed_lost;
        return $ret;
    }
    // Generate the array for the insert_query
    $attacharray = array("pid" => $pid, "posthash" => $posthash, "uid" => $mybb->user['uid'], "filename" => $db->escape_string($file['original_filename']), "filetype" => $db->escape_string($file['type']), "filesize" => (int) $file['size'], "attachname" => $filename, "downloads" => 0, "dateuploaded" => TIME_NOW);
    // If we're uploading an image, check the MIME type compared to the image type and attempt to generate a thumbnail
    if ($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe") {
        // Check a list of known MIME types to establish what kind of image we're uploading
        switch (my_strtolower($file['type'])) {
            case "image/gif":
                $img_type = 1;
                break;
            case "image/jpeg":
            case "image/x-jpg":
            case "image/x-jpeg":
            case "image/pjpeg":
            case "image/jpg":
                $img_type = 2;
                break;
            case "image/png":
            case "image/x-png":
                $img_type = 3;
                break;
            default:
                $img_type = 0;
        }
        $supported_mimes = array();
        foreach ($attachtypes as $attachtype) {
            if (!empty($attachtype['mimetype'])) {
                $supported_mimes[] = $attachtype['mimetype'];
            }
        }
        // Check if the uploaded file type matches the correct image type (returned by getimagesize)
        $img_dimensions = @getimagesize($mybb->settings['uploadspath'] . "/" . $filename);
        $mime = "";
        $file_path = $mybb->settings['uploadspath'] . "/" . $filename;
        if (function_exists("finfo_open")) {
            $file_info = finfo_open(FILEINFO_MIME);
            list($mime, ) = explode(';', finfo_file($file_info, MYBB_ROOT . $file_path), 1);
            finfo_close($file_info);
        } else {
            if (function_exists("mime_content_type")) {
                $mime = mime_content_type(MYBB_ROOT . $file_path);
            }
        }
        if (!is_array($img_dimensions) || $img_dimensions[2] != $img_type && !in_array($mime, $supported_mimes)) {
            delete_uploaded_file($mybb->settings['uploadspath'] . "/" . $filename);
            $ret['error'] = $lang->error_uploadfailed;
            return $ret;
        }
        require_once MYBB_ROOT . "inc/functions_image.php";
        $thumbname = str_replace(".attach", "_thumb.{$ext}", $filename);
        $attacharray = $plugins->run_hooks("upload_attachment_thumb_start", $attacharray);
        $thumbnail = generate_thumbnail($mybb->settings['uploadspath'] . "/" . $filename, $mybb->settings['uploadspath'], $thumbname, $mybb->settings['attachthumbh'], $mybb->settings['attachthumbw']);
        if ($thumbnail['filename']) {
            $attacharray['thumbnail'] = $thumbnail['filename'];
        } elseif ($thumbnail['code'] == 4) {
            $attacharray['thumbnail'] = "SMALL";
        }
    }
    if ($forumpermissions['modattachments'] == 1 && !is_moderator($forum['fid'], "canapproveunapproveattachs")) {
        $attacharray['visible'] = 0;
    } else {
        $attacharray['visible'] = 1;
    }
    $attacharray = $plugins->run_hooks("upload_attachment_do_insert", $attacharray);
    if ($prevattach['aid'] && $update_attachment == true) {
        unset($attacharray['downloads']);
        // Keep our download count if we're updating an attachment
        $db->update_query("attachments", $attacharray, "aid='" . $db->escape_string($prevattach['aid']) . "'");
        // Remove old attachment file
        // Check if this attachment is referenced in any other posts. If it isn't, then we are safe to delete the actual file.
        $query = $db->simple_select("attachments", "COUNT(aid) as numreferences", "attachname='" . $db->escape_string($prevattach['attachname']) . "'");
        if ($db->fetch_field($query, "numreferences") == 0) {
            delete_uploaded_file($mybb->settings['uploadspath'] . "/" . $prevattach['attachname']);
            if ($prevattach['thumbnail']) {
                delete_uploaded_file($mybb->settings['uploadspath'] . "/" . $prevattach['thumbnail']);
            }
            $date_directory = explode('/', $prevattach['attachname']);
            if (@is_dir($mybb->settings['uploadspath'] . "/" . $date_directory[0])) {
                delete_upload_directory($mybb->settings['uploadspath'] . "/" . $date_directory[0]);
            }
        }
        $aid = $prevattach['aid'];
    } else {
        $aid = $db->insert_query("attachments", $attacharray);
        if ($pid) {
            update_thread_counters($tid, array("attachmentcount" => "+1"));
        }
    }
    $ret['aid'] = $aid;
    return $ret;
}
Beispiel #3
0
 } else {
     //the first song doesn't have art, go to the next and exhaust all options
     $artwork_scanner->flag_as_skipped($value['album_id']);
     continue;
 }
 if (!strpos($temp_filename, '.')) {
     //invalid file type encountered
     $current_album_id = $value['album_id'];
     $artwork_scanner->flag_as_skipped($value['album_id']);
     continue;
 }
 file_put_contents($temp_dir . '/' . $temp_filename, $temp_data);
 if (is_readable($temp_dir . '/' . $temp_filename)) {
     $original = generate_thumbnail($temp_dir, $temp_filename, 'x', 600, $value);
     $medium = generate_thumbnail($temp_dir, $temp_filename, 'x', 300, $value);
     $small = generate_thumbnail($temp_dir, $temp_filename, 'x', 110, $value);
     if (@mkdir($art_dir, 0777, true)) {
         //copy new art to the album art list
         copy($temp_dir . '/' . $original, $art_dir . '/' . 'large.jpg');
         copy($temp_dir . '/' . $medium, $art_dir . '/' . 'medium.jpg');
         copy($temp_dir . '/' . $small, $art_dir . '/' . 'small.jpg');
         unlink($temp_dir . '/' . $temp_filename);
         //don't scan further files in this album
         $current_album_id = $value['album_id'];
         //it's scanned now
         $artwork_scanner->flag_as_added($value['album_id']);
     } else {
         //if the dir's already there, chances are it has art
         $current_album_id = $value['album_id'];
         $artwork_scanner->flag_as_skipped($value['album_id']);
     }
Beispiel #4
0
function &xthreads_build_thumbnail($thumbdims, $aid, $fieldname, $filename, $path, $month_dir, $img_dimensions = null)
{
    if (empty($img_dimensions)) {
        //$img_dimensions = @getimagesize($path.$month_dir.$filename);
        $img_dimensions = @getimagesize($filename);
    }
    $update_thumbs = array('orig' => array('w' => $img_dimensions[0], 'h' => $img_dimensions[1], 'type' => $img_dimensions[2]));
    if (is_array($img_dimensions)) {
        $filterfunc = 'xthreads_imgthumb_' . $fieldname;
        foreach ($thumbdims as $dims => $complex) {
            $destname = basename(substr($filename, 0, -6) . $dims . '.thumb');
            if ($complex) {
                require_once MYBB_ROOT . 'inc/xthreads/xt_image.php';
                $img = new XTImageTransform();
                if ($img->_load($filename)) {
                    // run filter chain
                    $filterfunc($dims, $img);
                    // write out file & save
                    $img->_enableWrite = true;
                    $img->write($path . $month_dir . '/' . $destname);
                    $update_thumbs[$dims] = array('w' => $img->WIDTH, 'h' => $img->HEIGHT, 'type' => $img->typeGD, 'file' => $month_dir . $destname);
                } else {
                    // failed
                    $update_thumbs[$dims] = array('w' => 0, 'h' => 0, 'type' => 0, 'file' => '');
                }
            } else {
                $p = strpos($dims, 'x');
                if (!$p) {
                    continue;
                }
                $w = (int) substr($dims, 0, $p);
                $h = (int) substr($dims, $p + 1);
                if ($img_dimensions[0] > $w || $img_dimensions[1] > $h) {
                    // TODO: think about using own function to apply image convolution
                    require_once MYBB_ROOT . 'inc/functions_image.php';
                    $thumbnail = generate_thumbnail($filename, $path . $month_dir, $destname, $h, $w);
                    // if it fails, there's nothing much we can do... so twiddle thumbs is the solution
                    if ($thumbnail['code'] == 1) {
                        $newdims = scale_image($img_dimensions[0], $img_dimensions[1], $w, $h);
                        $update_thumbs[$dims] = array('w' => $newdims['width'], 'h' => $newdims['height'], 'type' => $img_dimensions[2], 'file' => $month_dir . $destname);
                    } else {
                        $update_thumbs[$dims] = array('w' => 0, 'h' => 0, 'type' => 0, 'file' => '');
                    }
                } else {
                    // image is small (hopefully), just copy it over
                    // TODO: maybe use hardlink instead?
                    @copy($filename, $path . $month_dir . $destname);
                    $update_thumbs[$dims] = array('w' => $img_dimensions[0], 'h' => $img_dimensions[1], 'type' => $img_dimensions[2], 'file' => $month_dir . $destname);
                }
            }
        }
    }
    global $db;
    $db->update_query('xtattachments', array('thumbs' => $db->escape_string(serialize($update_thumbs))), 'aid=' . $aid);
    return $update_thumbs;
}
Beispiel #5
0
                 addDebugLog($action . " type={$type} position={$position} ERROR 11: No write privileges for this record.");
                 print "ERROR 11: No write privileges for this record.\n";
             }
             break;
     }
     exit;
 case 'uploadmedia':
     $error = "";
     if (isset($_FILES['mediafile'])) {
         if (!move_uploaded_file($_FILES['mediafile']['tmp_name'], $MEDIA_DIRECTORY . $_FILES['mediafile']['name'])) {
             $error .= "ERROR 19: " . $pgv_lang["upload_error"] . " " . file_upload_error_text($_FILES['mediafile']['error']);
         } else {
             if (!isset($_FILES['thumbnail'])) {
                 $filename = $MEDIA_DIRECTORY . $_FILES['mediafile']['name'];
                 $thumbnail = $MEDIA_DIRECTORY . "thumbs/" . $_FILES['mediafile']['name'];
                 generate_thumbnail($filename, $thumbnail);
                 //if (!$thumbgenned) $error .= "ERROR 19: ".$pgv_lang["thumbgen_error"].$filename;
             }
         }
     }
     if (isset($_FILES['thumbnail'])) {
         if (!move_uploaded_file($_FILES['thumbnail']['tmp_name'], $MEDIA_DIRECTORY . "thumbs/" . $_FILES['thumbnail']['name'])) {
             $error .= "\nERROR 19: " . $pgv_lang["upload_error"] . " " . file_upload_error_text($_FILES['thumbnail']['error']);
         }
     }
     if (!empty($error)) {
         addDebugLog($action . " {$error}");
         print $error . "\n";
     } else {
         addDebugLog($action . " SUCCESS");
         print "SUCCESS\n";
Beispiel #6
0
function upgrade3_convertattachments()
{
    global $db, $output;
    $output->print_header("Konwersja załączników na pliki");
    if (!$_POST['attachmentspage']) {
        $app = 50;
    } else {
        $app = $_POST['attachmentspage'];
    }
    if ($_POST['attachmentstart']) {
        $startat = $_POST['attachmentstart'];
        $upper = $startat + $app;
        $lower = $startat;
    } else {
        $startat = 0;
        $upper = $app;
        $lower = 1;
    }
    require_once MYBB_ROOT . "inc/settings.php";
    $query = $db->simple_select("attachments", "COUNT(aid) AS attachcount");
    $cnt = $db->fetch_array($query);
    $contents .= "<p>Konwersja załączników z {$lower} do {$upper} (Łącznie: " . $cnt['attachcount'] . ")</p>";
    echo "<p>Konwersja załączników z {$lower} do {$upper} (Łącznie: " . $cnt['attachcount'] . ")</p>";
    if ($db->field_exists("uid", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP uid;");
    }
    // Add uid column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD uid smallint(6) NOT NULL AFTER posthash;");
    if ($db->field_exists("thumbnail", TABLE_PREFIX . "attachments")) {
        // Drop thumbnail column
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnail");
    }
    if ($db->field_exists("thumbnail", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnail;");
    }
    // Add thumbnail column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD thumbnail varchar(120) NOT NULL;");
    if ($db->field_exists("attachname", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP attachname;");
    }
    // Add attachname column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD attachname varchar(120) NOT NULL AFTER filesize;");
    if (!$db->field_exists("donecon", TABLE_PREFIX . "attachments")) {
        // Add temporary column
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD donecon smallint(1) NOT NULL;");
    }
    $query = $db->query("\n\t\tSELECT a.*, p.uid AS puid, p.dateline \n\t\tFROM " . TABLE_PREFIX . "attachments a \n\t\tLEFT JOIN " . TABLE_PREFIX . "posts p ON (p.pid=a.pid) \n\t\tWHERE a.donecon != '1'\n\t\tORDER BY a.aid ASC LIMIT {$app}\n\t");
    while ($attachment = $db->fetch_array($query)) {
        $filename = "post_" . $attachment['puid'] . "_" . $attachment['dateline'] . $attachment['aid'] . ".attach";
        $ext = my_strtolower(my_substr(strrchr($attachment['filename'], "."), 1));
        $fp = fopen("../uploads/" . $filename, "wb");
        if (!$fp) {
            die("Nie można utworzyć pliku. Sprawdź uprawnienia i odśwież stronę.");
        }
        fwrite($fp, $attachment['filedata']);
        fclose($fp);
        unset($attachment['filedata']);
        if ($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe") {
            require_once MYBB_ROOT . "inc/functions_image.php";
            $thumbname = str_replace(".attach", "_thumb.{$ext}", $filename);
            $thumbnail = generate_thumbnail("../uploads/" . $filename, "../uploads", $thumbname, $settings['attachthumbh'], $settings['attachthumbw']);
            if ($thumbnail['code'] == 4) {
                // Image was too small - fake a filename
                $thumbnail['filename'] = "SMALL";
            }
        }
        $db->write_query("UPDATE " . TABLE_PREFIX . "attachments SET attachname='" . $filename . "', donecon='1', uid='" . $attachment['puid'] . "', thumbnail='" . $thumbnail['filename'] . "' WHERE aid='" . $attachment['aid'] . "'");
        unset($thumbnail);
    }
    echo "<p>Zakończono.</p>";
    $query = $db->simple_select("attachments", "COUNT(aid) AS attachrem", "donecon != '1'");
    $cnt = $db->fetch_array($query);
    if ($cnt['attachrem'] != 0) {
        $nextact = "3_convertattachments";
        $startat = $startat + $app;
        $contents .= "<p><input type=\"hidden\" name=\"attachmentspage\" value=\"{$app}\" /><input type=\"hidden\" name=\"attachmentstart\" value=\"{$startat}\" />Done. Click Next to move on to the next set of attachments.</p>";
    } else {
        if ($db->field_exists("donecon", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP donecon");
        }
        if ($db->field_exists("filedata", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP filedata");
        }
        if ($db->field_exists("thumbnailsm", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnailsm");
        }
        $nextact = "3_convertavatars";
        $contents .= "<p>Zakończono</p><p>Wszystkie załączniki zostały zamienione na pliki. W następnym kroku tej operacji zostaną poddane awatary.</p>";
        $contents .= "<p>Jeżeli chcesz zmienić liczbę awatarów do przetworzenia na stronę, możesz to zrobić poniżej.</p>";
        $contents .= "<p><strong>Ilość wpisów na stronę:</strong> <input type=\"text\" size=\"3\" value=\"200\" name=\"userspage\" /></p>";
        $contents .= "<p>Aby rozpocząć proces konwersji, naciśnij dalej.</p>";
    }
    $output->print_contents($contents);
    $output->print_footer($nextact);
}
Beispiel #7
0
 $fileType = getFileType($fileName);
 if ($imageAtt = getimagesize($path . $attachment)) {
     $fileWidth = $imageAtt[0];
     $fileHeight = $imageAtt[1];
 } else {
     $fileWidth = 0;
     $fileHeight = 0;
 }
 // 判断是否为图片格式
 if ($fileType == 'gif' || $fileType == 'jpg' || $fileType == 'jpeg' || $fileType == 'png') {
     // 判断是否使用缩略图
     if ($settingInfo['genThumb'] == "1") {
         $tsize = explode('x', strtolower($settingInfo['thumbSize']));
         if ($fileWidth > $tsize[0] || $fileHeight > $tsize[1]) {
             $attach_thumb = array('filepath' => "../attachments/" . $value, 'filename' => $attachment, 'extension' => $fileType, 'thumbswidth' => $tsize[0], 'thumbsheight' => $tsize[1]);
             $thumb_data = generate_thumbnail($attach_thumb);
             $fileWidth = $thumb_data['thumbwidth'];
             $fileHeight = $thumb_data['thumbheight'];
             $thumbfile = $thumb_data['thumbfilepath'];
             $value = str_replace("../attachments/", "", $thumbfile);
         }
     }
 } else {
     $thumbfile = "";
 }
 //写进数据库
 $fileName = $attdesc == "" ? $fileName : encode($attdesc) . "." . $fileType;
 $rsexits = getFieldValue($DBPrefix . "attachments", "attTitle='" . $fileName . "' and fileType='" . $updateStyle . "' and fileSize='" . $fileSize . "' and logId='0'", "name");
 if ($rsexits == "") {
     $sql = "INSERT INTO " . $DBPrefix . "attachments(name,attTitle,fileType,fileSize,fileWidth,fileHeight,postTime,logId) VALUES ('{$value}','{$fileName}','{$updateStyle}','{$fileSize}','{$fileWidth}','{$fileHeight}','" . time() . "',0)";
     $DMC->query($sql);
Beispiel #8
0
         // the file cannot be copied
         $error .= $pgv_lang["upload_error"] . "<br />" . print_text('copy_error', 0, 1) . "<br />";
     } else {
         @chmod(filename_decode($whichFile2), PGV_PERM_FILE);
         AddToLog("Media file {$folderName}{$mediaFile} copied from {$thumbFolderName}{$mediaFile}");
     }
 }
 if ($error == "" && !empty($_FILES["mediafile"]["name"]) && empty($_FILES["thumbnail"]["name"])) {
     if (safe_POST('genthumb', 'yes', 'no') == 'yes') {
         // Generate thumbnail from main image
         $parts = pathinfo_utf($mediaFile);
         if (!empty($parts["extension"])) {
             $ext = strtolower($parts["extension"]);
             if (isImageTypeSupported($ext)) {
                 $thumbnail = $thumbFolderName . $mediaFile;
                 $okThumb = generate_thumbnail($folderName . $mediaFile, $thumbnail, "OVERWRITE");
                 if (!$okThumb) {
                     $error .= print_text("thumbgen_error", 0, 1);
                 } else {
                     print_text("thumb_genned");
                     print "<br />";
                     AddToLog("Media thumbnail {$thumbnail} generated");
                 }
             }
         }
     }
 }
 // Let's see if there are any errors generated and print it
 if (!empty($error)) {
     echo '<span class="error">', $error, "</span><br />\n";
     $mediaFile = "";
Beispiel #9
0
     echo "</td></tr>";
     foreach ($dirs as $indexval => $dir) {
         echo "<tr><td class=\"list_value {$TEXT_DIRECTION}\" colspan=\"2\">";
         echo "<a href=\"", encode_url("find.php?directory={$directory}{$dir}/&thumbdir={$directory}{$dir}/&level=" . ($level + 1) . "{$thumbget}&type=media&choose={$choose}"), "\"><span dir=\"ltr\">", $dir, "</span></a>";
         echo "</td></tr>";
     }
 }
 echo "<tr><td class=\"descriptionbox {$TEXT_DIRECTION}\" colspan=\"2\"></td></tr>";
 /**
  * This action generates a thumbnail for the file
  *
  * @name $create->thumbnail
  */
 if ($create == "thumbnail") {
     $filename = $_REQUEST["file"];
     generate_thumbnail($directory . $filename, $thumbdir . $filename);
 }
 echo "<br />";
 // display the images TODO x across if lots of files??
 if (count($medialist) > 0) {
     foreach ($medialist as $indexval => $media) {
         // Check if the media belongs to the current folder
         preg_match_all("/\\//", $media["FILE"], $hits);
         $ct = count($hits[0]);
         if ($ct <= $level + 1 && $external_links != "http" && !isFileExternal($media["FILE"]) || isFileExternal($media["FILE"]) && $external_links == "http") {
             // simple filter to reduce the number of items to view
             $isvalid = filterMedia($media, $filter, 'http');
             if ($isvalid && $chooseType != "all") {
                 if ($chooseType == "0file" && !empty($media["XREF"])) {
                     $isvalid = false;
                 }
Beispiel #10
0
function insert_thumbnail_content($recid, $url)
{
    if (defined('DT_THUMBNAIL')) {
        $res = generate_thumbnail($url, false);
        if (!array_key_exists("error", $res)) {
            mysql_query('insert into recDetails (dtl_RecID, dtl_DetailTypeID, dtl_UploadedFileID) values (' . $recid . ',' . DT_THUMBNAIL . ',' . $res['file']['id'] . ')');
        }
    }
}
Beispiel #11
0
// travesal protection
if (!filepath_is_safe(GSDATAUPLOADPATH . $sub_path . $file, GSDATAUPLOADPATH, true, true)) {
    die('invalid image');
}
// Debugging Request
// returns the imagemanipulation object json encoded,
// add base64 encoded image data ['data']
// add filesize ['bytes']
// add url to image if it was saved ['url']
if (isset($_REQUEST['debug']) || isset($_REQUEST['json'])) {
    ob_start();
    // $outfile = null;
}
// @todo: if needing to save as attachement from post, might need this else second request might be made with post data missing
// header('Content-Disposition: Attachment;filename='.$outfile);
$image = generate_thumbnail($file, $sub_path, $outfile, $max_x, $max_y, $crop, $image_quality, $show = true, $image_type);
if (isset($_REQUEST['debug']) || isset($_REQUEST['json'])) {
    $output = ob_get_contents();
    // get the image as a string in a variable
    ob_end_clean();
    //Turn off output buffering and clean it
    header("Content-Type: text/json");
    // add filesize and base64 encoded image
    $image->image['bytes'] = strlen($output);
    // size in bytes
    $image->imagedata = base64_encode($output);
    // remove resources and filepaths
    unset($image->image['src']);
    unset($image->image['des']);
    unset($image->image['srcfile']);
    unset($image->image['outfile']);
Beispiel #12
0
function get_uploaded_image($var = 'product_image', $width = 0, $height = 0)
{
    // Check
    if (!isset($_FILES[$var])) {
        return false;
    }
    if (!isset($_FILES[$var]['tmp_name'])) {
        return false;
    }
    if (!is_uploaded_file($_FILES[$var]['tmp_name'])) {
        return false;
    }
    // Get tmp file
    $tmpfile = tempnam(sys_get_temp_dir(), 'pi');
    // Strip exif
    if ($_FILES[$var]['type'] == 'image/gif') {
        $image = imagecreatefromgif($_FILES[$var]['tmp_name']);
        imagegif($image, $tmpfile);
    } elseif ($_FILES[$var]['type'] == 'image/png') {
        $image = imagecreatefrompng($_FILES[$var]['tmp_name']);
        imagepng($image, $tmpfile, 100);
    } elseif ($_FILES[$var]['type'] == 'image/jpg') {
        $image = imagecreatefromjpeg($_FILES[$var]['tmp_name']);
        imagejpeg($image, $tmpfile, 100);
    } else {
        return file_get_contents($_FILES[$var]['tmp_name']);
    }
    // Resize, if needed
    if ($width > 0 && $height > 0) {
        $contents = generate_thumbnail($tmpfile, $width, $height);
    } else {
        $contents = file_get_contents($tmpfile);
    }
    // Return
    @unlink($tmpfile);
    return $contents;
}
/**
 * Upload an attachment in to the file system
 *
 * @param array Attachment data (as fed by PHPs $_FILE)
 * @return array Array of attachment data if successful, otherwise array of error data
 */
function upload_attachment($attachment)
{
    global $db, $theme, $templates, $posthash, $pid, $tid, $forum, $mybb, $lang, $plugins, $cache;
    $posthash = $db->escape_string($mybb->input['posthash']);
    if (isset($attachment['error']) && $attachment['error'] != 0) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail;
        switch ($attachment['error']) {
            case 1:
                // UPLOAD_ERR_INI_SIZE
                $ret['error'] .= $lang->error_uploadfailed_php1;
                break;
            case 2:
                // UPLOAD_ERR_FORM_SIZE
                $ret['error'] .= $lang->error_uploadfailed_php2;
                break;
            case 3:
                // UPLOAD_ERR_PARTIAL
                $ret['error'] .= $lang->error_uploadfailed_php3;
                break;
            case 4:
                // UPLOAD_ERR_NO_FILE
                $ret['error'] .= $lang->error_uploadfailed_php4;
                break;
            case 6:
                // UPLOAD_ERR_NO_TMP_DIR
                $ret['error'] .= $lang->error_uploadfailed_php6;
                break;
            case 7:
                // UPLOAD_ERR_CANT_WRITE
                $ret['error'] .= $lang->error_uploadfailed_php7;
                break;
            default:
                $ret['error'] .= $lang->sprintf($lang->error_uploadfailed_phpx, $attachment['error']);
                break;
        }
        return $ret;
    }
    if (!is_uploaded_file($attachment['tmp_name']) || empty($attachment['tmp_name'])) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_php4;
        return $ret;
    }
    $ext = get_extension($attachment['name']);
    // Check if we have a valid extension
    $query = $db->simple_select("attachtypes", "*", "extension='" . $db->escape_string($ext) . "'");
    $attachtype = $db->fetch_array($query);
    if (!$attachtype['atid']) {
        $ret['error'] = $lang->error_attachtype;
        return $ret;
    }
    // Check the size
    if ($attachment['size'] > $attachtype['maxsize'] * 1024 && $attachtype['maxsize'] != "") {
        $ret['error'] = $lang->sprintf($lang->error_attachsize, $attachtype['maxsize']);
        return $ret;
    }
    // Double check attachment space usage
    if ($mybb->usergroup['attachquota'] > 0) {
        $query = $db->simple_select("attachments", "SUM(filesize) AS ausage", "uid='" . $mybb->user['uid'] . "'");
        $usage = $db->fetch_array($query);
        $usage = $usage['ausage'] + $attachment['size'];
        if ($usage > $mybb->usergroup['attachquota'] * 1024) {
            $friendlyquota = get_friendly_size($mybb->usergroup['attachquota'] * 1024);
            $ret['error'] = $lang->sprintf($lang->error_reachedattachquota, $friendlyquota);
            return $ret;
        }
    }
    // Check if an attachment with this name is already in the post
    $query = $db->simple_select("attachments", "*", "filename='" . $db->escape_string($attachment['name']) . "' AND (posthash='{$posthash}' OR (pid='" . intval($pid) . "' AND pid!='0'))");
    $prevattach = $db->fetch_array($query);
    if ($prevattach['aid']) {
        $ret['error'] = $lang->error_alreadyuploaded;
        return $ret;
    }
    // Check if the attachment directory (YYYYMM) exists, if not, create it
    $month_dir = gmdate("Ym");
    if (!@is_dir($mybb->settings['uploadspath'] . "/" . $month_dir)) {
        @mkdir($mybb->settings['uploadspath'] . "/" . $month_dir);
        // Still doesn't exist - oh well, throw it in the main directory
        if (!@is_dir($mybb->settings['uploadspath'] . "/" . $month_dir)) {
            $month_dir = '';
        }
    }
    // If safe_mode is enabled, don't attempt to use the monthly directories as it won't work
    if (ini_get('safe_mode') == 1 || strtolower(ini_get('safe_mode')) == 'on') {
        $month_dir = '';
    }
    // All seems to be good, lets move the attachment!
    $filename = "post_" . $mybb->user['uid'] . "_" . TIME_NOW . "_" . md5(random_str()) . ".attach";
    $file = upload_file($attachment, $mybb->settings['uploadspath'] . "/" . $month_dir, $filename);
    // Failed to create the attachment in the monthly directory, just throw it in the main directory
    if ($file['error'] && $month_dir) {
        $file = upload_file($attachment, $mybb->settings['uploadspath'] . '/', $filename);
    }
    if ($month_dir) {
        $filename = $month_dir . "/" . $filename;
    }
    if ($file['error']) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail;
        switch ($file['error']) {
            case 1:
                $ret['error'] .= $lang->error_uploadfailed_nothingtomove;
                break;
            case 2:
                $ret['error'] .= $lang->error_uploadfailed_movefailed;
                break;
        }
        return $ret;
    }
    // Lets just double check that it exists
    if (!file_exists($mybb->settings['uploadspath'] . "/" . $filename)) {
        $ret['error'] = $lang->error_uploadfailed . $lang->error_uploadfailed_detail . $lang->error_uploadfailed_lost;
        return $ret;
    }
    // Generate the array for the insert_query
    $attacharray = array("pid" => intval($pid), "posthash" => $posthash, "uid" => $mybb->user['uid'], "filename" => $db->escape_string($file['original_filename']), "filetype" => $db->escape_string($file['type']), "filesize" => intval($file['size']), "attachname" => $filename, "downloads" => 0, "dateuploaded" => TIME_NOW);
    // If we're uploading an image, check the MIME type compared to the image type and attempt to generate a thumbnail
    if ($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe") {
        // Check a list of known MIME types to establish what kind of image we're uploading
        switch (my_strtolower($file['type'])) {
            case "image/gif":
                $img_type = 1;
                break;
            case "image/jpeg":
            case "image/x-jpg":
            case "image/x-jpeg":
            case "image/pjpeg":
            case "image/jpg":
                $img_type = 2;
                break;
            case "image/png":
            case "image/x-png":
                $img_type = 3;
                break;
            default:
                $img_type = 0;
        }
        $supported_mimes = array();
        $attachtypes = $cache->read("attachtypes");
        foreach ($attachtypes as $attachtype) {
            if (!empty($attachtype['mimetype'])) {
                $supported_mimes[] = $attachtype['mimetype'];
            }
        }
        // Check if the uploaded file type matches the correct image type (returned by getimagesize)
        $img_dimensions = @getimagesize($mybb->settings['uploadspath'] . "/" . $filename);
        if (!is_array($img_dimensions) || $img_dimensions[2] != $img_type && !in_array(mime_content_type($filename), $supported_mimes)) {
            @unlink($mybb->settings['uploadspath'] . "/" . $filename);
            $ret['error'] = $lang->error_uploadfailed;
            return $ret;
        }
        require_once MYBB_ROOT . "inc/functions_image.php";
        $thumbname = str_replace(".attach", "_thumb.{$ext}", $filename);
        $thumbnail = generate_thumbnail($mybb->settings['uploadspath'] . "/" . $filename, $mybb->settings['uploadspath'], $thumbname, $mybb->settings['attachthumbh'], $mybb->settings['attachthumbw']);
        if ($thumbnail['filename']) {
            $attacharray['thumbnail'] = $thumbnail['filename'];
        } elseif ($thumbnail['code'] == 4) {
            $attacharray['thumbnail'] = "SMALL";
        }
    }
    if ($forum['modattachments'] == 1 && !is_moderator($forum['fid'], "", $mybb->user['uid'])) {
        $attacharray['visible'] = 0;
    } else {
        $attacharray['visible'] = 1;
    }
    $plugins->run_hooks_by_ref("upload_attachment_do_insert", $attacharray);
    $aid = $db->insert_query("attachments", $attacharray);
    if ($tid) {
        update_thread_counters($tid, array("attachmentcount" => "+1"));
    }
    $ret['aid'] = $aid;
    return $ret;
}
Beispiel #14
0
function EditPicture2()
{
    global $mybb, $lang, $db, $gallerySettings, $gd2, $plugins;
    $id = intval($_REQUEST['id']);
    if (empty($id)) {
        fatal_error2($lang->gallery_error_no_pic_selected);
    }
    // Verify incoming POST request
    verify_post_check($mybb->get_input('my_post_key'));
    // Check the user permissions
    $dbresult = $db->query("\n    SELECT \n    \tID_MEMBER,thumbfilename,filename \n    FROM " . TABLE_PREFIX . "gallery_pic \n    WHERE ID_PICTURE = {$id} LIMIT 1");
    $row = $db->fetch_array($dbresult);
    $memID = $row['ID_MEMBER'];
    $oldfilename = $row['filename'];
    $oldthumbfilename = $row['thumbfilename'];
    if (allowedTo('manage') || allowedTo('edit') && $mybb->user['uid'] == $memID) {
        if (!is_writable($gallerySettings['gallery_path'])) {
            fatal_error2($lang->gallery_write_error . $gallerySettings['gallery_path']);
        }
        $title = htmlspecialchars_uni($_REQUEST['title']);
        $description = htmlspecialchars_uni($_REQUEST['description']);
        $keywords = htmlspecialchars_uni($_REQUEST['keywords']);
        $cat = intval($_REQUEST['cat']);
        @($allowcomments = $_REQUEST['allowcomments']);
        //Check if pictures are auto approved
        $approved = allowedTo('autoapprove') ? 1 : 0;
        //Allow comments on picture if no setting set.
        if (empty($gallerySettings['gallery_commentchoice']) || $gallerySettings['gallery_commentchoice'] == 0) {
            $allowcomments = 1;
        } else {
            if (empty($allowcomments)) {
                $allowcomments = 0;
            } else {
                $allowcomments = 1;
            }
        }
        if (trim($title) == '') {
            fatal_error2($lang->gallery_error_no_title, false);
        }
        if (empty($cat)) {
            fatal_error2($lang->gallery_error_no_cat, false);
        }
        CheckGalleryCategoryExists($cat);
        $testGD = get_extension_funcs('gd');
        $gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
        unset($testGD);
        require_once MYBB_ROOT . "inc/functions_image.php";
        //Process Uploaded file
        if (isset($_FILES['picture']['name']) && $_FILES['picture']['name'] != '') {
            $sizes = getimagesize($_FILES['picture']['tmp_name']);
            $failed = false;
            if ($sizes === false) {
                @unlink($gallerySettings['gallery_path'] . '/img.tmp');
                move_uploaded_file($_FILES['picture']['tmp_name'], $gallerySettings['gallery_path'] . '/img.tmp');
                $_FILES['picture']['tmp_name'] = $gallerySettings['gallery_path'] . '/img.tmp';
                $sizes = getimagesize($_FILES['picture']['tmp_name']);
                $failed = true;
            }
            // No size, then it's probably not a valid pic.
            if ($sizes === false) {
                fatal_error2($lang->gallery_error_invalid_picture, false);
            } elseif (!empty($gallerySettings['gallery_max_width']) && $sizes[0] > $gallerySettings['gallery_max_width'] || !empty($gallerySettings['gallery_max_height']) && $sizes[1] > $gallerySettings['gallery_max_height']) {
                fatal_error2($lang->gallery_error_img_size_height . $sizes[1] . $lang->gallery_error_img_size_width . $sizes[0], false);
            } else {
                //Get the filesize
                $filesize = $_FILES['picture']['size'];
                if (!empty($gallerySettings['gallery_max_filesize']) && $filesize > $gallerySettings['gallery_max_filesize']) {
                    //Delete the temp file
                    @unlink($_FILES['picture']['tmp_name']);
                    fatal_error2($lang->gallery_error_img_filesize . gallery_format_size($gallerySettings['gallery_max_filesize'], 2), false);
                }
                //Delete the old files
                @unlink($gallerySettings['gallery_path'] . $oldfilename);
                @unlink($gallerySettings['gallery_path'] . $oldthumbfilename);
                //Filename Member Id + Day + Month + Year + 24 hour, Minute Seconds
                $extensions = array(1 => 'gif', 2 => 'jpeg', 3 => 'png', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpeg', 14 => 'iff');
                $extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : '.bmp';
                $filename = $mybb->user['uid'] . '_' . date('d_m_y_g_i_s') . '.' . $extension;
                if ($failed == false) {
                    move_uploaded_file($_FILES['picture']['tmp_name'], $gallerySettings['gallery_path'] . $filename);
                } else {
                    rename($_FILES['picture']['tmp_name'], $gallerySettings['gallery_path'] . $filename);
                }
                @chmod($gallerySettings['gallery_path'] . $filename, 0644);
                //Create thumbnail
                $tmp = generate_thumbnail($gallerySettings['gallery_path'] . $filename, substr($gallerySettings['gallery_path'], 0, -1), 'thumb_' . $filename, $gallerySettings['gallery_set_thumb_height'], $gallerySettings['gallery_set_thumb_width']);
                $thumbname = 'thumb_' . $filename;
                if ($tmp['code'] == '4') {
                    copy($gallerySettings['gallery_path'] . $filename, $gallerySettings['gallery_path'] . $thumbname);
                    @chmod($gallerySettings['gallery_path'] . $thumbname, 0644);
                }
                //Update the Database entry
                $t = time();
                $db->query("UPDATE " . TABLE_PREFIX . "gallery_pic\n\t\t\t\t\tSET ID_CAT = {$cat}, filesize = {$filesize}, filename = '{$filename}',  thumbfilename = '{$thumbname}', height = {$sizes['1']}, width = {$sizes['0']}, approved = {$approved}, date =  {$t}, title = '{$title}', description = '{$description}', keywords = '{$keywords}', allowcomments = {$allowcomments} WHERE ID_PICTURE = {$id} LIMIT 1");
                $plugins->run_hooks("gallery_edit_picture_completed");
                //Redirect to the users image page.
                redirect('ezgallery.php?action=myimages&u=' . $mybb->user['uid']);
            }
        } else {
            // Update the image properties if no upload has been set
            $db->query("UPDATE " . TABLE_PREFIX . "gallery_pic\n\t\t\t\tSET ID_CAT = {$cat}, title = '{$title}', description = '{$description}', keywords = '{$keywords}', allowcomments = {$allowcomments} WHERE ID_PICTURE = {$id} LIMIT 1");
            // Redirect to the users image page.
            redirect('ezgallery.php?action=myimages&u=' . $mybb->user['uid']);
        }
    } else {
        fatal_error2($lang->gallery_error_noedit_permission);
    }
}
		$val = base64_encode($text);
		header("Location: ".HEURIST_BASE_URL."/#data=" . $val);
		return "";
	}
	ob_start("outputAsRedirect");

	if ($_POST["heurist-sessionid"] != $_COOKIE["heurist-sessionid"]) {	// saw TODO: check that this is ok or should this be the database session?
		// saveFile is only available through dispatcher.php, or if heurist-sessionid is known (presumably only our scripts will know this)
		getError("unauthorised HAPI user");
	}
}
*/
if (@$_REQUEST['url']) {
    $sURL = $_REQUEST['url'];
    //url to be thumbnailed
    $res = generate_thumbnail($sURL, true);
    print json_format($res);
    exit;
}
//
// main function
//
function generate_thumbnail($sURL, $needConnect)
{
    if (!is_logged_in()) {
        return getError("no logged-in user");
    }
    $res = array();
    //get picture from service
    //"http://www.sitepoint.com/forums/image.php?u=106816&dateline=1312480118";
    $remote_path = str_replace("[URL]", $sURL, WEBSITE_THUMBNAIL_SERVICE);
/**
 * Rebuild thumbnails for attachments
 */
function acp_rebuild_attachment_thumbnails()
{
    global $db, $mybb, $lang;
    $query = $db->simple_select("attachments", "COUNT(aid) as num_attachments");
    $num_attachments = $db->fetch_field($query, 'num_attachments');
    $page = $mybb->get_input('page', MyBB::INPUT_INT);
    $per_page = $mybb->get_input('attachmentthumbs', MyBB::INPUT_INT);
    if ($per_page <= 0) {
        $per_page = 20;
    }
    $start = ($page - 1) * $per_page;
    $end = $start + $per_page;
    require_once MYBB_ROOT . "inc/functions_image.php";
    $query = $db->simple_select("attachments", "*", '', array('order_by' => 'aid', 'order_dir' => 'asc', 'limit_start' => $start, 'limit' => $per_page));
    while ($attachment = $db->fetch_array($query)) {
        $ext = my_strtolower(my_substr(strrchr($attachment['filename'], "."), 1));
        if ($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe") {
            $thumbname = str_replace(".attach", "_thumb.{$ext}", $attachment['attachname']);
            $thumbnail = generate_thumbnail(MYBB_ROOT . "uploads/" . $attachment['attachname'], MYBB_ROOT . "uploads/", $thumbname, $mybb->settings['attachthumbh'], $mybb->settings['attachthumbw']);
            if ($thumbnail['code'] == 4) {
                $thumbnail['filename'] = "SMALL";
            }
            $db->update_query("attachments", array("thumbnail" => $thumbnail['filename']), "aid='{$attachment['aid']}'");
        }
    }
    check_proceed($num_attachments, $end, ++$page, $per_page, "attachmentthumbs", "do_rebuildattachmentthumbs", $lang->success_rebuilt_attachment_thumbnails);
}
Beispiel #17
0
function upgrade3_convertattachments()
{
    global $db, $output;
    $output->print_header("Attachment Conversion to Files");
    if (!$_POST['attachmentspage']) {
        $app = 50;
    } else {
        $app = (int) $_POST['attachmentspage'];
    }
    if ($_POST['attachmentstart']) {
        $startat = (int) $_POST['attachmentstart'];
        $upper = $startat + $app;
        $lower = $startat;
    } else {
        $startat = 0;
        $upper = $app;
        $lower = 1;
    }
    require_once MYBB_ROOT . "inc/settings.php";
    $query = $db->simple_select("attachments", "COUNT(aid) AS attachcount");
    $cnt = $db->fetch_array($query);
    $contents .= "<p>Converting attachments {$lower} to {$upper} (" . $cnt['attachcount'] . " Total)</p>";
    echo "<p>Converting attachments {$lower} to {$upper} (" . $cnt['attachcount'] . " Total)</p>";
    if ($db->field_exists("uid", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP uid;");
    }
    // Add uid column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD uid smallint(6) NOT NULL AFTER posthash;");
    if ($db->field_exists("thumbnail", TABLE_PREFIX . "attachments")) {
        // Drop thumbnail column
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnail");
    }
    if ($db->field_exists("thumbnail", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnail;");
    }
    // Add thumbnail column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD thumbnail varchar(120) NOT NULL;");
    if ($db->field_exists("attachname", TABLE_PREFIX . "attachments")) {
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP attachname;");
    }
    // Add attachname column
    $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD attachname varchar(120) NOT NULL AFTER filesize;");
    if (!$db->field_exists("donecon", TABLE_PREFIX . "attachments")) {
        // Add temporary column
        $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments ADD donecon smallint(1) NOT NULL;");
    }
    $query = $db->query("\n\t\tSELECT a.*, p.uid AS puid, p.dateline \n\t\tFROM " . TABLE_PREFIX . "attachments a \n\t\tLEFT JOIN " . TABLE_PREFIX . "posts p ON (p.pid=a.pid) \n\t\tWHERE a.donecon != '1'\n\t\tORDER BY a.aid ASC LIMIT {$app}\n\t");
    while ($attachment = $db->fetch_array($query)) {
        $filename = "post_" . $attachment['puid'] . "_" . $attachment['dateline'] . $attachment['aid'] . ".attach";
        $ext = my_strtolower(my_substr(strrchr($attachment['filename'], "."), 1));
        $fp = fopen("../uploads/" . $filename, "wb");
        if (!$fp) {
            die("Unable to create file. Please check permissions and refresh page.");
        }
        fwrite($fp, $attachment['filedata']);
        fclose($fp);
        unset($attachment['filedata']);
        if ($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe") {
            require_once MYBB_ROOT . "inc/functions_image.php";
            $thumbname = str_replace(".attach", "_thumb.{$ext}", $filename);
            $thumbnail = generate_thumbnail("../uploads/" . $filename, "../uploads", $thumbname, $settings['attachthumbh'], $settings['attachthumbw']);
            if ($thumbnail['code'] == 4) {
                // Image was too small - fake a filename
                $thumbnail['filename'] = "SMALL";
            }
        }
        $db->write_query("UPDATE " . TABLE_PREFIX . "attachments SET attachname='" . $filename . "', donecon='1', uid='" . $attachment['puid'] . "', thumbnail='" . $thumbnail['filename'] . "' WHERE aid='" . $attachment['aid'] . "'");
        unset($thumbnail);
    }
    echo "<p>Done.</p>";
    $query = $db->simple_select("attachments", "COUNT(aid) AS attachrem", "donecon != '1'");
    $cnt = $db->fetch_array($query);
    if ($cnt['attachrem'] != 0) {
        $nextact = "3_convertattachments";
        $startat = $startat + $app;
        $contents .= "<p><input type=\"hidden\" name=\"attachmentspage\" value=\"{$app}\" /><input type=\"hidden\" name=\"attachmentstart\" value=\"{$startat}\" />Done. Click Next to move on to the next set of attachments.</p>";
    } else {
        if ($db->field_exists("donecon", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP donecon");
        }
        if ($db->field_exists("filedata", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP filedata");
        }
        if ($db->field_exists("thumbnailsm", TABLE_PREFIX . "attachments")) {
            $db->write_query("ALTER TABLE " . TABLE_PREFIX . "attachments DROP thumbnailsm");
        }
        $nextact = "3_convertavatars";
        $contents .= "<p>Done</p><p>All attachments have been moved to the file system. The next step is converting avatars to the file system.</p>";
        $contents .= "<p>If you wish to change the number of uploaded avatars to process per page then you can do so below.</p>";
        $contents .= "<p><strong>Avatars Per Page:</strong> <input type=\"text\" size=\"3\" value=\"200\" name=\"userspage\" /></p>";
        $contents .= "<p>Once you're ready, press next to begin the conversion.</p>";
    }
    $output->print_contents($contents);
    $output->print_footer($nextact);
}
/**
 * Generate standard thumbnails
 * @param  string $path path to image
 * @param  string $name file name
 * @uses   GD
 */
function genStdThumb($subpath, $file)
{
    // set thumbnail width from GSIMAGEWIDTH
    if (!getDef('GSIMAGEWIDTH')) {
        $width = 200;
        //New width of image
    } else {
        $width = getDef('GSIMAGEWIDTH');
    }
    generate_thumbnail($file, $subpath, 'thumbnail.' . $file, $width);
}
Beispiel #19
0
                  *	------------------
                  */
                 load("image");
                 generate_thumbnail($target, $mime);
             }
         } else {
             $smarty->assign("upload_error", $upload_error);
         }
     }
     break;
 case "regenerate_thumbs":
     load("image");
     $images = $db->fetch_array("SELECT *\n\t\t\t\t\t\t\t\t\t\tFROM attachment_list\n\t\t\t\t\t\t\t\t\t\tWHERE attachment_type\n\t\t\t\t\t\t\t\t\t\tLIKE '%image%'\n\t\t\t\t\t\t\t\t\t\tORDER BY attachment_date");
     foreach ($images as $image) {
         $target = $config['uploader']['upload_dir'] . $image['attachment_file'];
         generate_thumbnail($target, $image['attachment_type']);
     }
     redirect("./?file", 3);
     break;
 case "delete":
     if (isset($_POST['submit']) && isset($_POST['id'])) {
         $file_query = $db->query("SELECT * FROM attachment_list WHERE attachment_id = " . $_POST['id']);
         if ($db->num_rows($file_query) == 1) {
             $file_info = $db->fetch_array($file_query);
             $target = $config['uploader']['upload_dir'] . $file_info[0]['attachment_file'];
             $query = "DELETE FROM attachment_list WHERE attachment_id = " . $_POST['id'];
             if ($db->query($query) && @unlink($target)) {
                 if (file_exists($target . "_thumb")) {
                     if (@unlink($target . "_thumb")) {
                         $success = true;
                     }
/**
 * Smarty {html_image} function plugin
 * 
 * Type:     function<br>
 * Name:     html_image<br>
 * Date:     Feb 24, 2003<br>
 * Purpose:  format HTML tags for the image<br>
 * Examples: {html_image file="/images/masthead.gif"}
 * Output:   <img src="/images/masthead.gif" width=400 height=23>
 * 
 * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
 *      (Smarty online manual)
 * @author Monte Ohrt <monte at ohrt dot com> 
 * @author credits to Duda <*****@*****.**> 
 * @version 1.0
 * @param array $params parameters
 * Input:<br>
 *          - file = file (and path) of image (required)
 *          - height = image height (optional, default actual height)
 *          - width = image width (optional, default actual width)
 *          - basedir = base directory for absolute paths, default
 *                      is environment variable DOCUMENT_ROOT
 *          - path_prefix = prefix for path output (optional, default empty)
 * @param object $template template object
 * @return string 
 * @uses smarty_function_escape_special_chars()
 */
function smarty_function_html_image($params, $template)
{
    global $config;
    require_once SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php';
    $alt = '';
    $file = '';
    $border = 0;
    $height = '';
    $width = '';
    $extra = '';
    $prefix = '';
    $suffix = '';
    $path_prefix = '';
    $server_vars = $_SERVER;
    $basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : '';
    foreach ($params as $_key => $_val) {
        switch ($_key) {
            case 'file':
            case 'height':
            case 'width':
            case 'dpi':
            case 'path_prefix':
            case 'basedir':
                //!! cpuidle@gmx.de
            //!! cpuidle@gmx.de
            case 'border':
            case 'max_width':
            case 'max_height':
                ${$_key} = $_val;
                break;
            case 'alt':
                if (!is_array($_val)) {
                    ${$_key} = smarty_function_escape_special_chars($_val);
                } else {
                    throw new SmartyException("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
                }
                break;
            case 'link':
            case 'href':
                // cpuidle@gmx.de suppress hrefs without link
                if (!empty($_val)) {
                    $prefix = '<a href="' . $_val . '">';
                    $suffix = '</a>';
                }
                break;
            default:
                if (!is_array($_val)) {
                    $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
                } else {
                    throw new SmartyException("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
                }
                break;
        }
    }
    if (empty($file)) {
        trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
        return;
    }
    if (substr($file, 0, 1) == '/') {
        $_image_path = $basedir . $file;
    } else {
        $_image_path = $file;
    }
    #dlog("\nimg: $_image_path");
    if (!isset($params['width']) || !isset($params['height'])) {
        // cpuidle@gmx.de check for non-local images
        if (preg_match("/nocover|^(http:|img\\.php)/", $_image_path)) {
            $no_scaling = true;
            #dlog("no scaling");
        } else {
            // do we already know this image?
            $cache_tag = md5($_image_path);
            // are we creating thumbnails and can we get the thumbnail from cache?
            if (!(THUMB_CACHE_SOURCE && html_image_get_cache($cache_tag, $width, $height))) {
                if ($_image_data = @getimagesize($_image_path)) {
                    if (!isset($params['width'])) {
                        $width = $_image_data[0];
                    }
                    if (!isset($params['height'])) {
                        $height = $_image_data[1];
                    }
                    if (THUMB_CACHE_SOURCE) {
                        html_image_put_cache($cache_tag, $width . 'x' . $height);
                    }
                    #dlog("cache commit: $width $height");
                } else {
                    #dlog("image error: $_image_path");
                    // TODO check how to handle non-existing images
                    if (!file_exists($_image_path)) {
                        trigger_error("html_image: unable to find '{$_image_path}'", E_USER_NOTICE);
                        return;
                    } else {
                        if (!is_readable($_image_path)) {
                            trigger_error("html_image: unable to read '{$_image_path}'", E_USER_NOTICE);
                            return;
                        } else {
                            trigger_error("html_image: '{$_image_path}' is not a valid image file", E_USER_NOTICE);
                            return;
                        }
                    }
                }
                if (isset($template->security_policy)) {
                    if (!$template->security_policy->isTrustedResourceDir($_image_path)) {
                        return;
                    }
                }
            }
        }
        if (empty($width)) {
            $width = $max_width;
        }
        if (empty($height)) {
            $height = $max_height;
        }
        /*
         * Scaling is required if:
         * - scale mode TUMB_SCALE
         * - scale mode TUMB_REDUCE_ONLY and dimensions > target dimensions
         * - scale mode is any other numeric and filesize > scale mode
         */
        if ($max_width && $max_height && !$no_scaling) {
            // even if thumbnails are not generated we should get aspect ratio right
            if ($config['thumbnail_level'] == TUMB_NO_SCALE) {
                $scale = min($max_width / $width, $max_height / $height);
                $width = round($width * $scale);
                $height = round($height * $scale);
            } else {
                generate_thumbnail($file, $width, $height, $max_width, $max_height, $cache_tag);
            }
        }
    }
    if (isset($params['dpi'])) {
        if (strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) {
            $dpi_default = 72;
        } else {
            $dpi_default = 96;
        }
        $_resize = $dpi_default / $params['dpi'];
        $width = round($width * $_resize);
        $height = round($height * $_resize);
    }
    $result = $prefix . '<img src="' . $file . '" alt="' . $alt;
    if (isset($border)) {
        $result .= '" border="' . $border;
    }
    if ($width) {
        $result .= '" width="' . $width;
    }
    if ($height) {
        $result .= '" height="' . $height;
    }
    $result .= '"' . $extra . ' />' . $suffix;
    return $result;
}
 /**
  * Create and display a thumbnail of an uploaded file.
  */
 public function utilityController_mediaThumbnail_create($sender, $media_id)
 {
     // When it makes it into core, it will be available in
     // functions.general.php
     require 'generate_thumbnail.php';
     $model = new Gdn_Model('Media');
     $media = $model->getID($media_id, DATASET_TYPE_ARRAY);
     if (!$media) {
         throw notFoundException('File');
     }
     // Get actual path to the file.
     $local_path = Gdn_Upload::copyLocal($media['Path']);
     if (!file_exists($local_path)) {
         throw notFoundException('File');
     }
     $file_extension = pathinfo($local_path, PATHINFO_EXTENSION);
     // Generate new path for thumbnail
     $thumb_path = $this->getBaseUploadDestinationDir() . '/' . 'thumb';
     // Grab full path with filename, and validate it.
     $thumb_destination_path = $this->getAbsoluteDestinationFilePath($local_path, $file_extension, $thumb_path);
     // Create thumbnail, and grab debug data from whole process.
     $thumb_payload = generate_thumbnail($local_path, $thumb_destination_path, array('height' => c('Plugins.FileUpload.ThumbnailHeight', 128)));
     if ($thumb_payload['success'] === true) {
         // Thumbnail dimensions
         $thumb_height = round($thumb_payload['result_height']);
         $thumb_width = round($thumb_payload['result_width']);
         // Move the thumbnail to its proper location. Calling SaveAs with
         // cloudfiles enabled will trigger the move to cloudfiles, so use
         // same path for each arg in SaveAs. The file will be removed from the local filesystem.
         $parsed = Gdn_Upload::parse($thumb_destination_path);
         $target = $thumb_destination_path;
         // $parsed['Name'];
         $Upload = new Gdn_Upload();
         $filepath_parsed = $Upload->saveAs($thumb_destination_path, $target, array('source' => 'content'));
         // Save thumbnail information to DB.
         $model->save(array('MediaID' => $media_id, 'StorageMethod' => $filepath_parsed['Type'], 'ThumbWidth' => $thumb_width, 'ThumbHeight' => $thumb_height, 'ThumbPath' => $filepath_parsed['SaveName']));
         // Remove cf scratch copy, typically in cftemp, if there was actually a file pulled in from CF.
         if (strpos($local_path, 'cftemp') !== false) {
             if (!unlink($local_path)) {
                 // Maybe add logging for local cf copies not deleted.
             }
         }
         $url = $filepath_parsed['Url'];
     } else {
         // Fix the thumbnail information so this isn't requested again and again.
         $model->save(array('MediaID' => $media_id, 'ImageWidth' => 0, 'ImageHeight' => 0, 'ThumbPath' => ''));
         $url = asset('/plugins/FileUpload/images/file.png');
     }
     redirect($url, 301);
 }
Beispiel #22
0
 public static function getThumbnailStat($delivery_id, $class = 'thumb')
 {
     $existingpic = glob(Config::get('jayon.picture_path') . $delivery_id . '*.jpg');
     //print_r($existingpic);
     $pidx = count($existingpic);
     foreach ($existingpic as $epic) {
         if (!file_exists(Config::get('jayon.thumbnail_path') . 'th_' . $epic)) {
             //generate_thumbnail( str_replace('.jpg', '', $epic ) );
         }
     }
     if ($pidx > 1) {
         $ths = '';
         foreach ($existingpic as $epic) {
             $epic2 = str_replace(Config::get('jayon.picture_path'), '', $epic);
             //if(!file_exists(Config::get('jayon.thumbnail_path').'th_'.$epic )){
             $thumb = URL::to('/') . '/public/receiver/' . $epic2;
             $ths .= sprintf('<img style="width:45px;35px;float:left;" alt="' . $epic2 . '" src="%s?' . time() . '" />', $thumb);
             //}
         }
         $class = 'thumb_multi';
         $thumper = '<img class="' . $class . '" style="width:100%;height:100%;" alt="' . $delivery_id . '" src="' . URL::to('/') . '/assets/images/10.png" >';
         $ths .= '<div style="width:100%;height:100%;display:block;position:absolute;top:0px;left:0px;">' . $thumper . '</div>';
         $thumbnail = '<div style="width:100px;height:75px;clear:both;display:block;cursor:pointer;position:relative;border:thin solid brown;overflow-y:hidden;">' . $ths . '</div>';
     } else {
         if (file_exists(Config::get('jayon.picture_path') . $delivery_id . '.jpg')) {
             if (file_exists(Config::get('jayon.thumbnail_path') . 'th_' . $delivery_id . '.jpg')) {
                 $thumbnail = URL::to('/') . '/public/receiver_thumb/th_' . $delivery_id . '.jpg';
                 $thumbnail = sprintf('<img style="cursor:pointer;" class="' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" /><br /><span class="rotate" id="r_' . $delivery_id . '" style="cursor:pointer;"  >rotate CW</span>', $thumbnail);
             } else {
                 if (generate_thumbnail($delivery_id)) {
                     $thumbnail = URL::to('/') . '/public/receiver_thumb/th_' . $delivery_id . '.jpg';
                     $thumbnail = sprintf('<img style="cursor:pointer;" class="' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" /><br /><span class="rotate" id="r_' . $delivery_id . '" style="cursor:pointer;"  >rotate CW</span>', $thumbnail);
                 } else {
                     $thumbnail = $CI->ag_asset->load_image('th_nopic.jpg');
                     $thumbnail = sprintf('<img style="cursor:pointer;" class="' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" /><br /><span class="rotate" id="r_' . $delivery_id . '" style="cursor:pointer;"  >rotate CW</span>', $thumbnail);
                 }
             }
         } else {
             if (file_exists(Config::get('jayon.thumbnail_path') . 'th_' . $delivery_id . '.jpg')) {
                 if ($pidx > 0) {
                     $class = 'thumb_multi';
                 }
                 $thumbnail = URL::to('/') . '/public/receiver_thumb/th_' . $delivery_id . '.jpg';
                 $thumbnail = sprintf('<img style="cursor:pointer;" class="' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" /><br /><span class="rotate" id="r_' . $delivery_id . '" style="cursor:pointer;"  >rotate CW</span>', $thumbnail);
             } else {
                 $thumbnail = URL::to('/') . '/assets/images/th_nopic.jpg';
                 $thumbnail = sprintf('<img style="cursor:pointer;" class="' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" /><br /><span class="rotate" id="r_' . $delivery_id . '" style="cursor:pointer;"  >rotate CW</span>', $thumbnail);
             }
         }
     }
     $has_sign = false;
     if (file_exists(Config::get('jayon.picture_path') . $delivery_id . '_sign.jpg')) {
         //if(file_exists(Config::get('jayon.thumbnail_path').'th_'.$delivery_id.'_sign.jpg')){
         $sthumbnail = URL::to('/') . '/public/receiver/' . $delivery_id . '_sign.jpg';
         $thumbnail .= sprintf('<img style="cursor:pointer;width:100px;height:auto;" class="sign ' . $class . '" alt="' . $delivery_id . '" src="%s?' . time() . '" />', $sthumbnail);
         //}
         $has_sign = true;
     }
     if ($has_sign) {
         $gal = '<br />' . ($pidx - 1) . ' pics & 1 signature';
     } else {
         $gal = '<br />' . $pidx . ' pics, no signature';
     }
     if ($pidx > 0) {
         for ($g = 0; $g < $pidx; $g++) {
             $img = str_replace(Config::get('jayon.picture_path'), '', $existingpic[$g]);
             $gal .= '<input type="hidden" class="gal_' . $delivery_id . '" value="' . $img . '" >';
         }
     }
     $thumbnail = $thumbnail . $gal;
     return $thumbnail;
 }