]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
98a77e20d179f6c758dcc4e07bab80e898ad1452
[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                 $notice->is_local = $is_local;
99                 $notice->reply_to = $reply_to;
100                 $notice->created = common_sql_now();
101                 $notice->content = $content;
102                 $notice->rendered = common_render_content($notice->content, $notice);
103                 $notice->source = $source;
104                 $notice->uri = $uri;
105
106                 $id = $notice->insert();
107
108                 if (!$id) {
109                         common_log_db_error($notice, 'INSERT', __FILE__);
110                         return _('Problem saving notice.');
111                 }
112
113                 # Update the URI after the notice is in the database
114                 if (!$uri) {
115                         $orig = clone($notice);
116                         $notice->uri = common_notice_uri($notice);
117
118                         if (!$notice->update($orig)) {
119                                 common_log_db_error($notice, 'UPDATE', __FILE__);
120                                 return _('Problem saving notice.');
121                         }
122                 }
123
124                 # XXX: do we need to change this for remote users?
125
126                 common_save_replies($notice);
127                 $notice->saveTags();
128
129                 # Clear the cache for subscribed users, so they'll update at next request
130                 # XXX: someone clever could prepend instead of clearing the cache
131
132                 if (common_config('memcached', 'enabled')) {
133                         $notice->blowCaches();
134                 }
135
136                 $notice->addToInboxes();
137                 return $notice;
138         }
139
140         function blowCaches($blowLast=false) {
141                 $this->blowSubsCache($blowLast);
142                 $this->blowNoticeCache($blowLast);
143                 $this->blowRepliesCache($blowLast);
144                 $this->blowPublicCache($blowLast);
145                 $this->blowTagCache($blowLast);
146         }
147
148         function blowTagCache($blowLast=false) {
149                 $cache = common_memcache();
150                 if ($cache) {
151                         $tag = new Notice_tag();
152                         $tag->notice_id = $this->id;
153                         if ($tag->find()) {
154                                 while ($tag->fetch()) {
155                                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
156                                         if ($blowLast) {
157                                                 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
158                                         }
159                                 }
160                         }
161                         $tag->free();
162                         unset($tag);
163                 }
164         }
165
166         function blowSubsCache($blowLast=false) {
167                 $cache = common_memcache();
168                 if ($cache) {
169                         $user = new User();
170
171                         $user->query('SELECT id ' .
172                                                  'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
173                                                  'WHERE subscription.subscribed = ' . $this->profile_id);
174
175                         while ($user->fetch()) {
176                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
177                                 if ($blowLast) {
178                                         $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
179                                 }
180                         }
181                         $user->free();
182                         unset($user);
183                 }
184         }
185
186         function blowNoticeCache($blowLast=false) {
187                 if ($this->is_local) {
188                         $cache = common_memcache();
189                         if ($cache) {
190                                 $cache->delete(common_cache_key('user:notices:'.$this->profile_id));
191                                 if ($blowLast) {
192                                         $cache->delete(common_cache_key('user:notices:'.$this->profile_id.';last'));
193                                 }
194                         }
195                 }
196         }
197
198         function blowRepliesCache($blowLast=false) {
199                 $cache = common_memcache();
200                 if ($cache) {
201                         $reply = new Reply();
202                         $reply->notice_id = $this->id;
203                         if ($reply->find()) {
204                                 while ($reply->fetch()) {
205                                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
206                                         if ($blowLast) {
207                                                 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
208                                         }
209                                 }
210                         }
211                         $reply->free();
212                         unset($reply);
213                 }
214         }
215
216         function blowPublicCache($blowLast=false) {
217                 if ($this->is_local) {
218                         $cache = common_memcache();
219                         if ($cache) {
220                                 $cache->delete(common_cache_key('public'));
221                                 if ($blowLast) {
222                                         $cache->delete(common_cache_key('public').';last');
223                                 }
224                         }
225                 }
226         }
227
228         function blowFavesCache($blowLast=false) {
229                 $cache = common_memcache();
230                 if ($cache) {
231                         $fave = new Fave();
232                         $fave->notice_id = $this->id;
233                         if ($fave->find()) {
234                                 while ($fave->fetch()) {
235                                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
236                                         if ($blowLast) {
237                                                 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
238                                         }
239                                 }
240                         }
241                         $fave->free();
242                         unset($fave);
243                 }
244         }
245
246         # XXX: too many args; we need to move to named params or even a separate
247         # class for notice streams
248
249         static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL) {
250
251                 if (common_config('memcached', 'enabled')) {
252
253                         # Skip the cache if this is a since_id or before_id qry
254                         if ($since_id > 0 || $before_id > 0) {
255                                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
256                         } else {
257                                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
258                         }
259                 }
260
261                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
262         }
263
264         static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order) {
265
266                 $needAnd = FALSE;
267                 $needWhere = TRUE;
268
269                 if (preg_match('/\bWHERE\b/i', $qry)) {
270                         $needWhere = FALSE;
271                         $needAnd = TRUE;
272                 }
273
274                 if ($since_id > 0) {
275
276                         if ($needWhere) {
277                         $qry .= ' WHERE ';
278                                 $needWhere = FALSE;
279                         } else {
280                                 $qry .= ' AND ';
281                         }
282
283                     $qry .= ' notice.id > ' . $since_id;
284                 }
285
286                 if ($before_id > 0) {
287
288                         if ($needWhere) {
289                         $qry .= ' WHERE ';
290                                 $needWhere = FALSE;
291                         } else {
292                                 $qry .= ' AND ';
293                         }
294
295                         $qry .= ' notice.id < ' . $before_id;
296                 }
297
298                 # Allow ORDER override
299
300                 if ($order) {
301                         $qry .= $order;
302                 } else {
303                         $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
304                 }
305
306                 if (common_config('db','type') == 'pgsql') {
307                         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
308                 } else {
309                         $qry .= ' LIMIT ' . $offset . ', ' . $limit;
310                 }
311
312                 $notice = new Notice();
313
314                 $notice->query($qry);
315
316                 return $notice;
317         }
318
319         # XXX: this is pretty long and should probably be broken up into
320         # some helper functions
321
322         static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
323
324                 # If outside our cache window, just go to the DB
325
326                 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
327                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
328                 }
329
330                 # Get the cache; if we can't, just go to the DB
331
332                 $cache = common_memcache();
333
334                 if (!$cache) {
335                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
336                 }
337
338                 # Get the notices out of the cache
339
340                 $notices = $cache->get(common_cache_key($cachekey));
341
342                 # On a cache hit, return a DB-object-like wrapper
343
344                 if ($notices !== FALSE) {
345                         $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
346                         return $wrapper;
347                 }
348
349                 # If the cache was invalidated because of new data being
350                 # added, we can try and just get the new stuff. We keep an additional
351                 # copy of the data at the key + ';last'
352
353                 # No cache hit. Try to get the *last* cached version
354
355                 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
356
357                 if ($last_notices) {
358
359                         # Reverse-chron order, so last ID is last.
360
361                         $last_id = $last_notices[0]->id;
362
363                         # XXX: this assumes monotonically increasing IDs; a fair
364                         # bet with our DB.
365
366                         $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
367                                                                                                   $last_id, NULL, $order);
368
369                         if ($new_notice) {
370                                 $new_notices = array();
371                                 while ($new_notice->fetch()) {
372                                         $new_notices[] = clone($new_notice);
373                                 }
374                                 $new_notice->free();
375                                 $notices = array_slice(array_merge($new_notices, $last_notices),
376                                                                            0, NOTICE_CACHE_WINDOW);
377
378                                 # Store the array in the cache for next time
379
380                                 $result = $cache->set(common_cache_key($cachekey), $notices);
381                                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
382
383                                 # return a wrapper of the array for use now
384
385                                 return new NoticeWrapper(array_slice($notices, $offset, $limit));
386                         }
387                 }
388
389                 # Otherwise, get the full cache window out of the DB
390
391                 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order);
392
393                 # If there are no hits, just return the value
394
395                 if (!$notice) {
396                         return $notice;
397                 }
398
399                 # Pack results into an array
400
401                 $notices = array();
402
403                 while ($notice->fetch()) {
404                         $notices[] = clone($notice);
405                 }
406
407                 $notice->free();
408
409                 # Store the array in the cache for next time
410
411                 $result = $cache->set(common_cache_key($cachekey), $notices);
412                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
413
414                 # return a wrapper of the array for use now
415
416                 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
417
418                 return $wrapper;
419         }
420
421         function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0) {
422
423                 $parts = array();
424
425                 $qry = 'SELECT * FROM notice ';
426
427                 if (common_config('public', 'localonly')) {
428                         $parts[] = 'is_local = 1';
429                 }
430
431                 if (common_config('public', 'blacklist')) {
432                         $parts[] = 'profile_id not in (' . implode(',', common_config('public', 'blacklist')) . ')';
433                 }
434
435                 if ($parts) {
436                         $qry .= ' WHERE ' . implode(' AND ', $parts);
437                 }
438
439                 return Notice::getStream($qry,
440                                                                  'public',
441                                                                  $offset, $limit, $since_id, $before_id);
442         }
443
444         function addToInboxes() {
445                 $enabled = common_config('inboxes', 'enabled');
446
447                 if ($enabled === true || $enabled === 'transitional') {
448                         $inbox = new Notice_inbox();
449                         $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
450                           'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
451                           'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
452                           'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
453                           'AND NOT EXISTS (SELECT user_id, notice_id ' .
454                           'FROM notice_inbox ' .
455                           'WHERE user_id = user.id ' .
456                           'AND notice_id = ' . $this->id . ' )';
457                         if ($enabled === 'transitional') {
458                                 $qry .= ' AND user.inboxed = 1';
459                         }
460                         $inbox->query($qry);
461                 }
462                 return;
463         }
464
465         # Delete from inboxes if we're deleted.
466
467         function blowInboxes() {
468
469                 $enabled = common_config('inboxes', 'enabled');
470
471                 if ($enabled === true || $enabled === 'transitional') {
472                         $inbox = new Notice_inbox();
473                         $inbox->notice_id = $this->id;
474                         $inbox->delete();
475                 }
476
477                 return;
478         }
479
480 }
481