Ejemplo n.º 1
0
/**
 * Triggered on loc_begin_index
 * 
 * Perform user logout after registration if account locked and redirection to profile page is password renewal is set
 */
function PP_Init()
{
    global $conf, $user;
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    $conf_PP = unserialize($conf['PasswordPolicy']);
    // Perfoming redirection for locked accounts
    // -----------------------------------------
    if (!is_a_guest() and $user['username'] != "16" and $user['username'] != "18") {
        // Perform user logout if user account is locked
        if (isset($conf_PP['LOGFAILBLOCK']) and $conf_PP['LOGFAILBLOCK'] == 'true' and PP_UsrBlock_Verif($user['username']) and !is_admin() and !is_webmaster()) {
            invalidate_user_cache();
            logout_user();
            if ($conf['guest_access']) {
                redirect(make_index_url() . '?PP_msg=locked', 0);
            } else {
                redirect(get_root_url() . 'identification.php?PP_msg=locked', 0);
            }
        }
    }
    // Performing redirection to profile page for password reset
    // ---------------------------------------------------------
    if (isset($conf_PP['PWDRESET']) and $conf_PP['PWDRESET'] == 'true') {
        $query = '
SELECT user_id, status
FROM ' . USER_INFOS_TABLE . '
WHERE user_id = ' . $user['id'] . '
;';
        $data = pwg_db_fetch_assoc(pwg_query($query));
        if ($data['status'] != "webmaster" and $data['status'] != "generic") {
            if (PP_check_pwdreset($user['id'])) {
                redirect(PHPWG_ROOT_PATH . 'profile.php');
            }
        }
    }
}
Ejemplo n.º 2
0
// |                    virtual categories management                      |
// +-----------------------------------------------------------------------+
// request to delete a virtual category
if (isset($_GET['delete']) and is_numeric($_GET['delete'])) {
    delete_categories(array($_GET['delete']));
    $_SESSION['page_infos'] = array(l10n('Virtual album deleted'));
    update_global_rank();
    invalidate_user_cache();
    $redirect_url = get_root_url() . 'admin.php?page=cat_list';
    if (isset($_GET['parent_id'])) {
        $redirect_url .= '&parent_id=' . $_GET['parent_id'];
    }
    redirect($redirect_url);
} elseif (isset($_POST['submitAdd'])) {
    $output_create = create_virtual_category($_POST['virtual_name'], @$_GET['parent_id']);
    invalidate_user_cache();
    if (isset($output_create['error'])) {
        $page['errors'][] = $output_create['error'];
    } else {
        $page['infos'][] = $output_create['info'];
    }
} elseif (isset($_POST['submitManualOrder'])) {
    asort($_POST['catOrd'], SORT_NUMERIC);
    save_categories_order(array_keys($_POST['catOrd']));
    $page['infos'][] = l10n('Album manual order was saved');
} elseif (isset($_POST['submitAutoOrder'])) {
    if (!isset($sort_orders[$_POST['order_by']])) {
        die('Invalid sort order');
    }
    $query = '
SELECT id
/**
 * API method
 * Moves a category
 * @param mixed[] $params
 *    @option string|int[] category_id
 *    @option int parent
 *    @option string pwg_token
 */
function ws_categories_move($params, &$service)
{
    global $page;
    if (get_pwg_token() != $params['pwg_token']) {
        return new PwgError(403, 'Invalid security token');
    }
    if (!is_array($params['category_id'])) {
        $params['category_id'] = preg_split('/[\\s,;\\|]/', $params['category_id'], -1, PREG_SPLIT_NO_EMPTY);
    }
    $params['category_id'] = array_map('intval', $params['category_id']);
    $category_ids = array();
    foreach ($params['category_id'] as $category_id) {
        if ($category_id > 0) {
            $category_ids[] = $category_id;
        }
    }
    if (count($category_ids) == 0) {
        return new PwgError(403, 'Invalid category_id input parameter, no category to move');
    }
    // we can't move physical categories
    $categories_in_db = array();
    $query = '
SELECT id, name, dir
  FROM ' . CATEGORIES_TABLE . '
  WHERE id IN (' . implode(',', $category_ids) . ')
;';
    $result = pwg_query($query);
    while ($row = pwg_db_fetch_assoc($result)) {
        $categories_in_db[$row['id']] = $row;
        // we break on error at first physical category detected
        if (!empty($row['dir'])) {
            $row['name'] = strip_tags(trigger_change('render_category_name', $row['name'], 'ws_categories_move'));
            return new PwgError(403, sprintf('Category %s (%u) is not a virtual category, you cannot move it', $row['name'], $row['id']));
        }
    }
    if (count($categories_in_db) != count($category_ids)) {
        $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
        return new PwgError(403, sprintf('Category %u does not exist', $unknown_category_ids[0]));
    }
    // does this parent exists? This check should be made in the
    // move_categories function, not here
    // 0 as parent means "move categories at gallery root"
    if (0 != $params['parent']) {
        $subcat_ids = get_subcat_ids(array($params['parent']));
        if (count($subcat_ids) == 0) {
            return new PwgError(403, 'Unknown parent category id');
        }
    }
    $page['infos'] = array();
    $page['errors'] = array();
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    move_categories($category_ids, $params['parent']);
    invalidate_user_cache();
    if (count($page['errors']) != 0) {
        return new PwgError(403, implode('; ', $page['errors']));
    }
}
function pfemail_reject($id)
{
    global $conf, $page;
    $query = '
DELETE
  FROM ' . PFEMAIL_PENDINGS_TABLE . '
  WHERE image_id = ' . $id . '
;';
    pwg_query($query);
    delete_elements(array($id), true);
    array_push($page['infos'], l10n('Photo rejected'));
    invalidate_user_cache();
    return true;
}
Ejemplo n.º 5
0
  VALUES (\'TakeATour\', \'active\')
;';
        pwg_query($query);
        $template->assign(array('button_label' => l10n('Home'), 'button_link' => 'index.php'));
        // if the webmaster has a session, let's give a link to discover new features
        if (!empty($_SESSION['pwg_uid'])) {
            $version_ = str_replace('.', '_', get_branch_from_version(PHPWG_VERSION) . '.0');
            if (file_exists(PHPWG_PLUGINS_PATH . 'TakeATour/tours/' . $version_ . '/config.inc.php')) {
                load_language('plugin.lang', PHPWG_PLUGINS_PATH . 'TakeATour/', array('language' => $language, 'force_fallback' => 'en_UK'));
                // we need the secret key for get_pwg_token()
                load_conf_from_db();
                $template->assign(array('button_label' => l10n('2_7_0_descrp'), 'button_link' => 'admin.php?submited_tour_path=tours/' . $version_ . '&pwg_token=' . get_pwg_token()));
            }
        }
        // Delete cache data
        invalidate_user_cache(true);
        $template->delete_compiled_templates();
        // Restore $page['infos'] in order to hide informations messages from functions calles
        // errors messages are not hide
        $page['infos'] = $page['infos_sav'];
    }
} else {
    if (!defined('PWG_CHARSET')) {
        define('PWG_CHARSET', 'utf-8');
    }
    include_once PHPWG_ROOT_PATH . 'admin/include/languages.class.php';
    $languages = new languages();
    foreach ($languages->fs_languages as $language_code => $fs_language) {
        if ($language == $language_code) {
            $template->assign('language_selection', $language_code);
        }
Ejemplo n.º 6
0
/**
 * Save picture form
 * @trigger loc_begin_picture
 */
function admintools_save_picture()
{
    global $page, $conf, $MultiView, $user, $picture;
    if (!isset($_GET['delete']) and !isset($_POST['action']) and @$_POST['action'] != 'quick_edit') {
        return;
    }
    $query = 'SELECT added_by FROM ' . IMAGES_TABLE . ' WHERE id = ' . $page['image_id'] . ';';
    list($added_by) = pwg_db_fetch_row(pwg_query($query));
    if (!$MultiView->is_admin() and $user['id'] != $added_by) {
        return;
    }
    if (isset($_GET['delete']) and get_pwg_token() == @$_GET['pwg_token']) {
        include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
        delete_elements(array($page['image_id']), true);
        invalidate_user_cache();
        if (isset($page['rank_of'][$page['image_id']])) {
            redirect(duplicate_index_url(array('start' => floor($page['rank_of'][$page['image_id']] / $page['nb_image_page']) * $page['nb_image_page'])));
        } else {
            redirect(make_index_url());
        }
    }
    if ($_POST['action'] == 'quick_edit') {
        include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
        $data = array('name' => $_POST['name'], 'author' => $_POST['author']);
        if ($MultiView->is_admin()) {
            $data['level'] = $_POST['level'];
        }
        if ($conf['allow_html_descriptions']) {
            $data['comment'] = @$_POST['comment'];
        } else {
            $data['comment'] = strip_tags(@$_POST['comment']);
        }
        if (!empty($_POST['date_creation']) and strtotime($_POST['date_creation']) !== false) {
            $data['date_creation'] = $_POST['date_creation'] . ' ' . $_POST['date_creation_time'];
        }
        single_update(IMAGES_TABLE, $data, array('id' => $page['image_id']));
        $tag_ids = array();
        if (!empty($_POST['tags'])) {
            $tag_ids = get_tag_ids($_POST['tags']);
        }
        set_tags($tag_ids, $page['image_id']);
    }
}
Ejemplo n.º 7
0
 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');
         }
     }
 }
