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