/**
 * API method
 * Returns a list of categories
 * @param mixed[] $params
 *    @option int cat_id (optional)
 *    @option bool recursive
 *    @option bool public
 *    @option bool tree_output
 *    @option bool fullname
 */
function ws_categories_getList($params, &$service)
{
    global $user, $conf;
    $where = array('1=1');
    $join_type = 'INNER';
    $join_user = $user['id'];
    if (!$params['recursive']) {
        if ($params['cat_id'] > 0) {
            $where[] = '(
        id_uppercat = ' . (int) $params['cat_id'] . '
        OR id=' . (int) $params['cat_id'] . '
      )';
        } else {
            $where[] = 'id_uppercat IS NULL';
        }
    } else {
        if ($params['cat_id'] > 0) {
            $where[] = 'uppercats ' . DB_REGEX_OPERATOR . ' \'(^|,)' . (int) $params['cat_id'] . '(,|$)\'';
        }
    }
    if ($params['public']) {
        $where[] = 'status = "public"';
        $where[] = 'visible = "true"';
        $join_user = $conf['guest_id'];
    } else {
        if (is_admin()) {
            // in this very specific case, we don't want to hide empty
            // categories. Function calculate_permissions will only return
            // categories that are either locked or private and not permitted
            //
            // calculate_permissions does not consider empty categories as forbidden
            $forbidden_categories = calculate_permissions($user['id'], $user['status']);
            $where[] = 'id NOT IN (' . $forbidden_categories . ')';
            $join_type = 'LEFT';
        }
    }
    $query = '
SELECT
    id, name, comment, permalink,
    uppercats, global_rank, id_uppercat,
    nb_images, count_images AS total_nb_images,
    representative_picture_id, user_representative_picture_id, count_images, count_categories,
    date_last, max_date_last, count_categories AS nb_categories
  FROM ' . CATEGORIES_TABLE . '
    ' . $join_type . ' JOIN ' . USER_CACHE_CATEGORIES_TABLE . '
    ON id=cat_id AND user_id=' . $join_user . '
  WHERE ' . implode("\n    AND ", $where) . '
