Ejemplo n.º 1
0
function AccountSearchSelect(&$s, $request = null)
{
    global $DB;
    if ($request != null) {
        $_REQUEST = array_merge($_REQUEST, $request);
    }
    $last_hour = gmdate('G', TIME_NOW - 3600);
    $this_hour = gmdate('G', TIME_NOW);
    $sorters = array_merge($DB->GetColumns('tlx_accounts', TRUE, TRUE), $DB->GetColumns('tlx_account_fields', TRUE, TRUE), $DB->GetColumns('tlx_account_hourly_stats', TRUE, TRUE), array('username' => '`tlx_accounts`.`username`', 'avg_rating' => '`ratings_total`/`ratings`', 'raw_in_last_hr' => '`raw_in_' . $last_hour . '`', 'unique_in_last_hr' => '`unique_in_' . $last_hour . '`', 'raw_out_last_hr' => '`raw_out_' . $last_hour . '`', 'unique_out_last_hr' => '`unique_out_' . $last_hour . '`', 'clicks_last_hr' => '`clicks_' . $last_hour . '`', 'raw_in_this_hr' => '`raw_in_' . $this_hour . '`', 'unique_in_this_hr' => '`unique_in_' . $this_hour . '`', 'raw_out_this_hr' => '`raw_out_' . $this_hour . '`', 'unique_out_this_hr' => '`unique_out_' . $this_hour . '`', 'clicks_this_hr' => '`clicks_' . $this_hour . '`'));
    if (preg_match('~(.*?)_days_(\\d+)~', $_REQUEST['order'], $matches)) {
        $sorters[$_REQUEST['order']] = "SUM(`{$matches[1]}`)";
    }
    $s = new SelectBuilder('*,' . $sorters[$_REQUEST['order']] . ' AS `sorter`', 'tlx_accounts');
    $fulltext = array('title,description,keywords');
    $user = $DB->GetColumns('tlx_account_fields');
    if ($_REQUEST['field'] == 'avg_rating') {
        $_REQUEST['field'] = 'ratings_total/ratings';
    }
    if ($_REQUEST['field'] == 'return_percent') {
        $_REQUEST['search'] = $_REQUEST['search'] / 100;
    }
    // Special handling of date searches (transform MM-DD-YYYY to YYYY-MM-DD format)
    if (preg_match('~^date_~', $_REQUEST['field'])) {
        $_REQUEST['search'] = trim($_REQUEST['search']);
        if (preg_match('~^(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)$~', $_REQUEST['search'], $date)) {
            $_REQUEST['search_type'] = ST_BETWEEN;
            $_REQUEST['search'] = "{$date[3]}-{$date[1]}-{$date[2]} 00:00:00,{$date[3]}-{$date[1]}-{$date[2]} 23:59:59";
        } else {
            if (preg_match('~^\\d\\d\\d\\d-\\d\\d-\\d\\d$~', $_REQUEST['search'])) {
                $_REQUEST['search_type'] = ST_BETWEEN;
                $_REQUEST['search'] = "{$_REQUEST['search']} 00:00:00,{$_REQUEST['search']} 23:59:59";
            }
        }
        $_REQUEST['search'] = preg_replace('~(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)~', '\\3-\\1-\\2', $_REQUEST['search']);
    }
    if (preg_match('~_days_\\d+~', $_REQUEST['order'])) {
        $s->AddJoin('tlx_accounts', 'tlx_account_daily_stats', 'LEFT', 'username');
        $s->AddGroup('tlx_accounts.username');
        $s->AddWhereString("`date_stats` >= DATE_ADD('" . MYSQL_CURDATE . "', INTERVAL -{$matches[2]} DAY)");
    } else {
        if (preg_match('~(raw_|unique_|clicks_)~', $_REQUEST['order'])) {
            $s->AddJoin('tlx_accounts', 'tlx_account_hourly_stats', '', 'username');
        }
    }
    if (in_array($_REQUEST['field'], $user) || in_array($_REQUEST['order'], $user)) {
        $s->AddJoin('tlx_accounts', 'tlx_account_fields', '', 'username');
    }
    if (in_array($_REQUEST['field'], $user)) {
        $s->AddWhere($_REQUEST['field'], $_REQUEST['search_type'], $_REQUEST['search'], $_REQUEST['search_type'] != ST_EMPTY);
    } else {
        if (in_array($_REQUEST['field'], $fulltext)) {
            $s->AddFulltextWhere($_REQUEST['field'], $_REQUEST['search'], $_REQUEST['search_type'] != ST_EMPTY);
        } else {
            $s->AddWhere($_REQUEST['field'], $_REQUEST['search_type'], $_REQUEST['search'], $_REQUEST['search_type'] != ST_EMPTY);
        }
    }
    $s_checked = count($_REQUEST['status']);
    if ($s_checked > 0 && $s_checked < 3) {
        $s->AddWhere('status', ST_IN, join(',', $_REQUEST['status']));
    }
    if (isset($_REQUEST['locked'])) {
        $s->AddWhere('locked', ST_MATCHES, 1);
    }
    if (isset($_REQUEST['disabled'])) {
        $s->AddWhere('disabled', ST_MATCHES, 1);
    }
    if (isset($_REQUEST['edited'])) {
        $s->AddWhere('edited', ST_MATCHES, 1);
    }
    if (count($_REQUEST['categories']) > 0 && !in_array('', $_REQUEST['categories'])) {
        $s->AddWhere('category_id', isset($_REQUEST['cat_exclude']) ? ST_NOT_IN : ST_IN, join(',', $_REQUEST['categories']));
    }
    $_REQUEST['order'] = 'sorter';
    $_REQUEST['order_next'] = 'tlx_accounts.username';
    return TRUE;
}
Ejemplo n.º 2
0
 function compile_ad_tag($tag_args)
 {
     global $DB;
     $defaults = array('pagedupes' => 'false', 'weight' => 'any', 'order' => 'times_displayed, (unique_clicks/times_displayed) DESC');
     $attrs = $this->parse_attributes($tag_args);
     $attrs = array_merge($defaults, $attrs);
     // Convert boolean values
     $attrs['pagedupes'] = $this->to_bool($attrs['pagedupes']);
     // Prepare RAND() values in order
     $attrs['order'] = preg_replace('~rand\\(\\)~i', 'RAND(%RAND%)', $attrs['order']);
     $s = new SelectBuilder('*,`lx_ads`.`ad_id` AS `ad_id`', 'lx_ads');
     // Process pagedupes
     if ($attrs['pagedupes'] === FALSE) {
         $s->AddJoin('lx_ads', 'lx_ads_used_page', 'LEFT', 'ad_id');
         $s->AddWhere('lx_ads_used_page.ad_id', ST_NULL, null);
     }
     // Process tags attribute
     if (isset($attrs['tags'])) {
         $s->AddFulltextWhere('tags', $attrs['tags']);
     }
     // Process weight attribute
     if (isset($attrs['weight']) && $attrs['weight'] != 'any') {
         $s->AddWhereString("`weight` {$attrs['weight']}");
     }
     $s->SetOrderString($attrs['order'], $DB->GetColumns('lx_ads'));
     $s->SetLimit('1');
     $query = $DB->Prepare($s->Generate(), $s->binds);
     // Perform replacements for placeholders
     $replacements = array('%RAND%' => '".rand()."');
     foreach ($replacements as $find => $replace) {
         $query = str_replace($find, $replace, $query);
     }
     return S_PHP . " if( !isset(\$GLOBALS['_CLEAR_PAGE_USED_']) )\n{\n" . "\$GLOBALS['DB']->Update('DELETE FROM `lx_ads_used_page`');\n" . "\$GLOBALS['_CLEAR_PAGE_USED_'] = TRUE;\n" . "}\n" . "\$_temp_ad = \$GLOBALS['DB']->Row(\"{$query}\");\n" . "if( \$_temp_ad )\n{\n" . "\$GLOBALS['DB']->Update(\"UPDATE `lx_ads` SET `times_displayed`=`times_displayed`+1 WHERE `ad_id`=?\", array(\$_temp_ad['ad_id']));\n" . "\$GLOBALS['DB']->Update(\"REPLACE INTO `lx_ads_used_page` VALUES (?)\", array(\$_temp_ad['ad_id']));\n" . "echo \$_temp_ad['ad_html'];\n" . "}\n" . E_PHP;
 }
