]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
update location while saving new profile
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
56     public $__table = 'notice';                          // table name
57     public $id;                              // int(4)  primary_key not_null
58     public $profile_id;                      // int(4)   not_null
59     public $uri;                             // varchar(255)  unique_key
60     public $content;                         // text()
61     public $rendered;                        // text()
62     public $url;                             // varchar(255)
63     public $created;                         // datetime()   not_null
64     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // tinyint(1)
67     public $source;                          // varchar(32)
68     public $conversation;                    // int(4)
69     public $lat;                             // decimal(10,7)
70     public $lon;                             // decimal(10,7)
71     public $location_id;                     // int(4)
72     public $location_ns;                     // int(4)
73
74     /* Static get */
75     function staticGet($k,$v=NULL) {
76         return Memcached_DataObject::staticGet('Notice',$k,$v);
77     }
78
79     /* the code above is auto generated do not remove the tag below */
80     ###END_AUTOCODE
81
82     /* Notice types */
83     const LOCAL_PUBLIC    =  1;
84     const REMOTE_OMB      =  0;
85     const LOCAL_NONPUBLIC = -1;
86     const GATEWAY         = -2;
87
88     function getProfile()
89     {
90         return Profile::staticGet('id', $this->profile_id);
91     }
92
93     function delete()
94     {
95         $this->blowCaches(true);
96         $this->blowFavesCache(true);
97         $this->blowSubsCache(true);
98
99         // For auditing purposes, save a record that the notice
100         // was deleted.
101
102         $deleted = new Deleted_notice();
103
104         $deleted->id         = $this->id;
105         $deleted->profile_id = $this->profile_id;
106         $deleted->uri        = $this->uri;
107         $deleted->created    = $this->created;
108         $deleted->deleted    = common_sql_now();
109
110         $this->query('BEGIN');
111
112         $deleted->insert();
113
114         //Null any notices that are replies to this notice
115         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
116         $related = array('Reply',
117                          'Fave',
118                          'Notice_tag',
119                          'Group_inbox',
120                          'Queue_item',
121                          'Notice_inbox');
122
123         foreach ($related as $cls) {
124             $inst = new $cls();
125             $inst->notice_id = $this->id;
126             $inst->delete();
127         }
128         $result = parent::delete();
129         $this->query('COMMIT');
130     }
131
132     function saveTags()
133     {
134         /* extract all #hastags */
135         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
136         if (!$count) {
137             return true;
138         }
139
140         //turn each into their canonical tag
141         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
142         $hashtags = array();
143         for($i=0; $i<count($match[1]); $i++) {
144             $hashtags[] = common_canonical_tag($match[1][$i]);
145         }
146
147         /* Add them to the database */
148         foreach(array_unique($hashtags) as $hashtag) {
149             /* elide characters we don't want in the tag */
150             $this->saveTag($hashtag);
151         }
152         return true;
153     }
154
155     function saveTag($hashtag)
156     {
157         $tag = new Notice_tag();
158         $tag->notice_id = $this->id;
159         $tag->tag = $hashtag;
160         $tag->created = $this->created;
161         $id = $tag->insert();
162
163         if (!$id) {
164             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
165                                               $last_error->message));
166             return;
167         }
168     }
169
170     static function saveNew($profile_id, $content, $source=null,
171                             $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null,
172                             $lat=null, $lon=null, $location_id=null, $location_ns=null) {
173
174         $profile = Profile::staticGet($profile_id);
175
176         $final = common_shorten_links($content);
177
178         if (Notice::contentTooLong($final)) {
179             throw new ClientException(_('Problem saving notice. Too long.'));
180         }
181
182         if (!$profile) {
183             throw new ClientException(_('Problem saving notice. Unknown user.'));
184         }
185
186         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
187             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
188             throw new ClientException(_('Too many notices too fast; take a breather '.
189                                         'and post again in a few minutes.'));
190         }
191
192         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
193             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
194             throw new ClientException(_('Too many duplicate messages too quickly;'.
195                                         ' take a breather and post again in a few minutes.'));
196         }
197
198         $banned = common_config('profile', 'banned');
199
200         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
201             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
202             throw new ClientException(_('You are banned from posting notices on this site.'));
203         }
204
205         $notice = new Notice();
206         $notice->profile_id = $profile_id;
207
208         $blacklist = common_config('public', 'blacklist');
209         $autosource = common_config('public', 'autosource');
210
211         # Blacklisted are non-false, but not 1, either
212
213         if (($blacklist && in_array($profile_id, $blacklist)) ||
214             ($source && $autosource && in_array($source, $autosource))) {
215             $notice->is_local = Notice::LOCAL_NONPUBLIC;
216         } else {
217             $notice->is_local = $is_local;
218         }
219
220         if (!empty($created)) {
221             $notice->created = $created;
222         } else {
223             $notice->created = common_sql_now();
224         }
225
226         $notice->content = $final;
227         $notice->rendered = common_render_content($final, $notice);
228         $notice->source = $source;
229         $notice->uri = $uri;
230
231         $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
232
233         if (!empty($notice->reply_to)) {
234             $reply = Notice::staticGet('id', $notice->reply_to);
235             $notice->conversation = $reply->conversation;
236         }
237
238         if (!empty($lat) && !empty($lon)) {
239             $notice->lat = $lat;
240             $notice->lon = $lon;
241             $notice->location_id = $location_id;
242             $notice->location_ns = $location_ns;
243         } else if (!empty($location_ns) && !empty($location_id)) {
244             $location = Location::fromId($location_id, $location_ns);
245             if (!empty($location)) {
246                 $notice->lat = $location->lat;
247                 $notice->lon = $location->lon;
248                 $notice->location_id = $location_id;
249                 $notice->location_ns = $location_ns;
250             }
251         } else {
252             $notice->lat         = $profile->lat;
253             $notice->lon         = $profile->lon;
254             $notice->location_id = $profile->location_id;
255             $notice->location_ns = $profile->location_ns;
256         }
257
258         if (Event::handle('StartNoticeSave', array(&$notice))) {
259
260             // XXX: some of these functions write to the DB
261
262             $notice->query('BEGIN');
263
264             $id = $notice->insert();
265
266             if (!$id) {
267                 common_log_db_error($notice, 'INSERT', __FILE__);
268                 throw new ServerException(_('Problem saving notice.'));
269             }
270
271             // Update ID-dependent columns: URI, conversation
272
273             $orig = clone($notice);
274
275             $changed = false;
276
277             if (empty($uri)) {
278                 $notice->uri = common_notice_uri($notice);
279                 $changed = true;
280             }
281
282             // If it's not part of a conversation, it's
283             // the beginning of a new conversation.
284
285             if (empty($notice->conversation)) {
286                 $notice->conversation = $notice->id;
287                 $changed = true;
288             }
289
290             if ($changed) {
291                 if (!$notice->update($orig)) {
292                     common_log_db_error($notice, 'UPDATE', __FILE__);
293                     throw new ServerException(_('Problem saving notice.'));
294                 }
295             }
296
297             // XXX: do we need to change this for remote users?
298
299             $notice->saveReplies();
300             $notice->saveTags();
301
302             $notice->addToInboxes();
303
304             $notice->saveUrls();
305
306             $notice->query('COMMIT');
307
308             Event::handle('EndNoticeSave', array($notice));
309         }
310
311         # Clear the cache for subscribed users, so they'll update at next request
312         # XXX: someone clever could prepend instead of clearing the cache
313
314         $notice->blowCaches();
315
316         return $notice;
317     }
318
319     /** save all urls in the notice to the db
320      *
321      * follow redirects and save all available file information
322      * (mimetype, date, size, oembed, etc.)
323      *
324      * @return void
325      */
326     function saveUrls() {
327         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
328     }
329
330     function saveUrl($data) {
331         list($url, $notice_id) = $data;
332         File::processNew($url, $notice_id);
333     }
334
335     static function checkDupes($profile_id, $content) {
336         $profile = Profile::staticGet($profile_id);
337         if (!$profile) {
338             return false;
339         }
340         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
341         if ($notice) {
342             $last = 0;
343             while ($notice->fetch()) {
344                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
345                     return true;
346                 } else if ($notice->content == $content) {
347                     return false;
348                 }
349             }
350         }
351         # If we get here, oldest item in cache window is not
352         # old enough for dupe limit; do direct check against DB
353         $notice = new Notice();
354         $notice->profile_id = $profile_id;
355         $notice->content = $content;
356         if (common_config('db','type') == 'pgsql')
357           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
358         else
359           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
360
361         $cnt = $notice->count();
362         return ($cnt == 0);
363     }
364
365     static function checkEditThrottle($profile_id) {
366         $profile = Profile::staticGet($profile_id);
367         if (!$profile) {
368             return false;
369         }
370         # Get the Nth notice
371         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
372         if ($notice && $notice->fetch()) {
373             # If the Nth notice was posted less than timespan seconds ago
374             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
375                 # Then we throttle
376                 return false;
377             }
378         }
379         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
380         return true;
381     }
382
383     function getUploadedAttachment() {
384         $post = clone $this;
385         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
386         $post->query($query);
387         $post->fetch();
388         if (empty($post->up) || empty($post->i)) {
389             $ret = false;
390         } else {
391             $ret = array($post->up, $post->i);
392         }
393         $post->free();
394         return $ret;
395     }
396
397     function hasAttachments() {
398         $post = clone $this;
399         $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);
400         $post->query($query);
401         $post->fetch();
402         $n_attachments = intval($post->n_attachments);
403         $post->free();
404         return $n_attachments;
405     }
406
407     function attachments() {
408         // XXX: cache this
409         $att = array();
410         $f2p = new File_to_post;
411         $f2p->post_id = $this->id;
412         if ($f2p->find()) {
413             while ($f2p->fetch()) {
414                 $f = File::staticGet($f2p->file_id);
415                 $att[] = clone($f);
416             }
417         }
418         return $att;
419     }
420
421     function blowCaches($blowLast=false)
422     {
423         $this->blowSubsCache($blowLast);
424         $this->blowNoticeCache($blowLast);
425         $this->blowRepliesCache($blowLast);
426         $this->blowPublicCache($blowLast);
427         $this->blowTagCache($blowLast);
428         $this->blowGroupCache($blowLast);
429         $this->blowConversationCache($blowLast);
430         $profile = Profile::staticGet($this->profile_id);
431         $profile->blowNoticeCount();
432     }
433
434     function blowConversationCache($blowLast=false)
435     {
436         $cache = common_memcache();
437         if ($cache) {
438             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
439             $cache->delete($ck);
440             if ($blowLast) {
441                 $cache->delete($ck.';last');
442             }
443         }
444     }
445
446     function blowGroupCache($blowLast=false)
447     {
448         $cache = common_memcache();
449         if ($cache) {
450             $group_inbox = new Group_inbox();
451             $group_inbox->notice_id = $this->id;
452             if ($group_inbox->find()) {
453                 while ($group_inbox->fetch()) {
454                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
455                     if ($blowLast) {
456                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
457                     }
458                     $member = new Group_member();
459                     $member->group_id = $group_inbox->group_id;
460                     if ($member->find()) {
461                         while ($member->fetch()) {
462                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
463                             if ($blowLast) {
464                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
465                             }
466                         }
467                     }
468                 }
469             }
470             $group_inbox->free();
471             unset($group_inbox);
472         }
473     }
474
475     function blowTagCache($blowLast=false)
476     {
477         $cache = common_memcache();
478         if ($cache) {
479             $tag = new Notice_tag();
480             $tag->notice_id = $this->id;
481             if ($tag->find()) {
482                 while ($tag->fetch()) {
483                     $tag->blowCache($blowLast);
484                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
485
486                     $cache->delete($ck);
487                     if ($blowLast) {
488                         $cache->delete($ck . ';last');
489                     }
490                 }
491             }
492             $tag->free();
493             unset($tag);
494         }
495     }
496
497     function blowSubsCache($blowLast=false)
498     {
499         $cache = common_memcache();
500         if ($cache) {
501             $user = new User();
502
503             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
504             $user->query('SELECT id ' .
505
506                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
507                          'WHERE subscription.subscribed = ' . $this->profile_id);
508
509             while ($user->fetch()) {
510                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
511                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
512                 if ($blowLast) {
513                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
514                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
515                 }
516             }
517             $user->free();
518             unset($user);
519         }
520     }
521
522     function blowNoticeCache($blowLast=false)
523     {
524         if ($this->is_local) {
525             $cache = common_memcache();
526             if (!empty($cache)) {
527                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
528                 if ($blowLast) {
529                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
530                 }
531             }
532         }
533     }
534
535     function blowRepliesCache($blowLast=false)
536     {
537         $cache = common_memcache();
538         if ($cache) {
539             $reply = new Reply();
540             $reply->notice_id = $this->id;
541             if ($reply->find()) {
542                 while ($reply->fetch()) {
543                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
544                     if ($blowLast) {
545                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
546                     }
547                 }
548             }
549             $reply->free();
550             unset($reply);
551         }
552     }
553
554     function blowPublicCache($blowLast=false)
555     {
556         if ($this->is_local == Notice::LOCAL_PUBLIC) {
557             $cache = common_memcache();
558             if ($cache) {
559                 $cache->delete(common_cache_key('public'));
560                 if ($blowLast) {
561                     $cache->delete(common_cache_key('public').';last');
562                 }
563             }
564         }
565     }
566
567     function blowFavesCache($blowLast=false)
568     {
569         $cache = common_memcache();
570         if ($cache) {
571             $fave = new Fave();
572             $fave->notice_id = $this->id;
573             if ($fave->find()) {
574                 while ($fave->fetch()) {
575                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
576                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
577                     if ($blowLast) {
578                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
579                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
580                     }
581                 }
582             }
583             $fave->free();
584             unset($fave);
585         }
586     }
587
588     # XXX: too many args; we need to move to named params or even a separate
589     # class for notice streams
590
591     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
592
593         if (common_config('memcached', 'enabled')) {
594
595             # Skip the cache if this is a since, since_id or max_id qry
596             if ($since_id > 0 || $max_id > 0 || $since) {
597                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
598             } else {
599                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
600             }
601         }
602
603         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
604     }
605
606     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
607
608         $needAnd = false;
609         $needWhere = true;
610
611         if (preg_match('/\bWHERE\b/i', $qry)) {
612             $needWhere = false;
613             $needAnd = true;
614         }
615
616         if ($since_id > 0) {
617
618             if ($needWhere) {
619                 $qry .= ' WHERE ';
620                 $needWhere = false;
621             } else {
622                 $qry .= ' AND ';
623             }
624
625             $qry .= ' notice.id > ' . $since_id;
626         }
627
628         if ($max_id > 0) {
629
630             if ($needWhere) {
631                 $qry .= ' WHERE ';
632                 $needWhere = false;
633             } else {
634                 $qry .= ' AND ';
635             }
636
637             $qry .= ' notice.id <= ' . $max_id;
638         }
639
640         if ($since) {
641
642             if ($needWhere) {
643                 $qry .= ' WHERE ';
644                 $needWhere = false;
645             } else {
646                 $qry .= ' AND ';
647             }
648
649             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
650         }
651
652         # Allow ORDER override
653
654         if ($order) {
655             $qry .= $order;
656         } else {
657             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
658         }
659
660         if (common_config('db','type') == 'pgsql') {
661             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
662         } else {
663             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
664         }
665
666         $notice = new Notice();
667
668         $notice->query($qry);
669
670         return $notice;
671     }
672
673     # XXX: this is pretty long and should probably be broken up into
674     # some helper functions
675
676     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
677
678         # If outside our cache window, just go to the DB
679
680         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
681             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
682         }
683
684         # Get the cache; if we can't, just go to the DB
685
686         $cache = common_memcache();
687
688         if (!$cache) {
689             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
690         }
691
692         # Get the notices out of the cache
693
694         $notices = $cache->get(common_cache_key($cachekey));
695
696         # On a cache hit, return a DB-object-like wrapper
697
698         if ($notices !== false) {
699             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
700             return $wrapper;
701         }
702
703         # If the cache was invalidated because of new data being
704         # added, we can try and just get the new stuff. We keep an additional
705         # copy of the data at the key + ';last'
706
707         # No cache hit. Try to get the *last* cached version
708
709         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
710
711         if ($last_notices) {
712
713             # Reverse-chron order, so last ID is last.
714
715             $last_id = $last_notices[0]->id;
716
717             # XXX: this assumes monotonically increasing IDs; a fair
718             # bet with our DB.
719
720             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
721                                                   $last_id, null, $order, null);
722
723             if ($new_notice) {
724                 $new_notices = array();
725                 while ($new_notice->fetch()) {
726                     $new_notices[] = clone($new_notice);
727                 }
728                 $new_notice->free();
729                 $notices = array_slice(array_merge($new_notices, $last_notices),
730                                        0, NOTICE_CACHE_WINDOW);
731
732                 # Store the array in the cache for next time
733
734                 $result = $cache->set(common_cache_key($cachekey), $notices);
735                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
736
737                 # return a wrapper of the array for use now
738
739                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
740             }
741         }
742
743         # Otherwise, get the full cache window out of the DB
744
745         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
746
747         # If there are no hits, just return the value
748
749         if (!$notice) {
750             return $notice;
751         }
752
753         # Pack results into an array
754
755         $notices = array();
756
757         while ($notice->fetch()) {
758             $notices[] = clone($notice);
759         }
760
761         $notice->free();
762
763         # Store the array in the cache for next time
764
765         $result = $cache->set(common_cache_key($cachekey), $notices);
766         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
767
768         # return a wrapper of the array for use now
769
770         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
771
772         return $wrapper;
773     }
774
775     function getStreamByIds($ids)
776     {
777         $cache = common_memcache();
778
779         if (!empty($cache)) {
780             $notices = array();
781             foreach ($ids as $id) {
782                 $n = Notice::staticGet('id', $id);
783                 if (!empty($n)) {
784                     $notices[] = $n;
785                 }
786             }
787             return new ArrayWrapper($notices);
788         } else {
789             $notice = new Notice();
790             if (empty($ids)) {
791                 //if no IDs requested, just return the notice object
792                 return $notice;
793             }
794             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
795             $notice->orderBy('id DESC');
796
797             $notice->find();
798             return $notice;
799         }
800     }
801
802     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
803     {
804         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
805                               array(),
806                               'public',
807                               $offset, $limit, $since_id, $max_id, $since);
808
809         return Notice::getStreamByIds($ids);
810     }
811
812     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
813     {
814         $notice = new Notice();
815
816         $notice->selectAdd(); // clears it
817         $notice->selectAdd('id');
818
819         $notice->orderBy('id DESC');
820
821         if (!is_null($offset)) {
822             $notice->limit($offset, $limit);
823         }
824
825         if (common_config('public', 'localonly')) {
826             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
827         } else {
828             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
829             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
830             $notice->whereAdd('is_local !='. Notice::GATEWAY);
831         }
832
833         if ($since_id != 0) {
834             $notice->whereAdd('id > ' . $since_id);
835         }
836
837         if ($max_id != 0) {
838             $notice->whereAdd('id <= ' . $max_id);
839         }
840
841         if (!is_null($since)) {
842             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
843         }
844
845         $ids = array();
846
847         if ($notice->find()) {
848             while ($notice->fetch()) {
849                 $ids[] = $notice->id;
850             }
851         }
852
853         $notice->free();
854         $notice = NULL;
855
856         return $ids;
857     }
858
859     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
860     {
861         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
862                               array($id),
863                               'notice:conversation_ids:'.$id,
864                               $offset, $limit, $since_id, $max_id, $since);
865
866         return Notice::getStreamByIds($ids);
867     }
868
869     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
870     {
871         $notice = new Notice();
872
873         $notice->selectAdd(); // clears it
874         $notice->selectAdd('id');
875
876         $notice->conversation = $id;
877
878         $notice->orderBy('id DESC');
879
880         if (!is_null($offset)) {
881             $notice->limit($offset, $limit);
882         }
883
884         if ($since_id != 0) {
885             $notice->whereAdd('id > ' . $since_id);
886         }
887
888         if ($max_id != 0) {
889             $notice->whereAdd('id <= ' . $max_id);
890         }
891
892         if (!is_null($since)) {
893             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
894         }
895
896         $ids = array();
897
898         if ($notice->find()) {
899             while ($notice->fetch()) {
900                 $ids[] = $notice->id;
901             }
902         }
903
904         $notice->free();
905         $notice = NULL;
906
907         return $ids;
908     }
909
910     function addToInboxes()
911     {
912         // XXX: loads constants
913
914         $inbox = new Notice_inbox();
915
916         $users = $this->getSubscribedUsers();
917
918         // FIXME: kind of ignoring 'transitional'...
919         // we'll probably stop supporting inboxless mode
920         // in 0.9.x
921
922         $ni = array();
923
924         foreach ($users as $id) {
925             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
926         }
927
928         $groups = $this->saveGroups();
929
930         foreach ($groups as $group) {
931             $users = $group->getUserMembers();
932             foreach ($users as $id) {
933                 if (!array_key_exists($id, $ni)) {
934                     $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
935                 }
936             }
937         }
938
939         $cnt = 0;
940
941         $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
942         $qry = $qryhdr;
943
944         foreach ($ni as $id => $source) {
945             if ($cnt > 0) {
946                 $qry .= ', ';
947             }
948             $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
949             $cnt++;
950             if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
951                 // FIXME: Causes lag in replicated servers
952                 // Notice_inbox::gc($id);
953             }
954             if ($cnt >= MAX_BOXCARS) {
955                 $inbox = new Notice_inbox();
956                 $inbox->query($qry);
957                 $qry = $qryhdr;
958                 $cnt = 0;
959             }
960         }
961
962         if ($cnt > 0) {
963             $inbox = new Notice_inbox();
964             $inbox->query($qry);
965         }
966
967         return;
968     }
969
970     function getSubscribedUsers()
971     {
972         $user = new User();
973
974         if(common_config('db','quote_identifiers'))
975           $user_table = '"user"';
976         else $user_table = 'user';
977
978         $qry =
979           'SELECT id ' .
980           'FROM '. $user_table .' JOIN subscription '.
981           'ON '. $user_table .'.id = subscription.subscriber ' .
982           'WHERE subscription.subscribed = %d ';
983
984         $user->query(sprintf($qry, $this->profile_id));
985
986         $ids = array();
987
988         while ($user->fetch()) {
989             $ids[] = $user->id;
990         }
991
992         $user->free();
993
994         return $ids;
995     }
996
997     function saveGroups()
998     {
999         $groups = array();
1000
1001         /* extract all !group */
1002         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
1003                                 strtolower($this->content),
1004                                 $match);
1005         if (!$count) {
1006             return $groups;
1007         }
1008
1009         $profile = $this->getProfile();
1010
1011         /* Add them to the database */
1012
1013         foreach (array_unique($match[1]) as $nickname) {
1014             /* XXX: remote groups. */
1015             $group = User_group::getForNickname($nickname);
1016
1017             if (empty($group)) {
1018                 continue;
1019             }
1020
1021             // we automatically add a tag for every group name, too
1022
1023             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1024                                              'notice_id' => $this->id));
1025
1026             if (is_null($tag)) {
1027                 $this->saveTag($nickname);
1028             }
1029
1030             if ($profile->isMember($group)) {
1031
1032                 $result = $this->addToGroupInbox($group);
1033
1034                 if (!$result) {
1035                     common_log_db_error($gi, 'INSERT', __FILE__);
1036                 }
1037
1038                 $groups[] = clone($group);
1039             }
1040         }
1041
1042         return $groups;
1043     }
1044
1045     function addToGroupInbox($group)
1046     {
1047         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1048                                          'notice_id' => $this->id));
1049
1050         if (empty($gi)) {
1051
1052             $gi = new Group_inbox();
1053
1054             $gi->group_id  = $group->id;
1055             $gi->notice_id = $this->id;
1056             $gi->created   = $this->created;
1057
1058             return $gi->insert();
1059         }
1060
1061         return true;
1062     }
1063
1064     function saveReplies()
1065     {
1066         // Alternative reply format
1067         $tname = false;
1068         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1069             $tname = $match[1];
1070         }
1071         // extract all @messages
1072         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1073
1074         $names = array();
1075
1076         if ($cnt || $tname) {
1077             // XXX: is there another way to make an array copy?
1078             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1079         }
1080
1081         $sender = Profile::staticGet($this->profile_id);
1082
1083         $replied = array();
1084
1085         // store replied only for first @ (what user/notice what the reply directed,
1086         // we assume first @ is it)
1087
1088         for ($i=0; $i<count($names); $i++) {
1089             $nickname = $names[$i];
1090             $recipient = common_relative_profile($sender, $nickname, $this->created);
1091             if (!$recipient) {
1092                 continue;
1093             }
1094             // Don't save replies from blocked profile to local user
1095             $recipient_user = User::staticGet('id', $recipient->id);
1096             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1097                 continue;
1098             }
1099             $reply = new Reply();
1100             $reply->notice_id = $this->id;
1101             $reply->profile_id = $recipient->id;
1102             $id = $reply->insert();
1103             if (!$id) {
1104                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1105                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1106                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1107                 return;
1108             } else {
1109                 $replied[$recipient->id] = 1;
1110             }
1111         }
1112
1113         // Hash format replies, too
1114         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1115         if ($cnt) {
1116             foreach ($match[1] as $tag) {
1117                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1118                 foreach ($tagged as $t) {
1119                     if (!$replied[$t->id]) {
1120                         // Don't save replies from blocked profile to local user
1121                         $t_user = User::staticGet('id', $t->id);
1122                         if ($t_user && $t_user->hasBlocked($sender)) {
1123                             continue;
1124                         }
1125                         $reply = new Reply();
1126                         $reply->notice_id = $this->id;
1127                         $reply->profile_id = $t->id;
1128                         $id = $reply->insert();
1129                         if (!$id) {
1130                             common_log_db_error($reply, 'INSERT', __FILE__);
1131                             return;
1132                         } else {
1133                             $replied[$recipient->id] = 1;
1134                         }
1135                     }
1136                 }
1137             }
1138         }
1139
1140         foreach (array_keys($replied) as $recipient) {
1141             $user = User::staticGet('id', $recipient);
1142             if ($user) {
1143                 mail_notify_attn($user, $this);
1144             }
1145         }
1146     }
1147
1148     function asAtomEntry($namespace=false, $source=false)
1149     {
1150         $profile = $this->getProfile();
1151
1152         $xs = new XMLStringer(true);
1153
1154         if ($namespace) {
1155             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1156                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1157         } else {
1158             $attrs = array();
1159         }
1160
1161         $xs->elementStart('entry', $attrs);
1162
1163         if ($source) {
1164             $xs->elementStart('source');
1165             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1166             $xs->element('link', array('href' => $profile->profileurl));
1167             $user = User::staticGet('id', $profile->id);
1168             if (!empty($user)) {
1169                 $atom_feed = common_local_url('api',
1170                                               array('apiaction' => 'statuses',
1171                                                     'method' => 'user_timeline',
1172                                                     'argument' => $profile->nickname.'.atom'));
1173                 $xs->element('link', array('rel' => 'self',
1174                                            'type' => 'application/atom+xml',
1175                                            'href' => $profile->profileurl));
1176                 $xs->element('link', array('rel' => 'license',
1177                                            'href' => common_config('license', 'url')));
1178             }
1179
1180             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1181         }
1182
1183         $xs->elementStart('author');
1184         $xs->element('name', null, $profile->nickname);
1185         $xs->element('uri', null, $profile->profileurl);
1186         $xs->elementEnd('author');
1187
1188         if ($source) {
1189             $xs->elementEnd('source');
1190         }
1191
1192         $xs->element('title', null, $this->content);
1193         $xs->element('summary', null, $this->content);
1194
1195         $xs->element('link', array('rel' => 'alternate',
1196                                    'href' => $this->bestUrl()));
1197
1198         $xs->element('id', null, $this->uri);
1199
1200         $xs->element('published', null, common_date_w3dtf($this->created));
1201         $xs->element('updated', null, common_date_w3dtf($this->modified));
1202
1203         if ($this->reply_to) {
1204             $reply_notice = Notice::staticGet('id', $this->reply_to);
1205             if (!empty($reply_notice)) {
1206                 $xs->element('link', array('rel' => 'related',
1207                                            'href' => $reply_notice->bestUrl()));
1208                 $xs->element('thr:in-reply-to',
1209                              array('ref' => $reply_notice->uri,
1210                                    'href' => $reply_notice->bestUrl()));
1211             }
1212         }
1213
1214         $xs->element('content', array('type' => 'html'), $this->rendered);
1215
1216         $tag = new Notice_tag();
1217         $tag->notice_id = $this->id;
1218         if ($tag->find()) {
1219             while ($tag->fetch()) {
1220                 $xs->element('category', array('term' => $tag->tag));
1221             }
1222         }
1223         $tag->free();
1224
1225         # Enclosures
1226         $attachments = $this->attachments();
1227         if($attachments){
1228             foreach($attachments as $attachment){
1229                 $enclosure=$attachment->getEnclosure();
1230                 if ($enclosure) {
1231                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1232                     if($enclosure->title){
1233                         $attributes['title']=$enclosure->title;
1234                     }
1235                     $xs->element('link', $attributes, null);
1236                 }
1237             }
1238         }
1239
1240         $xs->elementEnd('entry');
1241
1242         return $xs->getString();
1243     }
1244
1245     function bestUrl()
1246     {
1247         if (!empty($this->url)) {
1248             return $this->url;
1249         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1250             return $this->uri;
1251         } else {
1252             return common_local_url('shownotice',
1253                                     array('notice' => $this->id));
1254         }
1255     }
1256
1257     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1258     {
1259         $cache = common_memcache();
1260
1261         if (empty($cache) ||
1262             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1263             is_null($limit) ||
1264             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1265             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1266                                                                       $max_id, $since)));
1267         }
1268
1269         $idkey = common_cache_key($cachekey);
1270
1271         $idstr = $cache->get($idkey);
1272
1273         if (!empty($idstr)) {
1274             // Cache hit! Woohoo!
1275             $window = explode(',', $idstr);
1276             $ids = array_slice($window, $offset, $limit);
1277             return $ids;
1278         }
1279
1280         $laststr = $cache->get($idkey.';last');
1281
1282         if (!empty($laststr)) {
1283             $window = explode(',', $laststr);
1284             $last_id = $window[0];
1285             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1286                                                                           $last_id, 0, null)));
1287
1288             $new_window = array_merge($new_ids, $window);
1289
1290             $new_windowstr = implode(',', $new_window);
1291
1292             $result = $cache->set($idkey, $new_windowstr);
1293             $result = $cache->set($idkey . ';last', $new_windowstr);
1294
1295             $ids = array_slice($new_window, $offset, $limit);
1296
1297             return $ids;
1298         }
1299
1300         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1301                                                                      0, 0, null)));
1302
1303         $windowstr = implode(',', $window);
1304
1305         $result = $cache->set($idkey, $windowstr);
1306         $result = $cache->set($idkey . ';last', $windowstr);
1307
1308         $ids = array_slice($window, $offset, $limit);
1309
1310         return $ids;
1311     }
1312
1313     /**
1314      * Determine which notice, if any, a new notice is in reply to.
1315      *
1316      * For conversation tracking, we try to see where this notice fits
1317      * in the tree. Rough algorithm is:
1318      *
1319      * if (reply_to is set and valid) {
1320      *     return reply_to;
1321      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1322      *     return ID of last notice by initial @name in content;
1323      * }
1324      *
1325      * Note that all @nickname instances will still be used to save "reply" records,
1326      * so the notice shows up in the mentioned users' "replies" tab.
1327      *
1328      * @param integer $reply_to   ID passed in by Web or API
1329      * @param integer $profile_id ID of author
1330      * @param string  $source     Source tag, like 'web' or 'gwibber'
1331      * @param string  $content    Final notice content
1332      *
1333      * @return integer ID of replied-to notice, or null for not a reply.
1334      */
1335
1336     static function getReplyTo($reply_to, $profile_id, $source, $content)
1337     {
1338         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1339
1340         // If $reply_to is specified, we check that it exists, and then
1341         // return it if it does
1342
1343         if (!empty($reply_to)) {
1344             $reply_notice = Notice::staticGet('id', $reply_to);
1345             if (!empty($reply_notice)) {
1346                 return $reply_to;
1347             }
1348         }
1349
1350         // If it's not a "low bandwidth" source (one where you can't set
1351         // a reply_to argument), we return. This is mostly web and API
1352         // clients.
1353
1354         if (!in_array($source, $lb)) {
1355             return null;
1356         }
1357
1358         // Is there an initial @ or T?
1359
1360         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1361             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1362             $nickname = common_canonical_nickname($match[1]);
1363         } else {
1364             return null;
1365         }
1366
1367         // Figure out who that is.
1368
1369         $sender = Profile::staticGet('id', $profile_id);
1370         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1371
1372         if (empty($recipient)) {
1373             return null;
1374         }
1375
1376         // Get their last notice
1377
1378         $last = $recipient->getCurrentNotice();
1379
1380         if (!empty($last)) {
1381             return $last->id;
1382         }
1383     }
1384
1385     static function maxContent()
1386     {
1387         $contentlimit = common_config('notice', 'contentlimit');
1388         // null => use global limit (distinct from 0!)
1389         if (is_null($contentlimit)) {
1390             $contentlimit = common_config('site', 'textlimit');
1391         }
1392         return $contentlimit;
1393     }
1394
1395     static function contentTooLong($content)
1396     {
1397         $contentlimit = self::maxContent();
1398         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1399     }
1400 }