;';
    $result = pwg_query($query);
    // management of the album thumbnail -- starts here
    $image_ids = array();
    $categories = array();
    $user_representative_updates_for = array();
    // management of the album thumbnail -- stops here
    $cats = array();
    while ($row = pwg_db_fetch_assoc($result)) {
        $row['url'] = make_index_url(array('category' => $row));
        foreach (array('id', 'nb_images', 'total_nb_images', 'nb_categories') as $key) {
            $row[$key] = (int) $row[$key];
        }
        if ($params['fullname']) {
            $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null));
        } else {
            $row['name'] = strip_tags(trigger_change('render_category_name', $row['name'], 'ws_categories_getList'));
        }
        $row['comment'] = strip_tags(trigger_change('render_category_description', $row['comment'], 'ws_categories_getList'));
        // management of the album thumbnail -- starts here
        //
        // on branch 2.3, the algorithm is duplicated from
        // include/category_cats, but we should use a common code for Piwigo 2.4
        //
        // warning : if the API method is called with $params['public'], the
        // album thumbnail may be not accurate. The thumbnail can be viewed by
        // the connected user, but maybe not by the guest. Changing the
        // filtering method would be too complicated for now. We will simply
        // avoid to persist the user_representative_picture_id in the database
        // if $params['public']
        if (!empty($row['user_representative_picture_id'])) {
            $image_id = $row['user_representative_picture_id'];
        } else {
            if (!empty($row['representative_picture_id'])) {
                // if a representative picture is set, it has priority
                $image_id = $row['representative_picture_id'];
            } else {
                if ($conf['allow_random_representative']) {
                    // searching a random representant among elements in sub-categories
                    $image_id = get_random_image_in_category($row);
                } else {
                    // searching a random representant among representant of sub-categories
                    if ($row['count_categories'] > 0 and $row['count_images'] > 0) {
                        $query = '
SELECT representative_picture_id
  FROM ' . CATEGORIES_TABLE . '
    INNER JOIN ' . USER_CACHE_CATEGORIES_TABLE . '
    ON id=cat_id AND user_id=' . $user['id'] . '
  WHERE uppercats LIKE \'' . $row['uppercats'] . ',%\'
    AND representative_picture_id IS NOT NULL
        ' . get_sql_condition_FandF(array('visible_categories' => 'id'), "\n  AND") . '
  ORDER BY ' . DB_RANDOM_FUNCTION . '()
  LIMIT 1
;';
                        $subresult = pwg_query($query);
                        if (pwg_db_num_rows($subresult) > 0) {
                            list($image_id) = pwg_db_fetch_row($subresult);
                        }
                    }
                }
            }
        }
        if (isset($image_id)) {
            if ($conf['representative_cache_on_subcats'] and $row['user_representative_picture_id'] != $image_id) {
                $user_representative_updates_for[$row['id']] = $image_id;
            }
            $row['representative_picture_id'] = $image_id;
            $image_ids[] = $image_id;
            $categories[] = $row;
        }
        unset($image_id);
        // management of the album thumbnail -- stops here
        $cats[] = $row;
    }
    usort($cats, 'global_rank_compare');
    // management of the album thumbnail -- starts here
    if (count($categories) > 0) {
        $thumbnail_src_of = array();
        $new_image_ids = array();
        $query = '
SELECT id, path, representative_ext, level
  FROM ' . IMAGES_TABLE . '
  WHERE id IN (' . implode(',', $image_ids) . ')
;';
        $result = pwg_query($query);
        while ($row = pwg_db_fetch_assoc($result)) {
            if ($row['level'] <= $user['level']) {
                $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
            } else {
                // problem: we must not display the thumbnail of a photo which has a
                // higher privacy level than user privacy level
                //
                // * what is the represented category?
                // * find a random photo matching user permissions
                // * register it at user_representative_picture_id
                // * set it as the representative_picture_id for the category
                foreach ($categories as &$category) {
                    if ($row['id'] == $category['representative_picture_id']) {
                        // searching a random representant among elements in sub-categories
                        $image_id = get_random_image_in_category($category);
                        if (isset($image_id) and !in_array($image_id, $image_ids)) {
                            $new_image_ids[] = $image_id;
                        }
                        if ($conf['representative_cache_on_level']) {
                            $user_representative_updates_for[$category['id']] = $image_id;
                        }
                        $category['representative_picture_id'] = $image_id;
                    }
                }
                unset($category);
            }
        }
        if (count($new_image_ids) > 0) {
            $query = '
SELECT id, path, representative_ext
  FROM ' . IMAGES_TABLE . '
  WHERE id IN (' . implode(',', $new_image_ids) . ')
;';
            $result = pwg_query($query);
            while ($row = pwg_db_fetch_assoc($result)) {
                $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
            }
        }
    }
    // compared to code in include/category_cats, we only persist the new
    // user_representative if we have used $user['id'] and not the guest id,
    // or else the real guest may see thumbnail that he should not
    if (!$params['public'] and count($user_representative_updates_for)) {
        $updates = array();
        foreach ($user_representative_updates_for as $cat_id => $image_id) {
            $updates[] = array('user_id' => $user['id'], 'cat_id' => $cat_id, 'user_representative_picture_id' => $image_id);
        }
        mass_updates(USER_CACHE_CATEGORIES_TABLE, array('primary' => array('user_id', 'cat_id'), 'update' => array('user_representative_picture_id')), $updates);
    }
    foreach ($cats as &$cat) {
        foreach ($categories as $category) {
            if ($category['id'] == $cat['id'] and isset($category['representative_picture_id'])) {
                $cat['tn_url'] = $thumbnail_src_of[$category['representative_picture_id']];
            }
        }
        // we don't want them in the output
        unset($cat['user_representative_picture_id'], $cat['count_images'], $cat['count_categories']);
    }
    unset($cat);
    // management of the album thumbnail -- stops here
    if ($params['tree_output']) {
        return categories_flatlist_to_tree($cats);
    }
    return array('categories' => new PwgNamedArray($cats, 'category', ws_std_get_category_xml_attributes()));
}
Ejemplo n.º 2
0
/**
 * Deletes favorites of the current user if he's not allowed to see them.
 */
function check_user_favorites()
{
    global $user;
    if ($user['forbidden_categories'] == '') {
        return;
    }
    // $filter['visible_categories'] and $filter['visible_images']
    // must be not used because filter <> restriction
    // retrieving images allowed : belonging to at least one authorized
    // category
    $query = '
SELECT DISTINCT f.image_id
  FROM ' . FAVORITES_TABLE . ' AS f INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' AS ic
    ON f.image_id = ic.image_id
  WHERE f.user_id = ' . $user['id'] . '
  ' . get_sql_condition_FandF(array('forbidden_categories' => 'ic.category_id'), 'AND') . '
;';
    $authorizeds = query2array($query, null, 'image_id');
    $query = '
SELECT image_id
  FROM ' . FAVORITES_TABLE . '
  WHERE user_id = ' . $user['id'] . '
;';
    $favorites = query2array($query, null, 'image_id');
    $to_deletes = array_diff($favorites, $authorizeds);
    if (count($to_deletes) > 0) {
        $query = '
DELETE FROM ' . FAVORITES_TABLE . '
  WHERE image_id IN (' . implode(',', $to_deletes) . ')
    AND user_id = ' . $user['id'] . '
;';
        pwg_query($query);
    }
}
Ejemplo n.º 3
0
/**
 * returns the number of available comments for the connected user
 *
 * @return int
 */
function get_nb_available_comments()
{
    global $user;
    if (!isset($user['nb_available_comments'])) {
        $where = array();
        if (!is_admin()) {
            $where[] = 'validated=\'true\'';
        }
        $where[] = get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'forbidden_images' => 'ic.image_id'), '', true);
        $query = '