Ejemplo n.º 8
0
/**
 * API method
 * Updates users
 * @param mixed[] $params
 *    @option int[] user_id
 *    @option string username (optional)
 *    @option string password (optional)
 *    @option string email (optional)
 *    @option string status (optional)
 *    @option int level (optional)
 *    @option string language (optional)
 *    @option string theme (optional)
 *    @option int nb_image_page (optional)
 *    @option int recent_period (optional)
 *    @option bool expand (optional)
 *    @option bool show_nb_comments (optional)
 *    @option bool show_nb_hits (optional)
 *    @option bool enabled_high (optional)
 */
function ws_users_setInfo($params, &$service)
{
    if (get_pwg_token() != $params['pwg_token']) {
        return new PwgError(403, 'Invalid security token');
    }
    global $conf, $user;
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    $updates = $updates_infos = array();
    $update_status = null;
    if (count($params['user_id']) == 1) {
        if (get_username($params['user_id'][0]) === false) {
            return new PwgError(WS_ERR_INVALID_PARAM, 'This user does not exist.');
        }
        if (!empty($params['username'])) {
            $user_id = get_userid($params['username']);
            if ($user_id and $user_id != $params['user_id'][0]) {
                return new PwgError(WS_ERR_INVALID_PARAM, l10n('this login is already used'));
            }
            if ($params['username'] != strip_tags($params['username'])) {
                return new PwgError(WS_ERR_INVALID_PARAM, l10n('html tags are not allowed in login'));
            }
            $updates[$conf['user_fields']['username']] = $params['username'];
        }
        if (!empty($params['email'])) {
            if (($error = validate_mail_address($params['user_id'][0], $params['email'])) != '') {
                return new PwgError(WS_ERR_INVALID_PARAM, $error);
            }
            $updates[$conf['user_fields']['email']] = $params['email'];
        }
        if (!empty($params['password'])) {
            $updates[$conf['user_fields']['password']] = $conf['password_hash']($params['password']);
        }
    }
    if (!empty($params['status'])) {
        if (in_array($params['status'], array('webmaster', 'admin')) and !is_webmaster()) {
            return new PwgError(403, 'Only webmasters can grant "webmaster/admin" status');
        }
        if (!in_array($params['status'], array('guest', 'generic', 'normal', 'admin', 'webmaster'))) {
            return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid status');
        }
        $protected_users = array($user['id'], $conf['guest_id'], $conf['webmaster_id']);
        // an admin can't change status of other admin/webmaster
        if ('admin' == $user['status']) {
            $query = '
SELECT
    user_id
  FROM ' . USER_INFOS_TABLE . '
  WHERE status IN (\'webmaster\', \'admin\')
;';
            $protected_users = array_merge($protected_users, query2array($query, null, 'user_id'));
        }
        // status update query is separated from the rest as not applying to the same
        // set of users (current, guest and webmaster can't be changed)
        $params['user_id_for_status'] = array_diff($params['user_id'], $protected_users);
        $update_status = $params['status'];
    }
    if (!empty($params['level']) or @$params['level'] === 0) {
        if (!in_array($params['level'], $conf['available_permission_levels'])) {
            return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
        }
        $updates_infos['level'] = $params['level'];
    }
    if (!empty($params['language'])) {
        if (!in_array($params['language'], array_keys(get_languages()))) {
            return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid language');
        }
        $updates_infos['language'] = $params['language'];
    }
    if (!empty($params['theme'])) {
        if (!in_array($params['theme'], array_keys(get_pwg_themes()))) {
            return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid theme');
        }
        $updates_infos['theme'] = $params['theme'];
    }
    if (!empty($params['nb_image_page'])) {
        $updates_infos['nb_image_page'] = $params['nb_image_page'];
    }
    if (!empty($params['recent_period']) or @$params['recent_period'] === 0) {
        $updates_infos['recent_period'] = $params['recent_period'];
    }
    if (!empty($params['expand']) or @$params['expand'] === false) {
        $updates_infos['expand'] = boolean_to_string($params['expand']);
    }
    if (!empty($params['show_nb_comments']) or @$params['show_nb_comments'] === false) {
        $updates_infos['show_nb_comments'] = boolean_to_string($params['show_nb_comments']);
    }
    if (!empty($params['show_nb_hits']) or @$params['show_nb_hits'] === false) {
        $updates_infos['show_nb_hits'] = boolean_to_string($params['show_nb_hits']);
    }
    if (!empty($params['enabled_high']) or @$params['enabled_high'] === false) {
        $updates_infos['enabled_high'] = boolean_to_string($params['enabled_high']);
    }
    // perform updates
    single_update(USERS_TABLE, $updates, array($conf['user_fields']['id'] => $params['user_id'][0]));
    if (isset($update_status) and count($params['user_id_for_status']) > 0) {
        $query = '
UPDATE ' . USER_INFOS_TABLE . ' SET
    status = "' . $update_status . '"
  WHERE user_id IN(' . implode(',', $params['user_id_for_status']) . ')
;';
        pwg_query($query);
    }
    if (count($updates_infos) > 0) {
        $query = '
UPDATE ' . USER_INFOS_TABLE . ' SET ';
        $first = true;
        foreach ($updates_infos as $field => $value) {
            if (!$first) {
                $query .= ', ';
            } else {
                $first = false;
            }
            $query .= $field . ' = "' . $value . '"';
        }
        $query .= '
  WHERE user_id IN(' . implode(',', $params['user_id']) . ')
;';
        pwg_query($query);
    }
    // manage association to groups
    if (!empty($params['group_id'])) {
        $query = '
DELETE
  FROM ' . USER_GROUP_TABLE . '
  WHERE user_id IN (' . implode(',', $params['user_id']) . ')
;';
        pwg_query($query);
        // we remove all provided groups that do not really exist
        $query = '
SELECT
    id
  FROM ' . GROUPS_TABLE . '
  WHERE id IN (' . implode(',', $params['group_id']) . ')
;';
        $group_ids = array_from_query($query, 'id');
        // if only -1 (a group id that can't exist) is in the list, then no
        // group is associated
        if (count($group_ids) > 0) {
            $inserts = array();
            foreach ($group_ids as $group_id) {
                foreach ($params['user_id'] as $user_id) {
                    $inserts[] = array('user_id' => $user_id, 'group_id' => $group_id);
                }
            }
            mass_inserts(USER_GROUP_TABLE, array_keys($inserts[0]), $inserts);
        }
    }
    invalidate_user_cache();
    return $service->invoke('pwg.users.getList', array('user_id' => $params['user_id'], 'display' => 'basics,' . implode(',', array_keys($updates_infos))));
}
Ejemplo n.º 9
0
/**
 * API method
 * Removes user(s) from a group
 * @param mixed[] $params
 *    @option int group_id
 *    @option int[] user_id
 */
function ws_groups_deleteUser($params, &$service)
{
    if (get_pwg_token() != $params['pwg_token']) {
        return new PwgError(403, 'Invalid security token');
    }
    // does the group exist ?
    $query = '
SELECT COUNT(*)
  FROM ' . GROUPS_TABLE . '
  WHERE id = ' . $params['group_id'] . '
;';
    list($count) = pwg_db_fetch_row(pwg_query($query));
    if ($count == 0) {
        return new PwgError(WS_ERR_INVALID_PARAM, 'This group does not exist.');
    }
    $query = '
DELETE FROM ' . USER_GROUP_TABLE . '
  WHERE
    group_id = ' . $params['group_id'] . '
    AND user_id IN(' . implode(',', $params['user_id']) . ')
;';
    pwg_query($query);
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    invalidate_user_cache();
    return $service->invoke('pwg.groups.getList', array('group_id' => $params['group_id']));
}
Ejemplo n.º 10
0
/**
 * API method
 * Deletes an image
 * @param mixed[] $params
 *    @option int|int[] image_id
 *    @option string pwg_token
 */
function ws_images_delete($params, $service)
{
    if (get_pwg_token() != $params['pwg_token']) {
        return new PwgError(403, 'Invalid security token');
    }
    if (!is_array($params['image_id'])) {
        $params['image_id'] = preg_split('/[\\s,;\\|]/', $params['image_id'], -1, PREG_SPLIT_NO_EMPTY);
    }
    $params['image_id'] = array_map('intval', $params['image_id']);
    $image_ids = array();
    foreach ($params['image_id'] as $image_id) {
        if ($image_id > 0) {
            $image_ids[] = $image_id;
        }
    }
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    delete_elements($image_ids, true);
    invalidate_user_cache();
}
function pqv_end_section_init()
{
    global $template, $page;
    if (!pqv_is_active()) {
        return;
    }
    if (empty($page['items'])) {
        return;
    }
    $query = '
SELECT
    id
  FROM ' . IMAGES_TABLE . '
  WHERE id IN (' . implode(',', $page['items']) . ')
    AND pqv_validated = \'false\'
;';
    $pqv_rejected = query2array($query, null, 'id');
    if (isset($_GET['pqv_delete']) and count($pqv_rejected) > 0) {
        include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
        $deleted_count = delete_elements($pqv_rejected, true);
        if ($deleted_count > 0) {
            invalidate_user_cache();
            $_SESSION['page_infos'][] = l10n_dec('%d photo was deleted', '%d photos were deleted', $deleted_count);
            $redirect_url = duplicate_index_url(array(), array('pqv_delete'));
            redirect($redirect_url);
        }
    }
    if (count($pqv_rejected) > 0) {
        $delete_url = add_url_params(duplicate_index_url(), array('pqv_delete' => 1));
        $template->assign('CONTENT_DESCRIPTION', '<a href="' . $delete_url . '" onclick="return confirm(\'' . l10n('Are you sure?') . '\');">delete the ' . count($pqv_rejected) . ' rejected photo(s)</a>');
    }
}
Ejemplo n.º 12
0
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;
}
Ejemplo n.º 13
0
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;
}
Ejemplo n.º 14
0
/**
 * Function called from ConfirmMail.php to verify validation key used by user according time limit
 * Return true is key validation is OK else return false
 *
 * @param : User id
 * 
 * @return : Bool
 * 
 */
