]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
0b1017e126d95e0da7dd79c102a19e2474ed333c
[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     public $conversation;                    // int(4)
50
51     /* Static get */
52     function staticGet($k,$v=NULL) {
53         return Memcached_DataObject::staticGet('Notice',$k,$v);
54     }
55
56     /* the code above is auto generated do not remove the tag below */
57     ###END_AUTOCODE
58
59     function getProfile()
60     {
61         return Profile::staticGet('id', $this->profile_id);
62     }
63
64     function delete()
65     {
66         $this->blowCaches(true);
67         $this->blowFavesCache(true);
68         $this->blowSubsCache(true);
69
70         $this->query('BEGIN');
71         //Null any notices that are replies to this notice
72         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
73         $related = array('Reply',
74                          'Fave',
75                          'Notice_tag',
76                          'Group_inbox',
77                          'Queue_item');
78         if (common_config('inboxes', 'enabled')) {
79             $related[] = 'Notice_inbox';
80         }
81         foreach ($related as $cls) {
82             $inst = new $cls();
83             $inst->notice_id = $this->id;
84             $inst->delete();
85         }
86         $result = parent::delete();
87         $this->query('COMMIT');
88     }
89
90     function saveTags()
91     {
92         /* extract all #hastags */
93         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
94         if (!$count) {
95             return true;
96         }
97
98         /* Add them to the database */
99         foreach(array_unique($match[1]) as $hashtag) {
100             /* elide characters we don't want in the tag */
101             $this->saveTag($hashtag);
102         }
103         return true;
104     }
105
106     function saveTag($hashtag)
107     {
108         $hashtag = common_canonical_tag($hashtag);
109
110         $tag = new Notice_tag();
111         $tag->notice_id = $this->id;
112         $tag->tag = $hashtag;
113         $tag->created = $this->created;
114         $id = $tag->insert();
115
116         if (!$id) {
117             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
118                                               $last_error->message));
119             return;
120         }
121     }
122
123     static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
124
125         $profile = Profile::staticGet($profile_id);
126
127         if (!$profile) {
128             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
129             return _('Problem saving notice. Unknown user.');
130         }
131
132         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
133             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
134             return _('Too many notices too fast; take a breather and post again in a few minutes.');
135         }
136
137         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $content)) {
138             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
139                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
140         }
141
142                 $banned = common_config('profile', 'banned');
143
144         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
145             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
146             return _('You are banned from posting notices on this site.');
147         }
148
149         $notice = new Notice();
150         $notice->profile_id = $profile_id;
151
152         $blacklist = common_config('public', 'blacklist');
153         $autosource = common_config('public', 'autosource');
154
155         # Blacklisted are non-false, but not 1, either
156
157         if (($blacklist && in_array($profile_id, $blacklist)) ||
158             ($source && $autosource && in_array($source, $autosource))) {
159             $notice->is_local = -1;
160         } else {
161             $notice->is_local = $is_local;
162         }
163
164                 $notice->query('BEGIN');
165
166                 $notice->reply_to = $reply_to;
167                 $notice->created = common_sql_now();
168                 $notice->content = $content;
169                 $notice->rendered = common_render_content($content, $notice);
170                 $notice->source = $source;
171                 $notice->uri = $uri;
172
173         if (!empty($reply_to)) {
174             $reply_notice = Notice::staticGet('id', $reply_to);
175             if (!empty($reply_notice)) {
176                 $notice->reply_to = $reply_to;
177                 $notice->conversation = $reply_notice->conversation;
178             }
179         }
180
181         if (Event::handle('StartNoticeSave', array(&$notice))) {
182
183             $id = $notice->insert();
184
185             if (!$id) {
186                 common_log_db_error($notice, 'INSERT', __FILE__);
187                 return _('Problem saving notice.');
188             }
189
190             # Update the URI after the notice is in the database
191             if (!$uri) {
192                 $orig = clone($notice);
193                 $notice->uri = common_notice_uri($notice);
194
195                 if (!$notice->update($orig)) {
196                     common_log_db_error($notice, 'UPDATE', __FILE__);
197                     return _('Problem saving notice.');
198                 }
199             }
200
201             # XXX: do we need to change this for remote users?
202
203             $notice->saveReplies();
204             $notice->saveTags();
205             $notice->saveGroups();
206
207             if (common_config('queue', 'enabled')) {
208                 $notice->addToAuthorInbox();
209             } else {
210                 $notice->addToInboxes();
211             }
212
213             $notice->query('COMMIT');
214
215             Event::handle('EndNoticeSave', array($notice));
216         }
217
218         # Clear the cache for subscribed users, so they'll update at next request
219         # XXX: someone clever could prepend instead of clearing the cache
220
221         if (common_config('memcached', 'enabled')) {
222             if (common_config('queue', 'enabled')) {
223                 $notice->blowAuthorCaches();
224             } else {
225                 $notice->blowCaches();
226             }
227         }
228
229         return $notice;
230     }
231
232     static function checkDupes($profile_id, $content) {
233         $profile = Profile::staticGet($profile_id);
234         if (!$profile) {
235             return false;
236         }
237         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
238         if ($notice) {
239             $last = 0;
240             while ($notice->fetch()) {
241                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
242                     return true;
243                 } else if ($notice->content == $content) {
244                     return false;
245                 }
246             }
247         }
248         # If we get here, oldest item in cache window is not
249         # old enough for dupe limit; do direct check against DB
250         $notice = new Notice();
251         $notice->profile_id = $profile_id;
252         $notice->content = $content;
253         if (common_config('db','type') == 'pgsql')
254             $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
255         else
256             $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
257
258         $cnt = $notice->count();
259         return ($cnt == 0);
260     }
261
262     static function checkEditThrottle($profile_id) {
263         $profile = Profile::staticGet($profile_id);
264         if (!$profile) {
265             return false;
266         }
267         # Get the Nth notice
268         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
269         if ($notice && $notice->fetch()) {
270             # If the Nth notice was posted less than timespan seconds ago
271             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
272                 # Then we throttle
273                 return false;
274             }
275         }
276         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
277         return true;
278     }
279
280     function getUploadedAttachment() {
281         $post = clone $this;
282         $query = 'select file.url as uploaded from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
283         $post->query($query);
284         $post->fetch();
285         $ret = $post->uploaded;
286 //        var_dump($post);
287         $post->free();
288 //        die();
289         return $ret;
290     }
291
292     function hasAttachments() {
293         $post = clone $this;
294         $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
295         $post->query($query);
296         $post->fetch();
297         $n_attachments = intval($post->n_attachments);
298         $post->free();
299         return $n_attachments;
300     }
301
302     function blowCaches($blowLast=false)
303     {
304         $this->blowSubsCache($blowLast);
305         $this->blowNoticeCache($blowLast);
306         $this->blowRepliesCache($blowLast);
307         $this->blowPublicCache($blowLast);
308         $this->blowTagCache($blowLast);
309         $this->blowGroupCache($blowLast);
310     }
311
312     function blowAuthorCaches($blowLast=false)
313     {
314         // Clear the user's cache
315         $cache = common_memcache();
316         if (!empty($cache)) {
317             $cache->delete(common_cache_key('notice_inbox:by_user:'.$this->profile_id));
318         }
319         $this->blowNoticeCache($blowLast);
320         $this->blowPublicCache($blowLast);
321     }
322
323     function blowGroupCache($blowLast=false)
324     {
325         $cache = common_memcache();
326         if ($cache) {
327             $group_inbox = new Group_inbox();
328             $group_inbox->notice_id = $this->id;
329             if ($group_inbox->find()) {
330                 while ($group_inbox->fetch()) {
331                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
332                     if ($blowLast) {
333                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
334                     }
335                     $member = new Group_member();
336                     $member->group_id = $group_inbox->group_id;
337                     if ($member->find()) {
338                         while ($member->fetch()) {
339                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
340                             if ($blowLast) {
341                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
342                             }
343                         }
344                     }
345                 }
346             }
347             $group_inbox->free();
348             unset($group_inbox);
349         }
350     }
351
352     function blowTagCache($blowLast=false)
353     {
354         $cache = common_memcache();
355         if ($cache) {
356             $tag = new Notice_tag();
357             $tag->notice_id = $this->id;
358             if ($tag->find()) {
359                 while ($tag->fetch()) {
360                     $tag->blowCache($blowLast);
361                 }
362             }
363             $tag->free();
364             unset($tag);
365         }
366     }
367
368     function blowSubsCache($blowLast=false)
369     {
370         $cache = common_memcache();
371         if ($cache) {
372             $user = new User();
373
374             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
375             $user->query('SELECT id ' .
376
377                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
378                          'WHERE subscription.subscribed = ' . $this->profile_id);
379
380             while ($user->fetch()) {
381                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
382                 if ($blowLast) {
383                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
384                 }
385             }
386             $user->free();
387             unset($user);
388         }
389     }
390
391     function blowNoticeCache($blowLast=false)
392     {
393         if ($this->is_local) {
394             $cache = common_memcache();
395             if (!empty($cache)) {
396                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
397                 if ($blowLast) {
398                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
399                 }
400             }
401         }
402     }
403
404     function blowRepliesCache($blowLast=false)
405     {
406         $cache = common_memcache();
407         if ($cache) {
408             $reply = new Reply();
409             $reply->notice_id = $this->id;
410             if ($reply->find()) {
411                 while ($reply->fetch()) {
412                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
413                     if ($blowLast) {
414                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
415                     }
416                 }
417             }
418             $reply->free();
419             unset($reply);
420         }
421     }
422
423     function blowPublicCache($blowLast=false)
424     {
425         if ($this->is_local == 1) {
426             $cache = common_memcache();
427             if ($cache) {
428                 $cache->delete(common_cache_key('public'));
429                 if ($blowLast) {
430                     $cache->delete(common_cache_key('public').';last');
431                 }
432             }
433         }
434     }
435
436     function blowFavesCache($blowLast=false)
437     {
438         $cache = common_memcache();
439         if ($cache) {
440             $fave = new Fave();
441             $fave->notice_id = $this->id;
442             if ($fave->find()) {
443                 while ($fave->fetch()) {
444                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
445                     if ($blowLast) {
446                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
447                     }
448                 }
449             }
450             $fave->free();
451             unset($fave);
452         }
453     }
454
455     # XXX: too many args; we need to move to named params or even a separate
456     # class for notice streams
457
458     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
459
460         if (common_config('memcached', 'enabled')) {
461
462             # Skip the cache if this is a since, since_id or before_id qry
463             if ($since_id > 0 || $before_id > 0 || $since) {
464                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
465             } else {
466                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
467             }
468         }
469
470         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
471     }
472
473     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
474
475         $needAnd = false;
476         $needWhere = true;
477
478         if (preg_match('/\bWHERE\b/i', $qry)) {
479             $needWhere = false;
480             $needAnd = true;
481         }
482
483         if ($since_id > 0) {
484
485             if ($needWhere) {
486                 $qry .= ' WHERE ';
487                 $needWhere = false;
488             } else {
489                 $qry .= ' AND ';
490             }
491
492             $qry .= ' notice.id > ' . $since_id;
493         }
494
495         if ($before_id > 0) {
496
497             if ($needWhere) {
498                 $qry .= ' WHERE ';
499                 $needWhere = false;
500             } else {
501                 $qry .= ' AND ';
502             }
503
504             $qry .= ' notice.id < ' . $before_id;
505         }
506
507         if ($since) {
508
509             if ($needWhere) {
510                 $qry .= ' WHERE ';
511                 $needWhere = false;
512             } else {
513                 $qry .= ' AND ';
514             }
515
516             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
517         }
518
519         # Allow ORDER override
520
521         if ($order) {
522             $qry .= $order;
523         } else {
524             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
525         }
526
527         if (common_config('db','type') == 'pgsql') {
528             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
529         } else {
530             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
531         }
532
533         $notice = new Notice();
534
535         $notice->query($qry);
536
537         return $notice;
538     }
539
540     # XXX: this is pretty long and should probably be broken up into
541     # some helper functions
542
543     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
544
545         # If outside our cache window, just go to the DB
546
547         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
548             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
549         }
550
551         # Get the cache; if we can't, just go to the DB
552
553         $cache = common_memcache();
554
555         if (!$cache) {
556             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
557         }
558
559         # Get the notices out of the cache
560
561         $notices = $cache->get(common_cache_key($cachekey));
562
563         # On a cache hit, return a DB-object-like wrapper
564
565         if ($notices !== false) {
566             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
567             return $wrapper;
568         }
569
570         # If the cache was invalidated because of new data being
571         # added, we can try and just get the new stuff. We keep an additional
572         # copy of the data at the key + ';last'
573
574         # No cache hit. Try to get the *last* cached version
575
576         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
577
578         if ($last_notices) {
579
580             # Reverse-chron order, so last ID is last.
581
582             $last_id = $last_notices[0]->id;
583
584             # XXX: this assumes monotonically increasing IDs; a fair
585             # bet with our DB.
586
587             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
588                                                   $last_id, null, $order, null);
589
590             if ($new_notice) {
591                 $new_notices = array();
592                 while ($new_notice->fetch()) {
593                     $new_notices[] = clone($new_notice);
594                 }
595                 $new_notice->free();
596                 $notices = array_slice(array_merge($new_notices, $last_notices),
597                                        0, NOTICE_CACHE_WINDOW);
598
599                 # Store the array in the cache for next time
600
601                 $result = $cache->set(common_cache_key($cachekey), $notices);
602                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
603
604                 # return a wrapper of the array for use now
605
606                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
607             }
608         }
609
610         # Otherwise, get the full cache window out of the DB
611
612         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
613
614         # If there are no hits, just return the value
615
616         if (!$notice) {
617             return $notice;
618         }
619
620         # Pack results into an array
621
622         $notices = array();
623
624         while ($notice->fetch()) {
625             $notices[] = clone($notice);
626         }
627
628         $notice->free();
629
630         # Store the array in the cache for next time
631
632         $result = $cache->set(common_cache_key($cachekey), $notices);
633         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
634
635         # return a wrapper of the array for use now
636
637         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
638
639         return $wrapper;
640     }
641
642     function getStreamByIds($ids)
643     {
644         $cache = common_memcache();
645
646         if (!empty($cache)) {
647             $notices = array();
648             foreach ($ids as $id) {
649                 $notices[] = Notice::staticGet('id', $id);
650             }
651             return new ArrayWrapper($notices);
652         } else {
653             $notice = new Notice();
654             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
655             $notice->orderBy('id DESC');
656
657             $notice->find();
658             return $notice;
659         }
660     }
661
662     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
663     {
664         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
665                               array(),
666                               'public',
667                               $offset, $limit, $since_id, $before_id, $since);
668
669         return Notice::getStreamByIds($ids);
670     }
671
672     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
673     {
674         $notice = new Notice();
675
676         $notice->selectAdd(); // clears it
677         $notice->selectAdd('id');
678
679         $notice->orderBy('id DESC');
680
681         if (!is_null($offset)) {
682             $notice->limit($offset, $limit);
683         }
684
685         if (common_config('public', 'localonly')) {
686             $notice->whereAdd('is_local = 1');
687         } else {
688             # -1 == blacklisted
689             $notice->whereAdd('is_local != -1');
690         }
691
692         if ($since_id != 0) {
693             $notice->whereAdd('id > ' . $since_id);
694         }
695
696         if ($before_id != 0) {
697             $notice->whereAdd('id < ' . $before_id);
698         }
699
700         if (!is_null($since)) {
701             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
702         }
703
704         $ids = array();
705
706         if ($notice->find()) {
707             while ($notice->fetch()) {
708                 $ids[] = $notice->id;
709             }
710         }
711
712         $notice->free();
713         $notice = NULL;
714
715         return $ids;
716     }
717
718     function addToInboxes()
719     {
720         $enabled = common_config('inboxes', 'enabled');
721
722         if ($enabled === true || $enabled === 'transitional') {
723             $inbox = new Notice_inbox();
724             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
725             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
726               "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
727               "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
728               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
729               'AND NOT EXISTS (SELECT user_id, notice_id ' .
730               'FROM notice_inbox ' .
731               "WHERE user_id = $UT.id " .
732               'AND notice_id = ' . $this->id . ' )';
733             if ($enabled === 'transitional') {
734                 $qry .= " AND $UT.inboxed = 1";
735             }
736             $inbox->query($qry);
737         }
738         return;
739     }
740
741     function addToAuthorInbox()
742     {
743         $enabled = common_config('inboxes', 'enabled');
744
745         if ($enabled === true || $enabled === 'transitional') {
746             $user = User::staticGet('id', $this->profile_id);
747             if (empty($user)) {
748                 return;
749             }
750             $inbox = new Notice_inbox();
751             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
752             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
753               "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
754               "FROM $UT " .
755               "WHERE $UT.id = " . $this->profile_id . ' ' .
756               'AND NOT EXISTS (SELECT user_id, notice_id ' .
757               'FROM notice_inbox ' .
758               "WHERE user_id = " . $this->profile_id . ' '.
759               'AND notice_id = ' . $this->id . ' )';
760             if ($enabled === 'transitional') {
761                 $qry .= " AND $UT.inboxed = 1";
762             }
763             $inbox->query($qry);
764         }
765         return;
766     }
767
768     function saveGroups()
769     {
770         $enabled = common_config('inboxes', 'enabled');
771         if ($enabled !== true && $enabled !== 'transitional') {
772             return;
773         }
774
775         /* extract all !group */
776         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
777                                 strtolower($this->content),
778                                 $match);
779         if (!$count) {
780             return true;
781         }
782
783         $profile = $this->getProfile();
784
785         /* Add them to the database */
786
787         foreach (array_unique($match[1]) as $nickname) {
788             /* XXX: remote groups. */
789             $group = User_group::staticGet('nickname', $nickname);
790
791             if (!$group) {
792                 continue;
793             }
794
795             // we automatically add a tag for every group name, too
796
797             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
798                                            'notice_id' => $this->id));
799
800             if (is_null($tag)) {
801                 $this->saveTag($nickname);
802             }
803
804             if ($profile->isMember($group)) {
805
806                 $gi = new Group_inbox();
807
808                 $gi->group_id  = $group->id;
809                 $gi->notice_id = $this->id;
810                 $gi->created   = common_sql_now();
811
812                 $result = $gi->insert();
813
814                 if (!$result) {
815                     common_log_db_error($gi, 'INSERT', __FILE__);
816                 }
817
818                 // FIXME: do this in an offline daemon
819
820                 $this->addToGroupInboxes($group);
821             }
822         }
823     }
824
825     function addToGroupInboxes($group)
826     {
827         $inbox = new Notice_inbox();
828         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
829         $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
830           "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
831           "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
832           'WHERE group_member.group_id = ' . $group->id . ' ' .
833           'AND NOT EXISTS (SELECT user_id, notice_id ' .
834           'FROM notice_inbox ' .
835           "WHERE user_id = $UT.id " .
836           'AND notice_id = ' . $this->id . ' )';
837         if ($enabled === 'transitional') {
838             $qry .= " AND $UT.inboxed = 1";
839         }
840         $result = $inbox->query($qry);
841     }
842
843     function saveReplies()
844     {
845         // Alternative reply format
846         $tname = false;
847         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
848             $tname = $match[1];
849         }
850         // extract all @messages
851         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
852
853         $names = array();
854
855         if ($cnt || $tname) {
856             // XXX: is there another way to make an array copy?
857             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
858         }
859
860         $sender = Profile::staticGet($this->profile_id);
861
862         $replied = array();
863
864         // store replied only for first @ (what user/notice what the reply directed,
865         // we assume first @ is it)
866
867         for ($i=0; $i<count($names); $i++) {
868             $nickname = $names[$i];
869             $recipient = common_relative_profile($sender, $nickname, $this->created);
870             if (!$recipient) {
871                 continue;
872             }
873             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
874                 $reply_for = $recipient;
875                 $recipient_notice = $reply_for->getCurrentNotice();
876                 if ($recipient_notice) {
877                     $orig = clone($this);
878                     $this->reply_to = $recipient_notice->id;
879                     $this->conversation = $recipient_notice->conversation;
880                     $this->update($orig);
881                 }
882             }
883             // Don't save replies from blocked profile to local user
884             $recipient_user = User::staticGet('id', $recipient->id);
885             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
886                 continue;
887             }
888             $reply = new Reply();
889             $reply->notice_id = $this->id;
890             $reply->profile_id = $recipient->id;
891             $id = $reply->insert();
892             if (!$id) {
893                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
894                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
895                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
896                 return;
897             } else {
898                 $replied[$recipient->id] = 1;
899             }
900         }
901
902         // Hash format replies, too
903         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
904         if ($cnt) {
905             foreach ($match[1] as $tag) {
906                 $tagged = Profile_tag::getTagged($sender->id, $tag);
907                 foreach ($tagged as $t) {
908                     if (!$replied[$t->id]) {
909                         // Don't save replies from blocked profile to local user
910                         $t_user = User::staticGet('id', $t->id);
911                         if ($t_user && $t_user->hasBlocked($sender)) {
912                             continue;
913                         }
914                         $reply = new Reply();
915                         $reply->notice_id = $this->id;
916                         $reply->profile_id = $t->id;
917                         $id = $reply->insert();
918                         if (!$id) {
919                             common_log_db_error($reply, 'INSERT', __FILE__);
920                             return;
921                         } else {
922                             $replied[$recipient->id] = 1;
923                         }
924                     }
925                 }
926             }
927         }
928
929         // If it's not a reply, make it the root of a new conversation
930
931         if (empty($this->conversation)) {
932             $orig = clone($this);
933             $this->conversation = $this->id;
934             $this->update($orig);
935         }
936
937         foreach (array_keys($replied) as $recipient) {
938             $user = User::staticGet('id', $recipient);
939             if ($user) {
940                 mail_notify_attn($user, $this);
941             }
942         }
943     }
944
945     function asAtomEntry($namespace=false, $source=false)
946     {
947         $profile = $this->getProfile();
948
949         $xs = new XMLStringer(true);
950
951         if ($namespace) {
952             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
953                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
954         } else {
955             $attrs = array();
956         }
957
958         $xs->elementStart('entry', $attrs);
959
960         if ($source) {
961             $xs->elementStart('source');
962             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
963             $xs->element('link', array('href' => $profile->profileurl));
964             $user = User::staticGet('id', $profile->id);
965             if (!empty($user)) {
966                 $atom_feed = common_local_url('api',
967                                               array('apiaction' => 'statuses',
968                                                     'method' => 'user_timeline',
969                                                     'argument' => $profile->nickname.'.atom'));
970                 $xs->element('link', array('rel' => 'self',
971                                            'type' => 'application/atom+xml',
972                                            'href' => $profile->profileurl));
973                 $xs->element('link', array('rel' => 'license',
974                                            'href' => common_config('license', 'url')));
975             }
976
977             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
978         }
979
980         $xs->elementStart('author');
981         $xs->element('name', null, $profile->nickname);
982         $xs->element('uri', null, $profile->profileurl);
983         $xs->elementEnd('author');
984
985         if ($source) {
986             $xs->elementEnd('source');
987         }
988
989         $xs->element('title', null, $this->content);
990         $xs->element('summary', null, $this->content);
991
992         $xs->element('link', array('rel' => 'alternate',
993                                    'href' => $this->bestUrl()));
994
995         $xs->element('id', null, $this->uri);
996
997         $xs->element('published', null, common_date_w3dtf($this->created));
998         $xs->element('updated', null, common_date_w3dtf($this->modified));
999
1000         if ($this->reply_to) {
1001             $reply_notice = Notice::staticGet('id', $this->reply_to);
1002             if (!empty($reply_notice)) {
1003                 $xs->element('link', array('rel' => 'related',
1004                                            'href' => $reply_notice->bestUrl()));
1005                 $xs->element('thr:in-reply-to',
1006                              array('ref' => $reply_notice->uri,
1007                                    'href' => $reply_notice->bestUrl()));
1008             }
1009         }
1010
1011         $xs->element('content', array('type' => 'html'), $this->rendered);
1012
1013         $tag = new Notice_tag();
1014         $tag->notice_id = $this->id;
1015         if ($tag->find()) {
1016             while ($tag->fetch()) {
1017                 $xs->element('category', array('term' => $tag->tag));
1018             }
1019         }
1020         $tag->free();
1021
1022         $xs->elementEnd('entry');
1023
1024         return $xs->getString();
1025     }
1026
1027     function bestUrl()
1028     {
1029         if (!empty($this->url)) {
1030             return $this->url;
1031         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1032             return $this->uri;
1033         } else {
1034             return common_local_url('shownotice',
1035                                     array('notice' => $this->id));
1036         }
1037     }
1038
1039     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $since=null, $tag=null)
1040     {
1041         $cache = common_memcache();
1042
1043         if (empty($cache) ||
1044             $since_id != 0 || $before_id != 0 || !is_null($since) ||
1045             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1046             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1047                                                                       $before_id, $since, $tag)));
1048         }
1049
1050         $idkey = common_cache_key($cachekey);
1051
1052         $idstr = $cache->get($idkey);
1053
1054         if (!empty($idstr)) {
1055             // Cache hit! Woohoo!
1056             $window = explode(',', $idstr);
1057             $ids = array_slice($window, $offset, $limit);
1058             return $ids;
1059         }
1060
1061         $laststr = $cache->get($idkey.';last');
1062
1063         if (!empty($laststr)) {
1064             $window = explode(',', $laststr);
1065             $last_id = $window[0];
1066             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1067                                                                           $last_id, 0, null, $tag)));
1068
1069             $new_window = array_merge($new_ids, $window);
1070
1071             $new_windowstr = implode(',', $new_window);
1072
1073             $result = $cache->set($idkey, $new_windowstr);
1074             $result = $cache->set($idkey . ';last', $new_windowstr);
1075
1076             $ids = array_slice($new_window, $offset, $limit);
1077
1078             return $ids;
1079         }
1080
1081         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1082                                                                      0, 0, null, $tag)));
1083
1084         $windowstr = implode(',', $window);
1085
1086         $result = $cache->set($idkey, $windowstr);
1087         $result = $cache->set($idkey . ';last', $windowstr);
1088
1089         $ids = array_slice($window, $offset, $limit);
1090
1091         return $ids;
1092     }
1093 }