1<?php
2/**
3 * Coppermine Photo Gallery
4 *
5 * v1.0 originally written by Gregory Demar
6 *
7 * @copyright  Copyright (c) 2003-2021 Coppermine Dev Team
8 * @license    GNU General Public License version 3 or later; see LICENSE
9 *
10 * include/search.inc.php
11 * @since  1.6.10
12 */
13
14defined('IN_COPPERMINE') or die('Not in Coppermine...');
15
16// encoding match for workaround
17
18$multibyte_charset = 'utf-8, big5, shift_jis, euc-kr, gb2312';
19
20$charset = $CONFIG['charset'] == 'language file' ? $GLOBALS['lang_charset'] : $CONFIG['charset'];
21
22$sort_array = array('na' => 'filename ASC , pid ASC', 'nd' => 'filename DESC , pid ASC', 'ta'=>'title ASC , pid ASC', 'td'=>'title DESC , pid ASC', 'da' => 'pid ASC', 'dd' => 'pid DESC', 'pa' => 'position ASC , pid ASC', 'pd' => 'position DESC , pid ASC');
23$sort_code = isset($USER['sort'])? $USER['sort'] : $CONFIG['default_sort_order'];
24$sort_order = isset($sort_array[$sort_code]) ? $sort_array[$sort_code] : $sort_array[$CONFIG['default_sort_order']];
25
26$allowed = array('title', 'caption', 'keywords', 'filename', 'pic_raw_ip', 'pic_hdr_ip', 'user1', 'user2', 'user3', 'user4');
27
28global $cpg_udb;
29// Use actual column name for search by owner name
30if ($cpg_udb->can_join_tables && isset($USER['search']['params']['owner_name'])) {
31    $USER['search']['params'][$cpg_udb->field['username']] = true;
32    $allowed[] = $cpg_udb->field['username'];
33}
34
35$mb_charset = stristr($multibyte_charset, $charset);
36
37$search_string = str_replace('&quot;', '"', $search_string);
38$search_string = str_replace('\'', '"', $search_string);
39$search_string = preg_replace('/&.*;/i', '', $search_string);
40$search_string = Inspekt::getEscaped($search_string);
41
42if (!$mb_charset) {
43    $search_string = preg_replace('/[^0-9a-z %]/i', '', $search_string);
44}
45
46if (!isset($USER['search']['params'])) {
47	$USER['search']['params']['title'] = $USER['search']['params']['caption'] = $USER['search']['params']['keywords'] = $USER['search']['params']['filename'] = 1;
48	$USER['search']['params']['newer_than'] = $USER['search']['params']['older_than'] = '';
49}
50if (!isset($USER['search']['params']['newer_than'])) $USER['search']['params']['newer_than'] = '';
51if (!isset($USER['search']['params']['older_than'])) $USER['search']['params']['older_than'] = '';
52
53if ($superCage->get->keyExists('album') && $superCage->get->getAlpha('album') == 'search') {
54    $search_params = $USER['search'];
55} else {
56    //put all original $_POST vars in $search_params, don't know if this could be used???
57    $search_params = $superCage->post->_source;
58}
59
60if (!isset($search_params['params']['type'])) $search_params['params']['type'] = 'AND';
61
62$type = $search_params['params']['type'] == 'OR' ? " OR " : " AND ";
63
64if (isset($search_params['params']['pic_raw_ip'])) $search_params['params']['pic_hdr_ip']  = $search_params['params']['pic_raw_ip'];
65
66$sql = '';
67
68if ($search_string && isset($search_params['params'])) {
69        $sections = array();
70        $albcat_terms = array(); // For Album & Category Title Search: populated as needed
71        if ($search_params['params']['type'] == 'regex') {
72                $fields = array();
73                $search_string = preg_replace('/[^\w\+\*\?\{\,\}\|\(\)\\\^\$\[\]\:\<\>\-\.]/','',$search_string);
74                $search_string = addslashes($search_string);
75                if ($superCage->get->keyExists('album_title') || $superCage->get->keyExists('category_title')) $albcat_terms[] = " REGEXP '$search_string'";
76                foreach ($search_params['params'] as $param => $value) {
77                        if (in_array($param, $allowed)) $fields[] = "$param REGEXP '$search_string'";
78                }
79                $sql .= count($fields) ? ('((' . implode(' OR ', $fields) . '))') : '';
80         } else {
81                $search_string = strtr($search_string, array('_' => '\_', '%' => '\%', '*' => '%'));
82
83                $split_search = explode('"',$search_string);
84                foreach ($split_search as $index => $string) {
85                        if (($index & 1) && strlen($string)) {
86                                $fields = array();
87                                if ($superCage->get->keyExists('album_title') || $superCage->get->keyExists('category_title')) $albcat_terms[] = " LIKE '%$string%'";
88                                foreach ($search_params['params'] as $param => $value) {
89                                        if (in_array($param, $allowed)) $fields[] = "$param LIKE '%$string%'";
90                                }
91                                $sections[] = count($fields) ? '(' . implode(' OR ', $fields) . ')' : '';
92                        } elseif (strlen($string)) {
93                                $words = explode(' ', $string);
94                                foreach ($words as $word) {
95                                        if (strlen($word)) {
96                                                $word = addslashes($word);
97                                                $fields = array();
98                                                if ($superCage->get->keyExists('album_title') || $superCage->get->keyExists('category_title')) $albcat_terms[] = " LIKE '%$word%'";
99                                                foreach ($search_params['params'] as $param => $value) {
100                                                        if (in_array($param, $allowed)) $fields[] = ($param == 'title' ? 'p.title' : $param)." LIKE '%$word%'";
101                                                }
102                                                $sections[] = count($fields) ? '(' . implode(' OR ', $fields) . ')' : '';
103                                        }
104                                }
105                        }
106                }
107
108                $sql .= count($sections) ? '(' . implode($type, $sections) . ')' : '0';
109        }
110
111        $sql .= Inspekt::isInt($USER['search']['params']['newer_than']) ? ' AND ( ctime > '.time().' - '.( $USER['search']['params']['newer_than'] * 60*60*24).')' : '';
112        $sql .= Inspekt::isInt($USER['search']['params']['older_than']) ? ' AND ( ctime < '.time().' - '.( $USER['search']['params']['older_than'] * 60*60*24).')' : '';
113        $sql .=  " AND approved = 'YES' $FORBIDDEN_SET";
114
115        if ($superCage->get->keyExists('album_title')) {
116                $album_query = "SELECT aid, title, description FROM `{$CONFIG['TABLE_ALBUMS']}` AS p"
117                        ." WHERE (`title` " . implode(" $type `title` ",$albcat_terms) . ") $FORBIDDEN_SET";
118                $result = cpg_db_query($album_query);
119                if ($result->numRows() > 0) {
120                        starttable('100%', $lang_meta_album_names['album_search'],2);
121                        while ($alb = $result->fetchAssoc()) {
122                                $thumb_query = "SELECT filepath, filename, url_prefix, pwidth, pheight "
123                                        ." FROM `{$CONFIG['TABLE_PICTURES']}` "
124                                        ." WHERE (`aid` = '{$alb['aid']}') "
125                                        ." AND approved = 'YES' "
126                                        ." ORDER BY `pid` DESC";
127                                $thumb_result = cpg_db_query($thumb_query);
128                                $thumb = $thumb_result->fetchAssoc(true);
129                                // TODO: query above only pulls in last_pid in each album, not correct album thumb as set by user
130
131                                $thumb_url = get_pic_url($thumb, 'thumb');
132                                $thumb_size = compute_img_size($thumb['pwidth'], $thumb['pheight'], $CONFIG['alb_list_thumb_size'], true, 'cat_thumb');
133                                ?>
134                                <tr>
135                                  <td colspan="3" height="1" valign="top" class="tableh2">
136                                    <span class="alblink"><a href="<?php printf("thumbnails.php?album=%u", $alb['aid']); ?>"><?php echo $alb['title'] ?></a></span>
137                                  </td>
138                                </tr>
139                                <tr>
140                                        <td colspan="3">
141                                                <img src="images/spacer.gif" width="1" height="1" border="0" alt="" /><br />
142                                        </td>
143                                </tr>
144                                <tr>
145                                  <td>
146                                    <a href="<?php printf("thumbnails.php?album=%u", $alb['aid']); ?> ">
147                                        <img src="<?php echo $thumb_url?>"  class="image" <?php echo $thumb_size['geom'] ?> border="0" alt="<?php echo $thumb['filename'] ?>">
148                                    </a>
149                                  </td>
150                                  <td width="100%" valign=top>
151                                    <?php if ($alb['description'] == "") { echo '&nbsp;'; } else { echo $alb['description']; } ?>
152                                  </td>
153                                </tr>
154                                <?php
155                        }
156                        endtable();
157                        echo '<br/>';
158                }
159                $result->free();
160        }
161
162        if ($superCage->get->keyExists('category_title')) {
163                $category_query = "SELECT cid, name FROM `{$CONFIG['TABLE_CATEGORIES']}` WHERE (`name` " . implode(" $type `name` ",$albcat_terms) . ')';
164                $result = cpg_db_query($category_query);
165                if ($result->numRows() > 0) {
166                        starttable('100%', $lang_meta_album_names['category_search'],2);
167                        while ($cat = $result->fetchAssoc()) {
168                                $album_q = "SELECT aid, title FROM `{$CONFIG['TABLE_ALBUMS']}` AS p WHERE (`category` = '{$cat['cid']}') $FORBIDDEN_SET ORDER BY `aid` DESC LIMIT 1";
169                                $album_r = cpg_db_query($album_q);
170                                $album = $album_r->fetchArray(true);
171
172                                // TODO: This is weird.  It seems to pull in the largest aid's thumb for the category image?
173                                $thumb_query = "SELECT filepath, filename, url_prefix, pwidth, pheight "
174                                        ." FROM `{$CONFIG['TABLE_PICTURES']}` "
175                                        ." WHERE (`aid` = '{$album['aid']}') "
176                                        ." AND approved = 'YES' "
177                                        ." ORDER BY `pid` DESC";
178                                $thumb_result = cpg_db_query($thumb_query);
179                                $thumb = $thumb_result->fetchAssoc(true);
180                                $thumb_url = get_pic_url($thumb, 'thumb');
181                                $thumb_size = compute_img_size($thumb['pwidth'], $thumb['pheight'], $CONFIG['alb_list_thumb_size'], true, 'cat_thumb');
182
183                                ?>
184                                <tr>
185                                  <td colspan="3" height="1" valign="top" class="tableh2">
186                                    <span class="alblink"><a href="<?php printf("index.php?cat=%u", $cat['cid']); ?>"><?php echo $cat['name'] ?></a></span>
187                                  </td>
188                                </tr>
189                                <tr>
190                                        <td colspan="3">
191                                                <img src="images/spacer.gif" width="1" height="1" border="0" alt="" /><br />
192                                        </td>
193                                </tr>
194                                <tr>
195                                  <td>
196                                    <a href="<?php printf("thumbnails.php?album=%u", $album['aid']); ?> ">
197                                        <img src="<?php echo $thumb_url?>"  class="image" <?php echo $thumb_size['geom'] ?> border="0" alt="<?php echo $thumb['filename'] ?>"><br/>
198                                        <?php if ($album['title'] == "") { echo '&nbsp;'; } else { printf("<a href='thumbnails.php?album=%u'>{$album['title']}</a>", $album['aid']); } ?>
199                                    </a>
200                                  </td>
201                                </tr>
202                                <?php
203
204                        }
205                        endtable();
206                        echo '<br/>';
207                }
208                $result->free();
209        }
210
211        // Make sure they selected some parameter other than album/category
212        $other = 0;
213        foreach ($search_params['params'] as $param => $value) {
214            if (in_array($param, $allowed)) {
215                $other = 1;
216            }
217        }
218
219
220        if (!$other) {
221            $sql = '0';
222        }
223
224        $join_user_table = $cpg_udb->can_join_tables ? "LEFT JOIN {$cpg_udb->usertable} AS u ON p.owner_id = u.{$cpg_udb->field['user_id']}" : "";
225        $user_column = $cpg_udb->can_join_tables ? ", u.{$cpg_udb->field['username']} AS owner_name" : "";
226        if (defined('DISPLAYIMAGE_PHP') && $get_pic_pos == true) {
227
228            $sort_order_parts = explode(" ", $sort_order);
229            $criteria = $sort_order_parts[0];
230            $direction = $sort_order_parts[1];
231
232            $pid = $superCage->get->getInt('pid');
233
234            $query = "SELECT $criteria FROM {$CONFIG['TABLE_PICTURES']} WHERE pid = $pid";
235            $result = cpg_db_query($query);
236            $criteria_pid = $result->result(0, 0, true);
237
238            if ($direction == "ASC") {
239                $direction = "<";
240            } elseif ($direction == "DESC") {
241                $direction = ">";
242            } else {
243                $direction = "";
244            }
245
246            $sort_order = "$criteria $direction '$criteria_pid' OR $criteria = '$criteria_pid' AND pid < $pid";
247
248            $query = "SELECT COUNT(*) FROM {$CONFIG['TABLE_PICTURES']} AS p
249                $join_user_table
250                WHERE $sql
251                AND ($sort_order)";
252
253                $result = cpg_db_query($query);
254
255                list($pos) = $result->fetchRow(true);
256
257        } else {
258
259            $query = "SELECT p.*{$user_column} FROM {$CONFIG['TABLE_PICTURES']} AS p
260            $join_user_table
261            WHERE " . $sql;
262
263            $temp = str_replace("SELECT p.*{$user_column}", 'SELECT COUNT(*)', $query);
264            $result = cpg_db_query($temp);
265            $row = $result->fetchRow(true);
266            $count = $row[0];
267
268            $query .= " ORDER BY $sort_order $limit";
269            $result = cpg_db_query($query);
270            $rowset = cpg_db_fetch_rowset($result, true);
271
272            if ($set_caption) {
273                build_caption($rowset);
274            }
275
276        }
277
278}
279//EOF