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