/**
     * Generate search query based on set filters and obtain count of results
     */
    function query_init()
    {
        global $current_User;
        // Call reset to init the ItemQuery
        // This prevents from adding the same conditions twice if the ItemQuery was already initialized
        $this->reset();
        if (empty($this->filters)) {
            // Filters have not been set before, we'll use the default filterset:
            // If there is a preset filter, we need to activate its specific defaults:
            $this->filters['filter_preset'] = param($this->param_prefix . 'filter_preset', 'string', $this->default_filters['filter_preset'], true);
            $this->activate_preset_filters();
            // Use the default filters:
            $this->set_filters($this->default_filters);
        }
        // echo '<br />ItemListLight query';
        //pre_dump( $this->filters );
        // GENERATE THE QUERY:
        /*
         * Filtering stuff:
         */
        if (!is_null($this->Blog)) {
            // Get the posts only for current Blog
            $this->ItemQuery->where_chapter2($this->Blog, $this->filters['cat_array'], $this->filters['cat_modifier'], $this->filters['cat_focus'], $this->filters['coll_IDs']);
        } else {
            // If we want to get the posts from all blogs
            // Save for future use (permission checks..)
            $this->ItemQuery->blog = 0;
            $this->ItemQuery->Blog = $this->Blog;
        }
        $this->ItemQuery->where_tags($this->filters['tags']);
        $this->ItemQuery->where_author($this->filters['authors']);
        $this->ItemQuery->where_author_logins($this->filters['authors_login']);
        $this->ItemQuery->where_assignees($this->filters['assignees']);
        $this->ItemQuery->where_assignees_logins($this->filters['assignees_login']);
        $this->ItemQuery->where_author_assignee($this->filters['author_assignee']);
        $this->ItemQuery->where_locale($this->filters['lc']);
        $this->ItemQuery->where_statuses($this->filters['statuses']);
        $this->ItemQuery->where_types($this->filters['types']);
        $this->ItemQuery->where_keywords($this->filters['keywords'], $this->filters['phrase'], $this->filters['exact'], $this->filters['keyword_scope']);
        $this->ItemQuery->where_ID($this->filters['post_ID'], $this->filters['post_title']);
        $this->ItemQuery->where_ID_list($this->filters['post_ID_list']);
        $this->ItemQuery->where_datestart($this->filters['ymdhms'], $this->filters['week'], $this->filters['ymdhms_min'], $this->filters['ymdhms_max'], $this->filters['ts_min'], $this->filters['ts_max']);
        $this->ItemQuery->where_datecreated($this->filters['ts_created_max']);
        $this->ItemQuery->where_visibility($this->filters['visibility_array'], $this->filters['coll_IDs']);
        $this->ItemQuery->where_featured($this->filters['featured']);
        /*
         * ORDER BY stuff:
         */
        if ($this->filters['post_ID_list'] && $this->filters['orderby'] == 'ID_list') {
            $order_by = 'FIELD(' . $this->Cache->dbIDname . ', ' . $this->filters['post_ID_list'] . ')';
        } elseif ($this->filters['orderby'] == 'ID_list') {
            // Use blog setting here because 'orderby' might be set to 'ID_list' as default filter
            $this->filters['orderby'] = $this->Blog->get_setting('orderby');
        }
        if (empty($order_by)) {
            $available_fields = array_keys(get_available_sort_options());
            // Extend general list to allow order posts by these fields as well for some special cases
            $available_fields[] = 'creator_user_ID';
            $available_fields[] = 'assigned_user_ID';
            $available_fields[] = 'pst_ID';
            $available_fields[] = 'datedeadline';
            $available_fields[] = 'T_categories.cat_name';
            $available_fields[] = 'T_categories.cat_order';
            $order_by = gen_order_clause($this->filters['orderby'], $this->filters['order'], $this->Cache->dbprefix, $this->Cache->dbIDname, $available_fields);
        }
        $this->ItemQuery->order_by($order_by);
        /*
         * GET TOTAL ROW COUNT:
         */
        if ($this->single_post) {
            // Single post: no paging required!
            $this->total_rows = 1;
            $this->total_pages = 1;
            $this->page = 1;
        } elseif ($this->filters['unit'] == 'days' || $this->filters['unit'] == 'all') {
            $this->total_rows = NULL;
            // unknown!
            $this->total_pages = 1;
            $this->page = 1;
        } elseif ($this->filters['unit'] == 'posts') {
            // Calculate a count of the posts
            if ($this->ItemQuery->get_group_by() == '') {
                // SQL query without GROUP BY clause
                $sql_count = 'SELECT COUNT( DISTINCT ' . $this->Cache->dbIDname . ' )' . $this->ItemQuery->get_from() . $this->ItemQuery->get_where() . $this->ItemQuery->get_limit();
            } else {
                // SQL query with GROUP BY clause, Summarize a count of each grouped result
                $sql_count = 'SELECT SUM( cnt_tbl.cnt ) FROM (
						SELECT COUNT( DISTINCT ' . $this->Cache->dbIDname . ' ) AS cnt ' . $this->ItemQuery->get_from() . $this->ItemQuery->get_where() . $this->ItemQuery->get_group_by() . $this->ItemQuery->get_limit() . '
					) AS cnt_tbl ';
            }
            parent::count_total_rows($sql_count);
        } else {
            debug_die('Unhandled LIMITING mode in ItemList:' . $this->filters['unit'] . ' (paged mode is obsolete)');
        }
        /*
         * Paging LIMITs:
         */
        if ($this->single_post) {
            // Single post: no paging required!
        } elseif ($this->filters['unit'] == 'all') {
            // We want ALL results!
        } elseif ($this->filters['unit'] == 'posts') {
            // TODO: dh> check if $limit is NULL!? - though it should not arrive at $page>1 then..
            // echo 'LIMIT POSTS ';
            $pgstrt = '';
            if ($this->page > 1) {
                // We have requested a specific page number
                $pgstrt = (intval($this->page) - 1) * $this->limit . ', ';
            }
            $this->ItemQuery->LIMIT($pgstrt . $this->limit);
        } elseif ($this->filters['unit'] == 'days') {
            // We are going to limit to x days:
            // echo 'LIMIT DAYS ';
            if (empty($this->filters['ymdhms_min'])) {
                // We have no start date, we'll display the last x days:
                if (!empty($this->filters['keywords']) || !empty($this->filters['cat_array']) || !empty($this->filters['authors'])) {
                    // We are in DAYS mode but we can't restrict on these! (TODO: ?)
                    $limits = '';
                } else {
                    // We are going to limit to LAST x days:
                    $lastpostdate = $this->get_lastpostdate();
                    $lastpostdate = mysql2date('Y-m-d 00:00:00', $lastpostdate);
                    $lastpostdate = mysql2date('U', $lastpostdate);
                    // go back x days
                    $otherdate = date('Y-m-d H:i:s', $lastpostdate - ($this->limit - 1) * 86400);
                    $this->ItemQuery->WHERE_and($this->Cache->dbprefix . 'datestart > \'' . $otherdate . '\'');
                }
            } else {
                // We have a start date, we'll display x days starting from that point:
                // $dstart_mysql has been calculated earlier
                // TODO: this is redundant with previous dstart processing:
                // Add trailing 0s: YYYYMMDDHHMMSS
                $dstart0 = $this->filters['ymdhms_min'] . '00000000000000';
                $dstart_mysql = substr($dstart0, 0, 4) . '-' . substr($dstart0, 4, 2) . '-' . substr($dstart0, 6, 2) . ' ' . substr($dstart0, 8, 2) . ':' . substr($dstart0, 10, 2) . ':' . substr($dstart0, 12, 2);
                $dstart_ts = mysql2timestamp($dstart_mysql);
                // go forward x days
                $enddate_ts = date('Y-m-d H:i:s', $dstart_ts + $this->limit * 86400);
                $this->ItemQuery->WHERE_and($this->Cache->dbprefix . 'datestart < \'' . $enddate_ts . '\'');
            }
        } else {
            debug_die('Unhandled LIMITING mode in ItemList:' . $this->filters['unit'] . ' (paged mode is obsolete)');
        }
    }
    /**
     *
     *
     * @todo count?
     */
    function query_init()
    {
        global $current_User;
        if (empty($this->filters)) {
            // Filters have not been set before, we'll use the default filterset:
            // If there is a preset filter, we need to activate its specific defaults:
            $this->filters['filter_preset'] = param($this->param_prefix . 'filter_preset', 'string', $this->default_filters['filter_preset'], true);
            $this->activate_preset_filters();
            // Use the default filters:
            $this->set_filters($this->default_filters);
        }
        // echo '<br />ItemListLight query';
        //pre_dump( $this->filters );
        // GENERATE THE QUERY:
        /*
         * filtering stuff:
         */
        if (!is_null($this->Blog)) {
            // Get the posts only for current Blog
            $this->ItemQuery->where_chapter2($this->Blog, $this->filters['cat_array'], $this->filters['cat_modifier'], $this->filters['cat_focus']);
        } else {
            // If we want to get the posts from all blogs
            // Save for future use (permission checks..)
            $this->ItemQuery->blog = 0;
            $this->ItemQuery->Blog = $this->Blog;
        }
        $this->ItemQuery->where_tags($this->filters['tags']);
        $this->ItemQuery->where_author($this->filters['authors']);
        $this->ItemQuery->where_author_logins($this->filters['authors_login']);
        $this->ItemQuery->where_assignees($this->filters['assignees']);
        $this->ItemQuery->where_assignees_logins($this->filters['assignees_login']);
        $this->ItemQuery->where_author_assignee($this->filters['author_assignee']);
        $this->ItemQuery->where_locale($this->filters['lc']);
        $this->ItemQuery->where_statuses($this->filters['statuses']);
        $this->ItemQuery->where_types($this->filters['types']);
        $this->ItemQuery->where_keywords($this->filters['keywords'], $this->filters['phrase'], $this->filters['exact']);
        $this->ItemQuery->where_ID($this->filters['post_ID'], $this->filters['post_title']);
        $this->ItemQuery->where_ID_list($this->filters['post_ID_list']);
        $this->ItemQuery->where_datestart($this->filters['ymdhms'], $this->filters['week'], $this->filters['ymdhms_min'], $this->filters['ymdhms_max'], $this->filters['ts_min'], $this->filters['ts_max']);
        $this->ItemQuery->where_datecreated($this->filters['ts_created_max']);
        $this->ItemQuery->where_visibility($this->filters['visibility_array']);
        $this->ItemQuery->where_featured($this->filters['featured']);
        /*
         * ORDER BY stuff:
         */
        if ($this->filters['post_ID_list'] && $this->filters['orderby'] == 'ID_list') {
            $order_by = 'FIELD(' . $this->Cache->dbIDname . ', ' . $this->filters['post_ID_list'] . ')';
        } elseif ($this->filters['orderby'] == 'ID_list') {
            // Use blog setting here because 'orderby' might be set to 'ID_list' as default filter
            $this->filters['orderby'] = $this->Blog->get_setting('orderby');
        }
        if (empty($order_by)) {
            $order_by = gen_order_clause($this->filters['orderby'], $this->filters['order'], $this->Cache->dbprefix, $this->Cache->dbIDname);
        }
        $this->ItemQuery->order_by($order_by);
        /*
         * GET TOTAL ROW COUNT:
         */
        if ($this->single_post) {
            // Single post: no paging required!
            $this->total_rows = 1;
            $this->total_pages = 1;
            $this->page = 1;
        } elseif ($this->filters['unit'] == 'days' || $this->filters['unit'] == 'all') {
            $this->total_rows = NULL;
            // unknown!
            $this->total_pages = 1;
            $this->page = 1;
        } elseif ($this->filters['unit'] == 'posts') {
            /*
             * TODO: The result is incorrect when using AND on categories
             * We would need to use a HAVING close and thyen COUNT, which would be a subquery
             * This is nto compatible with mysql 3.23
             * We need fallback code.
             */
            $sql_count = '
				SELECT COUNT( DISTINCT ' . $this->Cache->dbIDname . ') ' . $this->ItemQuery->get_from() . $this->ItemQuery->get_where();
            //echo $DB->format_query( $sql_count );
            parent::count_total_rows($sql_count);
            //echo '<br />'.$this->total_rows;
        } else {
            debug_die('Unhandled LIMITING mode in ItemList:' . $this->filters['unit'] . ' (paged mode is obsolete)');
        }
        /*
         * Paging LIMITs:
         */
        if ($this->single_post) {
            // Single post: no paging required!
        } elseif ($this->filters['unit'] == 'all') {
            // We want ALL results!
        } elseif ($this->filters['unit'] == 'posts') {
            // TODO: dh> check if $limit is NULL!? - though it should not arrive at $page>1 then..
            // echo 'LIMIT POSTS ';
            $pgstrt = '';
            if ($this->page > 1) {
                // We have requested a specific page number
                $pgstrt = (intval($this->page) - 1) * $this->limit . ', ';
            }
            $this->ItemQuery->LIMIT($pgstrt . $this->limit);
        } elseif ($this->filters['unit'] == 'days') {
            // We are going to limit to x days:
            // echo 'LIMIT DAYS ';
            if (empty($this->filters['ymdhms_min'])) {
                // We have no start date, we'll display the last x days:
                if (!empty($this->filters['keywords']) || !empty($this->filters['cat_array']) || !empty($this->filters['authors'])) {
                    // We are in DAYS mode but we can't restrict on these! (TODO: ?)
                    $limits = '';
                } else {
                    // We are going to limit to LAST x days:
                    $lastpostdate = $this->get_lastpostdate();
                    $lastpostdate = mysql2date('Y-m-d 00:00:00', $lastpostdate);
                    $lastpostdate = mysql2date('U', $lastpostdate);
                    // go back x days
                    $otherdate = date('Y-m-d H:i:s', $lastpostdate - ($this->limit - 1) * 86400);
                    $this->ItemQuery->WHERE_and($this->Cache->dbprefix . 'datestart > \'' . $otherdate . '\'');
                }
            } else {
                // We have a start date, we'll display x days starting from that point:
                // $dstart_mysql has been calculated earlier
                // TODO: this is redundant with previous dstart processing:
                // Add trailing 0s: YYYYMMDDHHMMSS
                $dstart0 = $this->filters['ymdhms_min'] . '00000000000000';
                $dstart_mysql = substr($dstart0, 0, 4) . '-' . substr($dstart0, 4, 2) . '-' . substr($dstart0, 6, 2) . ' ' . substr($dstart0, 8, 2) . ':' . substr($dstart0, 10, 2) . ':' . substr($dstart0, 12, 2);
                $dstart_ts = mysql2timestamp($dstart_mysql);
                // go forward x days
                $enddate_ts = date('Y-m-d H:i:s', $dstart_ts + $this->limit * 86400);
                $this->ItemQuery->WHERE_and($this->Cache->dbprefix . 'datestart < \'' . $enddate_ts . '\'');
            }
        } else {
            debug_die('Unhandled LIMITING mode in ItemList:' . $this->filters['unit'] . ' (paged mode is obsolete)');
        }
    }
