]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
6d42a4f9af517dd21bacef981ab258ccfcf6337d
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 class Notice extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'notice';                          // table name
38     public $id;                              // int(4)  primary_key not_null
39     public $profile_id;                      // int(4)   not_null
40     public $uri;                             // varchar(255)  unique_key
41     public $content;                         // varchar(140)  
42     public $rendered;                        // text()  
43     public $url;                             // varchar(255)  
44     public $created;                         // datetime()   not_null
45     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
46     public $reply_to;                        // int(4)  
47     public $is_local;                        // tinyint(1)  
48     public $source;                          // varchar(32)  
49
50     /* Static get */
51     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
52
53     /* the code above is auto generated do not remove the tag below */
54     ###END_AUTOCODE
55
56         function getProfile() {
57                 return Profile::staticGet('id', $this->profile_id);
58         }
59
60         function delete() {
61                 $this->blowCaches(true);
62                 $this->blowFavesCache(true);
63                 $this->blowInboxes();
64                 parent::delete();
65         }
66
67         function saveTags() {
68                 /* extract all #hastags */
69                 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
70                 if (!$count) {
71                         return true;
72                 }
73
74                 /* elide characters we don't want in the tag */
75                 $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
76
77                 /* Add them to the database */
78                 foreach(array_unique($match[1]) as $hashtag) {
79                         $tag = DB_DataObject::factory('Notice_tag');
80                         $tag->notice_id = $this->id;
81                         $tag->tag = $hashtag;
82                         $tag->created = $this->created;
83                         $id = $tag->insert();
84                         if (!$id) {
85                                 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
86                                 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
87                                 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
88                                 return;
89                         }
90                 }
91                 return true;
92         }
93
94         static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) {
95
96                 $notice = new Notice();
97                 $notice->profile_id = $profile_id;
98
99                 $blacklist = common_config('public', 'blacklist');
100
101                 # Blacklisted are non-false, but not 1, either
102
103                 if ($blacklist && in_array($profile_id, $blacklist)) {
104                         $notice->is_local = -1;
105                 } else {
106                         $notice->is_local = $is_local;
107                 }
108
109                 $notice->reply_to = $reply_to;
110                 $notice->created = common_sql_now();
111                 $notice->content = $content;
112                 $notice->rendered = common_render_content($notice->content, $notice);
113                 $notice->source = $source;
114                 $notice->uri = $uri;
115
116                 $id = $notice->insert();
117
118                 if (!$id) {
119                         common_log_db_error($notice, 'INSERT', __FILE__);
120                         return _('Problem saving notice.');
121                 }
122
123                 # Update the URI after the notice is in the database
124                 if (!$uri) {
125                         $orig = clone($notice);
126                         $notice->uri = common_notice_uri($notice);
127
128                         if (!$notice->update($orig)) {
129                                 common_log_db_error($notice, 'UPDATE', __FILE__);
130                                 return _('Problem saving notice.');
131                         }
132                 }
133
134                 # XXX: do we need to change this for remote users?
135
136                 common_save_replies($notice);
137                 $notice->saveTags();
138
139                 # Clear the cache for subscribed users, so they'll update at next request
140                 # XXX: someone clever could prepend instead of clearing the cache
141
142                 if (common_config('memcached', 'enabled')) {
143                         $notice->blowCaches();
144                 }
145
146                 $notice->addToInboxes();
147                 return $notice;
148         }
149
150         function blowCaches($blowLast=false) {
151                 $this->blowSubsCache($blowLast);
152                 $this->blowNoticeCache($blowLast);
153                 $this->blowRepliesCache($blowLast);
154                 $this->blowPublicCache($blowLast);
155                 $this->blowTagCache($blowLast);
156         }
157
158         function blowTagCache($blowLast=false) {
159                 $cache = common_memcache();
160                 if ($cache) {
161                         $tag = new Notice_tag();
162                         $tag->notice_id = $this->id;
163                         if ($tag->find()) {
164                                 while ($tag->fetch()) {
165                                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
166                                         if ($blowLast) {
167                                                 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
168                                         }
169                                 }
170                         }
171                         $tag->free();
172                         unset($tag);
173                 }
174         }
175
176         function blowSubsCache($blowLast=false) {
177                 $cache = common_memcache();
178                 if ($cache) {
179                         $user = new User();
180
181                         $user->query('SELECT id ' .
182                                                  'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
183                                                  'WHERE subscription.subscribed = ' . $this->profile_id);
184
185                         while ($user->fetch()) {
186                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
187                                 if ($blowLast) {
188                                         $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
189                                 }
190                         }
191                         $user->free();
192                         unset($user);
193                 }
194         }
195
196         function blowNoticeCache($blowLast=false) {
197                 if ($this->is_local) {
198                         $cache = common_memcache();
199                         if ($cache) {
200                                 $cache->delete(common_cache_key('user:notices:'.$this->profile_id));
201                                 if ($blowLast) {
202                                         $cache->delete(common_cache_key('user:notices:'.$this->profile_id.';last'));
203                                 }
204                         }
205                 }
206         }
207
208         function blowRepliesCache($blowLast=false) {
209                 $cache = common_memcache();
210                 if ($cache) {
211                         $reply = new Reply();
212                         $reply->notice_id = $this->id;
213                         if ($reply->find()) {
214                                 while ($reply->fetch()) {
215                                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
216                                         if ($blowLast) {
217                                                 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
218                                         }
219                                 }
220                         }
221                         $reply->free();
222                         unset($reply);
223                 }
224         }
225
226         function blowPublicCache($blowLast=false) {
227                 if ($this->is_local == 1) {
228                         $cache = common_memcache();
229                         if ($cache) {
230                                 $cache->delete(common_cache_key('public'));
231                                 if ($blowLast) {
232                                         $cache->delete(common_cache_key('public').';last');
233                                 }
234                         }
235                 }
236         }
237
238         function blowFavesCache($blowLast=false) {
239                 $cache = common_memcache();
240                 if ($cache) {
241                         $fave = new Fave();
242                         $fave->notice_id = $this->id;
243                         if ($fave->find()) {
244                                 while ($fave->fetch()) {
245                                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
246                                         if ($blowLast) {
247                                                 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
248                                         }
249                                 }
250                         }
251                         $fave->free();
252                         unset($fave);
253                 }
254         }
255
256         # XXX: too many args; we need to move to named params or even a separate
257         # class for notice streams
258
259         static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL) {
260
261                 if (common_config('memcached', 'enabled')) {
262
263                         # Skip the cache if this is a since_id or before_id qry
264                         if ($since_id > 0 || $before_id > 0) {
265                                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
266                         } else {
267                                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
268                         }
269                 }
270
271                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
272         }
273
274         static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order) {
275
276                 $needAnd = FALSE;
277                 $needWhere = TRUE;
278
279                 if (preg_match('/\bWHERE\b/i', $qry)) {
280                         $needWhere = FALSE;
281                         $needAnd = TRUE;
282                 }
283
284                 if ($since_id > 0) {
285
286                         if ($needWhere) {
287                         $qry .= ' WHERE ';
288                                 $needWhere = FALSE;
289                         } else {
290                                 $qry .= ' AND ';
291                         }
292
293                     $qry .= ' notice.id > ' . $since_id;
294                 }
295
296                 if ($before_id > 0) {
297
298                         if ($needWhere) {
299                         $qry .= ' WHERE ';
300                                 $needWhere = FALSE;
301                         } else {
302                                 $qry .= ' AND ';
303                         }
304
305                         $qry .= ' notice.id < ' . $before_id;
306                 }
307
308                 # Allow ORDER override
309
310                 if ($order) {
311                         $qry .= $order;
312                 } else {
313                         $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
314                 }
315
316                 if (common_config('db','type') == 'pgsql') {
317                         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
318                 } else {
319                         $qry .= ' LIMIT ' . $offset . ', ' . $limit;
320                 }
321
322                 $notice = new Notice();
323
324                 $notice->query($qry);
325
326                 return $notice;
327         }
328
329         # XXX: this is pretty long and should probably be broken up into
330         # some helper functions
331
332         static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
333
334                 # If outside our cache window, just go to the DB
335
336                 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
337                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
338                 }
339
340                 # Get the cache; if we can't, just go to the DB
341
342                 $cache = common_memcache();
343
344                 if (!$cache) {
345                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
346                 }
347
348                 # Get the notices out of the cache
349
350                 $notices = $cache->get(common_cache_key($cachekey));
351
352                 # On a cache hit, return a DB-object-like wrapper
353
354                 if ($notices !== FALSE) {
355                         $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
356                         return $wrapper;
357                 }
358
359                 # If the cache was invalidated because of new data being
360                 # added, we can try and just get the new stuff. We keep an additional
361                 # copy of the data at the key + ';last'
362
363                 # No cache hit. Try to get the *last* cached version
364
365                 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
366
367                 if ($last_notices) {
368
369                         # Reverse-chron order, so last ID is last.
370
371                         $last_id = $last_notices[0]->id;
372
373                         # XXX: this assumes monotonically increasing IDs; a fair
374                         # bet with our DB.
375
376                         $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
377                                                                                                   $last_id, NULL, $order);
378
379                         if ($new_notice) {
380                                 $new_notices = array();
381                                 while ($new_notice->fetch()) {
382                                         $new_notices[] = clone($new_notice);
383                                 }
384                                 $new_notice->free();
385                                 $notices = array_slice(array_merge($new_notices, $last_notices),
386                                                                            0, NOTICE_CACHE_WINDOW);
387
388                                 # Store the array in the cache for next time
389
390                                 $result = $cache->set(common_cache_key($cachekey), $notices);
391                                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
392
393                                 # return a wrapper of the array for use now
394
395                                 return new NoticeWrapper(array_slice($notices, $offset, $limit));
396                         }
397                 }
398
399                 # Otherwise, get the full cache window out of the DB
400
401                 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order);
402
403                 # If there are no hits, just return the value
404
405                 if (!$notice) {
406                         return $notice;
407                 }
408
409                 # Pack results into an array
410
411                 $notices = array();
412
413                 while ($notice->fetch()) {
414                         $notices[] = clone($notice);
415                 }
416
417                 $notice->free();
418
419                 # Store the array in the cache for next time
420
421                 $result = $cache->set(common_cache_key($cachekey), $notices);
422                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
423
424                 # return a wrapper of the array for use now
425
426                 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
427
428                 return $wrapper;
429         }
430
431         function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0) {
432
433                 $parts = array();
434
435                 $qry = 'SELECT * FROM notice ';
436
437                 if (common_config('public', 'localonly')) {
438                         $parts[] = 'is_local = 1';
439                 } else {
440                         # -1 == blacklisted
441                         $parts[] = 'is_local != -1';
442                 }
443
444                 if ($parts) {
445                         $qry .= ' WHERE ' . implode(' AND ', $parts);
446                 }
447
448                 return Notice::getStream($qry,
449                                                                  'public',
450                                                                  $offset, $limit, $since_id, $before_id);
451         }
452
453         function addToInboxes() {
454                 $enabled = common_config('inboxes', 'enabled');
455
456                 if ($enabled === true || $enabled === 'transitional') {
457                         $inbox = new Notice_inbox();
458                         $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
459                           'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
460                           'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
461                           'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
462                           'AND NOT EXISTS (SELECT user_id, notice_id ' .
463                           'FROM notice_inbox ' .
464                           'WHERE user_id = user.id ' .
465                           'AND notice_id = ' . $this->id . ' )';
466                         if ($enabled === 'transitional') {
467                                 $qry .= ' AND user.inboxed = 1';
468                         }
469                         $inbox->query($qry);
470                 }
471                 return;
472         }
473
474         # Delete from inboxes if we're deleted.
475
476         function blowInboxes() {
477
478                 $enabled = common_config('inboxes', 'enabled');
479
480                 if ($enabled === true || $enabled === 'transitional') {
481                         $inbox = new Notice_inbox();
482                         $inbox->notice_id = $this->id;
483                         $inbox->delete();
484                 }
485
486                 return;
487         }
488
489 }
490