SELECT COUNT(DISTINCT(com.id))
  FROM ' . IMAGE_CATEGORY_TABLE . ' AS ic
    INNER JOIN ' . COMMENTS_TABLE . ' AS com
    ON ic.image_id = com.image_id
  WHERE ' . implode('
    AND ', $where);
        list($user['nb_available_comments']) = pwg_db_fetch_row(pwg_query($query));
        single_update(USER_CACHE_TABLE, array('nb_available_comments' => $user['nb_available_comments']), array('user_id' => $user['id']));
    }
    return $user['nb_available_comments'];
}
Ejemplo n.º 4
0
/**
 * Return the list of image ids corresponding to given tags.
 * AND & OR mode supported.
 *
 * @param int[] $tag_ids
 * @param string mode
 * @param string $extra_images_where_sql - optionally apply a sql where filter to retrieved images
 * @param string $order_by - optionally overwrite default photo order
 * @param bool $user_permissions
 * @return array
 */
function get_image_ids_for_tags($tag_ids, $mode = 'AND', $extra_images_where_sql = '', $order_by = '', $use_permissions = true)
{
    global $conf;
    if (empty($tag_ids)) {
        return array();
    }
    $query = '
SELECT id
  FROM ' . IMAGES_TABLE . ' i ';
    if ($use_permissions) {
        $query .= '
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' ic ON id=ic.image_id';
    }
    $query .= '
    INNER JOIN ' . IMAGE_TAG_TABLE . ' it ON id=it.image_id
    WHERE tag_id IN (' . implode(',', $tag_ids) . ')';
    if ($use_permissions) {
        $query .= get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'visible_categories' => 'category_id', 'visible_images' => 'id'), "\n  AND");
    }
    $query .= (empty($extra_images_where_sql) ? '' : " \nAND (" . $extra_images_where_sql . ')') . '
  GROUP BY id';
    if ($mode == 'AND' and count($tag_ids) > 1) {
        $query .= '
  HAVING COUNT(DISTINCT tag_id)=' . count($tag_ids);
    }
    $query .= "\n" . (empty($order_by) ? $conf['order_by'] : $order_by);
    return query2array($query, null, 'id');
}
Ejemplo n.º 5
0
/**
 * Find a random photo among all photos inside an album (including sub-albums)
 *
 * @param array $category (at least id,uppercats,count_images)
 * @param bool $recursive
 * @return int|null
 */