示例#3
0
 /**
  * Load blogs a user has permissions for.
  *
  * @param string permission: 'member' (default), 'browse' (files)
  * @param string
  * @param integer user ID
  * @return array The blog IDs
  */
 function load_user_blogs($permname = 'blog_ismember', $permlevel = 'view', $user_ID = NULL, $order_by = '', $order_dir = '', $limit = NULL)
 {
     global $DB, $Settings, $Debuglog;
     $Debuglog->add("Loading <strong>{$this->objtype}(permission: {$permname})</strong> into cache", 'dataobjects');
     if ($order_by == '') {
         // Use default value from settings
         $order_by = $Settings->get('blogs_order_by');
     }
     if ($order_dir == '') {
         // Use default value from settings
         $order_dir = $Settings->get('blogs_order_dir');
     }
     if (is_null($user_ID)) {
         global $current_User;
         $user_ID = $current_User->ID;
         $for_User = $current_User;
     } else {
         $UserCache =& get_UserCache();
         $for_User =& $UserCache->get_by_ID($user_ID);
     }
     $for_User->get_Group();
     // ensure Group is set
     $Group = $for_User->Group;
     // First check if we have a global access perm:
     if ($Group->check_perm('blogs', $permlevel)) {
         // If group grants a global permission:
         $this->load_all($order_by, $order_dir);
         return $this->get_ID_array();
     }
     // Note: We only JOIN in the advanced perms if any given blog has them enabled,
     // otherwise they are ignored!
     $sql = "SELECT DISTINCT T_blogs.*\n\t\t          FROM T_blogs LEFT JOIN T_coll_user_perms ON (blog_advanced_perms <> 0\n\t\t          \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND blog_ID = bloguser_blog_ID\n\t\t          \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND bloguser_user_ID = {$user_ID} )\n\t\t          \t\t LEFT JOIN T_coll_group_perms ON (blog_advanced_perms <> 0\n\t\t          \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND blog_ID = bloggroup_blog_ID\n\t\t          \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND bloggroup_group_ID = {$Group->ID} )\n\t\t         WHERE ";
     if ($permname != 'blog_admin') {
         // Only the admin perm is not convered by being the owner of the blog:
         $sql .= "blog_owner_user_ID = {$user_ID} ";
     }
     switch ($permname) {
         case 'blog_ismember':
             $sql .= "OR bloguser_ismember <> 0\n\t\t\t\t\t\t\t\t OR bloggroup_ismember <> 0";
             break;
         case 'blog_post_statuses':
             $sql .= "OR bloguser_perm_poststatuses <> ''\n\t\t\t\t\t\t\t   OR bloggroup_perm_poststatuses <> ''";
             break;
         case 'blog_comments':
             // user needs to have permission for at least one kind of comments
             $sql .= "OR bloguser_perm_cmtstatuses <> ''\n\t\t\t\t\t\tOR bloggroup_perm_cmtstatuses <> ''";
             break;
         case 'stats':
             $permname = 'blog_properties';
             // TEMP
         // TEMP
         case 'blog_cats':
         case 'blog_properties':
         case 'blog_admin':
         case 'blog_media_browse':
             $short_permname = substr($permname, 5);
             $sql .= "OR bloguser_perm_{$short_permname} <> 0\n\t\t\t\t\t\t\t\t OR bloggroup_perm_{$short_permname} <> 0";
             break;
         default:
             debug_die('BlogCache::load_user_blogs() : Unsupported perm [' . $permname . ']!');
     }
     $sql .= " ORDER BY " . gen_order_clause($order_by, $order_dir, $this->dbprefix, $this->dbIDname);
     if ($limit) {
         $sql .= " LIMIT {$limit}";
     }
     foreach ($DB->get_results($sql, OBJECT, 'Load user blog list') as $row) {
         // Instantiate a custom object
         $this->instantiate($row);
     }
     return $DB->get_col(NULL, 0);
 }
    /**
     * Initialize sql query
     *
     * @todo count?
     *
     * @param boolean
     */
    function query_init($force_init = false)
    {
        global $DB;
        if (!$force_init && !empty($this->query_is_initialized)) {
            // Don't initialize query because it was already done
            return;
        }
        // Save to know the query init was done
        $this->query_is_initialized = true;
        if (empty($this->filters)) {
            // Filters have not been set before, we'll use the default filterset:
            // If there is a preset filter, we need to activate its specific defaults:
            $this->filters['filter_preset'] = param($this->param_prefix . 'filter_preset', 'string', $this->default_filters['filter_preset'], true);
            $this->activate_preset_filters();
            // Use the default filters:
            $this->set_filters($this->default_filters);
        }
        // GENERATE THE QUERY:
        /*
         * Resrict to selected blog
         */
        // If we dont have specific comment or post ids, we have to restric to blog
        if (!is_null($this->Blog) && ($this->filters['post_ID'] == NULL || !empty($this->filters['post_ID']) && substr($this->filters['post_ID'], 0, 1) == '-') && ($this->filters['comment_ID'] == NULL || !empty($this->filters['comment_ID']) && substr($this->filters['comment_ID'], 0, 1) == '-') && ($this->filters['comment_ID_list'] == NULL || !empty($this->filters['comment_ID_list']) && substr($this->filters['comment_ID_list'], 0, 1) == '-')) {
            // restriction for blog
            $this->ItemQuery->where_chapter($this->Blog->ID);
        }
        /*
         * filtering stuff:
         */
        $this->CommentQuery->where_author($this->filters['author_IDs']);
        $this->CommentQuery->where_author_email($this->filters['author_email']);
        $this->CommentQuery->where_author_url($this->filters['author_url'], $this->filters['url_match'], $this->filters['include_emptyurl']);
        $this->CommentQuery->where_author_IP($this->filters['author_IP']);
        $this->ItemQuery->where_ID($this->filters['post_ID']);
        $this->CommentQuery->where_ID($this->filters['comment_ID'], $this->filters['author']);
        $this->CommentQuery->where_ID_list($this->filters['comment_ID_list']);
        $this->CommentQuery->where_rating($this->filters['rating_toshow'], $this->filters['rating_turn'], $this->filters['rating_limit']);
        $this->CommentQuery->where_keywords($this->filters['keywords'], $this->filters['phrase'], $this->filters['exact']);
        $this->CommentQuery->where_statuses($this->filters['statuses']);
        $this->CommentQuery->where_types($this->filters['types']);
        $this->ItemQuery->where_datestart('', '', '', '', $this->filters['timestamp_min'], $this->filters['timestamp_max']);
        if (!is_null($this->Blog) && isset($this->filters['user_perm'])) {
            // If Blog and required user permission is set, add the corresponding restriction
            $this->CommentQuery->user_perm_restrict($this->filters['user_perm'], $this->Blog->ID);
        }
        /*
         * ORDER BY stuff:
         */
        $available_sort_options = array('date', 'type', 'author', 'author_url', 'author_email', 'author_IP', 'spam_karma', 'status', 'item_ID');
        $order_by = gen_order_clause($this->filters['orderby'], $this->filters['order'], $this->Cache->dbprefix, $this->Cache->dbIDname, $available_sort_options);
        if ($this->filters['threaded_comments']) {
            // In mode "Threaded comments" we should get all replies in the begining of the list
            $order_by = $this->Cache->dbprefix . 'in_reply_to_cmt_ID DESC, ' . $order_by;
        }
        $this->CommentQuery->order_by($order_by);
        // GET Item IDs, this way we don't have to JOIN two times the items and the categories table into the comment query
        if (isset($this->filters['post_statuses'])) {
            // Set post statuses by filters
            $post_show_statuses = $this->filters['post_statuses'];
        } elseif (is_admin_page()) {
            // Allow all kind of post status ( This statuses will be filtered later by user perms )
            $post_show_statuses = get_visibility_statuses('keys');
        } else {
            // Allow only inskin statuses for posts
            $post_show_statuses = get_inskin_statuses(isset($this->Blog) ? $this->Blog->ID : NULL, 'post');
        }
        // Restrict post filters to available statuses. When blog = 0 we will check visibility statuses for each blog separately ( on the same query ).
        $this->ItemQuery->where_visibility($post_show_statuses);
        $sql_item_IDs = 'SELECT DISTINCT post_ID' . $this->ItemQuery->get_from();
        if (strpos($this->ItemQuery->get_from(), 'T_categories') === false && strpos($this->ItemQuery->get_where(), 'cat_blog_ID') !== false) {
            // Join categories table because it is required here for the field "cat_blog_ID"
            $sql_item_IDs .= ' INNER JOIN T_categories ON post_main_cat_ID = cat_ID ';
        }
        $sql_item_IDs .= $this->ItemQuery->get_where();
        $item_IDs = $DB->get_col($sql_item_IDs, 0, 'Get CommentQuery Item IDs');
        if (empty($item_IDs)) {
            // There is no item which belongs to the given blog and user may view it, so there are no comments either
            parent::count_total_rows(0);
            $this->CommentQuery->WHERE_and('FALSE');
            return;
        }
        $this->CommentQuery->where_post_ID(implode(',', $item_IDs));
        /*
         * Restrict to active comments by default, show expired comments only if it was requested
         * Note: This condition makes the CommentQuery a lot slower!
         */
        $this->CommentQuery->expiry_restrict($this->filters['expiry_statuses']);
        /*
         * GET TOTAL ROW COUNT:
         */
        $sql_count = '
				SELECT COUNT( ' . $this->Cache->dbIDname . ') ' . $this->CommentQuery->get_from() . $this->CommentQuery->get_where();
        parent::count_total_rows($sql_count);
        /*
         * Page set up:
         */
        if ($this->page > 1) {
            // We have requested a specific page number
            if ($this->limit > 0) {
                $pgstrt = '';
                $pgstrt = (intval($this->page) - 1) * $this->limit . ', ';
                $this->CommentQuery->LIMIT($pgstrt . $this->limit);
            }
        } else {
            $this->CommentQuery->LIMIT($this->limit);
        }
    }
    /**
     * Display the widget!
     *
     * @param array MUST contain at least the basic display params
     */
    function display($params)
    {
        global $localtimenow;
        $this->init_display($params);
        if ($this->disp_params['order_by'] == 'RAND' && isset($this->BlockCache)) {
            // Do NOT cache if display order is random
            $this->BlockCache->abort_collect();
        }
        global $Blog;
        $list_blogs = $this->disp_params['blog_ID'] ? $this->disp_params['blog_ID'] : $Blog->ID;
        //pre_dump( $list_blogs );
        // Display photos:
        // TODO: permissions, complete statuses...
        // TODO: A FileList object based on ItemListLight but adding File data into the query?
        //          overriding ItemListLigth::query() for starters ;)
        $FileCache =& get_FileCache();
        $FileList = new DataObjectList2($FileCache);
        // Query list of files:
        $SQL = new SQL();
        $SQL->SELECT('post_ID, post_datestart, post_datemodified, post_main_cat_ID, post_urltitle, post_canonical_slug_ID,
									post_tiny_slug_ID, post_ptyp_ID, post_title, post_excerpt, post_url, file_ID,
									file_title, file_root_type, file_root_ID, file_path, file_alt, file_desc');
        $SQL->FROM('T_categories INNER JOIN T_postcats ON cat_ID = postcat_cat_ID
									INNER JOIN T_items__item ON postcat_post_ID = post_ID
									INNER JOIN T_links ON post_ID = link_itm_ID
									INNER JOIN T_files ON link_file_ID = file_ID');
        $SQL->WHERE('cat_blog_ID IN (' . $list_blogs . ')');
        // fp> TODO: want to restrict on images :]
        $SQL->WHERE_and('post_status = "published"');
        // TODO: this is a dirty hack. More should be shown.
        $SQL->WHERE_and('post_datestart <= \'' . remove_seconds($localtimenow) . '\'');
        if (!empty($this->disp_params['item_type'])) {
            // Get items only with specified type
            $SQL->WHERE_and('post_ptyp_ID = ' . intval($this->disp_params['item_type']));
        }
        $SQL->GROUP_BY('link_ID');
        $SQL->LIMIT($this->disp_params['limit'] * 4);
        // fp> TODO: because we have no way of getting images only, we get 4 times more data than requested and hope that 25% at least will be images :/
        $SQL->ORDER_BY(gen_order_clause($this->disp_params['order_by'], $this->disp_params['order_dir'], 'post_', 'post_ID ' . $this->disp_params['order_dir'] . ', link_ID'));
        $FileList->sql = $SQL->get();
        $FileList->query(false, false, false, 'Media index widget');
        $layout = $this->disp_params['thumb_layout'];
        $nb_cols = $this->disp_params['grid_nb_cols'];
        $count = 0;
        $r = '';
        /**
         * @var File
         */
        while ($File =& $FileList->get_next()) {
            if ($count >= $this->disp_params['limit']) {
                // We have enough images already!
                break;
            }
            if (!$File->is_image()) {
                // Skip anything that is not an image
                // fp> TODO: maybe this property should be stored in link_ltype_ID or in the files table
                continue;
            }
            if ($layout == 'grid') {
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colstart'];
                }
                $r .= $this->disp_params['grid_cellstart'];
            } else {
                $r .= $this->disp_params['item_start'];
            }
            // 1/ Hack a dirty permalink( will redirect to canonical):
            // $link = url_add_param( $Blog->get('url'), 'p='.$post_ID );
            // 2/ Hack a link to the right "page". Very daring!!
            // $link = url_add_param( $Blog->get('url'), 'paged='.$count );
            // 3/ Instantiate a light object in order to get permamnent url:
            $ItemLight = new ItemLight($FileList->get_row_by_idx($FileList->current_idx - 1));
            // index had already been incremented
            $r .= '<a href="' . $ItemLight->get_permanent_url() . '">';
            // Generate the IMG THUMBNAIL tag with all the alt, title and desc if available
            $r .= $File->get_thumb_imgtag($this->disp_params['thumb_size'], '', '', $ItemLight->title);
            $r .= '</a>';
            if ($this->disp_params['disp_image_title']) {
                $title = $File->get('title') ? $this->get('title') : $ItemLight->title;
                $r .= '<span class="note">' . $title . '</span>';
            }
            ++$count;
            if ($layout == 'grid') {
                $r .= $this->disp_params['grid_cellend'];
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colend'];
                }
            } else {
                $r .= $this->disp_params['item_end'];
            }
        }
        // Exit if no files found
        if (empty($r)) {
            return;
        }
        echo $this->disp_params['block_start'];
        // Display title if requested
        $this->disp_title();
        if ($layout == 'grid') {
            echo $this->disp_params['grid_start'];
        } else {
            echo $this->disp_params['list_start'];
        }
        echo $r;
        if ($layout == 'grid') {
            if ($count && $count % $nb_cols != 0) {
                echo $this->disp_params['grid_colend'];
            }
            echo $this->disp_params['grid_end'];
        } else {
            echo $this->disp_params['list_end'];
        }
        echo $this->disp_params['block_end'];
        return true;
    }
    /**
     * Display the widget!
     *
     * @param array MUST contain at least the basic display params
     */
    function display($params)
    {
        global $localtimenow, $DB, $Blog;
        $this->init_display($params);
        $blog_ID = intval($this->disp_params['blog_ID']);
        if (empty($blog_ID)) {
            // Use current blog by default
            $blog_ID = $Blog->ID;
        }
        $BlogCache =& get_BlogCache();
        if (!$BlogCache->get_by_ID($blog_ID, false, false)) {
            // No blog exists
            return;
        }
        // Display photos:
        // TODO: permissions, complete statuses...
        // TODO: A FileList object based on ItemListLight but adding File data into the query?
        //          overriding ItemListLigth::query() for starters ;)
        // Init caches
        $FileCache =& get_FileCache();
        $ItemCache =& get_ItemCache();
        // Query list of files and posts fields:
        // Note: We use ItemQuery to get attachments from all posts which should be visible ( even in case of aggregate blogs )
        $ItemQuery = new ItemQuery($ItemCache->dbtablename, $ItemCache->dbprefix, $ItemCache->dbIDname);
        $ItemQuery->SELECT('post_ID, post_datestart, post_datemodified, post_main_cat_ID, post_urltitle, post_canonical_slug_ID,
									post_tiny_slug_ID, post_ityp_ID, post_title, post_excerpt, post_url, file_ID, file_type,
									file_title, file_root_type, file_root_ID, file_path, file_alt, file_desc, file_path_hash');
        $ItemQuery->FROM_add('INNER JOIN T_links ON post_ID = link_itm_ID');
        $ItemQuery->FROM_add('INNER JOIN T_files ON link_file_ID = file_ID');
        $ItemQuery->where_chapter($blog_ID);
        if ($this->disp_params['item_visibility'] == 'public') {
            // Get images only of the public items
            $ItemQuery->where_visibility(array('published'));
        } else {
            // Get image of all available posts for current user
            $ItemQuery->where_visibility(NULL);
        }
        $ItemQuery->WHERE_and('( file_type = "image" ) OR ( file_type IS NULL )');
        $ItemQuery->WHERE_and('post_datestart <= \'' . remove_seconds($localtimenow) . '\'');
        $ItemQuery->WHERE_and('link_position != "cover"');
        if (!empty($this->disp_params['item_type'])) {
            // Get items only with specified type
            $ItemQuery->WHERE_and('post_ityp_ID = ' . intval($this->disp_params['item_type']));
        }
        $ItemQuery->GROUP_BY('link_ID');
        // fp> TODO: because no way of getting images only, we get 4 times more data than requested and hope that 25% at least will be images :/
        // asimo> This was updated and we get images and those files where we don't know the file type yet. Now we get 2 times more data than requested.
        // Maybe it would be good to get only the requested amount of files, because after a very short period the file types will be set for all images.
        $ItemQuery->LIMIT(intval($this->disp_params['limit']) * 2);
        $ItemQuery->ORDER_BY(gen_order_clause($this->disp_params['order_by'], $this->disp_params['order_dir'], 'post_', 'post_ID ' . $this->disp_params['order_dir'] . ', link_ID'));
        // Init FileList with the above defined query
        $FileList = new DataObjectList2($FileCache);
        $FileList->sql = $ItemQuery->get();
        $FileList->query(false, false, false, 'Media index widget');
        $layout = $this->disp_params['thumb_layout'];
        $nb_cols = $this->disp_params['grid_nb_cols'];
        $count = 0;
        $r = '';
        /**
         * @var File
         */
        while ($File =& $FileList->get_next()) {
            if ($count >= $this->disp_params['limit']) {
                // We have enough images already!
                break;
            }
            if (!$File->is_image()) {
                // Skip anything that is not an image
                // Only images are selected or those files where we don't know the file type yet.
                // This check is only for those files where we don't know the filte type. The file type will be set during the check.
                continue;
            }
            if ($layout == 'grid') {
                // Grid layout
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colstart'];
                }
                $r .= $this->disp_params['grid_cellstart'];
            } elseif ($layout == 'flow') {
                // Flow block layout
                $r .= $this->disp_params['flow_block_start'];
            } else {
                // List layout
                $r .= $this->disp_params['item_start'];
            }
            // 1/ Hack a dirty permalink( will redirect to canonical):
            // $link = url_add_param( $Blog->get('url'), 'p='.$post_ID );
            // 2/ Hack a link to the right "page". Very daring!!
            // $link = url_add_param( $Blog->get('url'), 'paged='.$count );
            // 3/ Instantiate a light object in order to get permamnent url:
            $ItemLight = new ItemLight($FileList->get_row_by_idx($FileList->current_idx - 1));
            // index had already been incremented
            $r .= '<a href="' . $ItemLight->get_permanent_url() . '">';
            // Generate the IMG THUMBNAIL tag with all the alt, title and desc if available
            $r .= $File->get_thumb_imgtag($this->disp_params['thumb_size'], '', '', $ItemLight->title);
            $r .= '</a>';
            if ($this->disp_params['disp_image_title']) {
                // Dislay title of image or item
                $title = $File->get('title') ? $File->get('title') : $ItemLight->title;
                if (!empty($title)) {
                    $r .= '<span class="note">' . $title . '</span>';
                }
            }
            ++$count;
            if ($layout == 'grid') {
                // Grid layout
                $r .= $this->disp_params['grid_cellend'];
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colend'];
                }
            } elseif ($layout == 'flow') {
                // Flow block layout
                $r .= $this->disp_params['flow_block_end'];
            } else {
                // List layout
                $r .= $this->disp_params['item_end'];
            }
        }
        // Exit if no files found
        if (empty($r)) {
            return;
        }
        echo $this->disp_params['block_start'];
        // Display title if requested
        $this->disp_title();
        echo $this->disp_params['block_body_start'];
        if ($layout == 'grid') {
            // Grid layout
            echo $this->disp_params['grid_start'];
        } elseif ($layout == 'flow') {
            // Flow block layout
            echo $this->disp_params['flow_start'];
        } else {
            // List layout
            echo $this->disp_params['list_start'];
        }
        echo $r;
        if ($layout == 'grid') {
            // Grid layout
            if ($count && $count % $nb_cols != 0) {
                echo $this->disp_params['grid_colend'];
            }
            echo $this->disp_params['grid_end'];
        } elseif ($layout == 'flow') {
            // Flow block layout
            echo $this->disp_params['flow_end'];
        } else {
            // List layout
            echo $this->disp_params['list_end'];
        }
        echo $this->disp_params['block_body_end'];
        echo $this->disp_params['block_end'];
        return true;
    }