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