function ws_images_addRemote($params, &$service) { global $conf; if (!is_admin()) { return new PwgError(401, 'Access denied'); } load_language('plugin.lang', URLUPLOADER_PATH); $params = array_map('trim', $params); $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif'); $allowed_mimes = array('image/jpeg', 'image/png', 'image/gif'); // check empty url if (empty($params['file_url'])) { return new PwgError(WS_ERR_INVALID_PARAM, l10n('File URL is empty')); } // check remote url if (!url_is_remote($params['file_url'])) { return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file URL')); } // check file extension if (!in_array(strtolower(get_extension($params['file_url'])), $allowed_extensions)) { return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file type')); } // download file include_once PHPWG_ROOT_PATH . 'admin/include/functions.php'; $temp_filename = $conf['data_location'] . basename($params['file_url']); $file = fopen($temp_filename, 'w+'); $result = fetchRemote($params['file_url'], $file); fclose($file); // download failed ? if (!$result) { @unlink($temp_filename); return new PwgError(WS_ERR_INVALID_PARAM, l10n('Unable to download file')); } // check mime-type if (!in_array(get_mime($temp_filename, $allowed_mimes[0]), $allowed_mimes)) { @unlink($temp_filename); return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file type')); } // add photo include_once PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php'; $image_id = add_uploaded_file($temp_filename, basename($temp_filename), array($params['category']), $params['level']); $updates = array(); if (!empty($params['name'])) { $updates['name'] = $params['name']; } if ($params['url_in_comment'] == 'true') { $url = parse_url($params['file_url']); $url = $url['scheme'] . '://' . $url['host']; $updates['comment'] = '<a href="' . $url . '">' . $url . '</a>'; } single_update(IMAGES_TABLE, $updates, array('id' => $image_id)); // return infos $query = ' SELECT id, name, permalink FROM ' . CATEGORIES_TABLE . ' WHERE id = ' . $params['category'] . ' ;'; $category = pwg_db_fetch_assoc(pwg_query($query)); $url_params = array('image_id' => $image_id, 'section' => 'categories', 'category' => $category); $query = ' SELECT id, path, name FROM ' . IMAGES_TABLE . ' WHERE id = ' . $image_id . ' ;'; $image_infos = pwg_db_fetch_assoc(pwg_query($query)); $query = ' SELECT COUNT(*) AS nb_photos FROM ' . IMAGE_CATEGORY_TABLE . ' WHERE category_id = ' . $params['category'] . ' ;'; $category_infos = pwg_db_fetch_assoc(pwg_query($query)); $category_name = get_cat_display_name_from_id($params['category'], null); return array('image_id' => $image_id, 'url' => make_picture_url($url_params), 'src' => DerivativeImage::thumb_url($image_infos), 'name' => $image_infos['name'], 'category' => array('id' => $params['category'], 'nb_photos' => $category_infos['nb_photos'], 'label' => $category_name)); }
// webmaster admin user $inserts = array(array('id' => 1, 'username' => $admin_name, 'password' => md5($admin_pass1), 'mail_address' => $admin_mail), array('id' => 2, 'username' => 'guest')); mass_inserts(USERS_TABLE, array_keys($inserts[0]), $inserts); create_user_infos(array(1, 2), array('language' => $language)); // Available upgrades must be ignored after a fresh installation. To // make PWG avoid upgrading, we must tell it upgrades have already been // made. list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();')); define('CURRENT_DATE', $dbnow); $datas = array(); foreach (get_available_upgrade_ids() as $upgrade_id) { $datas[] = array('id' => $upgrade_id, 'applied' => CURRENT_DATE, 'description' => 'upgrade included in installation'); } mass_inserts(UPGRADE_TABLE, array_keys($datas[0]), $datas); if ($is_newsletter_subscribe) { fetchRemote(get_newsletter_subscribe_base_url($language) . $admin_mail, $result, array(), array('origin' => 'installation')); } } } //------------------------------------------------------ start template output foreach ($languages->fs_languages as $language_code => $fs_language) { if ($language == $language_code) { $template->assign('language_selection', $language_code); } $languages_options[$language_code] = $fs_language['name']; } $template->assign('language_options', $languages_options); $template->assign(array('T_CONTENT_ENCODING' => 'utf-8', 'RELEASE' => PHPWG_VERSION, 'F_ACTION' => 'install.php?language=' . $language, 'F_DB_HOST' => $dbhost, 'F_DB_USER' => $dbuser, 'F_DB_NAME' => $dbname, 'F_DB_PREFIX' => $prefixeTable, 'F_ADMIN' => $admin_name, 'F_ADMIN_EMAIL' => $admin_mail, 'EMAIL' => '<span class="adminEmail">' . $admin_mail . '</span>', 'F_NEWSLETTER_SUBSCRIBE' => $is_newsletter_subscribe, 'L_INSTALL_HELP' => l10n('Need help ? Ask your question on <a href="%s">Piwigo message board</a>.', PHPWG_URL . '/forum'))); //------------------------------------------------------ errors & infos display if ($step == 1) { $template->assign('install', true);
/** * Extract theme files from archive * * @param string - install or upgrade * @param string - remote revision identifier (numeric) * @param string - theme id or extension id */ function extract_theme_files($action, $revision, $dest) { if ($archive = tempnam(PHPWG_THEMES_PATH, 'zip')) { $url = PEM_URL . '/download.php'; $get_data = array('rid' => $revision, 'origin' => 'piwigo_' . $action); if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data)) { fclose($handle); include_once PHPWG_ROOT_PATH . 'admin/include/pclzip.lib.php'; $zip = new PclZip($archive); if ($list = $zip->listContent()) { foreach ($list as $file) { // we search main.inc.php in archive if (basename($file['filename']) == 'themeconf.inc.php' and (!isset($main_filepath) or strlen($file['filename']) < strlen($main_filepath))) { $main_filepath = $file['filename']; } } if (isset($main_filepath)) { $root = dirname($main_filepath); // main.inc.php path in archive if ($action == 'upgrade') { $extract_path = PHPWG_THEMES_PATH . $dest; } else { $extract_path = PHPWG_THEMES_PATH . ($root == '.' ? 'extension_' . $dest : basename($root)); } if ($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path, PCLZIP_OPT_REMOVE_PATH, $root, PCLZIP_OPT_REPLACE_NEWER)) { foreach ($result as $file) { if ($file['stored_filename'] == $main_filepath) { $status = $file['status']; break; } } if (file_exists($extract_path . '/obsolete.list') and $old_files = file($extract_path . '/obsolete.list', FILE_IGNORE_NEW_LINES) and !empty($old_files)) { $old_files[] = 'obsolete.list'; foreach ($old_files as $old_file) { $path = $extract_path . '/' . $old_file; if (is_file($path)) { @unlink($path); } elseif (is_dir($path)) { deltree($path, PHPWG_THEMES_PATH . 'trash'); } } } } else { $status = 'extract_error'; } } else { $status = 'archive_error'; } } else { $status = 'archive_error'; } } else { $status = 'dl_archive_error'; } } else { $status = 'temp_path_error'; } @unlink($archive); return $status; }
/** * Extract language files from archive * * @param string - install or upgrade * @param string - remote revision identifier (numeric) * @param string - language id or extension id */ function extract_language_files($action, $revision, $dest = '') { if ($archive = tempnam(PHPWG_ROOT_PATH . 'language', 'zip')) { $url = PEM_URL . '/download.php'; $get_data = array('rid' => $revision, 'origin' => 'piwigo_' . $action); if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data)) { fclose($handle); include_once PHPWG_ROOT_PATH . 'admin/include/pclzip.lib.php'; $zip = new PclZip($archive); if ($list = $zip->listContent()) { foreach ($list as $file) { // we search common.lang.php in archive if (basename($file['filename']) == 'common.lang.php' and (!isset($main_filepath) or strlen($file['filename']) < strlen($main_filepath))) { $main_filepath = $file['filename']; } } if (isset($main_filepath)) { $root = basename(dirname($main_filepath)); // common.lang.php path in archive if (preg_match('/^[a-z]{2}_[A-Z]{2}$/', $root)) { if ($action == 'install') { $dest = $root; } $extract_path = PHPWG_ROOT_PATH . 'language/' . $dest; if ($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path, PCLZIP_OPT_REMOVE_PATH, $root, PCLZIP_OPT_REPLACE_NEWER)) { foreach ($result as $file) { if ($file['stored_filename'] == $main_filepath) { $status = $file['status']; break; } } if ($status == 'ok') { $this->get_fs_languages(); if ($action == 'install') { $this->perform_action('activate', $dest); } } if (file_exists($extract_path . '/obsolete.list') and $old_files = file($extract_path . '/obsolete.list', FILE_IGNORE_NEW_LINES) and !empty($old_files)) { $old_files[] = 'obsolete.list'; foreach ($old_files as $old_file) { $path = $extract_path . '/' . $old_file; if (is_file($path)) { @unlink($path); } elseif (is_dir($path)) { deltree($path, PHPWG_ROOT_PATH . 'language/trash'); } } } } else { $status = 'extract_error'; } } else { $status = 'archive_error'; } } else { $status = 'archive_error'; } } else { $status = 'archive_error'; } } else { $status = 'dl_archive_error'; } } else { $status = 'temp_path_error'; } @unlink($archive); return $status; }
/** * Retrieve data from external URL. * * @param string $src * @param string|Ressource $dest - can be a file ressource or string * @param array $get_data - data added to request url * @param array $post_data - data transmitted with POST * @param string $user_agent * @param int $step (internal use) * @return bool */ function fetchRemote($src, &$dest, $get_data = array(), $post_data = array(), $user_agent = 'Piwigo', $step = 0) { // Try to retrieve data from local file? if (!url_is_remote($src)) { $content = @file_get_contents($src); if ($content !== false) { is_resource($dest) ? @fwrite($dest, $content) : ($dest = $content); return true; } else { return false; } } // After 3 redirections, return false if ($step > 3) { return false; } // Initialization $method = empty($post_data) ? 'GET' : 'POST'; $request = empty($post_data) ? '' : http_build_query($post_data, '', '&'); if (!empty($get_data)) { $src .= strpos($src, '?') === false ? '?' : '&'; $src .= http_build_query($get_data, '', '&'); } // Initialize $dest is_resource($dest) or $dest = ''; // Try curl to read remote file // TODO : remove all these @ if (function_exists('curl_init') && function_exists('curl_exec')) { $ch = @curl_init(); @curl_setopt($ch, CURLOPT_URL, $src); @curl_setopt($ch, CURLOPT_HEADER, 1); @curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($method == 'POST') { @curl_setopt($ch, CURLOPT_POST, 1); @curl_setopt($ch, CURLOPT_POSTFIELDS, $request); } $content = @curl_exec($ch); $header_length = @curl_getinfo($ch, CURLINFO_HEADER_SIZE); $status = @curl_getinfo($ch, CURLINFO_HTTP_CODE); @curl_close($ch); if ($content !== false and $status >= 200 and $status < 400) { if (preg_match('/Location:\\s+?(.+)/', substr($content, 0, $header_length), $m)) { return fetchRemote($m[1], $dest, array(), array(), $user_agent, $step + 1); } $content = substr($content, $header_length); is_resource($dest) ? @fwrite($dest, $content) : ($dest = $content); return true; } } // Try file_get_contents to read remote file if (ini_get('allow_url_fopen')) { $opts = array('http' => array('method' => $method, 'user_agent' => $user_agent)); if ($method == 'POST') { $opts['http']['content'] = $request; } $context = @stream_context_create($opts); $content = @file_get_contents($src, false, $context); if ($content !== false) { is_resource($dest) ? @fwrite($dest, $content) : ($dest = $content); return true; } } // Try fsockopen to read remote file $src = parse_url($src); $host = $src['host']; $path = isset($src['path']) ? $src['path'] : '/'; $path .= isset($src['query']) ? '?' . $src['query'] : ''; if (($s = @fsockopen($host, 80, $errno, $errstr, 5)) === false) { return false; } $http_request = $method . " " . $path . " HTTP/1.0\r\n"; $http_request .= "Host: " . $host . "\r\n"; if ($method == 'POST') { $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($request) . "\r\n"; } $http_request .= "User-Agent: " . $user_agent . "\r\n"; $http_request .= "Accept: */*\r\n"; $http_request .= "\r\n"; $http_request .= $request; fwrite($s, $http_request); $i = 0; $in_content = false; while (!feof($s)) { $line = fgets($s); if (rtrim($line, "\r\n") == '' && !$in_content) { $in_content = true; $i++; continue; } if ($i == 0) { if (!preg_match('/HTTP\\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', rtrim($line, "\r\n"), $m)) { fclose($s); return false; } $status = (int) $m[2]; if ($status < 200 || $status >= 400) { fclose($s); return false; } } if (!$in_content) { if (preg_match('/Location:\\s+?(.+)$/', rtrim($line, "\r\n"), $m)) { fclose($s); return fetchRemote(trim($m[1]), $dest, array(), array(), $user_agent, $step + 1); } $i++; continue; } is_resource($dest) ? @fwrite($dest, $line) : ($dest .= $line); $i++; } fclose($s); return true; }
/** * Fetch the file at $url in the destination $pathDestination * @param string $url * @param string $pathDestination * @param int $tries * @return true on success, throws Exception on failure */ public static function fetchRemoteFile($url, $pathDestination, $tries = 0) { if ($tries > 3) { return false; } $file = @fopen($pathDestination, 'wb'); if (!$file) { throw new Exception("Error while creating the file: " . $file); } $url = parse_url($url); $host = $url['host']; $path = $url['path']; if (($s = @fsockopen($host, $port = 80, $errno, $errstr, $timeout = 10)) === false) { throw new Exception("Error while connecting to: {$host}. Please try again later."); } fwrite($s, 'GET ' . $path . " HTTP/1.0\r\n" . 'Host: ' . $host . "\r\n" . "User-Agent: Piwik Update\r\n" . "\r\n"); $i = 0; $in_content = false; while (!feof($s)) { $line = fgets($s, 4096); if (rtrim($line, "\r\n") == '' && !$in_content) { $in_content = true; $i++; continue; } if ($i == 0) { if (!preg_match('/HTTP\\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', rtrim($line, "\r\n"), $m)) { fclose($s); return false; } $status = (int) $m[2]; if ($status < 200 || $status >= 400) { fclose($s); return false; } } if (!$in_content) { if (preg_match('/Location:\\s+?(.+)$/', rtrim($line, "\r\n"), $m)) { fclose($s); return fetchRemote(trim($m[1]), $pathDestination, $tries + 1); } $i++; continue; } if (is_resource($file)) { fwrite($file, $line); } $i++; } fclose($s); return true; }
static function upgrade_to($upgrade_to, &$step, $check_current_version = true) { global $page, $conf, $template; if ($check_current_version and !version_compare($upgrade_to, PHPWG_VERSION, '>')) { redirect(get_root_url() . 'admin.php?page=plugin-' . basename(dirname(__FILE__))); } if ($step == 2) { preg_match('/(\\d+\\.\\d+)\\.(\\d+)/', PHPWG_VERSION, $matches); $code = $matches[1] . '.x_to_' . $upgrade_to; $dl_code = str_replace(array('.', '_'), '', $code); $remove_path = $code; $obsolete_list = 'obsolete.list'; } else { $code = $upgrade_to; $dl_code = $code; $remove_path = version_compare($code, '2.0.8', '>=') ? 'piwigo' : 'piwigo-' . $code; $obsolete_list = PHPWG_ROOT_PATH . 'install/obsolete.list'; } if (empty($page['errors'])) { $path = PHPWG_ROOT_PATH . $conf['data_location'] . 'update'; $filename = $path . '/' . $code . '.zip'; @mkgetdir($path); $chunk_num = 0; $end = false; $zip = @fopen($filename, 'w'); while (!$end) { $chunk_num++; if (@fetchRemote(PHPWG_URL . '/download/dlcounter.php?code=' . $dl_code . '&chunk_num=' . $chunk_num, $result) and $input = @unserialize($result)) { if (0 == $input['remaining']) { $end = true; } @fwrite($zip, base64_decode($input['data'])); } else { $end = true; } } @fclose($zip); if (@filesize($filename)) { $zip = new PclZip($filename); if ($result = $zip->extract(PCLZIP_OPT_PATH, PHPWG_ROOT_PATH, PCLZIP_OPT_REMOVE_PATH, $remove_path, PCLZIP_OPT_SET_CHMOD, 0755, PCLZIP_OPT_REPLACE_NEWER)) { //Check if all files were extracted $error = ''; foreach ($result as $extract) { if (!in_array($extract['status'], array('ok', 'filtered', 'already_a_directory'))) { // Try to change chmod and extract if (@chmod(PHPWG_ROOT_PATH . $extract['filename'], 0777) and $res = $zip->extract(PCLZIP_OPT_BY_NAME, $remove_path . '/' . $extract['filename'], PCLZIP_OPT_PATH, PHPWG_ROOT_PATH, PCLZIP_OPT_REMOVE_PATH, $remove_path, PCLZIP_OPT_SET_CHMOD, 0755, PCLZIP_OPT_REPLACE_NEWER) and isset($res[0]['status']) and $res[0]['status'] == 'ok') { continue; } else { $error .= $extract['filename'] . ': ' . $extract['status'] . "\n"; } } } if (empty($error)) { self::process_obsolete_list($obsolete_list); deltree(PHPWG_ROOT_PATH . $conf['data_location'] . 'update'); invalidate_user_cache(true); $template->delete_compiled_templates(); unset($_SESSION['need_update']); if ($step == 2) { $page['infos'][] = l10n('Update Complete'); $page['infos'][] = $upgrade_to; $step = -1; } else { redirect(PHPWG_ROOT_PATH . 'upgrade.php?now='); } } else { file_put_contents(PHPWG_ROOT_PATH . $conf['data_location'] . 'update/log_error.txt', $error); $page['errors'][] = l10n('An error has occured during extract. Please check files permissions of your piwigo installation.<br><a href="%s">Click here to show log error</a>.', get_root_url() . $conf['data_location'] . 'update/log_error.txt'); } } else { deltree(PHPWG_ROOT_PATH . $conf['data_location'] . 'update'); $page['errors'][] = l10n('An error has occured during upgrade.'); } } else { $page['errors'][] = l10n('Piwigo cannot retrieve upgrade file from server'); } } }
die("Hacking attempt!"); } include_once PHPWG_ROOT_PATH . 'admin/include/functions.php'; include_once PHPWG_ROOT_PATH . 'admin/include/check_integrity.class.php'; include_once PHPWG_ROOT_PATH . 'admin/include/c13y_internal.class.php'; include_once PHPWG_ROOT_PATH . 'admin/include/image.class.php'; // +-----------------------------------------------------------------------+ // | Check Access and exit when user status is not ok | // +-----------------------------------------------------------------------+ check_status(ACCESS_ADMINISTRATOR); // +-----------------------------------------------------------------------+ // | actions | // +-----------------------------------------------------------------------+ // Check for upgrade : code inspired from punbb if (isset($_GET['action']) and 'check_upgrade' == $_GET['action']) { if (!fetchRemote(PHPWG_URL . '/download/latest_version', $result)) { $page['errors'][] = l10n('Unable to check for upgrade.'); } else { $versions = array('current' => PHPWG_VERSION); $lines = @explode("\r\n", $result); // if the current version is a BSF (development branch) build, we check // the first line, for stable versions, we check the second line if (preg_match('/^BSF/', $versions['current'])) { $versions['latest'] = trim($lines[0]); // because integer are limited to 4,294,967,296 we need to split BSF // versions in date.time foreach ($versions as $key => $value) { $versions[$key] = preg_replace('/BSF_(\\d{8})(\\d{4})/', '$1.$2', $value); } } else { $versions['latest'] = trim($lines[1]);
1 = new version on same branch AND new branch are available => user may choose upgrade. 2 = upgrade on same branch 3 = upgrade on different branch */ $step = isset($_GET['step']) ? $_GET['step'] : 0; $upgrade_to = isset($_GET['to']) ? $_GET['to'] : ''; // +-----------------------------------------------------------------------+ // | Step 0 | // +-----------------------------------------------------------------------+ if ($step == 0) { $template->assign(array('CHECK_VERSION' => false, 'DEV_VERSION' => false)); if (preg_match('/(\\d+\\.\\d+)\\.(\\d+)/', PHPWG_VERSION, $matches)) { $url = PHPWG_URL . '/download/all_versions.php'; $url .= '?rand=' . md5(uniqid(rand(), true)); // Avoid server cache if (@fetchRemote($url, $result) and $all_versions = @explode("\n", $result) and is_array($all_versions)) { $template->assign('CHECK_VERSION', true); $last_version = trim($all_versions[0]); $upgrade_to = $last_version; if (version_compare(PHPWG_VERSION, $last_version, '<')) { $new_branch = preg_replace('/(\\d+\\.\\d+)\\.\\d+/', '$1', $last_version); $actual_branch = $matches[1]; if ($new_branch == $actual_branch) { $step = 2; } else { $step = 3; // Check if new version exists in same branch foreach ($all_versions as $version) { $new_branch = preg_replace('/(\\d+\\.\\d+)\\.\\d+/', '$1', $version); if ($new_branch == $actual_branch) { if (version_compare(PHPWG_VERSION, $version, '<')) {
function add_uploaded_file($source_filepath, $original_filename = null, $categories = null, $level = null, $image_id = null, $original_md5sum = null) { // 1) move uploaded file to upload/2010/01/22/20100122003814-449ada00.jpg // // 2) keep/resize original // // 3) register in database // TODO // * check md5sum (already exists?) global $conf, $user; if (isset($original_md5sum)) { $md5sum = $original_md5sum; } else { $md5sum = md5_file($source_filepath); } $file_path = null; $is_tiff = false; if (isset($image_id)) { // this photo already exists, we update it $query = ' SELECT path FROM ' . IMAGES_TABLE . ' WHERE id = ' . $image_id . ' ;'; $result = pwg_query($query); while ($row = pwg_db_fetch_assoc($result)) { $file_path = $row['path']; } if (!isset($file_path)) { die('[' . __FUNCTION__ . '] this photo does not exist in the database'); } // delete all physical files related to the photo (thumbnail, web site, HD) delete_element_files(array($image_id)); } else { // this photo is new // current date list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();')); list($year, $month, $day) = preg_split('/[^\\d]/', $dbnow, 4); // upload directory hierarchy $upload_dir = sprintf(PHPWG_ROOT_PATH . $conf['upload_dir'] . '/%s/%s/%s', $year, $month, $day); // compute file path $date_string = preg_replace('/[^\\d]/', '', $dbnow); $random_string = substr($md5sum, 0, 8); $filename_wo_ext = $date_string . '-' . $random_string; $file_path = $upload_dir . '/' . $filename_wo_ext . '.'; list($width, $height, $type) = getimagesize($source_filepath); if (IMAGETYPE_PNG == $type) { $file_path .= 'png'; } elseif (IMAGETYPE_GIF == $type) { $file_path .= 'gif'; } elseif (IMAGETYPE_TIFF_MM == $type or IMAGETYPE_TIFF_II == $type) { $is_tiff = true; $file_path .= 'tif'; } elseif (IMAGETYPE_JPEG == $type) { $file_path .= 'jpg'; } elseif (isset($conf['upload_form_all_types']) and $conf['upload_form_all_types']) { $original_extension = strtolower(get_extension($original_filename)); if (in_array($original_extension, $conf['file_ext'])) { $file_path .= $original_extension; } else { die('unexpected file type'); } } else { die('forbidden file type'); } prepare_directory($upload_dir); } if (is_uploaded_file($source_filepath)) { move_uploaded_file($source_filepath, $file_path); } else { rename($source_filepath, $file_path); } @chmod($file_path, 0644); if ($is_tiff and pwg_image::get_library() == 'ext_imagick') { // move the uploaded file to pwg_representative sub-directory $representative_file_path = dirname($file_path) . '/pwg_representative/'; $representative_file_path .= get_filename_wo_extension(basename($file_path)) . '.'; $representative_ext = $conf['tiff_representative_ext']; $representative_file_path .= $representative_ext; prepare_directory(dirname($representative_file_path)); $exec = $conf['ext_imagick_dir'] . 'convert'; if ('jpg' == $conf['tiff_representative_ext']) { $exec .= ' -quality 98'; } $exec .= ' "' . realpath($file_path) . '"'; $dest = pathinfo($representative_file_path); $exec .= ' "' . realpath($dest['dirname']) . '/' . $dest['basename'] . '"'; $exec .= ' 2>&1'; @exec($exec, $returnarray); // sometimes ImageMagick creates file-0.jpg (full size) + file-1.jpg // (thumbnail). I don't know how to avoid it. $representative_file_abspath = realpath($dest['dirname']) . '/' . $dest['basename']; if (!file_exists($representative_file_abspath)) { $first_file_abspath = preg_replace('/\\.' . $representative_ext . '$/', '-0.' . $representative_ext, $representative_file_abspath); if (file_exists($first_file_abspath)) { rename($first_file_abspath, $representative_file_abspath); } } } // // generate pwg_representative in case of video // $ffmpeg_video_exts = array('wmv', 'mov', 'mkv', 'mp4', 'mpg', 'flv', 'asf', 'xvid', 'divx', 'mpeg', 'avi', 'rm'); if (isset($original_extension) and in_array($original_extension, $ffmpeg_video_exts)) { $representative_file_path = dirname($file_path) . '/pwg_representative/'; $representative_file_path .= get_filename_wo_extension(basename($file_path)) . '.'; $representative_ext = 'jpg'; $representative_file_path .= $representative_ext; prepare_directory(dirname($representative_file_path)); $second = 1; $ffmpeg = $conf['ffmpeg_dir'] . 'ffmpeg'; $ffmpeg .= ' -i "' . $file_path . '"'; $ffmpeg .= ' -an -ss ' . $second; $ffmpeg .= ' -t 1 -r 1 -y -vcodec mjpeg -f mjpeg'; $ffmpeg .= ' "' . $representative_file_path . '"'; // file_put_contents('/tmp/ffmpeg.log', "\n==== ".date('c')."\n".__FUNCTION__.' : '.$ffmpeg."\n", FILE_APPEND); @exec($ffmpeg); if (!file_exists($representative_file_path)) { $representative_ext = null; } } if (isset($original_extension) and 'pdf' == $original_extension and pwg_image::get_library() == 'ext_imagick') { $representative_file_path = dirname($file_path) . '/pwg_representative/'; $representative_file_path .= get_filename_wo_extension(basename($file_path)) . '.'; $representative_ext = 'jpg'; $representative_file_path .= $representative_ext; prepare_directory(dirname($representative_file_path)); $exec = $conf['ext_imagick_dir'] . 'convert'; $exec .= ' -quality 98'; $exec .= ' "' . realpath($file_path) . '"[0]'; $dest = pathinfo($representative_file_path); $exec .= ' "' . realpath($dest['dirname']) . '/' . $dest['basename'] . '"'; $exec .= ' 2>&1'; @exec($exec, $returnarray); } if (pwg_image::get_library() != 'gd') { if ($conf['original_resize']) { $need_resize = need_resize($file_path, $conf['original_resize_maxwidth'], $conf['original_resize_maxheight']); if ($need_resize) { $img = new pwg_image($file_path); $img->pwg_resize($file_path, $conf['original_resize_maxwidth'], $conf['original_resize_maxheight'], $conf['original_resize_quality'], $conf['upload_form_automatic_rotation'], false); $img->destroy(); } } } // we need to save the rotation angle in the database to compute // width/height of "multisizes" $rotation_angle = pwg_image::get_rotation_angle($file_path); $rotation = pwg_image::get_rotation_code_from_angle($rotation_angle); $file_infos = pwg_image_infos($file_path); if (isset($image_id)) { $update = array('file' => pwg_db_real_escape_string(isset($original_filename) ? $original_filename : basename($file_path)), 'filesize' => $file_infos['filesize'], 'width' => $file_infos['width'], 'height' => $file_infos['height'], 'md5sum' => $md5sum, 'added_by' => $user['id'], 'rotation' => $rotation); if (isset($level)) { $update['level'] = $level; } single_update(IMAGES_TABLE, $update, array('id' => $image_id)); } else { // database registration $file = pwg_db_real_escape_string(isset($original_filename) ? $original_filename : basename($file_path)); $insert = array('file' => $file, 'name' => get_name_from_file($file), 'date_available' => $dbnow, 'path' => preg_replace('#^' . preg_quote(PHPWG_ROOT_PATH) . '#', '', $file_path), 'filesize' => $file_infos['filesize'], 'width' => $file_infos['width'], 'height' => $file_infos['height'], 'md5sum' => $md5sum, 'added_by' => $user['id'], 'rotation' => $rotation); if (isset($level)) { $insert['level'] = $level; } if (isset($representative_ext)) { $insert['representative_ext'] = $representative_ext; } single_insert(IMAGES_TABLE, $insert); $image_id = pwg_db_insert_id(IMAGES_TABLE); } if (isset($categories) and count($categories) > 0) { associate_images_to_categories(array($image_id), $categories); } // update metadata from the uploaded file (exif/iptc) if ($conf['use_exif'] and !function_exists('read_exif_data')) { $conf['use_exif'] = false; } sync_metadata(array($image_id)); invalidate_user_cache(); // cache thumbnail $query = ' SELECT id, path FROM ' . IMAGES_TABLE . ' WHERE id = ' . $image_id . ' ;'; $image_infos = pwg_db_fetch_assoc(pwg_query($query)); set_make_full_url(); // in case we are on uploadify.php, we have to replace the false path $thumb_url = preg_replace('#admin/include/i#', 'i', DerivativeImage::thumb_url($image_infos)); unset_make_full_url(); fetchRemote($thumb_url, $dest); return $image_id; }
function add_uploaded_file($source_filepath, $original_filename = null, $categories = null, $level = null, $image_id = null, $original_md5sum = null) { // 1) move uploaded file to upload/2010/01/22/20100122003814-449ada00.jpg // // 2) keep/resize original // // 3) register in database // TODO // * check md5sum (already exists?) global $conf, $user; if (isset($original_md5sum)) { $md5sum = $original_md5sum; } else { $md5sum = md5_file($source_filepath); } $file_path = null; $is_tiff = false; if (isset($image_id)) { // this photo already exists, we update it $query = ' SELECT path FROM ' . IMAGES_TABLE . ' WHERE id = ' . $image_id . ' ;'; $result = pwg_query($query); while ($row = pwg_db_fetch_assoc($result)) { $file_path = $row['path']; } if (!isset($file_path)) { die('[' . __FUNCTION__ . '] this photo does not exist in the database'); } // delete all physical files related to the photo (thumbnail, web site, HD) delete_element_files(array($image_id)); } else { // this photo is new // current date list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();')); list($year, $month, $day) = preg_split('/[^\\d]/', $dbnow, 4); // upload directory hierarchy $upload_dir = sprintf(PHPWG_ROOT_PATH . $conf['upload_dir'] . '/%s/%s/%s', $year, $month, $day); // compute file path $date_string = preg_replace('/[^\\d]/', '', $dbnow); $random_string = substr($md5sum, 0, 8); $filename_wo_ext = $date_string . '-' . $random_string; $file_path = $upload_dir . '/' . $filename_wo_ext . '.'; list($width, $height, $type) = getimagesize($source_filepath); if (IMAGETYPE_PNG == $type) { $file_path .= 'png'; } elseif (IMAGETYPE_GIF == $type) { $file_path .= 'gif'; } elseif (IMAGETYPE_TIFF_MM == $type or IMAGETYPE_TIFF_II == $type) { $is_tiff = true; $file_path .= 'tif'; } elseif (IMAGETYPE_JPEG == $type) { $file_path .= 'jpg'; } elseif (isset($conf['upload_form_all_types']) and $conf['upload_form_all_types']) { $original_extension = strtolower(get_extension($original_filename)); if (in_array($original_extension, $conf['file_ext'])) { $file_path .= $original_extension; } else { die('unexpected file type'); } } else { die('forbidden file type'); } prepare_directory($upload_dir); } if (is_uploaded_file($source_filepath)) { move_uploaded_file($source_filepath, $file_path); } else { rename($source_filepath, $file_path); } @chmod($file_path, 0644); // handle the uploaded file type by potentially making a // pwg_representative file. $representative_ext = trigger_change('upload_file', null, $file_path); global $logger; $logger->info("Handling " . (string) $file_path . " got " . (string) $representative_ext); // If it is set to either true (the file didn't need a // representative generated) or false (the generation of the // representative failed), set it to null because we have no // representative file. if (is_bool($representative_ext)) { $representative_ext = null; } if (pwg_image::get_library() != 'gd') { if ($conf['original_resize']) { $need_resize = need_resize($file_path, $conf['original_resize_maxwidth'], $conf['original_resize_maxheight']); if ($need_resize) { $img = new pwg_image($file_path); $img->pwg_resize($file_path, $conf['original_resize_maxwidth'], $conf['original_resize_maxheight'], $conf['original_resize_quality'], $conf['upload_form_automatic_rotation'], false); $img->destroy(); } } } // we need to save the rotation angle in the database to compute // width/height of "multisizes" $rotation_angle = pwg_image::get_rotation_angle($file_path); $rotation = pwg_image::get_rotation_code_from_angle($rotation_angle); $file_infos = pwg_image_infos($file_path); if (isset($image_id)) { $update = array('file' => pwg_db_real_escape_string(isset($original_filename) ? $original_filename : basename($file_path)), 'filesize' => $file_infos['filesize'], 'width' => $file_infos['width'], 'height' => $file_infos['height'], 'md5sum' => $md5sum, 'added_by' => $user['id'], 'rotation' => $rotation); if (isset($level)) { $update['level'] = $level; } single_update(IMAGES_TABLE, $update, array('id' => $image_id)); } else { // database registration $file = pwg_db_real_escape_string(isset($original_filename) ? $original_filename : basename($file_path)); $insert = array('file' => $file, 'name' => get_name_from_file($file), 'date_available' => $dbnow, 'path' => preg_replace('#^' . preg_quote(PHPWG_ROOT_PATH) . '#', '', $file_path), 'filesize' => $file_infos['filesize'], 'width' => $file_infos['width'], 'height' => $file_infos['height'], 'md5sum' => $md5sum, 'added_by' => $user['id'], 'rotation' => $rotation); if (isset($level)) { $insert['level'] = $level; } if (isset($representative_ext)) { $insert['representative_ext'] = $representative_ext; } single_insert(IMAGES_TABLE, $insert); $image_id = pwg_db_insert_id(IMAGES_TABLE); } if (isset($categories) and count($categories) > 0) { associate_images_to_categories(array($image_id), $categories); } // update metadata from the uploaded file (exif/iptc) if ($conf['use_exif'] and !function_exists('read_exif_data')) { $conf['use_exif'] = false; } sync_metadata(array($image_id)); invalidate_user_cache(); // cache thumbnail $query = ' SELECT id, path FROM ' . IMAGES_TABLE . ' WHERE id = ' . $image_id . ' ;'; $image_infos = pwg_db_fetch_assoc(pwg_query($query)); set_make_full_url(); // in case we are on uploadify.php, we have to replace the false path $thumb_url = preg_replace('#admin/include/i#', 'i', DerivativeImage::thumb_url($image_infos)); unset_make_full_url(); fetchRemote($thumb_url, $dest); return $image_id; }