function get_random_image_in_category($category, $recursive = true)
{
    $image_id = null;
    if ($category['count_images'] > 0) {
        $query = '
SELECT image_id
  FROM ' . CATEGORIES_TABLE . ' AS c
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' AS ic ON ic.category_id = c.id
  WHERE ';
        if ($recursive) {
            $query .= '
    (c.id=' . $category['id'] . ' OR uppercats LIKE \'' . $category['uppercats'] . ',%\')';
        } else {
            $query .= '
    c.id=' . $category['id'];
        }
        $query .= '
    ' . get_sql_condition_FandF(array('forbidden_categories' => 'c.id', 'visible_categories' => 'c.id', 'visible_images' => 'image_id'), "\n  AND") . '
  ORDER BY ' . DB_RANDOM_FUNCTION . '()
  LIMIT 1
;';
        $result = pwg_query($query);
        if (pwg_db_num_rows($result) > 0) {
            list($image_id) = pwg_db_fetch_row($result);
        }
    }
    return $image_id;
}
Ejemplo n.º 6
0
/**
 * @see get_quick_search_results but without result caching
 */
function get_quick_search_results_no_cache($q, $options)
{
    global $conf;
    $q = trim(stripslashes($q));
    $search_results = array('items' => array(), 'qs' => array('q' => $q));
    $q = trigger_change('qsearch_pre', $q);
    $scopes = array();
    $scopes[] = new QSearchScope('tag', array('tags'));
    $scopes[] = new QSearchScope('photo', array('photos'));
    $scopes[] = new QSearchScope('file', array('filename'));
    $scopes[] = new QSearchScope('author', array(), true);
    $scopes[] = new QNumericRangeScope('width', array());
    $scopes[] = new QNumericRangeScope('height', array());
    $scopes[] = new QNumericRangeScope('ratio', array(), false, 0.001);
    $scopes[] = new QNumericRangeScope('size', array());
    $scopes[] = new QNumericRangeScope('filesize', array());
    $scopes[] = new QNumericRangeScope('hits', array('hit', 'visit', 'visits'));
    $scopes[] = new QNumericRangeScope('score', array('rating'), true);
    $scopes[] = new QNumericRangeScope('id', array());
    $createdDateAliases = array('taken', 'shot');
    $postedDateAliases = array('added');
    if ($conf['calendar_datefield'] == 'date_creation') {
        $createdDateAliases[] = 'date';
    } else {
        $postedDateAliases[] = 'date';
    }
    $scopes[] = new QDateRangeScope('created', $createdDateAliases, true);
    $scopes[] = new QDateRangeScope('posted', $postedDateAliases);
    // allow plugins to add their own scopes
    $scopes = trigger_change('qsearch_get_scopes', $scopes);
    $expression = new QExpression($q, $scopes);
    // get inflections for terms
    $inflector = null;
    $lang_code = substr(get_default_language(), 0, 2);
    @(include_once PHPWG_ROOT_PATH . 'include/inflectors/' . $lang_code . '.php');
    $class_name = 'Inflector_' . $lang_code;
    if (class_exists($class_name)) {
        $inflector = new $class_name();
        foreach ($expression->stokens as $token) {
            if (isset($token->scope) && !$token->scope->is_text) {
                continue;
            }
            if (strlen($token->term) > 2 && ($token->modifier & (QST_QUOTED | QST_WILDCARD)) == 0 && strcspn($token->term, '\'0123456789') == strlen($token->term)) {
                $token->variants = array_unique(array_diff($inflector->get_variants($token->term), array($token->term)));
            }
        }
    }
    trigger_notify('qsearch_expression_parsed', $expression);
    //var_export($expression);
    if (count($expression->stokens) == 0) {
        return $search_results;
    }
    $qsr = new QResults();
    qsearch_get_tags($expression, $qsr);
    qsearch_get_images($expression, $qsr);
    // allow plugins to evaluate their own scopes
    trigger_notify('qsearch_before_eval', $expression, $qsr);
    $ids = qsearch_eval($expression, $qsr, $tmp, $search_results['qs']['unmatched_terms']);
    $debug[] = "<!--\nparsed: " . $expression;
    $debug[] = count($expression->stokens) . ' tokens';
    for ($i = 0; $i < count($expression->stokens); $i++) {
        $debug[] = $expression->stokens[$i] . ': ' . count($qsr->tag_ids[$i]) . ' tags, ' . count($qsr->tag_iids[$i]) . ' tiids, ' . count($qsr->images_iids[$i]) . ' iiids, ' . count($qsr->iids[$i]) . ' iids' . ' modifier:' . dechex($expression->stoken_modifiers[$i]) . (!empty($expression->stokens[$i]->variants) ? ' variants: ' . implode(', ', $expression->stokens[$i]->variants) : '');
    }
    $debug[] = 'before perms ' . count($ids);
    $search_results['qs']['matching_tags'] = $qsr->all_tags;
    $search_results = trigger_change('qsearch_results', $search_results, $expression, $qsr);
    global $template;
    if (empty($ids)) {
        $debug[] = '-->';
        $template->append('footer_elements', implode("\n", $debug));
        return $search_results;
    }
    $permissions = !isset($options['permissions']) ? true : $options['permissions'];
    $where_clauses = array();
    $where_clauses[] = 'i.id IN (' . implode(',', $ids) . ')';
    if (!empty($options['images_where'])) {
        $where_clauses[] = '(' . $options['images_where'] . ')';
    }
    if ($permissions) {
        $where_clauses[] = get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'forbidden_images' => 'i.id'), null, true);
    }
    $query = '
SELECT DISTINCT(id) FROM ' . IMAGES_TABLE . ' i';
    if ($permissions) {
        $query .= '
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' AS ic ON id = ic.image_id';
    }
    $query .= '
  WHERE ' . implode("\n AND ", $where_clauses) . "\n" . $conf['order_by'];
    $ids = query2array($query, null, 'id');
    $debug[] = count($ids) . ' final photo count -->';
    $template->append('footer_elements', implode("\n", $debug));
    $search_results['items'] = $ids;
    return $search_results;
}
Ejemplo n.º 7
0
/**
 * Initialize _$page_ and _$template_ vars for calendar view.
 */
