function ChangeCategoryOrName($new_cat_id, $new_name = null, $add_existing = false, $overwrite = false) { // 1. apply new values (inherit permissions if nothing (Everyone) set!) // 2. check for name collision and rename // 3. move stuff // 4. notify parents // 5. update child paths if (empty($new_name)) { $new_name = $this->GetName(); } $this->Lock(true); $new_cat_id = intval($new_cat_id); $old_cat_id = $this->GetParentId(); $old_path_rel = $this->GetLocalPathRel(true); $old_path = $this->GetLocalPath(); $old_name = $this->GetName(); if ($this->is_file) { $old_thumb_path = $this->GetThumbPath(); } $old_cat = $this->GetParent(); $new_cat = WPFB_Category::GetCat($new_cat_id); if (!$new_cat) { $new_cat_id = 0; } $cat_changed = $new_cat_id != $old_cat_id; if ($cat_changed && $new_cat_id > 0 && $this->IsAncestorOf($new_cat)) { return array('error' => __('Cannot move category into a sub-category of itself.', WPFB)); } if ($this->is_file) { $this->file_category = $new_cat_id; $this->file_name = $new_name; $this->file_category_name = $new_cat_id == 0 ? '' : $new_cat->GetTitle(); } else { $this->cat_parent = $new_cat_id; $this->cat_folder = $new_name; } // inherit user roles if (count($this->GetReadPermissions()) == 0) { $this->SetReadPermissions($new_cat_id != 0 ? $new_cat->GetReadPermissions() : WPFB_Core::$settings->default_roles); } // flush cache $this->last_parent_id = -1; $new_path_rel = $this->GetLocalPathRel(true); $new_path = $this->GetLocalPath(); if ($new_path_rel != $old_path_rel) { $i = 1; if (!$add_existing) { $name = $this->GetName(); if ($overwrite) { if (@file_exists($new_path)) { $ex_file = WPFB_File::GetByPath($new_path_rel); if (!is_null($ex_file)) { $ex_file->Remove(); } else { @unlink($new_path); } } } else { // rename item if filename collision (ignore if coliding with $this) while (@file_exists($new_path) || !is_null($ex_file = WPFB_File::GetByPath($new_path_rel)) && !$this->Equals($ex_file)) { $i++; if ($this->is_file) { $p = strrpos($name, '.'); $this->file_name = $p <= 0 ? "{$name}({$i})" : substr($name, 0, $p) . "({$i})" . substr($name, $p); } else { $this->cat_folder = "{$name}({$i})"; } $new_path_rel = $this->GetLocalPathRel(true); $new_path = $this->GetLocalPath(); } } } // finally move it! if (!empty($old_name) && @file_exists($old_path)) { if ($this->is_file && $this->IsLocal()) { if (!@rename($old_path, $new_path)) { return array('error' => sprintf('Unable to move file %s!', $old_path)); } @chmod($new_path, octdec(WPFB_PERM_FILE)); } else { if (!@is_dir($new_path)) { wp_mkdir_p($new_path); } wpfb_loadclass('FileUtils'); if (!@WPFB_FileUtils::MoveDir($old_path, $new_path)) { return array('error' => sprintf('Could not move folder %s to %s', $old_path, $new_path)); } } } else { if ($this->is_category) { if (!@is_dir($new_path) && !wp_mkdir_p($new_path)) { return array('error' => sprintf(__('Unable to create directory %s. Is it\'s parent directory writable?'), $new_path)); } } } // move thumb if ($this->is_file && !empty($old_thumb_path) && @is_file($old_thumb_path)) { $thumb_path = $this->GetThumbPath(); if ($i > 1) { $p = strrpos($thumb_path, '-'); if ($p <= 0) { $p = strrpos($thumb_path, '.'); } $thumb_path = substr($thumb_path, 0, $p) . "({$i})" . substr($thumb_path, $p); $this->file_thumbnail = basename($thumb_path); } if (!is_dir(dirname($thumb_path))) { WPFB_Admin::Mkdir(dirname($thumb_path)); } if (!@rename($old_thumb_path, $thumb_path)) { return array('error' => 'Unable to move thumbnail! ' . $thumb_path); } @chmod($thumb_path, octdec(WPFB_PERM_FILE)); } $all_files = $this->is_file || $this->GetId() > 0 ? $this->GetChildFiles(true) : array(); // all children files (recursively) if (!empty($all_files)) { foreach ($all_files as $file) { if ($cat_changed) { if ($old_cat) { $old_cat->NotifyFileRemoved($file); } // notify parent cat to remove files if ($new_cat) { $new_cat->NotifyFileAdded($file); } } $file->GetLocalPathRel(true); // update file's path } } unset($all_files); if ($this->is_category && $this->GetId() > 0) { $cats = $this->GetChildCats(true); if (!empty($cats)) { foreach ($cats as $cat) { $cat->GetLocalPathRel(true); // update cats's path } } unset($cats); } } $this->Lock(false); if (!$this->locked) { $this->DBSave(); } return array('error' => false); /* * // create the directory if it doesnt exist // move file if($this->IsLocal() && !empty($old_file_path) && @is_file($old_file_path) && $new_file_path != $old_file_path) { if(!@rename($old_file_path, $new_file_path)) return array( 'error' => sprintf('Unable to move file %s!', $this->GetLocalPath())); @chmod($new_file_path, octdec(WPFB_PERM_FILE)); } */ }
static function SendFile($file_path, $args = array()) { global $wpdb; $defaults = array('bandwidth' => 0, 'etag' => null, 'force_download' => WPFB_Core::$settings->force_download, 'cache_max_age' => 0, 'md5_hash' => null, 'filename' => null); extract(wp_parse_args($args, $defaults), EXTR_SKIP); @ini_set('max_execution_time', '0'); @set_time_limit(0); @error_reporting(0); while (@ob_end_clean()) { } $no_cache = WPFB_Core::$settings->http_nocache && $cache_max_age != 0; @ini_set("zlib.output_compression", "Off"); // remove some headers if (function_exists('header_remove')) { header_remove(); } else { header("Expires: "); header("X-Pingback: "); } if (!@file_exists($file_path) || !is_file($file_path)) { header('HTTP/1.x 404 Not Found'); wp_die('File ' . basename($file_path) . ' not found!'); } wpfb_loadclass('FileUtils'); $size = WPFB_FileUtils::GetFileSize($file_path); $time = filemtime($file_path); $file_type = WPFB_Download::GetFileType($file_path); if (empty($etag)) { $etag = md5("{$size}|{$time}|{$file_type}"); } else { $etag = trim($etag, '"'); } // set basic headers if ($no_cache) { header("Cache-Control: no-cache, must-revalidate, max-age=0"); header("Pragma: no-cache"); header("Expires: Wed, 11 Jan 1984 05:00:00 GMT"); } elseif ($cache_max_age > 0) { header("Cache-Control: must-revalidate, max-age={$cache_max_age}"); } elseif ($cache_max_age == -1) { header("Cache-Control: public"); } //header("Connection: close"); //header("Keep-Alive: timeout=5, max=100"); //header("Connection: Keep-Alive"); header("Content-Type: " . $file_type . (strpos($file_type, 'text/') !== false ? '; charset=' : '')); // charset fix header("Last-Modified: " . gmdate("D, d M Y H:i:s", $no_cache ? time() : $time) . " GMT"); if (!empty($md5_hash) && $md5_hash[0] != '#') { // check if fake md5 $pmd5 = @pack('H32', $md5_hash); if (!empty($pmd5)) { header("Content-MD5: " . @base64_encode($pmd5)); } } if (!$no_cache) { header("ETag: \"{$etag}\""); $if_mod_since = !empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false; $if_none_match = !empty($_SERVER['HTTP_IF_NONE_MATCH']) ? $etag == trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') : false; if ($if_mod_since || $if_none_match) { $not_modified = true; if ($not_modified && $if_mod_since) { $not_modified = @strtotime($if_mod_since) >= $time; } if ($not_modified && $if_none_match) { $not_modified = $if_none_match == $etag; } if ($not_modified) { header("Content-Length: " . $size); header("HTTP/1.x 304 Not Modified"); exit; } } } if (!($fh = @fopen($file_path, 'rb'))) { wp_die(__('Could not read file!', 'wp-filebase')); } list($begin, $end) = self::ParseRangeHeader($size); if ($begin > 0 || $end < $size - 1) { header('HTTP/1.0 206 Partial Content'); header("Content-Range: bytes {$begin}-{$end}/{$size}"); } else { header('HTTP/1.0 200 OK'); } $length = $end - $begin + 1; WPFB_Download::AddTraffic($length); if (self::ShouldSendRangeHeader($file_path, $file_type)) { header("Accept-Ranges: bytes"); } $request_file_name = basename(urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); $filename_set = !empty($filename); if (!$filename_set) { $filename = basename($file_path); } // content headers if ($force_download) { header("Content-Disposition: attachment; filename=\"{$filename}\""); header("Content-Description: File Transfer"); } elseif ($filename != $request_file_name) { header("Content-Disposition: inline; filename=\"{$filename}\""); } header("Content-Length: " . $length); // clean up things that are not needed for download @session_write_close(); // disable blocking of multiple downloads at the same time // close db connection if (method_exists($wpdb, 'close')) { $wpdb->close(); } elseif (function_exists('mysql_close')) { if (!empty($wpdb->dbh) && is_resource($wpdb->dbh)) { @mysql_close($wpdb->dbh); } else { @mysql_close(); } } @ob_flush(); @flush(); // ready to send the file! if ($begin > 0) { fseek($fh, $begin, 0); } if (WPFB_Core::$settings->use_fpassthru) { fpassthru($fh); } else { $bandwidth = empty($bandwidth) ? 0 : (double) $bandwidth; if ($bandwidth <= 0) { $bandwidth = 1024 * 1024; } $buffer_size = (int) (1024 * min($bandwidth, 64)); // convert kib/s => bytes/ms $bandwidth *= 1024 / 1000; $cur = $begin; while (!@feof($fh) && $cur <= $end && @connection_status() == 0) { $nbytes = min($buffer_size, $end - $cur + 1); $ts = microtime(true); print @fread($fh, $nbytes); @ob_flush(); @flush(); $dt = (microtime(true) - $ts) * 1000; // dt = time delta in ms $st = $nbytes / $bandwidth - $dt; if ($st > 0) { usleep($st * 1000); } $cur += $nbytes; } } @fclose($fh); return true; }
static function CheckChangedFiles($sync_data) { $sync_id3 = !WPFB_Core::$settings->disable_id3; $upload_dir = self::cleanPath(WPFB_Core::UploadDir()); foreach ($sync_data->files as $id => $file) { $file_path = self::cleanPath($file->GetLocalPath(true)); $sync_data->known_filenames[] = substr($file_path, strlen($upload_dir)); if ($file->GetThumbPath()) { $sync_data->known_filenames[] = substr(self::cleanPath($file->GetThumbPath()), strlen($upload_dir)); } if ($file->file_category > 0 && is_null($file->GetParent())) { $sync_data->log['warnings'][] = sprintf(__('Category (ID %d) of file %s does not exist!', WPFB), $file->file_category, $file->GetLocalPathRel()); } // remove thumb if missing if ($file->file_thumbnail && !file_exists($file->GetThumbPath())) { $file->file_thumbnail = ''; $file->DBSave(); $sync_data->log['changed'][$id] = $file; } // TODO: check for file changes remotly if ($file->IsRemote()) { continue; } if (!@is_file($file_path) || !@is_readable($file_path)) { $sync_data->missing_files[$id] = $file; continue; } if ($sync_data->hash_sync) { $file_hash = WPFB_Admin::GetFileHash($file_path); } $file_size = WPFB_FileUtils::GetFileSize($file_path); $file_mtime = filemtime($file_path); $file_analyzetime = !$sync_id3 ? $file_mtime : WPFB_GetID3::GetFileAnalyzeTime($file); if (is_null($file_analyzetime)) { $file_analyzetime = 0; } if ($sync_data->hash_sync && $file->file_hash != $file_hash || $file->file_size != $file_size || $file->file_mtime != $file_mtime || $file_analyzetime < $file_mtime) { $file->file_size = $file_size; $file->file_mtime = $file_mtime; $file->file_hash = $sync_data->hash_sync ? $file_hash : WPFB_Admin::GetFileHash($file_path); WPFB_GetID3::UpdateCachedFileInfo($file); $res = $file->DBSave(); if (!empty($res['error'])) { $sync_data->log['error'][$id] = $file; } else { $sync_data->log['changed'][$id] = $file; } } } // prepare for binary search (fast_in_array) sort($sync_data->known_filenames); }
/** * * @param WPFB_SyncData $sync_data * @param boolean $output */ private static function CheckChangedFiles($sync_data, $output) { if ($output) { self::DEcho('<p>' . sprintf(__('Checking %d files for changes...', 'wp-filebase'), count($sync_data->files)) . ' '); } $sync_id3 = !WPFB_Core::$settings->disable_id3; $upload_dir = self::cleanPath(WPFB_Core::UploadDir()); if (count($sync_data->files) > 0) { wpfb_loadclass('ProgressReporter'); $progress_reporter = new WPFB_ProgressReporter(); $progress_reporter->InitProgress(count($sync_data->files)); $progress_reporter->InitProgressField('Current File: %#%', '-', true); } $i = 0; foreach ($sync_data->files as $id => $file) { $file_path = self::cleanPath($file->GetLocalPath(true)); $rel_file_path = substr($file_path, strlen($upload_dir)); $progress_reporter->SetProgress(++$i); $progress_reporter->SetField($rel_file_path); $sync_data->known_filenames[] = $rel_file_path; if ($file->GetThumbPath()) { $sync_data->known_filenames[] = substr(self::cleanPath($file->GetThumbPath()), strlen($upload_dir)); } if ($file->file_category > 0 && is_null($file->GetParent())) { $sync_data->log['warnings'][] = sprintf(__('Category (ID %d) of file %s does not exist!', 'wp-filebase'), $file->file_category, $file->GetLocalPathRel()); } // remove thumb if missing if ($file->file_thumbnail && !file_exists($file->GetThumbPath())) { $file->file_thumbnail = ''; $file->DBSave(); $sync_data->log['changed'][$id] = $file; } // TODO: check for file changes remotly if ($file->IsRemote()) { continue; } if (!@is_file($file_path) || !@is_readable($file_path)) { $sync_data->missing_files[$id] = $file; continue; } if ($sync_data->hash_sync) { $file_hash = WPFB_Admin::GetFileHash($file_path); } $file_size = WPFB_FileUtils::GetFileSize($file_path); $file_mtime = filemtime($file_path); $file_analyzetime = !$sync_id3 ? $file_mtime : WPFB_GetID3::GetFileAnalyzeTime($file); if (is_null($file_analyzetime)) { $file_analyzetime = 0; } if ($sync_data->hash_sync && $file->file_hash != $file_hash || $file->file_size != $file_size || $file->file_mtime != $file_mtime || $file_analyzetime < $file_mtime) { $file->file_size = $file_size; $file->file_mtime = $file_mtime; $file->file_hash = $sync_data->hash_sync ? $file_hash : WPFB_Admin::GetFileHash($file_path); WPFB_Sync::ScanFile($file); // this can be async! $res = $file->DBSave(); if (!empty($res['error'])) { $sync_data->log['error'][$id] = $res['error'] . " (file {$rel_file_path})"; } else { $sync_data->log['changed'][$id] = $file; } } } // prepare for binary search (fast_in_array) sort($sync_data->known_filenames); if ($output) { self::DEcho('- done!</p>'); } }
/** * * @param WPFB_SyncData $sync_data * @param boolean $output */ private static function CheckChangedFiles($sync_data, $output) { if ($sync_data->num_db_files == 0) { return; } if ($output) { self::DEcho('<p>' . sprintf(__('Checking %d files for changes...', 'wp-filebase'), $sync_data->num_db_files) . ' '); } $sync_id3 = !WPFB_Core::$settings->disable_id3; $upload_dir = trailingslashit(self::cleanPath(WPFB_Core::UploadDir())); wpfb_loadclass('ProgressReporter'); $progress_reporter = new WPFB_ProgressReporter(!$output); $progress_reporter->InitProgress($sync_data->num_db_files); $progress_reporter->InitProgressField('Current File: %#%', '-', true); $i = 0; /* * if ($file->file_category > 0 && is_null($file->GetParent())) { $sync_data->log['warnings'][] = sprintf(__('Category (ID %d) of file %s does not exist!', 'wp-filebase'), $file->file_category, $file->GetLocalPathRel()); } */ foreach ($sync_data->db_file_states as $fs) { $file_path = $upload_dir . $fs->path_rel; $rel_file_path = $fs->path_rel; if (empty($fs->path_rel)) { $rel_file_path = $fs->getFile()->GetLocalPath(true); } $progress_reporter->SetProgress(++$i); $progress_reporter->SetField($rel_file_path); $sync_data->known_filenames[$rel_file_path] = 1; if ($fs->thumb_file_name) { $rel_thumb_path = $fs->getThumbPath(); $sync_data->known_filenames[$rel_thumb_path] = 1; // remove thumb if missing if (!file_exists($upload_dir . $rel_thumb_path)) { $fs->getFile()->file_thumbnail = ''; $fs->getFile()->DBSave(); $sync_data->log['changed'][$fs->id] = $fs->getFile(); } } if ($fs->has_uri) { continue; } if (!@is_file($file_path) || !@is_readable($file_path)) { $sync_data->missing_files[$fs->id] = $fs->getFile(); continue; } $file_hash = $sync_data->hash_sync ? WPFB_Admin::GetFileHash($file_path) : ''; $file_size = WPFB_FileUtils::GetFileSize($file_path); $file_mtime = filemtime($file_path); if ($sync_data->hash_sync && $fs->hash != $file_hash || $fs->size != $file_size || $fs->mtime != $file_mtime) { $file = $fs->getFile(); $file->file_size = $file_size; $file->file_mtime = $file_mtime; $file->file_hash = $sync_data->hash_sync ? $file_hash : WPFB_Admin::GetFileHash($file_path); WPFB_Sync::ScanFile($file); // this can be async! $res = $file->DBSave(); if (!empty($res['error'])) { $sync_data->log['error'][$fs->id] = $res['error'] . " (file {$rel_file_path})"; } else { $sync_data->log['changed'][$fs->id] = $fs->getFile(); } } } if ($output) { self::DEcho('- done!</p>'); } }
static function InsertFile($data, $in_gui = false) { if (!is_object($data)) { $data = (object) $data; } $file_id = isset($data->file_id) ? (int) $data->file_id : 0; $file = null; if ($file_id > 0) { $file = WPFB_File::GetFile($file_id); if ($file == null) { $file_id = 0; } } $update = $file_id > 0 && $file != null && $file->is_file; if (!$update) { $file = new WPFB_File(array('file_id' => 0)); } $file->Lock(true); $add_existing = !empty($data->add_existing); // if the file is added by a sync (not uploaded) if (!$add_existing) { self::SyncCustomFields(); } // dont sync custom fields when file syncing! if (!empty($data->file_flash_upload)) { // check for flash upload and validate! $file_flash_upload = json_decode($data->file_flash_upload, true); $file_flash_upload['tmp_name'] = WPFB_Core::UploadDir() . '/' . str_replace('../', '', $file_flash_upload['tmp_name']); if (is_file($file_flash_upload['tmp_name'])) { $data->file_upload = $file_flash_upload; } } // are we uploading a file? $upload = !$add_existing && ((@is_uploaded_file($data->file_upload['tmp_name']) || !empty($data->file_flash_upload)) && !empty($data->file_upload['name'])); $remote_upload = !$add_existing && !$upload && !empty($data->file_is_remote) && !empty($data->file_remote_uri) && (!$update || $file->file_remote_uri != $data->file_remote_uri); $remote_redirect = !empty($data->file_remote_redirect) && !empty($data->file_remote_uri); if ($remote_redirect) { $remote_scan = !empty($data->file_remote_scan); } // are we uploading a thumbnail? $upload_thumb = !$add_existing && @is_uploaded_file($data->file_upload_thumb['tmp_name']); if ($upload_thumb && !(WPFB_FileUtils::FileHasImageExt($data->file_upload_thumb['name']) && WPFB_FileUtils::IsValidImage($data->file_upload_thumb['tmp_name']))) { return array('error' => __('Thumbnail is not a valid image!.', WPFB)); } if ($remote_upload) { unset($file_src_path); $remote_file_info = self::GetRemoteFileInfo($data->file_remote_uri); if (empty($remote_file_info)) { return array('error' => sprintf(__('Could not get file information from %s!', WPFB), $data->file_remote_uri)); } $file_name = $remote_file_info['name']; if ($remote_file_info['size'] > 0) { $file->file_size = $remote_file_info['size']; } if ($remote_file_info['time'] > 0) { $file->SetModifiedTime($remote_file_info['time']); } } else { $file_src_path = $upload ? $data->file_upload['tmp_name'] : ($add_existing ? $data->file_path : null); $file_name = $upload ? str_replace('\\', '', $data->file_upload['name']) : (empty($file_src_path) && $update ? $file->file_name : basename($file_src_path)); } if ($upload) { $data->file_rename = null; } // VALIDATION $current_user = wp_get_current_user(); if (empty($data->frontend_upload) && !$add_existing && empty($current_user->ID)) { return array('error' => __('Could not get user id!', WPFB)); } if (!$update && !$add_existing && !$upload && !$remote_upload) { return array('error' => __('No file was uploaded.', WPFB)); } // check extension if ($upload || $add_existing) { if (!self::IsAllowedFileExt($file_name)) { if (isset($file_src_path)) { @unlink($file_src_path); } return array('error' => sprintf(__('The file extension of the file <b>%s</b> is forbidden!', WPFB), $file_name)); } } // check url if ($remote_upload && !preg_match('/^(https?|file):\\/\\//', $data->file_remote_uri)) { return array('error' => __('Only HTTP links are supported.', WPFB)); } // do some simple file stuff if ($update && (!empty($data->file_delete_thumb) || $upload_thumb)) { $file->DeleteThumbnail(); } // delete thumbnail if user wants to if ($update && ($upload || $remote_upload)) { $file->Delete(true); } // if we update, delete the old file (keep thumb!) // handle display name and version if (isset($data->file_version)) { $file->file_version = $data->file_version; } if (isset($data->file_display_name)) { $file->file_display_name = $data->file_display_name; } $result = self::ParseFileNameVersion($file_name, $file->file_version); if (empty($file->file_version)) { $file->file_version = $result['version']; } if (empty($file->file_display_name)) { $file->file_display_name = $result['title']; } // handle category & name $file_category = intval($data->file_category); $new_cat = null; if ($file_category > 0 && ($new_cat = WPFB_Category::GetCat($file_category)) == null) { $file_category = 0; } // this inherits permissions as well: $result = $file->ChangeCategoryOrName($file_category, empty($data->file_rename) ? $file_name : $data->file_rename, $add_existing, !empty($data->overwrite)); if (is_array($result) && !empty($result['error'])) { return $result; } $prev_read_perms = $file->file_offline ? array('administrator') : $file->GetReadPermissions(); // explicitly set permissions: if (!empty($data->file_perm_explicit) && isset($data->file_user_roles)) { $file->SetReadPermissions(empty($data->file_user_roles) || count(array_filter($data->file_user_roles)) == 0 ? array() : $data->file_user_roles); } // if there is an uploaded file if ($upload) { $file_dest_path = $file->GetLocalPath(); $file_dest_dir = dirname($file_dest_path); if (@file_exists($file_dest_path)) { return array('error' => sprintf(__('File %s already exists. You have to delete it first!', WPFB), $file->GetLocalPath())); } if (!is_dir($file_dest_dir)) { self::Mkdir($file_dest_dir); } // try both move_uploaded_file for http, rename for flash uploads! if (!(move_uploaded_file($file_src_path, $file_dest_path) || rename($file_src_path, $file_dest_path)) || !@file_exists($file_dest_path)) { return array('error' => sprintf(__('Unable to move file %s! Is the upload directory writeable?', WPFB), $file->file_name) . ' ' . $file->GetLocalPathRel()); } } elseif ($remote_upload) { if (!$remote_redirect || $remote_scan) { $tmp_file = self::GetTmpFile($file->file_name); $result = self::SideloadFile($data->file_remote_uri, $tmp_file, $in_gui ? $remote_file_info['size'] : -1); if (is_array($result) && !empty($result['error'])) { return $result; } if (!rename($tmp_file, $file->GetLocalPath())) { return array('error' => 'Could not rename temp file!'); } } } elseif (!$add_existing && !$update) { return array('error' => __('No file was uploaded.', WPFB)); } // handle date/time stuff if (!empty($data->file_date)) { $file->file_date = $data->file_date; } elseif ($add_existing || empty($file->file_date)) { $file->file_date = gmdate('Y-m-d H:i:s', file_exists($file->GetLocalPath()) ? filemtime($file->GetLocalPath()) : time()); } self::fileApplyMeta($file, $data); // set the user id if (!$update && !empty($current_user)) { $file->file_added_by = $current_user->ID; } // save into db $file->Lock(false); $result = $file->DBSave(); if (is_array($result) && !empty($result['error'])) { return $result; } $file_id = (int) $result['file_id']; // get file info if (!($update && $remote_redirect) && is_file($file->GetLocalPath()) && empty($data->no_scan)) { $file->file_size = isset($data->file_size) ? $data->file_size : WPFB_FileUtils::GetFileSize($file->GetLocalPath()); $file->file_mtime = filemtime($file->GetLocalPath()); $old_hash = $file->file_hash; $file->file_hash = WPFB_Admin::GetFileHash($file->GetLocalPath()); // only analyze files if changed! if ($upload || !$update || $file->file_hash != $old_hash) { wpfb_loadclass('GetID3'); $file_info = WPFB_GetID3::UpdateCachedFileInfo($file); if (!$upload_thumb && empty($data->file_thumbnail)) { if (!empty($file_info['comments']['picture'][0]['data'])) { $cover_img =& $file_info['comments']['picture'][0]['data']; } elseif (!empty($file_info['id3v2']['APIC'][0]['data'])) { $cover_img =& $file_info['id3v2']['APIC'][0]['data']; } else { $cover_img = null; } // TODO unset pic in info? if (!empty($cover_img)) { $cover = $file->GetLocalPath(); $cover = substr($cover, 0, strrpos($cover, '.')) . '.jpg'; file_put_contents($cover, $cover_img); $file->CreateThumbnail($cover, true); @unlink($cover); } } } } else { if (isset($data->file_size)) { $file->file_size = $data->file_size; } if (isset($data->file_hash)) { $file->file_hash = $data->file_hash; } } if ($remote_redirect) { if (file_exists($file->GetLocalPath())) { @unlink($file->GetLocalPath()); } // when download redircet the actual files is not needed anymore } else { // set permissions @chmod($file->GetLocalPath(), octdec(WPFB_PERM_FILE)); $file->file_remote_uri = $data->file_remote_uri = ''; // no redirection, URI is not neede anymore } // handle thumbnail if ($upload_thumb) { $file->DeleteThumbnail(); // delete the old thumbnail (if existing) $thumb_dest_path = dirname($file->GetLocalPath()) . '/thumb_' . $data->file_upload_thumb['name']; if (@move_uploaded_file($data->file_upload_thumb['tmp_name'], $thumb_dest_path)) { $file->CreateThumbnail($thumb_dest_path, true); } } else { if ($upload || $remote_upload || $add_existing) { if ($add_existing && !empty($data->file_thumbnail)) { $file->file_thumbnail = $data->file_thumbnail; // we already got the thumbnail on disk! } elseif (empty($file->file_thumbnail) && !$upload_thumb && (!$remote_redirect || $remote_scan) && empty($data->no_scan)) { $file->CreateThumbnail(); // check if the file is an image and create thumbnail } } } // save into db again $result = $file->DBSave(); if (is_array($result) && !empty($result['error'])) { return $result; } return array('error' => false, 'file_id' => $file_id, 'file' => $file); }
function CreateThumbnail($src_image = '', $del_src = false) { wpfb_loadclass('FileUtils'); $src_set = !empty($src_image) && file_exists($src_image); $tmp_src = $del_src; if (!$src_set) { if (file_exists($this->GetLocalPath())) { $src_image = $this->GetLocalPath(); } elseif ($this->IsRemote()) { // if remote file, download it and use as source $res = wpfb_call('Admin', 'SideloadFile', $this->GetRemoteUri()); $src_image = $res['file']; $tmp_src = true; } } if (!file_exists($src_image) || @filesize($src_image) < 3) { if ($tmp_src) { @unlink($src_image); } return; } $ext = trim($this->GetExtension(), '.'); $src_size = array(); if (!WPFB_FileUtils::FileHasImageExt($this->file_name) && !($src_set && WPFB_FileUtils::IsValidImage($src_image, $src_size))) { // check if valid image if ($tmp_src) { @unlink($src_image); } return; } $this->DeleteThumbnail(); // delete old thumbnail $thumb_size = (int) WPFB_Core::$settings->thumbnail_size; if ($thumb_size == 0) { if ($tmp_src) { @unlink($src_image); } return; } $thumb = WPFB_FileUtils::CreateThumbnail($src_image, $thumb_size); $success = !empty($thumb) && !is_wp_error($thumb) && is_string($thumb) && file_exists($thumb); if (!$src_set && !$success) { $this->file_thumbnail = null; } else { // fallback to source image WARNING: src img will be moved or deleted! if ($src_set && !$success) { $thumb = $src_image; } $this->file_thumbnail = basename(trim($thumb, '.')); // FIX: need to trim . when image has no extension if (!is_dir(dirname($this->GetThumbPath()))) { WPFB_Admin::Mkdir(dirname($this->GetThumbPath())); } if (!@rename($thumb, $this->GetThumbPath())) { $this->file_thumbnail = null; @unlink($thumb); } else { @chmod($this->GetThumbPath(), octdec(WPFB_PERM_FILE)); } } if ($tmp_src) { @unlink($src_image); } }
static function CreateThumbnail($src_img, $max_size) { $ext = trim(strtolower(strrchr($src_img, '.')), '.'); $extras_dir = WPFB_PLUGIN_ROOT . 'extras/'; $tmp_img = $src_img . '_thumb.jpg'; $tmp_del = true; switch ($ext) { case 'bmp': if (@file_exists($extras_dir . 'phpthumb.functions.php') && @file_exists($extras_dir . 'phpthumb.bmp.php')) { @(include_once $extras_dir . 'phpthumb.functions.php'); @(include_once $extras_dir . 'phpthumb.bmp.php'); if (class_exists('phpthumb_functions') && class_exists('phpthumb_bmp')) { $phpthumb_bmp = new phpthumb_bmp(); $im = $phpthumb_bmp->phpthumb_bmpfile2gd($src_img); if ($im) { @imagejpeg($im, $tmp_img, 100); } else { return false; } } } break; default: $tmp_img = $src_img; $tmp_del = false; break; } $tmp_size = array(); if (!@file_exists($tmp_img) || @filesize($tmp_img) == 0 || !WPFB_FileUtils::IsValidImage($tmp_img, $tmp_size)) { if ($tmp_del && is_file($tmp_img)) { @unlink($tmp_img); } return false; } if (!function_exists('image_make_intermediate_size')) { require_once ABSPATH . 'wp-includes/media.php'; if (!function_exists('image_make_intermediate_size')) { if ($tmp_del && is_file($tmp_img)) { @unlink($tmp_img); } wp_die('Function image_make_intermediate_size does not exist!'); return false; } } $dir = dirname($src_img) . '/'; $thumb = @image_make_intermediate_size($tmp_img, $max_size, $max_size); if ((!$thumb || is_wp_error($thumb)) && !empty($tmp_size) && max($tmp_size) <= $max_size) { // error occurs when image is smaller than thumb_size. in this case, just copy original $name = wp_basename($src_img, ".{$ext}"); $new_thumb = "{$name}-{$tmp_size[0]}x{$tmp_size[1]}" . strtolower(strrchr($tmp_img, '.')); if ($tmp_del) { rename($tmp_img, $dir . $new_thumb); } else { copy($tmp_img, $dir . $new_thumb); } $thumb = array('file' => $new_thumb); } if ($tmp_del && is_file($tmp_img)) { unlink($tmp_img); } if (!$thumb) { return false; } rename($dir . $thumb['file'], $fn = $dir . str_ireplace(array('.pdf_thumb', '.tiff_thumb', '.tif_thumb', '.bmp_thumb'), '', $thumb['file'])); return $fn; }
static function InsertFile($data, $in_gui = false) { if (!is_object($data)) { $data = (object) $data; } $file_id = isset($data->file_id) ? (int) $data->file_id : 0; $file = null; if ($file_id > 0) { $file = WPFB_File::GetFile($file_id); if ($file == null) { $file_id = 0; } } $update = $file_id > 0 && $file != null && $file->is_file; if (!$update) { $file = new WPFB_File(array('file_id' => 0)); } $file->Lock(true); $add_existing = !empty($data->add_existing); // if the file is added by a sync (not uploaded) if (!$add_existing) { self::SyncCustomFields(); } // dont sync custom fields when file syncing! if (!empty($data->file_flash_upload)) { // check for flash upload and validate! $file_flash_upload = json_decode($data->file_flash_upload, true); $file_flash_upload['tmp_name'] = WPFB_Core::UploadDir() . '/' . str_replace('../', '', $file_flash_upload['tmp_name']); if (is_file($file_flash_upload['tmp_name'])) { $data->file_upload = $file_flash_upload; } } // are we uploading a file? $upload = !$add_existing && ((@is_uploaded_file($data->file_upload['tmp_name']) || !empty($data->file_flash_upload)) && !empty($data->file_upload['name'])); $remote_upload = !$add_existing && !$upload && !empty($data->file_remote_uri) && (!$update || $file->file_remote_uri != $data->file_remote_uri); $remote_redirect = !empty($data->file_remote_redirect) && !empty($data->file_remote_uri); if ($remote_redirect) { $remote_scan = !empty($data->file_remote_scan); } // if we change the actual file on disk $change = $upload || $remote_upload; if ($update && ($change || !empty($data->file_rename) && $data->file_rename != $file->file_name) && $file->IsScanLocked()) { return array('error' => sprintf(__('%s is currently locked. Please try again in %s.', 'wp-filebase'), $file, human_time_diff(time(), $file->file_scan_lock))); } // are we uploading a thumbnail? $upload_thumb = !$add_existing && @is_uploaded_file($data->file_upload_thumb['tmp_name']); if ($upload_thumb && !(WPFB_FileUtils::FileHasImageExt($data->file_upload_thumb['name']) && WPFB_FileUtils::IsValidImage($data->file_upload_thumb['tmp_name']))) { return array('error' => __('Thumbnail is not a valid image!.', 'wp-filebase')); } if ($remote_upload) { unset($file_src_path); $remote_file_info = self::GetRemoteFileInfo($data->file_remote_uri); if (is_wp_error($remote_file_info)) { return array('error' => sprintf(__('Could not get file information from %s!', 'wp-filebase'), $data->file_remote_uri) . ' (' . $remote_file_info->get_error_message() . ')'); } $file_name = $remote_file_info['name']; if ($remote_file_info['size'] > 0) { $file->file_size = $remote_file_info['size']; } if ($remote_file_info['time'] > 0) { $file->SetModifiedTime($remote_file_info['time']); } } else { $file_src_path = $upload ? $data->file_upload['tmp_name'] : ($add_existing ? $data->file_path : null); $file_name = $upload ? str_replace('\\', '', $data->file_upload['name']) : (empty($file_src_path) && $update ? $file->file_name : substr(strrchr(str_replace('\\', '/', $file_src_path), '/'), 1)); // no basename here! } if ($upload) { $data->file_rename = null; } // VALIDATION $current_user = wp_get_current_user(); if (empty($data->frontend_upload) && !$add_existing && empty($current_user->ID)) { return array('error' => __('Could not get user id!', 'wp-filebase')); } if (!$update && !$add_existing && !$upload && !$remote_upload) { return array('error' => __('No file was uploaded.', 'wp-filebase')); } // check extension if ($upload || $add_existing) { if (!self::IsAllowedFileExt($file_name)) { if (isset($file_src_path)) { @unlink($file_src_path); } return array('error' => sprintf(__('The file extension of the file <b>%s</b> is forbidden!', 'wp-filebase'), $file_name)); } } // check url if ($remote_upload && !preg_match('/^(https?|file):\\/\\//', $data->file_remote_uri)) { return array('error' => __('Only HTTP links are supported.', 'wp-filebase')); } // do some simple file stuff if ($update && (!empty($data->file_delete_thumb) || $upload_thumb)) { $file->DeleteThumbnail(); } // delete thumbnail if user wants to if ($update && ($upload || $remote_upload)) { $file->Delete(true); } // if we update, delete the old file (keep thumb!) // handle display name and version if (isset($data->file_version)) { $file->file_version = $data->file_version; } if (isset($data->file_display_name)) { $file->file_display_name = $data->file_display_name; } $result = self::ParseFileNameVersion($file_name, $file->file_version); if (empty($file->file_version)) { $file->file_version = $result['version']; } if (empty($file->file_display_name)) { $file->file_display_name = $result['title']; } // handle category & name $file_category = isset($data->file_category) ? is_object($data->file_category) ? $data->file_category->GetId() : 0 + $data->file_category : 0; $new_cat = null; if ($file_category > 0 && ($new_cat = WPFB_Category::GetCat($file_category)) == null) { $file_category = 0; } // this inherits permissions as well: $result = $file->ChangeCategoryOrName($file_category, empty($data->file_rename) ? $file_name : $data->file_rename, $add_existing, !empty($data->overwrite)); if (is_array($result) && !empty($result['error'])) { return $result; } $prev_read_perms = $file->file_offline ? array('administrator') : $file->GetReadPermissions(); // explicitly set permissions: if (!empty($data->file_perm_explicit) && isset($data->file_user_roles)) { $file->SetReadPermissions(empty($data->file_user_roles) || count(array_filter($data->file_user_roles)) == 0 ? array() : $data->file_user_roles); } // if there is an uploaded file if ($upload) { $file_dest_path = $file->GetLocalPath(); $file_dest_dir = dirname($file_dest_path); if (@file_exists($file_dest_path)) { return array('error' => sprintf(__('File %s already exists. You have to delete it first!', 'wp-filebase'), $file->GetLocalPath())); } if (!is_dir($file_dest_dir)) { self::Mkdir($file_dest_dir); } // try both move_uploaded_file for http, rename for flash uploads! if (!(move_uploaded_file($file_src_path, $file_dest_path) || rename($file_src_path, $file_dest_path)) || !@file_exists($file_dest_path)) { return array('error' => sprintf(__('Unable to move file %s! Is the upload directory writeable?', 'wp-filebase'), $file->file_name) . ' ' . $file->GetLocalPathRel()); } } elseif ($remote_upload) { if (!$remote_redirect || $remote_scan) { $tmp_file = self::GetTmpFile($file->file_name); $result = self::SideloadFile($data->file_remote_uri, $tmp_file, $in_gui ? $remote_file_info['size'] : -1); if (is_array($result) && !empty($result['error'])) { return $result; } if (!rename($tmp_file, $file->GetLocalPath())) { return array('error' => "Could not rename temp file {$tmp_file} -> {$file->GetLocalPath()} !"); } if (!$remote_redirect) { $data->file_remote_uri = ''; } } } elseif (!$add_existing && !$update) { return array('error' => __('No file was uploaded.', 'wp-filebase')); } // handle date/time stuff if (!empty($data->file_date)) { $file->file_date = $data->file_date; } elseif ($add_existing || empty($file->file_date)) { $file->file_date = file_exists($file->GetLocalPath()) ? gmdate('Y-m-d H:i:s', min(filemtime($file->GetLocalPath()), time()) + get_option('gmt_offset') * HOUR_IN_SECONDS) : current_time('mysql'); } if (!$update) { // since 4.4, wpdb will acutally set NULL values, so make sure everything is an empty string $file->file_hash = ''; $file->file_remote_uri = ''; $file->file_tags = ''; $file->file_license = ''; $file->file_password = ''; $file->file_last_dl_ip = ''; $file->file_added_by = empty($current_user) ? 0 : $current_user->ID; } self::fileApplyMeta($file, $data); // save into db $file->Lock(false); $result = $file->DBSave(); if (is_array($result) && !empty($result['error'])) { return $result; } $file_id = (int) $result['file_id']; if (!$update) { // on new file, remove any existing data global $wpdb; $wpdb->query("DELETE FROM {$wpdb->wpfilebase_files_id3} WHERE file_id = {$file_id}"); } if (!empty($data->no_scan) && !empty($data->add_rsync)) { $file->file_rescan_pending = 1; } // get file info if ((!$update || !$remote_redirect) && is_file($file->GetLocalPath())) { $old_size = $file->file_size; $old_mtime = $file->file_mtime; $old_hash = $file->file_hash; $file->file_size = isset($data->file_size) ? $data->file_size : WPFB_FileUtils::GetFileSize($file->GetLocalPath()); $file->file_mtime = filemtime($file->GetLocalPath()); $size_or_mtime_changed = $old_size != $file->file_size || $old_mtime != $file->file_mtime; $file->file_hash = empty($data->no_scan) ? WPFB_Admin::GetFileHash($file->GetLocalPath()) : ($size_or_mtime_changed ? '' : $old_hash); // TODO: revise conditions / make more readable if (!empty($data->no_scan) && ($upload || $add_existing || $size_or_mtime_changed)) { $file->file_rescan_pending = 1; } elseif (empty($data->no_scan) && ($upload || !$update || $file->file_hash != $old_hash)) { wpfb_loadclass('Sync'); WPFB_Sync::ScanFile($file, false, !$remote_redirect); // dont do async scan if temporary file } } else { if (isset($data->file_size)) { $file->file_size = $data->file_size; } if (isset($data->file_hash)) { $file->file_hash = $data->file_hash; } } if ($remote_redirect) { if (file_exists($file->GetLocalPath())) { @unlink($file->GetLocalPath()); } // when download redircet the actual files is not needed anymore } else { // set permissions is_file($file->GetLocalPath()) && @chmod($file->GetLocalPath(), octdec(WPFB_PERM_FILE)); $file->file_remote_uri = $data->file_remote_uri = ''; // no redirection, URI is not neede anymore } // handle thumbnail if ($upload_thumb) { $file->DeleteThumbnail(); // delete the old thumbnail (if existing) $thumb_dest_path = dirname($file->GetLocalPath()) . '/thumb_' . $data->file_upload_thumb['name']; if (@move_uploaded_file($data->file_upload_thumb['tmp_name'], $thumb_dest_path)) { $file->CreateThumbnail($thumb_dest_path, true); } } else { if ($upload || $remote_upload || $add_existing) { if ($add_existing && !empty($data->file_thumbnail)) { $file->file_thumbnail = $data->file_thumbnail; // we already got the thumbnail on disk! } elseif (empty($file->file_thumbnail) && !$upload_thumb && (!$remote_redirect || $remote_scan) && empty($data->no_scan)) { // WPFB_Sync::ScanFile should've done this, this may never be reached $file->CreateThumbnail(); // check if the file is an image and create thumbnail } } } // save into db again $result = $file->DBSave(); if (is_array($result) && !empty($result['error'])) { return $result; } return array('error' => false, 'file_id' => $file_id, 'file' => $file); }
static function CreateThumbnail($src_img, $max_size) { $ext = trim(strtolower(strrchr($src_img, '.')), '.'); $extras_dir = WPFB_PLUGIN_ROOT . 'extras/'; $tmp_img = $src_img . '_thumb.jpg'; $tmp_del = true; switch ($ext) { case 'bmp': if (@file_exists($extras_dir . 'phpthumb.functions.php') && @file_exists($extras_dir . 'phpthumb.bmp.php')) { @(include_once $extras_dir . 'phpthumb.functions.php'); @(include_once $extras_dir . 'phpthumb.bmp.php'); if (class_exists('phpthumb_functions') && class_exists('phpthumb_bmp')) { $phpthumb_bmp = new phpthumb_bmp(); $im = $phpthumb_bmp->phpthumb_bmpfile2gd($src_img); if ($im) { @imagejpeg($im, $tmp_img, 100); } else { return false; } } } break; default: $tmp_img = $src_img; $tmp_del = false; break; } $tmp_size = array(); if (!@file_exists($tmp_img) || @filesize($tmp_img) == 0 || !WPFB_FileUtils::IsValidImage($tmp_img, $tmp_size)) { return $tmp_del && is_file($tmp_img) && @unlink($tmp_img) && false; } if (!function_exists('wp_get_image_editor') && !(include_once ABSPATH . 'wp-includes/media.php') && !function_exists('wp_get_image_editor')) { return $tmp_del && is_file($tmp_img) && @unlink($tmp_img) && false; } // load image $editor = wp_get_image_editor($tmp_img); if (is_wp_error($editor)) { return $tmp_del && is_file($tmp_img) && @unlink($tmp_img) && false; } // "trim" image whitespaces $boundary = self::GetImageBoundary($tmp_img); if (array_sum($boundary) > 0 && is_wp_error($editor->crop($boundary[0], $boundary[1], $boundary[2], $boundary[3]))) { return $tmp_del && is_file($tmp_img) && @unlink($tmp_img) && false; } // resize to max thumb size if (is_wp_error($editor->resize($max_size, $max_size))) { return $tmp_del && is_file($tmp_img) && @unlink($tmp_img) && false; } // save $thumb = $editor->save(); $dir = dirname($src_img) . '/'; // error occurs when image is smaller than thumb_size. in this case, just copy original if (is_wp_error($thumb) && !empty($tmp_size) && max($tmp_size) <= $max_size) { $name = wp_basename($src_img, ".{$ext}"); $new_thumb = "{$name}-{$tmp_size[0]}x{$tmp_size[1]}" . strtolower(strrchr($tmp_img, '.')); if ($tmp_del) { rename($tmp_img, $dir . $new_thumb); } else { copy($tmp_img, $dir . $new_thumb); } $thumb = array('file' => $new_thumb); } $tmp_del && is_file($tmp_img) && unlink($tmp_img); if (!$thumb) { return false; } $fn = $dir . str_ireplace(array('.pdf_thumb', '.jpg_thumb', '.tiff_thumb', '.tif_thumb', '.bmp_thumb'), '', $thumb['file']); // make sure we have a thumb file name like `._[KK..K].thumb.(jpg|png)$` $thumb_suffix = '.thumb'; $lts = strlen($thumb_suffix); $p = strrpos($fn, '.'); if ($p <= $lts || strcmp($thumb_suffix, substr($fn, $p - $lts, $lts)) != 0) { // add token to make thumbnail url non-guessable $token = '._' . wp_generate_password(12, false, false); $fn = substr($fn, 0, $p) . $token . $thumb_suffix . substr($fn, $p); } rename($dir . $thumb['file'], $fn); return $fn; }