Ejemplo n.º 3
0
 function compile_accounts_tag($tag_args)
 {
     global $DB;
     $defaults = array('category' => 'MIXED', 'ranks' => '1-25', 'storeranks' => 'false', 'storecatranks' => 'false', 'minhits' => 0, 'order' => 'unique_in_last_hour DESC');
     $attrs = $this->parse_attributes($tag_args);
     $attrs = array_merge($defaults, $attrs);
     if (empty($attrs['var'])) {
         return $this->syntax_error("accounts: missing 'var' attribute");
     }
     if (!preg_match('~^\\d+-\\d+$~', $attrs['ranks'])) {
         return $this->syntax_error("accounts: the 'ranks' attribute must be in START-END format");
     }
     $attrs['var'] = $this->parse_vars($attrs['var']);
     $attrs['storeranks'] = $this->to_bool($attrs['storeranks']);
     $attrs['storecatranks'] = $this->to_bool($attrs['storecatranks']);
     // Prepare RAND() values in order attribute
     $attrs['order'] = preg_replace('~rand\\(\\)~i', 'RAND(%RAND%)', $attrs['order']);
     // Pulling accounts from database using user-specified SELECT statements
     if (isset($attrs['select'])) {
         // TODO: User specified select statement
     } else {
         $s = new SelectBuilder('*,%SORTER% AS `sorter`,`tlx_accounts`.`username` AS `username`', 'tlx_accounts');
         $attrs['category'] = FormatCommaSeparated($attrs['category']);
         if ($this->flags['category_id']) {
             $s->AddWhere('category_id', ST_MATCHES, $this->flags['category_id'], TRUE);
         } else {
             if (strtoupper($attrs['category']) != 'MIXED') {
                 $category_not_in = array();
                 $category_in = array();
                 if (!isset($GLOBALS['CATEGORY_CACHE'])) {
                     $GLOBALS['CATEGORY_CACHE'] =& $DB->FetchAll('SELECT * FROM `tlx_categories`', null, 'name');
                 }
                 foreach (explode(',', $attrs['category']) as $category) {
                     switch ($category) {
                         case 'MIXED':
                         case 'mixed':
                         case 'Mixed':
                             break;
                         default:
                             $minus = FALSE;
                             if (preg_match('~^-(.*)~i', $category, $matches)) {
                                 $minus = TRUE;
                                 $category = $matches[1];
                             }
                             if ($GLOBALS['CATEGORY_CACHE'][$category]) {
                                 if ($minus) {
                                     $category_not_in[] = $GLOBALS['CATEGORY_CACHE'][$category]['category_id'];
                                 } else {
                                     $category_in[] = $GLOBALS['CATEGORY_CACHE'][$category]['category_id'];
                                 }
                             }
                     }
                 }
                 $s->AddWhere('category_id', ST_IN, join(',', $category_in), TRUE);
                 $s->AddWhere('category_id', ST_NOT_IN, join(',', $category_not_in), TRUE);
             }
         }
     }
     // Handle the order attribute
     $order = trim($attrs['order']);
     $direction = null;
     $sorter = null;
     if (strpos($order, ' ')) {
         list($order, $direction) = explode(' ', $order);
     }
     switch (strtolower($order)) {
         case 'ratings':
         case 'date_added':
         case 'date_activated':
         case 'inactive':
             $sorter = "`{$order}`";
             break;
         case 'average_rating':
             $sorter = '`ratings_total`/`ratings`';
             break;
         default:
             if (preg_match('~^(.*?)_(last|this|yesterday)_?(\\d+)?_?(.*)?$~', $order, $matches)) {
                 list($full, $field, $type, $amount, $period) = $matches;
                 $join = 'tlx_account_daily_stats';
                 if ($type == 'yesterday') {
                     $type = 'last';
                     $amount = 1;
                     $period = 'day';
                 }
                 if (empty($amount)) {
                     $amount = 1;
                 }
                 if (stristr($period, 'hour')) {
                     $s->AddJoin('tlx_accounts', 'tlx_account_hourly_stats', 'LEFT', 'username');
                     if ($field == 'productivity') {
                         $sorter = $amount == 24 ? "`clicks_total`/`unique_in_total`" : "(\" . SorterLastHours('clicks_%%', {$amount}) . \")/(\" . SorterLastHours('unique_in_%%', {$amount}) . \")";
                     } else {
                         $sorter = $amount == 24 ? "`{$field}" . "_total`" : "\" . SorterLastHours('{$field}" . "_%%', {$amount}) . \"";
                     }
                     if (!empty($attrs['minhits']) && is_numeric($attrs['minhits'])) {
                         $s->AddWhereString("({$sorter}) >= {$attrs['minhits']}");
                     }
                 } else {
                     if (stristr($period, 'day')) {
                         $s->AddJoin('tlx_accounts', 'tlx_account_daily_stats', 'LEFT', 'username');
                         $s->AddGroup('tlx_accounts.username');
                         if ($field == 'productivity') {
                             $sorter = $amount >= 365 ? "SUM(`clicks`)/SUM(`unique_in`)" : "SUM(IF(`date_stats` >= DATE_ADD('%TODAY%', INTERVAL -{$amount} DAY), `clicks`, 0))/SUM(IF(`date_stats` >= DATE_ADD('%TODAY%', INTERVAL -{$amount} DAY), `unique_in`, 0))";
                         } else {
                             $sorter = $amount >= 365 ? "SUM(`{$field}`)" : "SUM(IF(`date_stats` >= DATE_ADD('%TODAY%', INTERVAL -{$amount} DAY), `{$field}`, 0))";
                         }
                         if (!empty($attrs['minhits']) && is_numeric($attrs['minhits'])) {
                             $s->AddHavingString("`sorter` >= {$attrs['minhits']}");
                         }
                     } else {
                         $sorter = '`unique_in_last_hour`';
                         $direction = 'DESC';
                     }
                 }
             } else {
                 $sorter = '`unique_in_last_hour`';
                 $direction = 'DESC';
             }
             break;
     }
     $s->AddWhere('disabled', ST_MATCHES, 0);
     $s->AddWhere('status', ST_MATCHES, STATUS_ACTIVE);
     $s->AddOrder('sorter', $direction);
     $s->AddOrder('tlx_accounts.username');
     // Set the range of accounts to select
     list($start, $end) = explode('-', $attrs['ranks']);
     $s->SetLimit($start - 1 . ',' . ($end - $start + 1));
     // Generate the SQL query to pull accounts from the database
     $query = $DB->Prepare($s->Generate(), $s->binds);
     // Query replacements
     $replacements = array('%SORTER%' => $sorter, '%TODAY%' => '" . MYSQL_CURDATE . "');
     foreach ($replacements as $find => $replace) {
         $query = str_replace($find, $replace, $query);
     }
     if (isset($attrs['stats'])) {
         $attrs['stats'] = FormatCommaSeparated($attrs['stats']);
     }
     return S_PHP . " {$attrs['var']} =& LoadAccounts(\"{$query}\", '{$attrs['ranks']}', \$this->vars['fillranks'], " . ($attrs['storeranks'] === TRUE ? 'TRUE' : 'FALSE') . ", " . ($attrs['storecatranks'] === TRUE ? 'TRUE' : 'FALSE') . ", '{$attrs['stats']}'); " . E_PHP;
 }