function initialize_calendar()
{
    global $page, $conf, $user, $template, $persistent_cache, $filter;
    //------------------ initialize the condition on items to take into account ---
    $inner_sql = ' FROM ' . IMAGES_TABLE;
    if ($page['section'] == 'categories') {
        // we will regenerate the items by including subcats elements
        $page['items'] = array();
        $inner_sql .= '
INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' ON id = image_id';
        if (isset($page['category'])) {
            $sub_ids = array_diff(get_subcat_ids(array($page['category']['id'])), explode(',', $user['forbidden_categories']));
            if (empty($sub_ids)) {
                return;
                // nothing to do
            }
            $inner_sql .= '
WHERE category_id IN (' . implode(',', $sub_ids) . ')';
            $inner_sql .= '
    ' . get_sql_condition_FandF(array('visible_images' => 'id'), 'AND', false);
        } else {
            $inner_sql .= '
    ' . get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'visible_categories' => 'category_id', 'visible_images' => 'id'), 'WHERE', true);
        }
    } else {
        if (empty($page['items'])) {
            return;
            // nothing to do
        }
        $inner_sql .= '
WHERE id IN (' . implode(',', $page['items']) . ')';
    }
    //-------------------------------------- initialize the calendar parameters ---
    pwg_debug('start initialize_calendar');
    $fields = array('created' => array('label' => l10n('Creation date')), 'posted' => array('label' => l10n('Post date')));
    $styles = array('monthly' => array('include' => 'calendar_monthly.class.php', 'view_calendar' => true, 'classname' => 'CalendarMonthly'), 'weekly' => array('include' => 'calendar_weekly.class.php', 'view_calendar' => false, 'classname' => 'CalendarWeekly'));
    $views = array(CAL_VIEW_LIST, CAL_VIEW_CALENDAR);
    // Retrieve calendar field
    isset($fields[$page['chronology_field']]) or fatal_error('bad chronology field');
    // Retrieve style
    if (!isset($styles[$page['chronology_style']])) {
        $page['chronology_style'] = 'monthly';
    }
    $cal_style = $page['chronology_style'];
    $classname = $styles[$cal_style]['classname'];
    include PHPWG_ROOT_PATH . 'include/' . $styles[$cal_style]['include'];
    $calendar = new $classname();
    // Retrieve view
    if (!isset($page['chronology_view']) or !in_array($page['chronology_view'], $views)) {
        $page['chronology_view'] = CAL_VIEW_LIST;
    }
    if (CAL_VIEW_CALENDAR == $page['chronology_view'] and !$styles[$cal_style]['view_calendar']) {
        $page['chronology_view'] = CAL_VIEW_LIST;
    }
    // perform a sanity check on $requested
    if (!isset($page['chronology_date'])) {
        $page['chronology_date'] = array();
    }
    while (count($page['chronology_date']) > 3) {
        array_pop($page['chronology_date']);
    }
    $any_count = 0;
    for ($i = 0; $i < count($page['chronology_date']); $i++) {
        if ($page['chronology_date'][$i] == 'any') {
            if ($page['chronology_view'] == CAL_VIEW_CALENDAR) {
                // we dont allow any in calendar view
                while ($i < count($page['chronology_date'])) {
                    array_pop($page['chronology_date']);
                }
                break;
            }
            $any_count++;
        } elseif ($page['chronology_date'][$i] == '') {
            while ($i < count($page['chronology_date'])) {
                array_pop($page['chronology_date']);
            }
        } else {
            $page['chronology_date'][$i] = (int) $page['chronology_date'][$i];
        }
    }
    if ($any_count == 3) {
        array_pop($page['chronology_date']);
    }
    $calendar->initialize($inner_sql);
    //echo ('<pre>'. var_export($calendar, true) . '</pre>');
    $must_show_list = true;
    // true until calendar generates its own display
    if (script_basename() != 'picture') {
        if ($calendar->generate_category_content()) {
            $page['items'] = array();
            $must_show_list = false;
        }
        $page['comment'] = '';
        $template->assign('FILE_CHRONOLOGY_VIEW', 'month_calendar.tpl');
        foreach ($styles as $style => $style_data) {
            foreach ($views as $view) {
                if ($style_data['view_calendar'] or $view != CAL_VIEW_CALENDAR) {
                    $selected = false;
                    if ($style != $cal_style) {
                        $chronology_date = array();
                        if (isset($page['chronology_date'][0])) {
                            $chronology_date[] = $page['chronology_date'][0];
                        }
                    } else {
                        $chronology_date = $page['chronology_date'];
                    }
                    $url = duplicate_index_url(array('chronology_style' => $style, 'chronology_view' => $view, 'chronology_date' => $chronology_date));
                    if ($style == $cal_style and $view == $page['chronology_view']) {
                        $selected = true;
                    }
                    $template->append('chronology_views', array('VALUE' => $url, 'CONTENT' => l10n('chronology_' . $style . '_' . $view), 'SELECTED' => $selected));
                }
            }
        }
        $url = duplicate_index_url(array(), array('start', 'chronology_date'));
        $calendar_title = '<a href="' . $url . '">' . $fields[$page['chronology_field']]['label'] . '</a>';
        $calendar_title .= $calendar->get_display_name();
        $template->assign('chronology', array('TITLE' => $calendar_title));
    }
    // end category calling
    if ($must_show_list) {
        if (isset($page['super_order_by'])) {
            $order_by = $conf['order_by'];
        } else {
            if (count($page['chronology_date']) == 0 or in_array('any', $page['chronology_date'])) {
                // selected period is very big so we show newest first
                $order = ' DESC, ';
            } else {
                // selected period is small (month,week) so we show oldest first
                $order = ' ASC, ';
            }
            $order_by = str_replace('ORDER BY ', 'ORDER BY ' . $calendar->date_field . $order, $conf['order_by']);
        }
        if ('categories' == $page['section'] && !isset($page['category']) && (count($page['chronology_date']) == 0 or $page['chronology_date'][0] == 'any' && count($page['chronology_date']) == 1)) {
            $cache_key = $persistent_cache->make_key($user['id'] . $user['cache_update_time'] . $calendar->date_field . $order_by);
        }
        if (!isset($cache_key) || !$persistent_cache->get($cache_key, $page['items'])) {
            $query = 'SELECT DISTINCT id ' . $calendar->inner_sql . '
  ' . $calendar->get_date_where() . '
  ' . $order_by;
            $page['items'] = array_from_query($query, 'id');
            if (isset($cache_key)) {
                $persistent_cache->set($cache_key, $page['items']);
            }
        }
    }
    pwg_debug('end initialize_calendar');
}
Ejemplo n.º 8
0
;';
$author_counts = array();
$result = pwg_query($query);
while ($row = pwg_db_fetch_assoc($result)) {
    if (!isset($author_counts[$row['author']])) {
        $author_counts[$row['author']] = 0;
    }
    $author_counts[$row['author']]++;
}
foreach ($author_counts as $author => $counter) {
    $authors[] = array('author' => $author, 'counter' => $counter);
}
$template->assign('AUTHORS', $authors);
//------------------------------------------------------------- categories form
$query = '
SELECT id,name,global_rank,uppercats
  FROM ' . CATEGORIES_TABLE . '
