]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Merge pull request #9933 from annando/avoid-foreign-key
[friendica.git] / src / Object / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Object;
23
24 use Friendica\Content\ContactSelector;
25 use Friendica\Content\Feature;
26 use Friendica\Core\Addon;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post as PostModel;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44
45 /**
46  * An item
47  */
48 class Post
49 {
50         private $data = [];
51         private $template = null;
52         private $available_templates = [
53                 'wall' => 'wall_thread.tpl',
54                 'wall2wall' => 'wallwall_thread.tpl'
55         ];
56         private $comment_box_template = 'comment_item.tpl';
57         private $toplevel = false;
58         private $writable = false;
59         /**
60          * @var Post[]
61          */
62         private $children = [];
63         private $parent = null;
64
65         /**
66          * @var Thread
67          */
68         private $thread = null;
69         private $redirect_url = null;
70         private $owner_url = '';
71         private $owner_photo = '';
72         private $owner_name = '';
73         private $wall_to_wall = false;
74         private $threaded = false;
75         private $visiting = false;
76
77         /**
78          * Constructor
79          *
80          * @param array $data data array
81          * @throws \Exception
82          */
83         public function __construct(array $data)
84         {
85                 $this->data = $data;
86                 $this->setTemplate('wall');
87                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
88
89                 if (!empty(Session::getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
90                         $this->visiting = true;
91                 }
92
93                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
94                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
95                         'network' => $this->getDataValue('author-network'),
96                         'url' => $this->getDataValue('author-link')];
97                 $this->redirect_url = Contact::magicLinkByContact($author);
98                 if (!$this->isToplevel()) {
99                         $this->threaded = true;
100                 }
101
102                 // Prepare the children
103                 if (!empty($data['children'])) {
104                         foreach ($data['children'] as $item) {
105                                 // Only add will be displayed
106                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
107                                         continue;
108                                 } elseif (!visible_activity($item)) {
109                                         continue;
110                                 }
111
112                                 // You can always comment on Diaspora and OStatus items
113                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
114                                         $item['writable'] = true;
115                                 }
116
117                                 $item['pagedrop'] = $data['pagedrop'];
118                                 $child = new Post($item);
119                                 $this->addChild($child);
120                         }
121                 }
122         }
123
124         /**
125          * Get data in a form usable by a conversation template
126          *
127          * @param array   $conv_responses conversation responses
128          * @param integer $thread_level   default = 1
129          *
130          * @return mixed The data requested on success
131          *               false on failure
132          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133          * @throws \ImagickException
134          */
135         public function getTemplateData(array $conv_responses, $thread_level = 1)
136         {
137                 $a = DI::app();
138
139                 $item = $this->getData();
140                 $edited = false;
141                 // If the time between "created" and "edited" differs we add
142                 // a notice that the post was edited.
143                 // Note: In some networks reshared items seem to have (sometimes) a difference
144                 // between creation time and edit time of a second. Thats why we add the notice
145                 // only if the difference is more than 1 second.
146                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
147                         $edited = [
148                                 'label'    => DI::l10n()->t('This entry was edited'),
149                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
150                                 'relative' => Temporal::getRelativeDate($item['edited'])
151                         ];
152                 }
153                 $sparkle = '';
154                 $buttons = [
155                         'like'     => null,
156                         'dislike'  => null,
157                         'share'    => null,
158                         'announce' => null,
159                 ];
160                 $dropping = false;
161                 $pinned = '';
162                 $pin = false;
163                 $star = false;
164                 $ignore = false;
165                 $ispinned = "unpinned";
166                 $isstarred = "unstarred";
167                 $indent = '';
168                 $shiny = '';
169                 $osparkle = '';
170                 $total_children = $this->countDescendants();
171
172                 $conv = $this->getThread();
173
174                 $lock = ((($item['private'] == Item::PRIVATE) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
175                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
176                         ? DI::l10n()->t('Private Message')
177                         : false);
178
179                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE;
180                 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER]);
181
182                 // On Diaspora only toplevel posts can be reshared
183                 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != GRAVITY_PARENT)) {
184                         $announceable = false;
185                 }
186
187                 $edpost = false;
188
189                 if (local_user()) {
190                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
191                                 if ($item["event-id"] != 0) {
192                                         $edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")];
193                                 } else {
194                                         $edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")];
195                                 }
196                         }
197                         $dropping = in_array($item['uid'], [0, local_user()]);
198                 }
199
200                 // Editing on items of not subscribed users isn't currently possible
201                 // There are some issues on editing that prevent this.
202                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
203                 if ($item['uid'] == 0) {
204                         $edpost = false;
205                 }
206
207                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
208                         $dropping = true;
209                 }
210
211                 $origin = $item['origin'];
212
213                 if (!$origin) {
214                         /// @todo This shouldn't be done as query here, but better during the data creation.
215                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
216                         $parent = PostModel::selectFirst(['origin'], ['id' => $item['parent']]);
217                         if (DBA::isResult($parent)) {
218                                 $origin = $parent['origin'];
219                         }
220                 } elseif ($item['pinned']) {
221                         $pinned = DI::l10n()->t('pinned item');
222                 }
223
224                 if ($origin && ($item['gravity'] != GRAVITY_PARENT) && ($item['network'] == Protocol::ACTIVITYPUB)) {
225                         // ActivityPub doesn't allow removal of remote comments
226                         $delete = DI::l10n()->t('Delete locally');
227                 } else {
228                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
229                         $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
230                 }
231
232                 $drop = false;
233                 $block = false;
234                 if (local_user()) {
235                         $drop = [
236                                 'dropping' => $dropping,
237                                 'pagedrop' => $item['pagedrop'],
238                                 'select'   => DI::l10n()->t('Select'),
239                                 'delete'   => $delete,
240                         ];
241                         $block = [
242                                 'blocking' => true,
243                                 'block'   => DI::l10n()->t('Block %s', $item['author-name']),
244                                 'author_id'   => $item['author-id'],
245                         ];
246                 }
247
248                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? DI::l10n()->t("save to folder") : false);
249
250                 $profile_name = $item['author-name'];
251                 if (!empty($item['author-link']) && empty($item['author-name'])) {
252                         $profile_name = $item['author-link'];
253                 }
254
255                 $author = ['uid' => 0, 'id' => $item['author-id'],
256                         'network' => $item['author-network'], 'url' => $item['author-link']];
257
258                 if (Session::isAuthenticated()) {
259                         $profile_link = Contact::magicLinkByContact($author);
260                 } else {
261                         $profile_link = $item['author-link'];
262                 }
263
264                 if (strpos($profile_link, 'redir/') === 0) {
265                         $sparkle = ' sparkle';
266                 }
267
268                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
269                 Hook::callAll('render_location', $locate);
270                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
271
272                 // process action responses - e.g. like/dislike/attend/agree/whatever
273                 $response_verbs = ['like', 'dislike', 'announce'];
274
275                 $isevent = false;
276                 $attend = [];
277                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
278                         $response_verbs[] = 'attendyes';
279                         $response_verbs[] = 'attendno';
280                         $response_verbs[] = 'attendmaybe';
281                         if ($conv->isWritable()) {
282                                 $isevent = true;
283                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
284                         }
285                 }
286
287                 $responses = [];
288                 foreach ($response_verbs as $value => $verb) {
289                         $responses[$verb] = [
290                                 'self'   => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
291                                 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? format_activity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
292                         ];
293                 }
294
295                 /*
296                  * We should avoid doing this all the time, but it depends on the conversation mode
297                  * And the conv mode may change when we change the conv, or it changes its mode
298                  * Maybe we should establish a way to be notified about conversation changes
299                  */
300                 $this->checkWallToWall();
301
302                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
303                         $osparkle = ' sparkle';
304                 }
305
306                 $tagger = '';
307
308                 if ($this->isToplevel()) {
309                         if(local_user()) {
310                                 $ignored = PostModel\ThreadUser::getIgnored($item['uri-id'], local_user());
311                                 $ignore = [
312                                         'do'        => DI::l10n()->t("ignore thread"),
313                                         'undo'      => DI::l10n()->t("unignore thread"),
314                                         'toggle'    => DI::l10n()->t("toggle ignore status"),
315                                         'classdo'   => $ignored ? "hidden" : "",
316                                         'classundo' => $ignored ? "" : "hidden",
317                                         'ignored'   => DI::l10n()->t('ignored'),
318                                 ];
319
320                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
321                                         if ($origin) {
322                                                 $ispinned = ($item['pinned'] ? 'pinned' : 'unpinned');
323
324                                                 $pin = [
325                                                         'do'        => DI::l10n()->t('pin'),
326                                                         'undo'      => DI::l10n()->t('unpin'),
327                                                         'toggle'    => DI::l10n()->t('toggle pin status'),
328                                                         'classdo'   => $item['pinned'] ? 'hidden' : '',
329                                                         'classundo' => $item['pinned'] ? '' : 'hidden',
330                                                         'pinned'   => DI::l10n()->t('pinned'),
331                                                 ];
332                                         }
333
334                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
335
336                                         $star = [
337                                                 'do'        => DI::l10n()->t("add star"),
338                                                 'undo'      => DI::l10n()->t("remove star"),
339                                                 'toggle'    => DI::l10n()->t("toggle star status"),
340                                                 'classdo'   => $item['starred'] ? "hidden" : "",
341                                                 'classundo' => $item['starred'] ? "" : "hidden",
342                                                 'starred'   => DI::l10n()->t('starred'),
343                                         ];
344
345                                         $tagger = [
346                                                 'add'   => DI::l10n()->t("add tag"),
347                                                 'class' => "",
348                                         ];
349                                 }
350                         }
351                 } else {
352                         $indent = 'comment';
353                 }
354
355                 if ($conv->isWritable()) {
356                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29")      , DI::l10n()->t("like")];
357                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t("dislike")];
358                         if ($shareable) {
359                                 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
360                         }
361                         if ($announceable) {
362                                 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
363                                 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
364                         }
365                 }
366
367                 $comment_html = $this->getCommentBox($indent);
368
369                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
370                         $shiny = 'shiny';
371                 }
372
373                 localize_item($item);
374
375                 $body_html = Item::prepareBody($item, true);
376
377                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
378
379                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
380                         $title = ucfirst($item['content-warning']);
381                 } else {
382                         $title = $item['title'];
383                 }
384
385                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
386                         $buttons['dislike'] = false;
387                 }
388
389                 // Disable features that aren't available in several networks
390                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
391                         if ($buttons["dislike"]) {
392                                 $buttons["dislike"] = false;
393                         }
394
395                         $isevent = false;
396                         $tagger = '';
397                 }
398
399                 if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) {
400                         $buttons["like"] = false;
401                 }
402
403                 $tags = Tag::populateFromItem($item);
404
405                 $ago = Temporal::getRelativeDate($item['created']);
406                 $ago_received = Temporal::getRelativeDate($item['received']);
407                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
408                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
409                 }
410
411                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
412                 if (($item['network'] != Protocol::DIASPORA) && empty($comment) && !empty(Session::get('remote_comment'))) {
413                         $remote_comment = [DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('remote comment'),
414                                 str_replace('{uri}', urlencode($item['uri']), Session::get('remote_comment'))];
415                 } else {
416                         $remote_comment = '';
417                 }
418
419                 $direction = [];
420                 if (!empty($item['direction'])) {
421                         $direction = $item['direction'];
422                 } elseif (DI::config()->get('debug', 'show_direction')) {
423                         $conversation = DBA::selectFirst('conversation', ['direction'], ['item-uri' => $item['uri']]);
424                         if (!empty($conversation['direction']) && in_array($conversation['direction'], [1, 2])) {
425                                 $direction_title = [1 => DI::l10n()->t('Pushed'), 2 => DI::l10n()->t('Pulled')];
426                                 $direction = ['direction' => $conversation['direction'], 'title' => $direction_title[$conversation['direction']]];
427                         }
428                 }
429
430                 $languages = [];
431                 if (!empty($item['language'])) {
432                         $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
433                 }
434
435                 $tmp_item = [
436                         'template'        => $this->getTemplate(),
437                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
438                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
439                         'tags'            => $tags['tags'],
440                         'hashtags'        => $tags['hashtags'],
441                         'mentions'        => $tags['mentions'],
442                         'implicit_mentions' => $tags['implicit_mentions'],
443                         'txt_cats'        => DI::l10n()->t('Categories:'),
444                         'txt_folders'     => DI::l10n()->t('Filed under:'),
445                         'has_cats'        => ((count($categories)) ? 'true' : ''),
446                         'has_folders'     => ((count($folders)) ? 'true' : ''),
447                         'categories'      => $categories,
448                         'folders'         => $folders,
449                         'body_html'       => $body_html,
450                         'text'            => strip_tags($body_html),
451                         'id'              => $this->getId(),
452                         'guid'            => urlencode($item['guid']),
453                         'isevent'         => $isevent,
454                         'attend'          => $attend,
455                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
456                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
457                         'to'              => DI::l10n()->t('to'),
458                         'via'             => DI::l10n()->t('via'),
459                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
460                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
461                         'profile_url'     => $profile_link,
462                         'name'            => $profile_name,
463                         'item_photo_menu_html' => item_photo_menu($item),
464                         'thumb'           => DI::baseUrl()->remove($item['author-avatar']),
465                         'osparkle'        => $osparkle,
466                         'sparkle'         => $sparkle,
467                         'title'           => $title,
468                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
469                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
470                         'app'             => $item['app'],
471                         'created'         => $ago,
472                         'lock'            => $lock,
473                         'location_html'   => $location_html,
474                         'indent'          => $indent,
475                         'shiny'           => $shiny,
476                         'owner_self'      => $item['author-link'] == Session::get('my_url'),
477                         'owner_url'       => $this->getOwnerUrl(),
478                         'owner_photo'     => DI::baseUrl()->remove($item['owner-avatar']),
479                         'owner_name'      => $this->getOwnerName(),
480                         'plink'           => Item::getPlink($item),
481                         'edpost'          => $edpost,
482                         'ispinned'        => $ispinned,
483                         'pin'             => $pin,
484                         'pinned'          => $pinned,
485                         'isstarred'       => $isstarred,
486                         'star'            => $star,
487                         'ignore'          => $ignore,
488                         'tagger'          => $tagger,
489                         'filer'           => $filer,
490                         'language'        => $languages,
491                         'drop'            => $drop,
492                         'block'           => $block,
493                         'vote'            => $buttons,
494                         'like_html'       => $responses['like']['output'],
495                         'dislike_html'    => $responses['dislike']['output'],
496                         'responses'       => $responses,
497                         'switchcomment'   => DI::l10n()->t('Comment'),
498                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
499                         'comment_html'    => $comment_html,
500                         'remote_comment'  => $remote_comment,
501                         'menu'            => DI::l10n()->t('More'),
502                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
503                         'wait'            => DI::l10n()->t('Please wait'),
504                         'thread_level'    => $thread_level,
505                         'edited'          => $edited,
506                         'network'         => $item["network"],
507                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
508                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
509                         'received'        => $item['received'],
510                         'commented'       => $item['commented'],
511                         'created_date'    => $item['created'],
512                         'uriid'           => $item['uri-id'],
513                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
514                         'direction'       => $direction,
515                         'reshared'        => $item['reshared'] ?? '',
516                         'delivery'        => [
517                                 'queue_count'       => $item['delivery_queue_count'],
518                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
519                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
520                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
521                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
522                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
523                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
524                         ],
525                 ];
526
527                 $arr = ['item' => $item, 'output' => $tmp_item];
528                 Hook::callAll('display_item', $arr);
529
530                 $result = $arr['output'];
531
532                 $result['children'] = [];
533                 $children = $this->getChildren();
534                 $nb_children = count($children);
535                 if ($nb_children > 0) {
536                         foreach ($children as $child) {
537                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
538                         }
539
540                         // Collapse
541                         if (($nb_children > 2) || ($thread_level > 1)) {
542                                 $result['children'][0]['comment_firstcollapsed'] = true;
543                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
544                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
545                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
546                                 if ($thread_level > 1) {
547                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
548                                 } else {
549                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
550                                 }
551                         }
552                 }
553
554                 if ($this->isToplevel()) {
555                         $result['total_comments_num'] = "$total_children";
556                         $result['total_comments_text'] = DI::l10n()->tt('comment', 'comments', $total_children);
557                 }
558
559                 $result['private'] = $item['private'];
560                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
561
562                 if ($this->isThreaded()) {
563                         $result['flatten'] = false;
564                         $result['threaded'] = true;
565                 } else {
566                         $result['flatten'] = true;
567                         $result['threaded'] = false;
568                 }
569
570                 return $result;
571         }
572
573         /**
574          * @return integer
575          */
576         public function getId()
577         {
578                 return $this->getDataValue('id');
579         }
580
581         /**
582          * @return boolean
583          */
584         public function isThreaded()
585         {
586                 return $this->threaded;
587         }
588
589         /**
590          * Add a child item
591          *
592          * @param Post $item The child item to add
593          *
594          * @return mixed
595          * @throws \Exception
596          */
597         public function addChild(Post $item)
598         {
599                 $item_id = $item->getId();
600                 if (!$item_id) {
601                         Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
602                         return false;
603                 } elseif ($this->getChild($item->getId())) {
604                         Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
605                         return false;
606                 }
607
608                 $activity = DI::activity();
609
610                 /*
611                  * Only add what will be displayed
612                  */
613                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
614                         return false;
615                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
616                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
617                         return false;
618                 }
619
620                 $item->setParent($this);
621                 $this->children[] = $item;
622
623                 return end($this->children);
624         }
625
626         /**
627          * Get a child by its ID
628          *
629          * @param integer $id The child id
630          *
631          * @return mixed
632          */
633         public function getChild($id)
634         {
635                 foreach ($this->getChildren() as $child) {
636                         if ($child->getId() == $id) {
637                                 return $child;
638                         }
639                 }
640
641                 return null;
642         }
643
644         /**
645          * Get all our children
646          *
647          * @return Post[]
648          */
649         public function getChildren()
650         {
651                 return $this->children;
652         }
653
654         /**
655          * Set our parent
656          *
657          * @param Post $item The item to set as parent
658          *
659          * @return void
660          */
661         protected function setParent(Post $item)
662         {
663                 $parent = $this->getParent();
664                 if ($parent) {
665                         $parent->removeChild($this);
666                 }
667
668                 $this->parent = $item;
669                 $this->setThread($item->getThread());
670         }
671
672         /**
673          * Remove our parent
674          *
675          * @return void
676          */
677         protected function removeParent()
678         {
679                 $this->parent = null;
680                 $this->thread = null;
681         }
682
683         /**
684          * Remove a child
685          *
686          * @param Post $item The child to be removed
687          *
688          * @return boolean Success or failure
689          * @throws \Exception
690          */
691         public function removeChild(Post $item)
692         {
693                 $id = $item->getId();
694                 foreach ($this->getChildren() as $key => $child) {
695                         if ($child->getId() == $id) {
696                                 $child->removeParent();
697                                 unset($this->children[$key]);
698                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
699                                 $this->children = array_values($this->children);
700                                 return true;
701                         }
702                 }
703                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
704                 return false;
705         }
706
707         /**
708          * Get parent item
709          *
710          * @return object
711          */
712         protected function getParent()
713         {
714                 return $this->parent;
715         }
716
717         /**
718          * Set conversation thread
719          *
720          * @param Thread $thread
721          *
722          * @return void
723          */
724         public function setThread(Thread $thread = null)
725         {
726                 $this->thread = $thread;
727
728                 // Set it on our children too
729                 foreach ($this->getChildren() as $child) {
730                         $child->setThread($thread);
731                 }
732         }
733
734         /**
735          * Get conversation
736          *
737          * @return Thread
738          */
739         public function getThread()
740         {
741                 return $this->thread;
742         }
743
744         /**
745          * Get raw data
746          *
747          * We shouldn't need this
748          *
749          * @return array
750          */
751         public function getData()
752         {
753                 return $this->data;
754         }
755
756         /**
757          * Get a data value
758          *
759          * @param string $name key
760          *
761          * @return mixed value on success
762          *               false on failure
763          */
764         public function getDataValue($name)
765         {
766                 if (!isset($this->data[$name])) {
767                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
768                         return false;
769                 }
770
771                 return $this->data[$name];
772         }
773
774         /**
775          * Set template
776          *
777          * @param string $name template name
778          * @return bool
779          * @throws \Exception
780          */
781         private function setTemplate($name)
782         {
783                 if (empty($this->available_templates[$name])) {
784                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
785                         return false;
786                 }
787
788                 $this->template = $this->available_templates[$name];
789
790                 return true;
791         }
792
793         /**
794          * Get template
795          *
796          * @return object
797          */
798         private function getTemplate()
799         {
800                 return $this->template;
801         }
802
803         /**
804          * Check if this is a toplevel post
805          *
806          * @return boolean
807          */
808         private function isToplevel()
809         {
810                 return $this->toplevel;
811         }
812
813         /**
814          * Check if this is writable
815          *
816          * @return boolean
817          */
818         private function isWritable()
819         {
820                 $conv = $this->getThread();
821
822                 if ($conv) {
823                         // This will allow us to comment on wall-to-wall items owned by our friends
824                         // and community forums even if somebody else wrote the post.
825                         // bug #517 - this fixes for conversation owner
826                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
827                                 return true;
828                         }
829
830                         // this fixes for visitors
831                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
832                 }
833                 return $this->writable;
834         }
835
836         /**
837          * Count the total of our descendants
838          *
839          * @return integer
840          */
841         private function countDescendants()
842         {
843                 $children = $this->getChildren();
844                 $total = count($children);
845                 if ($total > 0) {
846                         foreach ($children as $child) {
847                                 $total += $child->countDescendants();
848                         }
849                 }
850
851                 return $total;
852         }
853
854         /**
855          * Get the template for the comment box
856          *
857          * @return string
858          */
859         private function getCommentBoxTemplate()
860         {
861                 return $this->comment_box_template;
862         }
863
864         /**
865          * Get default text for the comment box
866          *
867          * @return string
868          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
869          */
870         private function getDefaultText()
871         {
872                 $a = DI::app();
873
874                 if (!local_user()) {
875                         return '';
876                 }
877
878                 $owner = User::getOwnerDataById($a->user['uid']);
879
880                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
881                         return '';
882                 }
883
884                 $item = PostModel::selectFirst(['author-addr', 'uri-id', 'network', 'gravity'], ['id' => $this->getId()]);
885                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
886                         // Should not happen
887                         return '';
888                 }
889
890                 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
891                         $text = '@' . $item['author-addr'] . ' ';
892                 } else {
893                         $text = '';
894                 }
895
896                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
897                 foreach ($terms as $term) {
898                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
899                         if (!empty($profile['addr']) && ((($profile['contact-type'] ?? '') ?: Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
900                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
901                                 $text .= '@' . $profile['addr'] . ' ';
902                         }
903                 }
904
905                 return $text;
906         }
907
908         /**
909          * Get the comment box
910          *
911          * @param string $indent Indent value
912          *
913          * @return mixed The comment box string (empty if no comment box)
914          *               false on failure
915          * @throws \Exception
916          */
917         private function getCommentBox($indent)
918         {
919                 $a = DI::app();
920
921                 $comment_box = '';
922                 $conv = $this->getThread();
923
924                 if ($conv->isWritable() && $this->isWritable()) {
925                         /*
926                          * Hmmm, code depending on the presence of a particular addon?
927                          * This should be better if done by a hook
928                          */
929                         $qcomment = null;
930                         if (Addon::isEnabled('qcomment')) {
931                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
932                                 $qcomment = $words ? explode("\n", $words) : [];
933                         }
934
935                         // Fetch the user id from the parent when the owner user is empty
936                         $uid = $conv->getProfileOwner();
937                         $parent_uid = $this->getDataValue('uid');
938
939                         $default_text = $this->getDefaultText();
940
941                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
942                                 $uid = $parent_uid;
943                         }
944
945                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
946                         $comment_box = Renderer::replaceMacros($template, [
947                                 '$return_path' => DI::args()->getQueryString(),
948                                 '$threaded'    => $this->isThreaded(),
949                                 '$jsreload'    => '',
950                                 '$wall'        => ($conv->getMode() === 'profile'),
951                                 '$id'          => $this->getId(),
952                                 '$parent'      => $this->getId(),
953                                 '$qcomment'    => $qcomment,
954                                 '$default'     => $default_text,
955                                 '$profile_uid' => $uid,
956                                 '$mylink'      => DI::baseUrl()->remove($a->contact['url']),
957                                 '$mytitle'     => DI::l10n()->t('This is you'),
958                                 '$myphoto'     => DI::baseUrl()->remove($a->contact['thumb']),
959                                 '$comment'     => DI::l10n()->t('Comment'),
960                                 '$submit'      => DI::l10n()->t('Submit'),
961                                 '$loading'     => DI::l10n()->t('Loading...'),
962                                 '$edbold'      => DI::l10n()->t('Bold'),
963                                 '$editalic'    => DI::l10n()->t('Italic'),
964                                 '$eduline'     => DI::l10n()->t('Underline'),
965                                 '$edquote'     => DI::l10n()->t('Quote'),
966                                 '$edcode'      => DI::l10n()->t('Code'),
967                                 '$edimg'       => DI::l10n()->t('Image'),
968                                 '$edurl'       => DI::l10n()->t('Link'),
969                                 '$edattach'    => DI::l10n()->t('Link or Media'),
970                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
971                                 '$preview'     => DI::l10n()->t('Preview'),
972                                 '$indent'      => $indent,
973                                 '$sourceapp'   => DI::l10n()->t($a->sourcename),
974                                 '$rand_num'    => Crypto::randomDigits(12)
975                         ]);
976                 }
977
978                 return $comment_box;
979         }
980
981         /**
982          * @return string
983          */
984         private function getRedirectUrl()
985         {
986                 return $this->redirect_url;
987         }
988
989         /**
990          * Check if we are a wall to wall item and set the relevant properties
991          *
992          * @return void
993          * @throws \Exception
994          */
995         protected function checkWallToWall()
996         {
997                 $a = DI::app();
998                 $conv = $this->getThread();
999                 $this->wall_to_wall = false;
1000
1001                 if ($this->isToplevel()) {
1002                         if ($conv->getMode() !== 'profile') {
1003                                 if ($this->getDataValue('wall') && !$this->getDataValue('self') && !empty($a->page_contact)) {
1004                                         // On the network page, I am the owner. On the display page it will be the profile owner.
1005                                         // This will have been stored in $a->page_contact by our calling page.
1006                                         // Put this person as the wall owner of the wall-to-wall notice.
1007
1008                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
1009                                         $this->owner_photo = $a->page_contact['thumb'];
1010                                         $this->owner_name = $a->page_contact['name'];
1011                                         $this->wall_to_wall = true;
1012                                 } elseif ($this->getDataValue('owner-link')) {
1013                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1014                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1015                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1016
1017                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1018                                                 // The author url doesn't match the owner (typically the contact)
1019                                                 // and also doesn't match the contact alias.
1020                                                 // The name match is a hack to catch several weird cases where URLs are
1021                                                 // all over the park. It can be tricked, but this prevents you from
1022                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1023                                                 // well that it's the same Bob Smith.
1024                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1025
1026
1027                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
1028                                                 $this->owner_name = $this->getDataValue('owner-name');
1029                                                 $this->wall_to_wall = true;
1030
1031                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1032                                                         'network' => $this->getDataValue('owner-network'),
1033                                                         'url' => $this->getDataValue('owner-link')];
1034                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1035                                         }
1036                                 }
1037                         }
1038                 }
1039
1040                 if (!$this->wall_to_wall) {
1041                         $this->setTemplate('wall');
1042                         $this->owner_url = '';
1043                         $this->owner_photo = '';
1044                         $this->owner_name = '';
1045                 }
1046         }
1047
1048         /**
1049          * @return boolean
1050          */
1051         private function isWallToWall()
1052         {
1053                 return $this->wall_to_wall;
1054         }
1055
1056         /**
1057          * @return string
1058          */
1059         private function getOwnerUrl()
1060         {
1061                 return $this->owner_url;
1062         }
1063
1064         /**
1065          * @return string
1066          */
1067         private function getOwnerName()
1068         {
1069                 return $this->owner_name;
1070         }
1071
1072         /**
1073          * @return boolean
1074          */
1075         private function isVisiting()
1076         {
1077                 return $this->visiting;
1078         }
1079 }