]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/classes/Bookmark.php
Bookmarks are almost migrated
[quix0rs-gnu-social.git] / plugins / Bookmark / classes / Bookmark.php
1 <?php
2 /**
3  * Data class to mark notices as bookmarks
4  *
5  * PHP version 5
6  *
7  * @category Data
8  * @package  StatusNet
9  * @author   Evan Prodromou <evan@status.net>
10  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
11  * @link     http://status.net/
12  *
13  * StatusNet - the distributed open-source microblogging tool
14  * Copyright (C) 2009, StatusNet, Inc.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU Affero General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
24  * GNU Affero General Public License for more details.
25  *
26  * You should have received a copy of the GNU Affero General Public License
27  * along with this program. If not, see <http://www.gnu.org/licenses/>.
28  */
29
30 if (!defined('GNUSOCIAL')) { exit(1); }
31
32 /**
33  * For storing the fact that a notice is a bookmark
34  *
35  * @category Bookmark
36  * @package  StatusNet
37  * @author   Evan Prodromou <evan@status.net>
38  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
39  * @link     http://status.net/
40  *
41  * @see      DB_DataObject
42  */
43 class Bookmark extends Managed_DataObject
44 {
45     public $__table = 'bookmark'; // table name
46     public $id;          // char(36) primary_key not_null
47     public $profile_id;  // int(4) not_null
48     public $url;         // varchar(191) not_null   not 255 because utf8mb4 takes more space
49     public $title;       // varchar(191)   not 255 because utf8mb4 takes more space
50     public $uri;         // varchar(191)   not 255 because utf8mb4 takes more space
51     public $description; // text
52     public $created;     // datetime
53
54     public static function schemaDef()
55     {
56         return array(
57             'fields' => array(
58                 'id' => array('type' => 'char',
59                             'length' => 36,
60                             'not null' => true),
61                 'profile_id' => array('type' => 'int', 'not null' => true),
62                 'uri' => array('type' => 'varchar',
63                             'length' => 191,
64                             'not null' => true),
65                 'url' => array('type' => 'varchar',
66                             'length' => 191,
67                             'not null' => true),
68                 'title' => array('type' => 'varchar', 'length' => 191),
69                 'description' => array('type' => 'text'),
70                 'created' => array('type' => 'datetime', 'not null' => true),
71             ),
72             'primary key' => array('uri'),
73             'unique keys' => array(
74                 'bookmark_id_key' => array('id'),
75             ),
76             'foreign keys' => array(
77                 'bookmark_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
78                 'bookmark_uri_fkey' => array('notice', array('uri' => 'uri')),
79             ),
80             'indexes' => array('bookmark_created_idx' => array('created'),
81                             'bookmark_url_idx' => array('url'),
82                             'bookmark_profile_id_idx' => array('profile_id'),
83             ),
84         );
85     }
86
87     /**
88      * Get a bookmark based on a notice
89      *
90      * @param   Notice              $stored Notice activity which represents the Bookmark
91      *
92      * @return  Bookmark            The found bookmark object.
93      * @throws  NoResultException   When you don't find it after all.
94      */
95     static public function fromStored(Notice $stored)
96     {
97         return self::getByPK(array('uri' => $stored->getUri()));
98     }
99
100     public function getStored()
101     {
102         return Notice::getByKeys(array('uri' => $this->getUri()));
103     }
104
105     public function getDescription()
106     {
107         return $this->description;
108     }
109
110     public function getTitle()
111     {
112         return $this->title;
113     }
114
115     public function getUri()
116     {
117         return $this->uri;
118     }
119
120     public function getUrl()
121     {
122         if (empty($this->url)) {
123             throw new InvalidUrlException($this->url);
124         }
125         return $this->url;
126     }
127
128     /**
129      * Get the bookmark that a user made for an URL
130      *
131      * @param Profile $profile Profile to check for
132      * @param string  $url     URL to check for
133      *
134      * @return Bookmark bookmark found or null
135      */
136     static function getByURL(Profile $profile, $url)
137     {
138         $nb = new Bookmark();
139
140         $nb->profile_id = $profile->getID();
141         $nb->url        = $url;
142
143         if (!$nb->find(true)) {
144             throw new NoResultException($nb);
145         }
146
147         return $nb;
148     }
149
150     /**
151      * Store a Bookmark object
152      *
153      * @param Profile $profile     To save the bookmark for
154      * @param string  $title       Title of the bookmark
155      * @param string  $url         URL of the bookmark
156      * @param string  $description Description of the bookmark
157      *
158      * @return Bookmark the Bookmark object
159      */
160     static function saveActivityObject(ActivityObject $actobj, Notice $stored)
161     {
162         $relLinkEls = ActivityUtils::getLinks($actobj->element, 'related');
163
164         if (count($relLinkEls) !== 1) {
165             // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
166             throw new ClientException(sprintf(_m('Expected exactly 1 link rel=related in a Bookmark, got %1$d.'), count($relLinkEls)));
167         }
168
169         $url = $relLinkEls[0]->getAttribute('href');
170
171         if (!strlen($actobj->title)) {
172             throw new ClientException(_m('You must provide a non-empty title.'));
173         }
174         if (!common_valid_http_url($url)) {
175             throw new ClientException(_m('Only web bookmarks can be posted (HTTP or HTTPS).'));
176         }
177
178         try {
179             $object = self::getByURL($stored->getProfile(), $url);
180             throw new ClientException(_m('You have already bookmarked this URL.'));
181         } catch (NoResultException $e) {
182             // Alright, so then we have to create it.
183         }
184
185         $nb = new Bookmark();
186
187         $nb->id          = UUID::gen();
188         $nb->uri         = $stored->getUri();
189         $nb->profile_id  = $stored->getProfile()->getID();
190         $nb->title       = $actobj->title;
191         $nb->url         = $url;
192         $nb->description = $actobj->summary;
193         $nb->created     = $stored->created;
194
195         $result = $nb->insert();
196         if ($result === false) {
197             throw new ServerException('Could not insert Bookmark into database!');
198         }
199
200         return $nb;
201     }
202
203     public function asActivityObject()
204     {
205         $stored = $this->getStored();
206
207         $object = new ActivityObject();
208         $object->id      = $this->getUri();
209         $object->type    = ActivityObject::BOOKMARK;
210         $object->title   = $this->getTitle();
211         $object->summary = $this->getDescription();
212         $object->link    = $stored->getUrl();
213         $object->content = $stored->getRendered();
214
215         // Attributes of the URL
216
217         $attachments = $stored->attachments();
218
219         if (count($attachments) != 1) {
220             // TRANS: Server exception thrown when a bookmark has multiple attachments.
221             throw new ServerException(_m('Bookmark notice with the '.
222                                         'wrong number of attachments.'));
223         }
224
225         $bookmarkedurl = $attachments[0];
226
227         $attrs = array('rel' => 'related',
228                        'href' => $bookmarkedurl->getUrl());
229
230         if (!strlen($bookmarkedurl->title)) {
231             $attrs['title'] = $bookmarkedurl->title;
232         }
233
234         $object->extra[] = array('link', $attrs, null);
235
236         // Attributes of the thumbnail, if any
237
238         try {
239             $thumbnail = $bookmarkedurl->getThumbnail();
240             $tattrs = array('rel' => 'preview',
241                             'href' => $thumbnail->getUrl());
242
243             if (!empty($thumbnail->width)) {
244                 $tattrs['media:width'] = $thumbnail->width;
245             }
246
247             if (!empty($thumbnail->height)) {
248                 $tattrs['media:height'] = $thumbnail->height;
249             }
250
251             $object->extra[] = array('link', $tattrs, null);
252         } catch (UnsupportedMediaException $e) {
253             // No image thumbnail metadata available
254         }
255
256         return $object;
257     }
258
259     /**
260      * Save a new notice bookmark
261      *
262      * @param Profile $profile     To save the bookmark for
263      * @param string  $title       Title of the bookmark
264      * @param string  $url         URL of the bookmark
265      * @param array   $rawtags     array of tags
266      * @param string  $description Description of the bookmark
267      * @param array   $options     Options for the Notice::saveNew()
268      *
269      * @return Notice saved notice
270      */
271     static function addNew(Profile $actor, $title, $url, array $rawtags, $description, array $options=array())
272     {
273         $act        = new Activity();
274         $act->verb  = ActivityVerb::POST;
275         $act->time  = time();
276         $act->actor = $actor->asActivityObject();
277
278         $actobj = new ActivityObject();
279         $actobj->type = ActivityObject::BOOKMARK;
280         $actobj->title = $title;
281         $actobj->summary = $description;
282         $actobj->extra[] = array('link', $attrs, null);
283         $act->objects[] = $actobj;
284
285         $act->enclosures[] = $url;
286
287         $tags    = array();
288         $replies = array();
289
290         // filter "for:nickname" tags
291         foreach ($rawtags as $tag) {
292             if (strtolower(mb_substr($tag, 0, 4)) == 'for:') {
293                 // skip if done by caller
294                 if (!array_key_exists('replies', $options)) {
295                     $nickname = mb_substr($tag, 4);
296                     $other    = common_relative_profile($actor, $nickname);
297                     if (!empty($other)) {
298                         $replies[] = $other->getUri();
299                     }
300                 }
301             } else {
302                 $tags[] = common_canonical_tag($tag);
303             }
304         }
305
306         $hashtags = array();
307         $taglinks = array();
308
309         foreach ($tags as $tag) {
310             $hashtags[] = '#'.$tag;
311             $attrs      = array('href' => Notice_tag::url($tag),
312                                 'rel'  => $tag,
313                                 'class' => 'tag');
314             $taglinks[] = XMLStringer::estring('a', $attrs, $tag);
315         }
316
317         // Use user's preferences for short URLs, if possible
318         // FIXME: Should be possible to with the Profile object...
319         try {
320             $user = $actor->getUser();
321             $shortUrl = File_redirection::makeShort($url, empty($user) ? null : $user);
322         } catch (Exception $e) {
323             // Don't let this stop us.
324             $shortUrl = $url;
325         }
326
327         // TRANS: Rendered bookmark content.
328         // TRANS: %1$s is a URL, %2$s the bookmark title, %3$s is the bookmark description,
329         // TRANS: %4$s is space separated list of hash tags.
330         $actobj->content = sprintf(_m('<span class="xfolkentry">'.
331                                       '<a class="taggedlink" href="%1$s">%2$s</a> '.
332                                       '<span class="description">%3$s</span> '.
333                                       '<span class="meta">%4$s</span>'.
334                                       '</span>'),
335                                     htmlspecialchars($url),
336                                     htmlspecialchars($title),
337                                     htmlspecialchars($description),
338                                     implode(' ', $taglinks));
339
340         foreach ($tags as $term) {
341             $catEl = new AtomCategory();
342             $catEl->term = $term;
343             $activity->categories[] = $catEl;
344         }
345
346         $options = array_merge(array('urls' => array($url),
347                                      'rendered' => $rendered,
348                                      'tags' => $tags,
349                                      'replies' => $replies,
350                                      'object_type' => ActivityObject::BOOKMARK),
351                                $options);
352
353         return Notice::saveActivity($act, $actor, $options);
354     }
355 }