' . get_sql_condition_FandF(array('forbidden_categories' => 'id', 'visible_categories' => 'id'), 'WHERE') . '
;';
display_select_cat_wrapper($query, array(), 'category_options', true);
// include menubar
$themeconf = $template->get_template_vars('themeconf');
if (!isset($themeconf['hide_menu_on']) or !in_array('theSearchPage', $themeconf['hide_menu_on'])) {
    include PHPWG_ROOT_PATH . 'include/menubar.inc.php';
}
//------------------------------------------------------------ html code display
include PHPWG_ROOT_PATH . 'include/page_header.php';
trigger_notify('loc_end_search');
flush_page_messages();
$template->pparse('search');
include PHPWG_ROOT_PATH . 'include/page_tail.php';
Ejemplo n.º 9
0
                check_user_favorites();
                $page = array_merge($page, array('title' => l10n('Favorites')));
                if (!empty($_GET['action']) && $_GET['action'] == 'remove_all_from_favorites') {
                    $query = '
DELETE FROM ' . FAVORITES_TABLE . '
  WHERE user_id = ' . $user['id'] . '
;';
                    pwg_query($query);
                    redirect(make_index_url(array('section' => 'favorites')));
                } else {
                    $query = '
SELECT image_id
  FROM ' . FAVORITES_TABLE . '
    INNER JOIN ' . IMAGES_TABLE . ' ON image_id = id
  WHERE user_id = ' . $user['id'] . '
' . get_sql_condition_FandF(array('visible_images' => 'id'), 'AND') . '
  ' . $conf['order_by'] . '
;';
                    $page = array_merge($page, array('items' => query2array($query, null, 'image_id')));
                    if (count($page['items']) > 0) {
                        $template->assign('favorite', array('U_FAVORITE' => add_url_params(make_index_url(array('section' => 'favorites')), array('action' => 'remove_all_from_favorites'))));
                    }
                }
            } else {
                if ($page['section'] == 'recent_pics') {
                    if (!isset($page['super_order_by'])) {
                        $conf['order_by'] = str_replace('ORDER BY ', 'ORDER BY date_available DESC,', $conf['order_by']);
                    }
                    $query = '
SELECT DISTINCT(id)
  FROM ' . IMAGES_TABLE . '
Ejemplo n.º 10
0
        $categories[] = $row;
        $category_ids[] = $row['id'];
    }
    unset($image_id);
}
if ($conf['display_fromto']) {
    if (count($category_ids) > 0) {
        $query = '
SELECT
    category_id,
    MIN(date_creation) AS `from`,
    MAX(date_creation) AS `to`
  FROM ' . IMAGE_CATEGORY_TABLE . '
    INNER JOIN ' . IMAGES_TABLE . ' ON image_id = id
  WHERE category_id IN (' . implode(',', $category_ids) . ')
' . get_sql_condition_FandF(array('visible_categories' => 'category_id', 'visible_images' => 'id'), 'AND') . '
  GROUP BY category_id
;';
        $dates_of_category = query2array($query, 'category_id');
    }
}
if ($page['section'] == 'recent_cats') {
    usort($categories, 'global_rank_compare');
}
if (count($categories) > 0) {
    $infos_of_image = array();
    $new_image_ids = array();
    $query = '
SELECT *
  FROM ' . IMAGES_TABLE . '
  WHERE id IN (' . implode(',', $image_ids) . ')
Ejemplo n.º 11
0
/**
 * Get standard sql where in order to restrict and filter categories and images.
 * IMAGE_CATEGORY_TABLE must be named "ic" in the query
 *
 * @param string $prefix_condition
 * @param string $img_field
 * @param bool $force_one_condition
 * @return string
 */
function get_std_sql_where_restrict_filter($prefix_condition, $img_field = 'ic.image_id', $force_one_condition = false)
{
    return get_sql_condition_FandF(array('forbidden_categories' => 'ic.category_id', 'visible_categories' => 'ic.category_id', 'visible_images' => $img_field), $prefix_condition, $force_one_condition);
}
Ejemplo n.º 12
0
    return isset($match[1]) ? $match[1] : null;
}
$path = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL);
$file_part = get_file_from_path($path);
if (!$file_part) {
    do_error(400, 'Invalid request - path');
}
$query = 'SELECT * FROM ' . IMAGES_TABLE . ' WHERE path LIKE \'%' . pwg_db_real_escape_string($file_part) . '%\' LIMIT 1;';
$element_info = pwg_db_fetch_assoc(pwg_query($query));
if (empty($element_info)) {
    //make sure reply is the same for forbidden and nonexisiting files
    do_error(401, 'Access denied');
}
// $filter['visible_categories'] and $filter['visible_images']
// are not used because it's not necessary (filter <> restriction)
$query = '
SELECT id
  FROM ' . CATEGORIES_TABLE . '
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' ON category_id = id
  WHERE image_id = ' . $element_info['id'] . '
