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