Ejemplo n.º 4
0
 function compile_galleries_tag($tag_args)
 {
     global $DB;
     $defaults = array('preview' => 'any', 'type' => 'submitted', 'format' => 'any', 'category' => 'MIXED', 'sponsor' => 'any', 'amount' => '20', 'globaldupes' => isset($this->defines['globaldupes']) ? $this->defines['globaldupes'] : 'true', 'pagedupes' => isset($this->defines['pagedupes']) ? $this->defines['pagedupes'] : 'false', 'getnew' => 'true', 'allowused' => 'true', 'description' => 'false', 'weight' => 'any');
     $attrs = $this->parse_attributes($tag_args);
     $attrs = array_merge($defaults, $attrs);
     if (empty($attrs['var'])) {
         return $this->syntax_error("galleries: missing 'var' attribute");
     }
     if (!empty($attrs['previewsize']) && !preg_match('~^\\d+x\\d+$~', $attrs['previewsize'])) {
         return $this->syntax_error("galleries: the 'previewsize' value must be provided and in WxH format");
     }
     $attrs['var'] = $this->parse_vars($attrs['var']);
     // Convert boolean values
     $attrs['preview'] = $this->to_bool($attrs['preview']);
     $attrs['globaldupes'] = $this->to_bool($attrs['globaldupes']);
     $attrs['pagedupes'] = $this->to_bool($attrs['pagedupes']);
     $attrs['getnew'] = $this->to_bool($attrs['getnew']);
     $attrs['allowused'] = $this->to_bool($attrs['allowused']);
     $attrs['description'] = $this->to_bool($attrs['description']);
     // Whether or not to pull a preview thumb
     $pull_preview = 'FALSE';
     // Set default sorting options
     if ($attrs['getnew'] === TRUE) {
         if (isset($attrs['order']) && !isset($attrs['reorder'])) {
             $attrs['reorder'] = $attrs['order'];
         } else {
             if (!isset($attrs['reorder'])) {
                 $attrs['reorder'] = 'date_displayed DESC, date_approved';
             }
         }
         if (!isset($attrs['order'])) {
             $attrs['order'] = 'date_approved';
         }
     } else {
         if (isset($attrs['order']) && !isset($attrs['reorder'])) {
             $attrs['reorder'] = $attrs['order'];
         } else {
             if (!isset($attrs['reorder'])) {
                 $attrs['reorder'] = 'date_displayed DESC, date_approved';
             }
         }
         if (!isset($attrs['order'])) {
             $attrs['order'] = 'date_displayed DESC, date_approved';
         }
     }
     // Prepare RAND() values in order and reorder
     $attrs['order'] = preg_replace('~rand\\(\\)~i', 'RAND(%RAND%)', $attrs['order']);
     $attrs['reorder'] = preg_replace('~rand\\(\\)~i', 'RAND(%RAND%)', $attrs['reorder']);
     // Pulling galleries from a text file
     if (isset($attrs['file'])) {
         // galleries from text file...coming soon
     } else {
         if (isset($attrs['select'])) {
             if (!isset($attrs['reselect']) || empty($attrs['reselect'])) {
                 $attrs['reselect'] = $attrs['select'];
             }
             $replacements = array('%MYSQL_CURDATE%' => '".MYSQL_CURDATE."', '%MYSQL_NOW%' => '".MYSQL_NOW."', '%RAND%' => '".rand()."', '%LIMIT%' => isset($attrs['fillvar']) ? '" . (' . $attrs['amount'] . ' - count(' . $attrs['fillvar'] . ') - $_got) . "' : '" . (' . $attrs['amount'] . ' - $_got) . "', '%PAGEID%' => '" . $this->vars[\'page\'][\'page_id\'] . "', '%FILL%' => '" . (' . $attrs['amount'] . ' - count(' . $attrs['fillvar'] . ')). "');
             foreach ($replacements as $find => $replace) {
                 $attrs['select'] = str_replace($find, $replace, $attrs['select']);
                 $attrs['reselect'] = str_replace($find, $replace, $attrs['reselect']);
             }
             return S_PHP . NEWLINE . "if( \$GLOBALS['_build_type'] == BT_BUILD_WITH_NEW )" . NEWLINE . "{" . NEWLINE . "{$attrs['var']} =& LoadGalleries(\"{$attrs['select']}\", \$this->vars['this_page']['page_id'], \$this->vars['this_page']['category_id']);" . NEWLINE . "}" . NEWLINE . "else" . NEWLINE . "{" . NEWLINE . "{$attrs['var']} =& LoadGalleries(\"{$attrs['reselect']}\", \$this->vars['this_page']['page_id'], \$this->vars['this_page']['category_id']);" . NEWLINE . "}" . NEWLINE . E_PHP;
         } else {
             if (isset($attrs['age']) && (isset($attrs['minage']) || isset($attrs['maxage']))) {
                 return $this->syntax_error("galleries: 'age' attribute cannot be combined with 'minage' or 'maxage'");
             }
             $s = new SelectBuilder('*,`tx_galleries`.`gallery_id` AS `gallery_id`', 'tx_galleries');
             // Process globaldupes
             if ($attrs['globaldupes'] === FALSE) {
                 $s->AddJoin('tx_galleries', 'tx_gallery_used', 'LEFT', 'gallery_id');
                 $s->AddWhere('tx_gallery_used.gallery_id', ST_NULL, null);
             }
             // Process pagedupes
             if ($attrs['pagedupes'] === FALSE) {
                 $s->AddJoin('tx_galleries', 'tx_gallery_used_page', 'LEFT', 'gallery_id');
                 $s->AddWhere('tx_gallery_used_page.gallery_id', ST_NULL, null);
             }
             // Process preview attribute
             if ($attrs['preview'] === TRUE) {
                 if (empty($attrs['previewsize'])) {
                     $s->AddWhere('has_preview', ST_MATCHES, 1);
                     $pull_preview = 'TRUE';
                 } else {
                     $s->AddJoin('tx_galleries', 'tx_gallery_previews', '', 'gallery_id');
                     $s->AddWhere('dimensions', ST_MATCHES, $attrs['previewsize']);
                 }
             } else {
                 if ($attrs['preview'] === FALSE) {
                     $s->AddWhere('has_preview', ST_MATCHES, 0);
                 } else {
                     $pull_preview = 'TRUE';
                 }
             }
             // Process type attribute
             $attrs['type'] = strtolower($attrs['type']);
             if ($attrs['type'] != 'any') {
                 $s->AddWhere('type', ST_MATCHES, $attrs['type']);
             }
             // Process format attribute
             $attrs['format'] = strtolower($attrs['format']);
             if ($attrs['format'] != 'any') {
                 $s->AddWhere('format', ST_MATCHES, $attrs['format']);
             }
             // Process description attribute
             if ($attrs['description'] === TRUE) {
                 $s->AddWhere('description', ST_NOT_EMPTY, null);
             }
             // Process partner attribute
             if (isset($attrs['partner'])) {
                 $s->AddWhere('partner', ST_MATCHES, $attrs['partner']);
             }
             // Process keywords attribute
             if (isset($attrs['keywords'])) {
                 $s->AddFulltextWhere('keywords', $attrs['keywords']);
             }
             // Process tags attribute
             if (isset($attrs['tags'])) {
                 $s->AddFulltextWhere('tags', $attrs['tags']);
             }
             // Process category attribute
             if (isset($attrs['category'])) {
                 $attrs['category'] = FormatCommaSeparated($attrs['category']);
                 if ($this->flags['category_id']) {
                     if (!isset($GLOBALS['CATEGORY_CACHE_ID'])) {
                         $GLOBALS['CATEGORY_CACHE_ID'] =& $DB->FetchAll('SELECT * FROM `tx_categories`', null, 'category_id');
                     }
                     $s->AddFulltextWhere('categories', $GLOBALS['CATEGORY_CACHE_ID'][$this->flags['category_id']]['tag'], TRUE);
                 } else {
                     if (strtoupper($attrs['category']) != 'MIXED') {
                         $fulltext = array();
                         if (!isset($GLOBALS['CATEGORY_CACHE'])) {
                             $GLOBALS['CATEGORY_CACHE'] =& $DB->FetchAll('SELECT * FROM `tx_categories`', null, 'name');
                         }
                         foreach (explode(',', $attrs['category']) as $category) {
                             switch ($category) {
                                 case 'MIXED':
                                 case 'mixed':
                                 case 'Mixed':
                                     $fulltext[] = MIXED_CATEGORY;
                                     break;
                                 default:
                                     $minus = '';
                                     if (preg_match('~^([-+])(.*)~i', $category, $matches)) {
                                         $minus = $matches[1];
                                         $category = $matches[2];
                                     }
                                     if ($GLOBALS['CATEGORY_CACHE'][$category]) {
                                         $fulltext[] = $minus . $GLOBALS['CATEGORY_CACHE'][$category]['tag'];
                                     }
                             }
                         }
                         if (count($fulltext) < 1) {
                             return $this->syntax_error("galleries: 'category' attribute contains an invalid category name [{$attrs['category']}]");
                         }
                         $s->AddFulltextWhere('categories', join(' ', $fulltext));
                     }
                 }
             }
             // Process sponsor attribute
             if (isset($attrs['sponsor'])) {
                 $attrs['sponsor'] = FormatCommaSeparated($attrs['sponsor']);
                 if (strtolower($attrs['sponsor']) != 'any') {
                     $sponsors =& $DB->FetchAll('SELECT * FROM `tx_sponsors`', null, 'name');
                     $sponsor_ids = array();
                     $not_in = FALSE;
                     foreach (explode(',', $attrs['sponsor']) as $sponsor) {
                         $minus = FALSE;
                         if (preg_match('~^-(.*)~i', $sponsor, $matches)) {
                             $minus = TRUE;
                             $sponsor = $matches[1];
                         }
                         if ($sponsor == 'any') {
                             $not_in = TRUE;
                         } else {
                             if (isset($sponsors[$sponsor])) {
                                 $sponsor_ids[] = $sponsors[$sponsor]['sponsor_id'];
                             }
                         }
                     }
                     if ($not_in) {
                         $s->AddMultiWhere(array('sponsor_id', 'sponsor_id'), array(ST_NOT_IN, ST_NULL), array(join(',', $sponsor_ids), null));
                     } else {
                         $s->AddWhere('sponsor_id', ST_IN, join(',', $sponsor_ids));
                     }
                 }
             }
             // Process weight attribute
             if (isset($attrs['weight']) && $attrs['weight'] != 'any') {
                 $s->AddWhereString("`weight` {$attrs['weight']}");
             }
             // Process amount attribute
             $s->SetLimit($attrs['amount']);
             if (isset($attrs['fillvar'])) {
                 $attrs['fillvar'] = $this->parse_vars($attrs['fillvar']);
                 $s->SetLimit('%FILL%');
             }
             // Get available sorting columns and copy the SelectBuilder object
             // Little hack to workaround differences in object copying between PHP4 and PHP5
             $tx_galleries = $DB->GetColumns('tx_galleries');
             if (function_exists('array_combine')) {
                 $s_new = unserialize(serialize($s));
             } else {
                 $s_new = $s;
             }
             if ($attrs['getnew'] === TRUE) {
                 $s->AddWhere('status', ST_IN, 'used,holding');
                 $s->SetOrderString($attrs['reorder'], $tx_galleries);
                 $s_new->AddWhere('status', ST_MATCHES, 'approved');
                 $s_new->AddMultiWhere(array('date_scheduled', 'date_scheduled'), array(ST_NULL, ST_LESS), array(null, '%MYSQL_NOW%'));
                 $s_new->SetOrderString($attrs['order'], $tx_galleries);
             } else {
                 $s->AddWhere('status', ST_IN, 'used,holding');
                 $s->SetOrderString($attrs['reorder'], $tx_galleries);
                 $s_new->AddWhere('status', ST_IN, 'used,holding');
                 $s_new->SetOrderString($attrs['order'], $tx_galleries);
             }
             // Process age, minage and maxage attributes
             if (isset($attrs['age'])) {
                 $s->AddWhereString("`date_displayed` BETWEEN SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['age']} DAY) AND SUBDATE('%MYSQL_CURDATE% 23:59:59', INTERVAL {$attrs['age']} DAY)");
                 if ($attrs['getnew'] !== TRUE) {
                     $s_new->AddWhereString("`date_displayed` BETWEEN SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['age']} DAY) AND SUBDATE('%MYSQL_CURDATE% 23:59:59', INTERVAL {$attrs['age']} DAY)");
                 }
             } else {
                 if (isset($attrs['minage']) && isset($attrs['maxage'])) {
                     $s->AddWhereString("`date_displayed` BETWEEN SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['maxage']} DAY) AND SUBDATE('%MYSQL_CURDATE% 23:59:59', INTERVAL {$attrs['minage']} DAY)");
                     if ($attrs['getnew'] !== TRUE) {
                         $s_new->AddWhereString("`date_displayed` BETWEEN SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['maxage']} DAY) AND SUBDATE('%MYSQL_CURDATE% 23:59:59', INTERVAL {$attrs['minage']} DAY)");
                     }
                 } else {
                     if (isset($attrs['minage'])) {
                         $s->AddWhereString("`date_displayed` <= SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['minage']} DAY)");
                         if ($attrs['getnew'] !== TRUE) {
                             $s_new->AddWhereString("`date_displayed` <= SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['minage']} DAY)");
                         }
                     } else {
                         if (isset($attrs['maxage'])) {
                             $s->AddWhereString("`date_displayed` >= SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['maxage']} DAY)");
                             if ($attrs['getnew'] !== TRUE) {
                                 $s_new->AddWhereString("`date_displayed` >= SUBDATE('%MYSQL_CURDATE% 00:00:00', INTERVAL {$attrs['maxage']} DAY)");
                             }
                         }
                     }
                 }
             }
             // Generate the build and build with new queries
             $b_query = $DB->Prepare($s->Generate(), $s->binds);
             $bwn_query = $DB->Prepare($s_new->Generate(), $s_new->binds);
             $s->SetLimit('%LIMIT%');
             $bwnau_query = $DB->Prepare($s->Generate(), $s->binds);
             $replacements = array('%MYSQL_CURDATE%' => '".MYSQL_CURDATE."', '%MYSQL_NOW%' => '".MYSQL_NOW."', '%RAND%' => '".rand()."', '%LIMIT%' => isset($attrs['fillvar']) ? '" . (' . $attrs['amount'] . ' - count(' . $attrs['fillvar'] . ') - $_got) . "' : '" . (' . $attrs['amount'] . ' - $_got) . "', '%PAGEID%' => '" . $this->vars[\'page\'][\'page_id\'] . "', '%FILL%' => '" . (' . $attrs['amount'] . ' - count(' . $attrs['fillvar'] . ')). "');
             foreach ($replacements as $find => $replace) {
                 $b_query = str_replace($find, $replace, $b_query);
                 $bwn_query = str_replace($find, $replace, $bwn_query);
                 $bwnau_query = str_replace($find, $replace, $bwnau_query);
             }
             return S_PHP . NEWLINE . "{$attrs['var']} = null;" . NEWLINE . "\$this->vars['_temp_galleries'] = null;" . NEWLINE . (isset($attrs['fillvar']) ? 'if(' . $attrs['amount'] . ' - count(' . $attrs['fillvar'] . ') > 0)' . NEWLINE . '{' . NEWLINE : '') . "if( \$GLOBALS['_build_type'] == BT_BUILD_WITH_NEW )" . NEWLINE . "{" . NEWLINE . "{$attrs['var']} =& LoadGalleries(\"{$bwn_query}\", \$this->vars['this_page']['page_id'], \$this->vars['this_page']['category_id'], {$pull_preview});" . NEWLINE . ($attrs['getnew'] === TRUE && $attrs['allowused'] === TRUE ? "\$_got = count({$attrs['var']});" . NEWLINE . "if( \$_got < " . (isset($attrs['fillvar']) ? "{$attrs['amount']} - count({$attrs['fillvar']})" : $attrs['amount']) . " )" . NEWLINE . "{" . NEWLINE . "\$this->vars['_temp_galleries'] =& LoadGalleries(\"{$bwnau_query}\", \$this->vars['this_page']['page_id'], \$this->vars['this_page']['category_id'], {$pull_preview});" . NEWLINE . "{$attrs['var']} = ArrayIntermix({$attrs['var']}, \$this->vars['_temp_galleries'], 'end');" . NEWLINE . "}" . NEWLINE : '') . "}" . NEWLINE . "else" . NEWLINE . "{" . NEWLINE . "{$attrs['var']} =& LoadGalleries(\"{$b_query}\", \$this->vars['this_page']['page_id'], \$this->vars['this_page']['category_id'], {$pull_preview});" . NEWLINE . (isset($attrs['fillvar']) ? "}" . NEWLINE : '') . "}" . NEWLINE . E_PHP;
         }
     }
 }