]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
New post class in the rest of the classes
[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 ModelPost;
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 = ModelPost::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                 if (local_user()) {
234                         $drop = [
235                                 'dropping' => $dropping,
236                                 'pagedrop' => $item['pagedrop'],
237                                 'select'   => DI::l10n()->t('Select'),
238                                 'delete'   => $delete,
239                         ];
240                 }
241
242                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? DI::l10n()->t("save to folder") : false);
243
244                 $profile_name = $item['author-name'];
245                 if (!empty($item['author-link']) && empty($item['author-name'])) {
246                         $profile_name = $item['author-link'];
247                 }
248
249                 $author = ['uid' => 0, 'id' => $item['author-id'],
250                         'network' => $item['author-network'], 'url' => $item['author-link']];
251
252                 if (Session::isAuthenticated()) {
253                         $profile_link = Contact::magicLinkByContact($author);
254                 } else {
255                         $profile_link = $item['author-link'];
256                 }
257
258                 if (strpos($profile_link, 'redir/') === 0) {
259                         $sparkle = ' sparkle';
260                 }
261
262                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
263                 Hook::callAll('render_location', $locate);
264                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
265
266                 // process action responses - e.g. like/dislike/attend/agree/whatever
267                 $response_verbs = ['like', 'dislike', 'announce'];
268
269                 $isevent = false;
270                 $attend = [];
271                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
272                         $response_verbs[] = 'attendyes';
273                         $response_verbs[] = 'attendno';
274                         $response_verbs[] = 'attendmaybe';
275                         if ($conv->isWritable()) {
276                                 $isevent = true;
277                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
278                         }
279                 }
280
281                 $responses = [];
282                 foreach ($response_verbs as $value => $verb) {
283                         $responses[$verb] = [
284                                 'self'   => $conv_responses[$verb][$item['uri']]['self'] ?? 0,
285                                 'output' => !empty($conv_responses[$verb][$item['uri']]) ? format_activity($conv_responses[$verb][$item['uri']]['links'], $verb, $item['uri']) : '',
286                         ];
287                 }
288
289                 /*
290                  * We should avoid doing this all the time, but it depends on the conversation mode
291                  * And the conv mode may change when we change the conv, or it changes its mode
292                  * Maybe we should establish a way to be notified about conversation changes
293                  */
294                 $this->checkWallToWall();
295
296                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
297                         $osparkle = ' sparkle';
298                 }
299
300                 $tagger = '';
301
302                 if ($this->isToplevel()) {
303                         if(local_user()) {
304                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
305                                 if (DBA::isResult($thread)) {
306                                         $ignore = [
307                                                 'do'        => DI::l10n()->t("ignore thread"),
308                                                 'undo'      => DI::l10n()->t("unignore thread"),
309                                                 'toggle'    => DI::l10n()->t("toggle ignore status"),
310                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
311                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
312                                                 'ignored'   => DI::l10n()->t('ignored'),
313                                         ];
314                                 }
315
316                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
317                                         if ($origin) {
318                                                 $ispinned = ($item['pinned'] ? 'pinned' : 'unpinned');
319
320                                                 $pin = [
321                                                         'do'        => DI::l10n()->t('pin'),
322                                                         'undo'      => DI::l10n()->t('unpin'),
323                                                         'toggle'    => DI::l10n()->t('toggle pin status'),
324                                                         'classdo'   => $item['pinned'] ? 'hidden' : '',
325                                                         'classundo' => $item['pinned'] ? '' : 'hidden',
326                                                         'pinned'   => DI::l10n()->t('pinned'),
327                                                 ];
328                                         }
329
330                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
331
332                                         $star = [
333                                                 'do'        => DI::l10n()->t("add star"),
334                                                 'undo'      => DI::l10n()->t("remove star"),
335                                                 'toggle'    => DI::l10n()->t("toggle star status"),
336                                                 'classdo'   => $item['starred'] ? "hidden" : "",
337                                                 'classundo' => $item['starred'] ? "" : "hidden",
338                                                 'starred'   => DI::l10n()->t('starred'),
339                                         ];
340
341                                         $tagger = [
342                                                 'add'   => DI::l10n()->t("add tag"),
343                                                 'class' => "",
344                                         ];
345                                 }
346                         }
347                 } else {
348                         $indent = 'comment';
349                 }
350
351                 if ($conv->isWritable()) {
352                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29")      , DI::l10n()->t("like")];
353                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t("dislike")];
354                         if ($shareable) {
355                                 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
356                         }
357                         if ($announceable) {
358                                 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
359                                 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
360                         }
361                 }
362
363                 $comment_html = $this->getCommentBox($indent);
364
365                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
366                         $shiny = 'shiny';
367                 }
368
369                 localize_item($item);
370
371                 $body_html = Item::prepareBody($item, true);
372
373                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
374
375                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
376                         $title = ucfirst($item['content-warning']);
377                 } else {
378                         $title = $item['title'];
379                 }
380
381                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
382                         $buttons['dislike'] = false;
383                 }
384
385                 // Disable features that aren't available in several networks
386                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
387                         if ($buttons["dislike"]) {
388                                 $buttons["dislike"] = false;
389                         }
390
391                         $isevent = false;
392                         $tagger = '';
393                 }
394
395                 if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) {
396                         $buttons["like"] = false;
397                 }
398
399                 $tags = Tag::populateFromItem($item);
400
401                 $ago = Temporal::getRelativeDate($item['created']);
402                 $ago_received = Temporal::getRelativeDate($item['received']);
403                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
404                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
405                 }
406
407                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
408                 if (($item['network'] != Protocol::DIASPORA) && empty($comment) && !empty(Session::get('remote_comment'))) {
409                         $remote_comment = [DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('remote comment'),
410                                 str_replace('{uri}', urlencode($item['uri']), Session::get('remote_comment'))];
411                 } else {
412                         $remote_comment = '';
413                 }
414
415                 $direction = [];
416                 if (!empty($item['direction'])) {
417                         $direction = $item['direction'];
418                 } elseif (DI::config()->get('debug', 'show_direction')) {
419                         $conversation = DBA::selectFirst('conversation', ['direction'], ['item-uri' => $item['uri']]);
420                         if (!empty($conversation['direction']) && in_array($conversation['direction'], [1, 2])) {
421                                 $direction_title = [1 => DI::l10n()->t('Pushed'), 2 => DI::l10n()->t('Pulled')];
422                                 $direction = ['direction' => $conversation['direction'], 'title' => $direction_title[$conversation['direction']]];
423                         }
424                 }
425
426                 $languages = [];
427                 if (!empty($item['language'])) {
428                         $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
429                 }
430
431                 $tmp_item = [
432                         'template'        => $this->getTemplate(),
433                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
434                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
435                         'tags'            => $tags['tags'],
436                         'hashtags'        => $tags['hashtags'],
437                         'mentions'        => $tags['mentions'],
438                         'implicit_mentions' => $tags['implicit_mentions'],
439                         'txt_cats'        => DI::l10n()->t('Categories:'),
440                         'txt_folders'     => DI::l10n()->t('Filed under:'),
441                         'has_cats'        => ((count($categories)) ? 'true' : ''),
442                         'has_folders'     => ((count($folders)) ? 'true' : ''),
443                         'categories'      => $categories,
444                         'folders'         => $folders,
445                         'body_html'       => $body_html,
446                         'text'            => strip_tags($body_html),
447                         'id'              => $this->getId(),
448                         'guid'            => urlencode($item['guid']),
449                         'isevent'         => $isevent,
450                         'attend'          => $attend,
451                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
452                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
453                         'to'              => DI::l10n()->t('to'),
454                         'via'             => DI::l10n()->t('via'),
455                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
456                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
457                         'profile_url'     => $profile_link,
458                         'name'            => $profile_name,
459                         'item_photo_menu_html' => item_photo_menu($item),
460                         'thumb'           => DI::baseUrl()->remove($item['author-avatar']),
461                         'osparkle'        => $osparkle,
462                         'sparkle'         => $sparkle,
463                         'title'           => $title,
464                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
465                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
466                         'app'             => $item['app'],
467                         'created'         => $ago,
468                         'lock'            => $lock,
469                         'location_html'   => $location_html,
470                         'indent'          => $indent,
471                         'shiny'           => $shiny,
472                         'owner_self'      => $item['author-link'] == Session::get('my_url'),
473                         'owner_url'       => $this->getOwnerUrl(),
474                         'owner_photo'     => DI::baseUrl()->remove($item['owner-avatar']),
475                         'owner_name'      => $this->getOwnerName(),
476                         'plink'           => Item::getPlink($item),
477                         'edpost'          => $edpost,
478                         'ispinned'        => $ispinned,
479                         'pin'             => $pin,
480                         'pinned'          => $pinned,
481                         'isstarred'       => $isstarred,
482                         'star'            => $star,
483                         'ignore'          => $ignore,
484                         'tagger'          => $tagger,
485                         'filer'           => $filer,
486                         'language'        => $languages,
487                         'drop'            => $drop,
488                         'vote'            => $buttons,
489                         'like_html'       => $responses['like']['output'],
490                         'dislike_html'    => $responses['dislike']['output'],
491                         'responses'       => $responses,
492                         'switchcomment'   => DI::l10n()->t('Comment'),
493                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
494                         'comment_html'    => $comment_html,
495                         'remote_comment'  => $remote_comment,
496                         'menu'            => DI::l10n()->t('More'),
497                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
498                         'wait'            => DI::l10n()->t('Please wait'),
499                         'thread_level'    => $thread_level,
500                         'edited'          => $edited,
501                         'network'         => $item["network"],
502                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
503                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
504                         'received'        => $item['received'],
505                         'commented'       => $item['commented'],
506                         'created_date'    => $item['created'],
507                         'uriid'           => $item['uri-id'],
508                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
509                         'direction'       => $direction,
510                         'reshared'        => $item['reshared'] ?? '',
511                         'delivery'        => [
512                                 'queue_count'       => $item['delivery_queue_count'],
513                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
514                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
515                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
516                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
517                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
518                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
519                         ],
520                 ];
521
522                 $arr = ['item' => $item, 'output' => $tmp_item];
523                 Hook::callAll('display_item', $arr);
524
525                 $result = $arr['output'];
526
527                 $result['children'] = [];
528                 $children = $this->getChildren();
529                 $nb_children = count($children);
530                 if ($nb_children > 0) {
531                         foreach ($children as $child) {
532                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
533                         }
534
535                         // Collapse
536                         if (($nb_children > 2) || ($thread_level > 1)) {
537                                 $result['children'][0]['comment_firstcollapsed'] = true;
538                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
539                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
540                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
541                                 if ($thread_level > 1) {
542                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
543                                 } else {
544                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
545                                 }
546                         }
547                 }
548
549                 if ($this->isToplevel()) {
550                         $result['total_comments_num'] = "$total_children";
551                         $result['total_comments_text'] = DI::l10n()->tt('comment', 'comments', $total_children);
552                 }
553
554                 $result['private'] = $item['private'];
555                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
556
557                 if ($this->isThreaded()) {
558                         $result['flatten'] = false;
559                         $result['threaded'] = true;
560                 } else {
561                         $result['flatten'] = true;
562                         $result['threaded'] = false;
563                 }
564
565                 return $result;
566         }
567
568         /**
569          * @return integer
570          */
571         public function getId()
572         {
573                 return $this->getDataValue('id');
574         }
575
576         /**
577          * @return boolean
578          */
579         public function isThreaded()
580         {
581                 return $this->threaded;
582         }
583
584         /**
585          * Add a child item
586          *
587          * @param Post $item The child item to add
588          *
589          * @return mixed
590          * @throws \Exception
591          */
592         public function addChild(Post $item)
593         {
594                 $item_id = $item->getId();
595                 if (!$item_id) {
596                         Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
597                         return false;
598                 } elseif ($this->getChild($item->getId())) {
599                         Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
600                         return false;
601                 }
602
603                 $activity = DI::activity();
604
605                 /*
606                  * Only add what will be displayed
607                  */
608                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
609                         return false;
610                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
611                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
612                         return false;
613                 }
614
615                 $item->setParent($this);
616                 $this->children[] = $item;
617
618                 return end($this->children);
619         }
620
621         /**
622          * Get a child by its ID
623          *
624          * @param integer $id The child id
625          *
626          * @return mixed
627          */
628         public function getChild($id)
629         {
630                 foreach ($this->getChildren() as $child) {
631                         if ($child->getId() == $id) {
632                                 return $child;
633                         }
634                 }
635
636                 return null;
637         }
638
639         /**
640          * Get all our children
641          *
642          * @return Post[]
643          */
644         public function getChildren()
645         {
646                 return $this->children;
647         }
648
649         /**
650          * Set our parent
651          *
652          * @param Post $item The item to set as parent
653          *
654          * @return void
655          */
656         protected function setParent(Post $item)
657         {
658                 $parent = $this->getParent();
659                 if ($parent) {
660                         $parent->removeChild($this);
661                 }
662
663                 $this->parent = $item;
664                 $this->setThread($item->getThread());
665         }
666
667         /**
668          * Remove our parent
669          *
670          * @return void
671          */
672         protected function removeParent()
673         {
674                 $this->parent = null;
675                 $this->thread = null;
676         }
677
678         /**
679          * Remove a child
680          *
681          * @param Post $item The child to be removed
682          *
683          * @return boolean Success or failure
684          * @throws \Exception
685          */
686         public function removeChild(Post $item)
687         {
688                 $id = $item->getId();
689                 foreach ($this->getChildren() as $key => $child) {
690                         if ($child->getId() == $id) {
691                                 $child->removeParent();
692                                 unset($this->children[$key]);
693                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
694                                 $this->children = array_values($this->children);
695                                 return true;
696                         }
697                 }
698                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
699                 return false;
700         }
701
702         /**
703          * Get parent item
704          *
705          * @return object
706          */
707         protected function getParent()
708         {
709                 return $this->parent;
710         }
711
712         /**
713          * Set conversation thread
714          *
715          * @param Thread $thread
716          *
717          * @return void
718          */
719         public function setThread(Thread $thread = null)
720         {
721                 $this->thread = $thread;
722
723                 // Set it on our children too
724                 foreach ($this->getChildren() as $child) {
725                         $child->setThread($thread);
726                 }
727         }
728
729         /**
730          * Get conversation
731          *
732          * @return Thread
733          */
734         public function getThread()
735         {
736                 return $this->thread;
737         }
738
739         /**
740          * Get raw data
741          *
742          * We shouldn't need this
743          *
744          * @return array
745          */
746         public function getData()
747         {
748                 return $this->data;
749         }
750
751         /**
752          * Get a data value
753          *
754          * @param string $name key
755          *
756          * @return mixed value on success
757          *               false on failure
758          */
759         public function getDataValue($name)
760         {
761                 if (!isset($this->data[$name])) {
762                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
763                         return false;
764                 }
765
766                 return $this->data[$name];
767         }
768
769         /**
770          * Set template
771          *
772          * @param string $name template name
773          * @return bool
774          * @throws \Exception
775          */
776         private function setTemplate($name)
777         {
778                 if (empty($this->available_templates[$name])) {
779                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
780                         return false;
781                 }
782
783                 $this->template = $this->available_templates[$name];
784
785                 return true;
786         }
787
788         /**
789          * Get template
790          *
791          * @return object
792          */
793         private function getTemplate()
794         {
795                 return $this->template;
796         }
797
798         /**
799          * Check if this is a toplevel post
800          *
801          * @return boolean
802          */
803         private function isToplevel()
804         {
805                 return $this->toplevel;
806         }
807
808         /**
809          * Check if this is writable
810          *
811          * @return boolean
812          */
813         private function isWritable()
814         {
815                 $conv = $this->getThread();
816
817                 if ($conv) {
818                         // This will allow us to comment on wall-to-wall items owned by our friends
819                         // and community forums even if somebody else wrote the post.
820                         // bug #517 - this fixes for conversation owner
821                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
822                                 return true;
823                         }
824
825                         // this fixes for visitors
826                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
827                 }
828                 return $this->writable;
829         }
830
831         /**
832          * Count the total of our descendants
833          *
834          * @return integer
835          */
836         private function countDescendants()
837         {
838                 $children = $this->getChildren();
839                 $total = count($children);
840                 if ($total > 0) {
841                         foreach ($children as $child) {
842                                 $total += $child->countDescendants();
843                         }
844                 }
845
846                 return $total;
847         }
848
849         /**
850          * Get the template for the comment box
851          *
852          * @return string
853          */
854         private function getCommentBoxTemplate()
855         {
856                 return $this->comment_box_template;
857         }
858
859         /**
860          * Get default text for the comment box
861          *
862          * @return string
863          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864          */
865         private function getDefaultText()
866         {
867                 $a = DI::app();
868
869                 if (!local_user()) {
870                         return '';
871                 }
872
873                 $owner = User::getOwnerDataById($a->user['uid']);
874
875                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
876                         return '';
877                 }
878
879                 $item = ModelPost::selectFirst(['author-addr', 'uri-id'], ['id' => $this->getId()]);
880                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
881                         // Should not happen
882                         return '';
883                 }
884
885                 if ($item['author-addr'] != $owner['addr']) {
886                         $text = '@' . $item['author-addr'] . ' ';
887                 } else {
888                         $text = '';
889                 }
890
891                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
892                 foreach ($terms as $term) {
893                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
894                         if (!empty($profile['addr']) && ((($profile['contact-type'] ?? '') ?: Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
895                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
896                                 $text .= '@' . $profile['addr'] . ' ';
897                         }
898                 }
899
900                 return $text;
901         }
902
903         /**
904          * Get the comment box
905          *
906          * @param string $indent Indent value
907          *
908          * @return mixed The comment box string (empty if no comment box)
909          *               false on failure
910          * @throws \Exception
911          */
912         private function getCommentBox($indent)
913         {
914                 $a = DI::app();
915
916                 $comment_box = '';
917                 $conv = $this->getThread();
918
919                 if ($conv->isWritable() && $this->isWritable()) {
920                         /*
921                          * Hmmm, code depending on the presence of a particular addon?
922                          * This should be better if done by a hook
923                          */
924                         $qcomment = null;
925                         if (Addon::isEnabled('qcomment')) {
926                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
927                                 $qcomment = $words ? explode("\n", $words) : [];
928                         }
929
930                         // Fetch the user id from the parent when the owner user is empty
931                         $uid = $conv->getProfileOwner();
932                         $parent_uid = $this->getDataValue('uid');
933
934                         $default_text = $this->getDefaultText();
935
936                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
937                                 $uid = $parent_uid;
938                         }
939
940                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
941                         $comment_box = Renderer::replaceMacros($template, [
942                                 '$return_path' => DI::args()->getQueryString(),
943                                 '$threaded'    => $this->isThreaded(),
944                                 '$jsreload'    => '',
945                                 '$wall'        => ($conv->getMode() === 'profile'),
946                                 '$id'          => $this->getId(),
947                                 '$parent'      => $this->getId(),
948                                 '$qcomment'    => $qcomment,
949                                 '$default'     => $default_text,
950                                 '$profile_uid' => $uid,
951                                 '$mylink'      => DI::baseUrl()->remove($a->contact['url']),
952                                 '$mytitle'     => DI::l10n()->t('This is you'),
953                                 '$myphoto'     => DI::baseUrl()->remove($a->contact['thumb']),
954                                 '$comment'     => DI::l10n()->t('Comment'),
955                                 '$submit'      => DI::l10n()->t('Submit'),
956                                 '$loading'     => DI::l10n()->t('Loading...'),
957                                 '$edbold'      => DI::l10n()->t('Bold'),
958                                 '$editalic'    => DI::l10n()->t('Italic'),
959                                 '$eduline'     => DI::l10n()->t('Underline'),
960                                 '$edquote'     => DI::l10n()->t('Quote'),
961                                 '$edcode'      => DI::l10n()->t('Code'),
962                                 '$edimg'       => DI::l10n()->t('Image'),
963                                 '$edurl'       => DI::l10n()->t('Link'),
964                                 '$edattach'    => DI::l10n()->t('Link or Media'),
965                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
966                                 '$preview'     => DI::l10n()->t('Preview'),
967                                 '$indent'      => $indent,
968                                 '$sourceapp'   => DI::l10n()->t($a->sourcename),
969                                 '$rand_num'    => Crypto::randomDigits(12)
970                         ]);
971                 }
972
973                 return $comment_box;
974         }
975
976         /**
977          * @return string
978          */
979         private function getRedirectUrl()
980         {
981                 return $this->redirect_url;
982         }
983
984         /**
985          * Check if we are a wall to wall item and set the relevant properties
986          *
987          * @return void
988          * @throws \Exception
989          */
990         protected function checkWallToWall()
991         {
992                 $a = DI::app();
993                 $conv = $this->getThread();
994                 $this->wall_to_wall = false;
995
996                 if ($this->isToplevel()) {
997                         if ($conv->getMode() !== 'profile') {
998                                 if ($this->getDataValue('wall') && !$this->getDataValue('self') && !empty($a->page_contact)) {
999                                         // On the network page, I am the owner. On the display page it will be the profile owner.
1000                                         // This will have been stored in $a->page_contact by our calling page.
1001                                         // Put this person as the wall owner of the wall-to-wall notice.
1002
1003                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
1004                                         $this->owner_photo = $a->page_contact['thumb'];
1005                                         $this->owner_name = $a->page_contact['name'];
1006                                         $this->wall_to_wall = true;
1007                                 } elseif ($this->getDataValue('owner-link')) {
1008                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1009                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1010                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1011
1012                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1013                                                 // The author url doesn't match the owner (typically the contact)
1014                                                 // and also doesn't match the contact alias.
1015                                                 // The name match is a hack to catch several weird cases where URLs are
1016                                                 // all over the park. It can be tricked, but this prevents you from
1017                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1018                                                 // well that it's the same Bob Smith.
1019                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1020
1021
1022                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
1023                                                 $this->owner_name = $this->getDataValue('owner-name');
1024                                                 $this->wall_to_wall = true;
1025
1026                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1027                                                         'network' => $this->getDataValue('owner-network'),
1028                                                         'url' => $this->getDataValue('owner-link')];
1029                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1030                                         }
1031                                 }
1032                         }
1033                 }
1034
1035                 if (!$this->wall_to_wall) {
1036                         $this->setTemplate('wall');
1037                         $this->owner_url = '';
1038                         $this->owner_photo = '';
1039                         $this->owner_name = '';
1040                 }
1041         }
1042
1043         /**
1044          * @return boolean
1045          */
1046         private function isWallToWall()
1047         {
1048                 return $this->wall_to_wall;
1049         }
1050
1051         /**
1052          * @return string
1053          */
1054         private function getOwnerUrl()
1055         {
1056                 return $this->owner_url;
1057         }
1058
1059         /**
1060          * @return string
1061          */
1062         private function getOwnerName()
1063         {
1064                 return $this->owner_name;
1065         }
1066
1067         /**
1068          * @return boolean
1069          */
1070         private function isVisiting()
1071         {
1072                 return $this->visiting;
1073         }
1074 }