' . get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'forbidden_images' => 'image_id'), '    AND') . '
  LIMIT 1
;';
if (pwg_db_num_rows(pwg_query($query)) < 1) {
    do_error(401, 'Access denied');
}
include_once PHPWG_ROOT_PATH . 'include/functions_picture.inc.php';
if (!$user['enabled_high'] && strpos($element_info['path'], $path) !== false) {
    do_error(401, 'Access denied');
}
echo 'OK';
Ejemplo n.º 13
0
/**
 * API method
 * Rates an image
 * @param mixed[] $params
 *    @option int image_id
 *    @option float rate
 */
function ws_images_rate($params, $service)
{
    $query = '
SELECT DISTINCT id
  FROM ' . IMAGES_TABLE . '
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' ON id=image_id
  WHERE id=' . $params['image_id'] . get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'forbidden_images' => 'id'), '    AND') . '
  LIMIT 1
;';
    if (pwg_db_num_rows(pwg_query($query)) == 0) {
        return new PwgError(404, 'Invalid image_id or access denied');
    }
    include_once PHPWG_ROOT_PATH . 'include/functions_rate.inc.php';
    $res = rate_picture($params['image_id'], (int) $params['rate']);
    if ($res == false) {
        global $conf;
        return new PwgError(403, 'Forbidden or rate not in ' . implode(',', $conf['rate_items']));
    }
    return $res;
}
Ejemplo n.º 14
0
function osm_get_items($page)
{
    // Limit search by category, by tag, by smartalbum
    $LIMIT_SEARCH = "";
    $INNER_JOIN = "";
    if (isset($page['section'])) {
        if ($page['section'] === 'categories' and isset($page['category']) and isset($page['category']['id'])) {
            $LIMIT_SEARCH = "FIND_IN_SET(" . $page['category']['id'] . ", c.uppercats) AND ";
            $INNER_JOIN = "INNER JOIN " . CATEGORIES_TABLE . " AS c ON ic.category_id = c.id";
        }
        if ($page['section'] === 'tags' and isset($page['tags']) and isset($page['tags'][0]['id'])) {
            $items = get_image_ids_for_tags(array($page['tags'][0]['id']));
            if (!empty($items)) {
                $LIMIT_SEARCH = "ic.image_id IN (" . implode(',', $items) . ") AND ";
            }
        }
        if ($page['section'] === 'tags' and isset($page['category']) and isset($page['category']['id'])) {
            $LIMIT_SEARCH = "FIND_IN_SET(" . $page['category']['id'] . ", c.uppercats) AND ";
            $INNER_JOIN = "INNER JOIN " . CATEGORIES_TABLE . " AS c ON ic.category_id = c.id";
        }
    }
    $forbidden = get_sql_condition_FandF(array('forbidden_categories' => 'ic.category_id', 'visible_categories' => 'ic.category_id', 'visible_images' => 'i.id'), "\n AND");
    /* We have lat and lng coordonate for virtual album */
    if (isset($_GET['min_lat']) and isset($_GET['max_lat']) and isset($_GET['min_lng']) and isset($_GET['max_lng'])) {
        $LIMIT_SEARCH = "";
        $INNER_JOIN = "";
        /* Delete all previous album */
        $query = "SELECT `id` FROM " . CATEGORIES_TABLE . " WHERE `name` = 'Locations' AND `comment` LIKE '%OSM plugin%';";
        $ids = array_from_query($query, 'id');
        /* Unlink items for the previous album */
        delete_categories($ids, $photo_deletion_mode = 'no_delete');
        /* Create an album */
        $options = array('comment' => 'Generated by OSM plugin');
        $osm_album = create_virtual_category('Locations', NULL, $options);
        /* Create a sub album */
        $options = array('comment' => "OSM virtual album\nlat:" . $_GET['min_lat'] . " " . $_GET['max_lat'] . "\nlng:" . $_GET['min_lng'] . " " . $_GET['max_lng']);
        $osm_sub_album = create_virtual_category("OSM" . $_GET['min_lat'] . "", $osm_album['id'], $options);
        /* Get all items inside the lat and lng */
        $query = "SELECT  `id`, `latitude`, `longitude` \n    FROM " . IMAGES_TABLE . " AS i\n        INNER JOIN " . IMAGE_CATEGORY_TABLE . " AS ic ON id = ic.image_id\n    WHERE " . $LIMIT_SEARCH . " `latitude` IS NOT NULL AND `longitude` IS NOT NULL \n    AND `latitude` > " . $_GET['min_lat'] . " AND `latitude` < " . $_GET['max_lat'] . "\n    AND `longitude` > " . $_GET['min_lng'] . " AND `longitude` < " . $_GET['max_lng'] . "\n    " . $forbidden . ";";
        $items = hash_from_query($query, 'id');
        /* Add  items to the new sub album */
        foreach ($items as $item) {
            $query = "INSERT INTO " . IMAGE_CATEGORY_TABLE . " ( `image_id` ,`category_id` ,`rank` ) VALUES ( '" . $item['id'] . "', '" . $osm_sub_album['id'] . "', NULL );";
            pwg_query($query);
        }
        /* Redirect to the new album */
        header('Location: ' . get_absolute_root_url() . 'index.php?/category/' . $osm_sub_album['id']);
        exit;
    }
    // Fetch data with latitude and longitude
    //$query="SELECT `latitude`, `longitude`, `name`, `path` FROM ".IMAGES_TABLE." WHERE `latitude` IS NOT NULL AND `longitude` IS NOT NULL;";
    // SUBSTRING_INDEX(TRIM(LEADING '.' FROM `path`), '.', 1) full path without filename extension
    // SUBSTRING_INDEX(TRIM(LEADING '.' FROM `path`), '.', -1) full path with only filename extension
    if (isset($page['image_id'])) {
        $LIMIT_SEARCH .= 'i.id = ' . $page['image_id'] . ' AND ';
    }
    $query = "SELECT i.latitude, i.longitude,\n    IFNULL(i.name, '') AS `name`,\n    IF(i.representative_ext IS NULL,\n        CONCAT(SUBSTRING_INDEX(TRIM(LEADING '.' FROM i.path), '.', 1 ), '-sq.', SUBSTRING_INDEX(TRIM(LEADING '.' FROM i.path), '.', -1 )),\n        TRIM(LEADING '.' FROM\n            REPLACE(i.path, TRIM(TRAILING '.' FROM SUBSTRING_INDEX(i.path, '/', -1 )),\n                CONCAT('pwg_representative/',\n                    CONCAT(\n                        TRIM(TRAILING '.' FROM SUBSTRING_INDEX( SUBSTRING_INDEX(i.path, '/', -1 ) , '.', 1 )),\n                        CONCAT('-sq.', i.representative_ext)\n                    )\n                )\n            )\n        )\n    ) AS `pathurl`,\n    TRIM(TRAILING '/' FROM CONCAT( i.id, '/category/', IFNULL(i.storage_category_id, '') ) ) AS `imgurl`,\n    IFNULL(i.comment, '') AS `comment`,\n    IFNULL(i.author, '') AS `author`,\n    i.width\n        FROM " . IMAGES_TABLE . " AS i\n            INNER JOIN (" . IMAGE_CATEGORY_TABLE . " AS ic " . $INNER_JOIN . ") ON i.id = ic.image_id\n            WHERE " . $LIMIT_SEARCH . " i.latitude IS NOT NULL AND i.longitude IS NOT NULL " . $forbidden . " GROUP BY i.id;";
    //echo $query;
    $php_data = array_from_query($query);
    //print_r($php_data);
    $js_data = array();
    foreach ($php_data as $array) {
        // MySQL did all the job
        //print_r($array);
        $js_data[] = array((double) $array['latitude'], (double) $array['longitude'], $array['name'], get_absolute_root_url() . "i.php?" . $array['pathurl'], get_absolute_root_url() . "picture.php?/" . $array['imgurl'], $array['comment'], $array['author'], (int) $array['width']);
    }
    /* START Debug generate dummy data
       $js_data = array();
       $str = 'abcdef';
       $minLat = -90.00;
       $maxLat = 90.00;
       $minLon = -180.00;
       $maxLon = 180.00;
       for ($i = 1; $i <= 5000; $i++)
       {
           $js_data[] = array( (double)$minLat + (double)((float)rand()/(float)getrandmax() * (($maxLat - $minLat) + 1)),
                      (double)$minLon + (double)((float)rand()/(float)getrandmax() * (($maxLon - $minLon) + 1)),
                      str_shuffle($str),
                      "http://placehold.it/120x120",
                      "http://placehold.it/200x200",
                      "Comment",
                      "Author",
                      (int)120
                      );
       }
       END Debug generate dummy data */
    return $js_data;
}
Ejemplo n.º 15
0
function pshare_is_photo_visible($image_id)
{
    $query = '
SELECT id
  FROM ' . CATEGORIES_TABLE . '
    INNER JOIN ' . IMAGE_CATEGORY_TABLE . ' ON category_id = id
  WHERE image_id = ' . $image_id . '
' . get_sql_condition_FandF(array('forbidden_categories' => 'category_id', 'forbidden_images' => 'image_id'), '    AND') . '
  LIMIT 1
;';
    if (pwg_db_num_rows(pwg_query($query)) < 1) {
        return false;
    }
    return true;
}