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

Benjamin Mako Hill || Want to submit a patch?