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