* Fixed REG_BADRPT error in isValidEmail() that prevented registration
[scuttle] / services / bookmarkservice.php
1 <?php
2 class BookmarkService {
3     var $db;
4
5     function & getInstance(& $db) {
6         static $instance;
7         if (!isset ($instance))
8             $instance = & new BookmarkService($db);
9         return $instance;
10     }
11
12     function BookmarkService(& $db) {
13         $this->db = & $db;
14     }
15
16     function _getbookmark($fieldname, $value, $all = false) {
17         if (!$all) {
18             $userservice = & ServiceFactory :: getServiceInstance('UserService');
19             $sId = $userservice->getCurrentUserId();
20             $range = ' AND uId = '. $sId;
21         }
22
23         $query = 'SELECT * FROM '. $GLOBALS['tableprefix'] .'bookmarks WHERE '. $fieldname .' = "'. $this->db->sql_escape($value) .'"'. $range;
24
25         if (!($dbresult = & $this->db->sql_query_limit($query, 1, 0))) {
26             message_die(GENERAL_ERROR, 'Could not get bookmark', '', __LINE__, __FILE__, $query, $this->db);
27             return false;
28         }
29
30         if ($row =& $this->db->sql_fetchrow($dbresult)) {
31             return $row;
32         } else {
33             return false;
34         }
35     }
36
37     function & getBookmark($bid, $include_tags = false) {
38         if (!is_numeric($bid))
39             return;
40
41         $sql = 'SELECT * FROM '. $GLOBALS['tableprefix'] .'bookmarks WHERE bId = '. $this->db->sql_escape($bid);
42
43         if (!($dbresult = & $this->db->sql_query($sql)))
44             message_die(GENERAL_ERROR, 'Could not get vars', '', __LINE__, __FILE__, $sql, $this->db);
45
46         if ($row = & $this->db->sql_fetchrow($dbresult)) {
47             if ($include_tags) {
48                 $tagservice = & ServiceFactory :: getServiceInstance('TagService');
49                 $row['tags'] = $tagservice->getTagsForBookmark($bid);
50             }
51             return $row;
52         } else {
53             return false;
54         }
55     }
56
57     function getBookmarkByAddress($address) {
58         $hash = md5($address);
59         return $this->getBookmarkByHash($hash);
60     }
61
62     function getBookmarkByHash($hash) {
63         return $this->_getbookmark('bHash', $hash, true);
64     }
65
66     function editAllowed($bookmark) {
67         if (!is_numeric($bookmark) && (!is_array($bookmark) || !is_numeric($bookmark['bId'])))
68             return false;
69
70         if (!is_array($bookmark))
71             if (!($bookmark = $this->getBookmark($bookmark)))
72                 return false;
73
74         $userservice = & ServiceFactory :: getServiceInstance('UserService');
75         $userid = $userservice->getCurrentUserId();
76         if ($userservice->isAdmin($userid))
77             return true;
78         else
79             return ($bookmark['uId'] == $userid);
80     }
81
82     function bookmarkExists($address = false, $uid = NULL) {
83         if (!$address) {
84             return;
85         }
86
87         // If address doesn't contain ":", add "http://" as the default protocol
88         if (strpos($address, ':') === false) {
89             $address = 'http://'. $address;
90         }
91
92         $crit = array ('bHash' => md5($address));
93         if (isset ($uid)) {
94             $crit['uId'] = $uid;
95         }
96
97         $sql = 'SELECT COUNT(*) FROM '. $GLOBALS['tableprefix'] .'bookmarks WHERE '. $this->db->sql_build_array('SELECT', $crit);
98         if (!($dbresult = & $this->db->sql_query($sql))) {
99             message_die(GENERAL_ERROR, 'Could not get vars', '', __LINE__, __FILE__, $sql, $this->db);
100         }
101         return ($this->db->sql_fetchfield(0, 0) > 0);
102     }
103
104     // Adds a bookmark to the database.
105     // Note that date is expected to be a string that's interpretable by strtotime().
106     function addBookmark($address, $title, $description, $status, $categories, $date = NULL, $fromApi = false, $fromImport = false) {
107         $userservice = & ServiceFactory :: getServiceInstance('UserService');
108         $sId = $userservice->getCurrentUserId();
109
110         // If bookmark address doesn't contain ":", add "http://" to the start as a default protocol
111         if (strpos($address, ':') === false) {
112             $address = 'http://'. $address;
113         }
114
115         // Get the client's IP address and the date; note that the date is in GMT.
116         if (getenv('HTTP_CLIENT_IP'))
117             $ip = getenv('HTTP_CLIENT_IP');
118         else
119             if (getenv('REMOTE_ADDR'))
120                 $ip = getenv('REMOTE_ADDR');
121             else
122                 $ip = getenv('HTTP_X_FORWARDED_FOR');
123
124         // Note that if date is NULL, then it's added with a date and time of now, and if it's present,
125         // it's expected to be a string that's interpretable by strtotime().
126         if (is_null($date))
127             $time = time();
128         else
129             $time = strtotime($date);
130         $datetime = gmdate('Y-m-d H:i:s', $time);
131
132         // Set up the SQL insert statement and execute it.
133         $values = array('uId' => intval($sId), 'bIp' => $ip, 'bDatetime' => $datetime, 'bModified' => $datetime, 'bTitle' => $title, 'bAddress' => $address, 'bDescription' => $description, 'bStatus' => intval($status), 'bHash' => md5($address));
134         $sql = 'INSERT INTO '. $GLOBALS['tableprefix'] .'bookmarks '. $this->db->sql_build_array('INSERT', $values);
135         $this->db->sql_transaction('begin');
136         if (!($dbresult = & $this->db->sql_query($sql))) {
137             $this->db->sql_transaction('rollback');
138             message_die(GENERAL_ERROR, 'Could not insert bookmark', '', __LINE__, __FILE__, $sql, $this->db);
139             return false;
140         }
141         // Get the resultant row ID for the bookmark.
142         $bId = $this->db->sql_nextid($dbresult);
143         if (!isset($bId) || !is_int($bId)) {
144             $this->db->sql_transaction('rollback');
145             message_die(GENERAL_ERROR, 'Could not insert bookmark', '', __LINE__, __FILE__, $sql, $this->db);
146             return false;
147         }
148
149         $uriparts = explode('.', $address);
150         $extension = end($uriparts);
151         unset($uriparts);
152
153         $tagservice = & ServiceFactory :: getServiceInstance('TagService');
154         if (!$tagservice->attachTags($bId, $categories, $fromApi, $extension, false, $fromImport)) {
155             $this->db->sql_transaction('rollback');
156             message_die(GENERAL_ERROR, 'Could not insert bookmark', '', __LINE__, __FILE__, $sql, $this->db);
157             return false;
158         }
159         $this->db->sql_transaction('commit');
160         // Everything worked out, so return the new bookmark's bId.
161         return $bId;
162     }
163
164     function updateBookmark($bId, $address, $title, $description, $status, $categories, $date = NULL, $fromApi = false) {
165         if (!is_numeric($bId))
166             return false;
167
168         // Get the client's IP address and the date; note that the date is in GMT.
169         if (getenv('HTTP_CLIENT_IP'))
170             $ip = getenv('HTTP_CLIENT_IP');
171         else
172             if (getenv('REMOTE_ADDR'))
173                 $ip = getenv('REMOTE_ADDR');
174             else
175                 $ip = getenv('HTTP_X_FORWARDED_FOR');
176
177         $moddatetime = gmdate('Y-m-d H:i:s', time());
178
179         // Set up the SQL update statement and execute it.
180         $updates = array('bModified' => $moddatetime, 'bTitle' => $title, 'bAddress' => $address, 'bDescription' => $description, 'bStatus' => $status, 'bHash' => md5($address));
181
182         if (!is_null($date)) {
183             $updates['bDateTime'] = gmdate('Y-m-d H:i:s', strtotime($date));
184         }
185
186         $sql = 'UPDATE '. $GLOBALS['tableprefix'] .'bookmarks SET '. $this->db->sql_build_array('UPDATE', $updates) .' WHERE bId = '. intval($bId);
187         $this->db->sql_transaction('begin');
188
189         if (!($dbresult = & $this->db->sql_query($sql))) {
190             $this->db->sql_transaction('rollback');
191             message_die(GENERAL_ERROR, 'Could not update bookmark', '', __LINE__, __FILE__, $sql, $this->db);
192             return false;
193         }
194
195         $uriparts = explode('.', $address);
196         $extension = end($uriparts);
197         unset($uriparts);
198
199         $tagservice = & ServiceFactory :: getServiceInstance('TagService');
200         if (!$tagservice->attachTags($bId, $categories, $fromApi, $extension)) {
201             $this->db->sql_transaction('rollback');
202             message_die(GENERAL_ERROR, 'Could not update bookmark', '', __LINE__, __FILE__, $sql, $this->db);
203             return false;
204         }
205
206         $this->db->sql_transaction('commit');
207         // Everything worked out, so return true.
208         return true;
209     }
210
211     function & getBookmarks($start = 0, $perpage = NULL, $user = NULL, $tags = NULL, $terms = NULL, $sortOrder = NULL, $watched = NULL, $startdate = NULL, $enddate = NULL, $hash = NULL) {
212         // Only get the bookmarks that are visible to the current user.  Our rules:
213         //  - if the $user is NULL, that means get bookmarks from ALL users, so we need to make
214         //    sure to check the logged-in user's watchlist and get the contacts-only bookmarks from
215         //    those users. If the user isn't logged-in, just get the public bookmarks.
216         //  - if the $user is set and isn't the logged-in user, then get that user's bookmarks, and
217         //    if that user is on the logged-in user's watchlist, get the public AND contacts-only
218         //    bookmarks; otherwise, just get the public bookmarks.
219         //  - if the $user is set and IS the logged-in user, then get all bookmarks.
220         $userservice =& ServiceFactory::getServiceInstance('UserService');
221         $tagservice =& ServiceFactory::getServiceInstance('TagService');
222         $sId = $userservice->getCurrentUserId();
223
224         if ($userservice->isLoggedOn()) {
225             // All public bookmarks, user's own bookmarks and any shared with user
226             $privacy = ' AND ((B.bStatus = 0) OR (B.uId = '. $sId .')';
227             $watchnames = $userservice->getWatchNames($sId, true);
228             foreach($watchnames as $watchuser) {
229                 $privacy .= ' OR (U.username = "'. $watchuser .'" AND B.bStatus = 1)'; 
230             }
231             $privacy .= ')';
232         } else {
233             // Just public bookmarks
234             $privacy = ' AND B.bStatus = 0';
235         }
236
237         // Set up the tags, if need be.
238         if (!is_array($tags) && !is_null($tags)) {
239             $tags = explode('+', trim($tags));
240         }
241
242         $tagcount = count($tags);
243         for ($i = 0; $i < $tagcount; $i ++) {
244             $tags[$i] = trim($tags[$i]);
245         }
246
247         // Set up the SQL query.
248         $query_1 = 'SELECT DISTINCT ';
249         if (SQL_LAYER == 'mysql4') {
250             $query_1 .= 'SQL_CALC_FOUND_ROWS ';
251         }
252         $query_1 .= 'B.*, U.'. $userservice->getFieldName('username');
253
254         $query_2 = ' FROM '. $userservice->getTableName() .' AS U, '. $GLOBALS['tableprefix'] .'bookmarks AS B';
255
256         $query_3 = ' WHERE B.uId = U.'. $userservice->getFieldName('primary') . $privacy;
257         if (is_null($watched)) {
258             if (!is_null($user)) {
259                 $query_3 .= ' AND B.uId = '. $user;
260             }
261         } else {
262             $arrWatch = $userservice->getWatchlist($user);
263             if (count($arrWatch) > 0) {
264                 foreach($arrWatch as $row) {
265                     $query_3_1 .= 'B.uId = '. intval($row) .' OR ';
266                 }
267                 $query_3_1 = substr($query_3_1, 0, -3);
268             } else {
269                 $query_3_1 = 'B.uId = -1';
270             }
271             $query_3 .= ' AND ('. $query_3_1 .') AND B.bStatus IN (0, 1)';
272         }
273
274         switch($sortOrder) {
275             case 'date_asc':
276                 $query_5 = ' ORDER BY B.bDatetime ASC ';
277                 break;
278             case 'title_desc':
279                 $query_5 = ' ORDER BY B.bTitle DESC ';
280                 break;
281             case 'title_asc':
282                 $query_5 = ' ORDER BY B.bTitle ASC ';
283                 break;
284             case 'url_desc':
285                 $query_5 = ' ORDER BY B.bAddress DESC ';
286                 break;
287             case 'url_asc':
288                 $query_5 = ' ORDER BY B.bAddress ASC ';
289                 break;
290             default:
291                 $query_5 = ' ORDER BY B.bDatetime DESC ';
292         }
293
294         // Handle the parts of the query that depend on any tags that are present.
295         $query_4 = '';
296         for ($i = 0; $i < $tagcount; $i ++) {
297             $query_2 .= ', '. $GLOBALS['tableprefix'] .'tags AS T'. $i;
298             $query_4 .= ' AND T'. $i .'.tag = "'. $this->db->sql_escape($tags[$i]) .'" AND T'. $i .'.bId = B.bId';
299         }
300
301         // Search terms
302         if ($terms) {
303             // Multiple search terms okay
304             $aTerms = explode(' ', $terms);
305             $aTerms = array_map('trim', $aTerms);
306
307             // Search terms in tags as well when none given
308             if (!count($tags)) {
309                 $query_2 .= ' LEFT JOIN '. $GLOBALS['tableprefix'] .'tags AS T ON B.bId = T.bId';
310                 $dotags = true;
311             } else {
312                 $dotags = false;
313             }
314
315             $query_4 = '';
316             for ($i = 0; $i < count($aTerms); $i++) {
317                 $query_4 .= ' AND (B.bTitle LIKE "%'. $this->db->sql_escape($aTerms[$i]) .'%"';
318                 $query_4 .= ' OR B.bDescription LIKE "%'. $this->db->sql_escape($aTerms[$i]) .'%"';
319                 if ($dotags) {
320                     $query_4 .= ' OR T.tag = "'. $this->db->sql_escape($aTerms[$i]) .'"';
321                 }
322                 $query_4 .= ')';
323             }
324         }
325
326         // Start and end dates
327         if ($startdate) {
328             $query_4 .= ' AND B.bDatetime > "'. $startdate .'"';
329         }
330         if ($enddate) {
331             $query_4 .= ' AND B.bDatetime < "'. $enddate .'"';
332         }
333
334         // Hash
335         if ($hash) {
336             $query_4 .= ' AND B.bHash = "'. $hash .'"';
337         }
338
339         $query = $query_1 . $query_2 . $query_3 . $query_4 . $query_5;
340         if (!($dbresult = & $this->db->sql_query_limit($query, intval($perpage), intval($start)))) {
341             message_die(GENERAL_ERROR, 'Could not get bookmarks', '', __LINE__, __FILE__, $query, $this->db);
342             return false;
343         }
344
345         if (SQL_LAYER == 'mysql4') {
346             $totalquery = 'SELECT FOUND_ROWS() AS total';
347         } else {
348             $totalquery = 'SELECT COUNT(*) AS total'. $query_2 . $query_3 . $query_4;
349         }
350
351         if (!($totalresult = & $this->db->sql_query($totalquery)) || (!($row = & $this->db->sql_fetchrow($totalresult)))) {
352             message_die(GENERAL_ERROR, 'Could not get total bookmarks', '', __LINE__, __FILE__, $totalquery, $this->db);
353             return false;
354         }
355
356         $total = $row['total'];
357
358         $bookmarks = array();
359         while ($row = & $this->db->sql_fetchrow($dbresult)) {
360             $row['tags'] = $tagservice->getTagsForBookmark(intval($row['bId']));
361             $bookmarks[] = $row;
362         }
363         return array ('bookmarks' => $bookmarks, 'total' => $total);
364     }
365
366     function deleteBookmark($bookmarkid) {
367         $query = 'DELETE FROM '. $GLOBALS['tableprefix'] .'bookmarks WHERE bId = '. intval($bookmarkid);
368         $this->db->sql_transaction('begin');
369         if (!($dbresult = & $this->db->sql_query($query))) {
370             $this->db->sql_transaction('rollback');
371             message_die(GENERAL_ERROR, 'Could not delete bookmarks', '', __LINE__, __FILE__, $query, $this->db);
372             return false;
373         }
374
375         $query = 'DELETE FROM '. $GLOBALS['tableprefix'] .'tags WHERE bId = '. intval($bookmarkid);
376         $this->db->sql_transaction('begin');
377         if (!($dbresult = & $this->db->sql_query($query))) {
378             $this->db->sql_transaction('rollback');
379             message_die(GENERAL_ERROR, 'Could not delete bookmarks', '', __LINE__, __FILE__, $query, $this->db);
380             return false;
381         }
382
383         $this->db->sql_transaction('commit');
384         return true;
385     }
386
387     function countOthers($address) {
388         if (!$address) {
389             return false;
390         }
391
392         $userservice = & ServiceFactory :: getServiceInstance('UserService');
393         $sId = $userservice->getCurrentUserId();
394
395         if ($userservice->isLoggedOn()) {
396             // All public bookmarks, user's own bookmarks and any shared with user
397             $privacy = ' AND ((B.bStatus = 0) OR (B.uId = '. $sId .')';
398             $watchnames = $userservice->getWatchNames($sId, true);
399             foreach($watchnames as $watchuser) {
400                 $privacy .= ' OR (U.username = "'. $watchuser .'" AND B.bStatus = 1)'; 
401             }
402             $privacy .= ')';
403         } else {
404             // Just public bookmarks
405             $privacy = ' AND B.bStatus = 0';
406         }
407
408         $sql = 'SELECT COUNT(*) FROM '. $userservice->getTableName() .' AS U, '. $GLOBALS['tableprefix'] .'bookmarks AS B WHERE U.'. $userservice->getFieldName('primary') .' = B.uId AND B.bHash = "'. md5($address) .'"'. $privacy;
409         if (!($dbresult = & $this->db->sql_query($sql))) {
410             message_die(GENERAL_ERROR, 'Could not get vars', '', __LINE__, __FILE__, $sql, $this->db);
411         }
412         return $this->db->sql_fetchfield(0, 0) - 1;
413     }
414 }
415 ?>

Benjamin Mako Hill || Want to submit a patch?