function VerifyConfirmMail($id)
{
    global $conf;
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    $conf_UAM = unserialize($conf['UserAdvManager']);
    $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
    $query = '
SELECT COUNT(*)
FROM ' . USER_CONFIRM_MAIL_TABLE . '
WHERE id = "' . $id . '"
;';
    list($count) = pwg_db_fetch_row(pwg_query($query));
    if ($count == 1) {
        $query = '
SELECT user_id, status, date_check
FROM ' . USER_CONFIRM_MAIL_TABLE . '
WHERE id = "' . $id . '"
;';
        $data = pwg_db_fetch_assoc(pwg_query($query));
        if (!empty($data) and isset($data['user_id']) and is_null($data['date_check'])) {
            $query = '
SELECT registration_date
FROM ' . USER_INFOS_TABLE . '
WHERE user_id = ' . $data['user_id'] . '
;';
            list($registration_date) = pwg_db_fetch_row(pwg_query($query));
            //              Time limit process
            // ********************************************
            if (!empty($registration_date)) {
                // Verify Confirmmail with time limit ON
                // -------------------------------------
                if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'])) {
                    // Dates formating and compare
                    // ---------------------------
                    $today = date("d-m-Y");
                    // Get today's date
                    list($day, $month, $year) = explode('-', $today);
                    // explode date of today
                    $daytimestamp = mktime(0, 0, 0, $month, $day, $year);
                    // Generate UNIX timestamp
                    list($regdate, $regtime) = explode(' ', $registration_date);
                    // Explode date and time from registration date
                    list($regyear, $regmonth, $regday) = explode('-', $regdate);
                    // Explode date from registration date
                    $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);
                    // Generate UNIX timestamp
                    $deltasecs = $daytimestamp - $regtimestamp;
                    // Compare the 2 UNIX timestamps
                    $deltadays = floor($deltasecs / 86400);
                    // Convert result from seconds to days
                    // Condition with the value set for time limit
                    // -------------------------------------------
                    if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) {
                        $dbnow = date("Y-m-d H:i:s");
                        // Update ConfirmMail table
                        // ------------------------
                        $query = '
UPDATE ' . USER_CONFIRM_MAIL_TABLE . '
SET date_check="' . $dbnow . '", reminder="false"
WHERE id = "' . $id . '"
;';
                        pwg_query($query);
                        // Update LastVisit table - Force reminder field to false
                        // Usefull when a user has been automatically downgraded and revalidate its registration
                        // -------------------------------------------------------------------------------------
                        $query = '
UPDATE ' . USER_LASTVISIT_TABLE . '
SET reminder="false"
WHERE user_id = "' . $data['user_id'] . '"
;';
                        pwg_query($query);
                        if ($conf_UAM['NO_CONFIRM_GROUP'] != -1) {
                            $query = '
DELETE FROM ' . USER_GROUP_TABLE . '
WHERE user_id = ' . $data['user_id'] . '
  AND group_id = ' . $conf_UAM['NO_CONFIRM_GROUP'] . '
;';
                            pwg_query($query);
                        }
                        if ($conf_UAM['VALIDATED_GROUP'] != -1) {
                            $query = '
INSERT INTO ' . USER_GROUP_TABLE . '
  (user_id, group_id)
VALUES
  (' . $data['user_id'] . ', ' . $conf_UAM['VALIDATED_GROUP'] . ')
;';
                            pwg_query($query);
                        }
                        if ($conf_UAM['VALIDATED_STATUS'] != -1) {
                            $query = '
UPDATE ' . USER_INFOS_TABLE . '
SET status = "' . $conf_UAM['VALIDATED_STATUS'] . '"
WHERE user_id = ' . $data['user_id'] . '
;';
                            pwg_query($query);
                        }
                        if ($conf_UAM['VALID_LEVEL'] != -1) {
                            $query = '
UPDATE ' . USER_INFOS_TABLE . '
SET level = "' . $conf_UAM['VALID_LEVEL'] . '"
WHERE user_id = ' . $data['user_id'] . '
;';
                            pwg_query($query);
                        }
                        // Set UAM_validated field to True in #_users table
                        SetValidated($data['user_id']);
                        // Refresh user's category cache
                        // -----------------------------
                        invalidate_user_cache();
                        return true;
                    } elseif ($deltadays > $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) {
                        return false;
                    }
                } else {
                    $dbnow = date("Y-m-d H:i:s");
                    // Update ConfirmMail table
                    // ------------------------
                    $query = '
UPDATE ' . USER_CONFIRM_MAIL_TABLE . '
SET date_check="' . $dbnow . '"
WHERE id = "' . $id . '"
;';
                    pwg_query($query);
                    // Update LastVisit table - Force reminder field to false
                    // Usefull when a user has been automatically downgraded and revalidate its registration
                    // -------------------------------------------------------------------------------------
                    $query = '
UPDATE ' . USER_LASTVISIT_TABLE . '
SET reminder="false"
WHERE user_id = "' . $data['user_id'] . '"
;';
                    pwg_query($query);
                    if ($conf_UAM['NO_CONFIRM_GROUP'] != -1) {
                        $query = '
DELETE FROM ' . USER_GROUP_TABLE . '
WHERE user_id = ' . $data['user_id'] . '
AND group_id = ' . $conf_UAM['NO_CONFIRM_GROUP'] . '
;';
                        pwg_query($query);
                    }
                    if ($conf_UAM['VALIDATED_GROUP'] != -1) {
                        $query = '
DELETE FROM ' . USER_GROUP_TABLE . '
WHERE user_id = ' . $data['user_id'] . '
AND group_id = ' . $conf_UAM['VALIDATED_GROUP'] . '
;';
                        pwg_query($query);
                        $query = '
INSERT INTO ' . USER_GROUP_TABLE . '
  (user_id, group_id)
VALUES
  (' . $data['user_id'] . ', ' . $conf_UAM['VALIDATED_GROUP'] . ')
;';
                        pwg_query($query);
                    }
                    if ($conf_UAM['VALIDATED_STATUS'] != -1) {
                        $query = '
UPDATE ' . USER_INFOS_TABLE . '
SET status = "' . $conf_UAM['VALIDATED_STATUS'] . '"
WHERE user_id = ' . $data['user_id'] . '
;';
                        pwg_query($query);
                    }
                    if ($conf_UAM['VALID_LEVEL'] != -1) {
                        $query = '
UPDATE ' . USER_INFOS_TABLE . '
SET level = "' . $conf_UAM['VALID_LEVEL'] . '"
WHERE user_id = ' . $data['user_id'] . '
;';
                        pwg_query($query);
                    }
                    // Set UAM_validated field to True in #_users table
                    SetValidated($data['user_id']);
                    // Refresh user's category cache
                    // -----------------------------
                    invalidate_user_cache();
                    return true;
                }
            }
        } else {
            if (!empty($data) and !is_null($data['date_check'])) {
                return false;
            }
        }
    } else {
        return false;
    }
}