3 * @file src/Object/Post.php
5 namespace Friendica\Object;
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\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
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;
30 class Post extends BaseObject
33 private $template = null;
34 private $available_templates = [
35 'wall' => 'wall_thread.tpl',
36 'wall2wall' => 'wallwall_thread.tpl'
38 private $comment_box_template = 'comment_item.tpl';
39 private $toplevel = false;
40 private $writable = false;
41 private $children = [];
42 private $parent = null;
43 private $thread = null;
44 private $redirect_url = null;
45 private $owner_url = '';
46 private $owner_photo = '';
47 private $owner_name = '';
48 private $wall_to_wall = false;
49 private $threaded = false;
50 private $visiting = false;
55 * @param array $data data array
57 public function __construct(array $data)
62 $this->setTemplate('wall');
63 $this->toplevel = $this->getId() == $this->getDataValue('parent');
65 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
66 foreach ($_SESSION['remote'] as $visitor) {
67 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
68 $this->visiting = true;
74 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
75 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
76 'network' => $this->getDataValue('author-network'),
77 'url' => $this->getDataValue('author-link')];
78 $this->redirect_url = Contact::magicLinkbyContact($author);
79 if (!$this->isToplevel()) {
80 $this->threaded = true;
83 // Prepare the children
84 if (!empty($data['children'])) {
85 foreach ($data['children'] as $item) {
86 // Only add will be displayed
87 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
89 } elseif (!visible_activity($item)) {
93 // You can always comment on Diaspora and OStatus items
94 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
95 $item['writable'] = true;
98 $item['pagedrop'] = $data['pagedrop'];
99 $child = new Post($item);
100 $this->addChild($child);
106 * Get data in a form usable by a conversation template
108 * @param object $conv_responses conversation responses
109 * @param integer $thread_level default = 1
111 * @return mixed The data requested on success
114 public function getTemplateData($conv_responses, $thread_level = 1)
120 $item = $this->getData();
122 // If the time between "created" and "edited" differs we add
123 // a notice that the post was edited.
124 // Note: In some networks reshared items seem to have (sometimes) a difference
125 // between creation time and edit time of a second. Thats why we add the notice
126 // only if the difference is more than 1 second.
127 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
129 'label' => L10n::t('This entry was edited'),
130 'date' => DateTimeFormat::local($item['edited'], 'r'),
131 'relative' => Temporal::getRelativeDate($item['edited'])
140 $isstarred = "unstarred";
144 $total_children = $this->countDescendants();
146 $conv = $this->getThread();
148 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
149 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
150 ? L10n::t('Private Message')
153 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
158 if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
159 if ($item["event-id"] != 0) {
160 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
162 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
165 $dropping = in_array($item['uid'], [0, local_user()]);
168 // Editing on items of not subscribed users isn't currently possible
169 // There are some issues on editing that prevent this.
170 // But also it is an issue of the supported protocols that doesn't allow editing at all.
171 if ($item['uid'] == 0) {
175 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
179 $origin = $item['origin'];
182 /// @todo This shouldn't be done as query here, but better during the data creation.
183 // it is now done here, since during the RC phase we shouldn't make to intense changes.
184 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
185 if (DBA::isResult($parent)) {
186 $origin = $parent['origin'];
190 if ($origin && ($item['id'] != $item['parent']) && ($item['network'] == Protocol::ACTIVITYPUB)) {
191 // ActivityPub doesn't allow removal of remote comments
192 $delete = L10n::t('Delete locally');
194 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
195 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
199 'dropping' => $dropping,
200 'pagedrop' => $item['pagedrop'],
201 'select' => L10n::t('Select'),
209 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
211 $profile_name = $item['author-name'];
212 if (!empty($item['author-link']) && empty($item['author-name'])) {
213 $profile_name = $item['author-link'];
216 $author = ['uid' => 0, 'id' => $item['author-id'],
217 'network' => $item['author-network'], 'url' => $item['author-link']];
219 if (local_user() || remote_user()) {
220 $profile_link = Contact::magicLinkbyContact($author);
222 $profile_link = $item['author-link'];
225 if (strpos($profile_link, 'redir/') === 0) {
226 $sparkle = ' sparkle';
229 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
230 Addon::callHooks('render_location', $locate);
231 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
233 // process action responses - e.g. like/dislike/attend/agree/whatever
234 $response_verbs = ['like', 'dislike'];
238 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
239 $response_verbs[] = 'attendyes';
240 $response_verbs[] = 'attendno';
241 $response_verbs[] = 'attendmaybe';
242 if ($conv->isWritable()) {
244 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
248 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
250 foreach ($response_verbs as $value => $verbs) {
251 $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']) : '';
255 * We should avoid doing this all the time, but it depends on the conversation mode
256 * And the conv mode may change when we change the conv, or it changes its mode
257 * Maybe we should establish a way to be notified about conversation changes
259 $this->checkWallToWall();
261 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
262 $osparkle = ' sparkle';
267 if ($this->isToplevel()) {
269 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
270 if (DBA::isResult($thread)) {
272 'do' => L10n::t("ignore thread"),
273 'undo' => L10n::t("unignore thread"),
274 'toggle' => L10n::t("toggle ignore status"),
275 'classdo' => $thread['ignored'] ? "hidden" : "",
276 'classundo' => $thread['ignored'] ? "" : "hidden",
277 'ignored' => L10n::t('ignored'),
281 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
282 $isstarred = (($item['starred']) ? "starred" : "unstarred");
285 'do' => L10n::t("add star"),
286 'undo' => L10n::t("remove star"),
287 'toggle' => L10n::t("toggle star status"),
288 'classdo' => $item['starred'] ? "hidden" : "",
289 'classundo' => $item['starred'] ? "" : "hidden",
290 'starred' => L10n::t('starred'),
294 'add' => L10n::t("add tag"),
303 if ($conv->isWritable()) {
305 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
306 'dislike' => [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")],
309 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
313 $comment = $this->getCommentBox($indent);
315 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
319 localize_item($item);
321 $body = Item::prepareBody($item, true);
323 list($categories, $folders) = get_cats_and_terms($item);
326 $text_e = strip_tags($body);
327 $name_e = $profile_name;
329 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
330 $title_e = ucfirst($item['content-warning']);
332 $title_e = $item['title'];
335 $location_e = $location;
336 $owner_name_e = $this->getOwnerName();
338 // Disable features that aren't available in several networks
339 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
340 unset($buttons["dislike"]);
345 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
346 unset($buttons["like"]);
349 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
350 unset($buttons["like"]);
353 $tags = Term::populateTagsFromItem($item);
356 'template' => $this->getTemplate(),
357 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
358 'suppress_tags' => Config::get('system', 'suppress_tags'),
359 'tags' => $tags['tags'],
360 'hashtags' => $tags['hashtags'],
361 'mentions' => $tags['mentions'],
362 'txt_cats' => L10n::t('Categories:'),
363 'txt_folders' => L10n::t('Filed under:'),
364 'has_cats' => ((count($categories)) ? 'true' : ''),
365 'has_folders' => ((count($folders)) ? 'true' : ''),
366 'categories' => $categories,
367 'folders' => $folders,
370 'id' => $this->getId(),
371 'guid' => urlencode($item['guid']),
372 'isevent' => $isevent,
374 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
375 'olinktitle' => L10n::t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
376 'to' => L10n::t('to'),
377 'via' => L10n::t('via'),
378 'wall' => L10n::t('Wall-to-Wall'),
379 'vwall' => L10n::t('via Wall-To-Wall:'),
380 'profile_url' => $profile_link,
381 'item_photo_menu' => item_photo_menu($item),
383 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
384 'osparkle' => $osparkle,
385 'sparkle' => $sparkle,
387 'localtime' => DateTimeFormat::local($item['created'], 'r'),
388 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
389 'app' => $item['app'],
390 'created' => Temporal::getRelativeDate($item['created']),
392 'location' => $location_e,
395 'owner_url' => $this->getOwnerUrl(),
396 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
397 'owner_name' => $owner_name_e,
398 'plink' => Item::getPlink($item),
400 'isstarred' => $isstarred,
407 'like' => $responses['like']['output'],
408 'dislike' => $responses['dislike']['output'],
409 'responses' => $responses,
410 'switchcomment' => L10n::t('Comment'),
411 'comment' => $comment,
412 'previewing' => $conv->isPreview() ? ' preview ' : '',
413 'wait' => L10n::t('Please wait'),
414 'thread_level' => $thread_level,
416 'network' => $item["network"],
417 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
418 'received' => $item['received'],
419 'commented' => $item['commented'],
420 'created_date' => $item['created'],
421 'return' => ($a->cmd) ? bin2hex($a->cmd) : '',
424 $arr = ['item' => $item, 'output' => $tmp_item];
425 Addon::callHooks('display_item', $arr);
427 $result = $arr['output'];
429 $result['children'] = [];
430 $children = $this->getChildren();
431 $nb_children = count($children);
432 if ($nb_children > 0) {
433 foreach ($children as $child) {
434 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
437 if (($nb_children > 2) || ($thread_level > 1)) {
438 $result['children'][0]['comment_firstcollapsed'] = true;
439 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
440 $result['children'][0]['hidden_comments_num'] = $total_children;
441 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
442 $result['children'][0]['hide_text'] = L10n::t('show more');
443 if ($thread_level > 1) {
444 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
446 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
451 if ($this->isToplevel()) {
452 $result['total_comments_num'] = "$total_children";
453 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
456 $result['private'] = $item['private'];
457 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
459 if ($this->isThreaded()) {
460 $result['flatten'] = false;
461 $result['threaded'] = true;
463 $result['flatten'] = true;
464 $result['threaded'] = false;
473 public function getId()
475 return $this->getDataValue('id');
481 public function isThreaded()
483 return $this->threaded;
489 * @param object $item The child item to add
493 public function addChild(Post $item)
495 $item_id = $item->getId();
497 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
499 } elseif ($this->getChild($item->getId())) {
500 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
504 * Only add what will be displayed
506 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
508 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
512 $item->setParent($this);
513 $this->children[] = $item;
515 return end($this->children);
519 * Get a child by its ID
521 * @param integer $id The child id
525 public function getChild($id)
527 foreach ($this->getChildren() as $child) {
528 if ($child->getId() == $id) {
537 * Get all our children
541 public function getChildren()
543 return $this->children;
549 * @param object $item The item to set as parent
553 protected function setParent($item)
555 $parent = $this->getParent();
557 $parent->removeChild($this);
560 $this->parent = $item;
561 $this->setThread($item->getThread());
569 protected function removeParent()
571 $this->parent = null;
572 $this->thread = null;
578 * @param object $item The child to be removed
580 * @return boolean Success or failure
582 public function removeChild($item)
584 $id = $item->getId();
585 foreach ($this->getChildren() as $key => $child) {
586 if ($child->getId() == $id) {
587 $child->removeParent();
588 unset($this->children[$key]);
589 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
590 $this->children = array_values($this->children);
594 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
603 protected function getParent()
605 return $this->parent;
611 * @param object $conv The conversation
615 public function setThread($conv)
617 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
619 $this->thread = $conv;
621 // Set it on our children too
622 foreach ($this->getChildren() as $child) {
623 $child->setThread($conv);
632 public function getThread()
634 return $this->thread;
640 * We shouldn't need this
644 public function getData()
652 * @param object $name key
654 * @return mixed value on success
657 public function getDataValue($name)
659 if (!isset($this->data[$name])) {
660 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
664 return $this->data[$name];
670 * @param object $name template name
674 private function setTemplate($name)
676 if (empty($this->available_templates[$name])) {
677 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
681 $this->template = $this->available_templates[$name];
689 private function getTemplate()
691 return $this->template;
695 * Check if this is a toplevel post
699 private function isToplevel()
701 return $this->toplevel;
705 * Check if this is writable
709 private function isWritable()
711 $conv = $this->getThread();
714 // This will allow us to comment on wall-to-wall items owned by our friends
715 // and community forums even if somebody else wrote the post.
716 // bug #517 - this fixes for conversation owner
717 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
721 // this fixes for visitors
722 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
724 return $this->writable;
728 * Count the total of our descendants
732 private function countDescendants()
734 $children = $this->getChildren();
735 $total = count($children);
737 foreach ($children as $child) {
738 $total += $child->countDescendants();
746 * Get the template for the comment box
750 private function getCommentBoxTemplate()
752 return $this->comment_box_template;
756 * Get the comment box
758 * @param string $indent Indent value
760 * @return mixed The comment box string (empty if no comment box)
763 private function getCommentBox($indent)
768 $conv = $this->getThread();
770 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
774 if ($conv->isWritable() && $this->isWritable()) {
775 $qc = $qcomment = null;
778 * Hmmm, code depending on the presence of a particular addon?
779 * This should be better if done by a hook
781 if (Addon::isEnabled('qcomment')) {
782 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
783 $qcomment = (($qc) ? explode("\n", $qc) : null);
786 // Fetch the user id from the parent when the owner user is empty
787 $uid = $conv->getProfileOwner();
788 $parent_uid = $this->getDataValue('uid');
790 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
794 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
795 $comment_box = Renderer::replaceMacros($template, [
796 '$return_path' => $a->query_string,
797 '$threaded' => $this->isThreaded(),
799 '$wall' => ($conv->getMode() === 'profile'),
800 '$id' => $this->getId(),
801 '$parent' => $this->getId(),
802 '$qcomment' => $qcomment,
803 '$profile_uid' => $uid,
804 '$mylink' => $a->removeBaseURL($a->contact['url']),
805 '$mytitle' => L10n::t('This is you'),
806 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
807 '$comment' => L10n::t('Comment'),
808 '$submit' => L10n::t('Submit'),
809 '$edbold' => L10n::t('Bold'),
810 '$editalic' => L10n::t('Italic'),
811 '$eduline' => L10n::t('Underline'),
812 '$edquote' => L10n::t('Quote'),
813 '$edcode' => L10n::t('Code'),
814 '$edimg' => L10n::t('Image'),
815 '$edurl' => L10n::t('Link'),
816 '$edattach' => L10n::t('Link or Media'),
817 '$prompttext' => L10n::t('Please enter a image/video/audio/webpage URL:'),
818 '$preview' => L10n::t('Preview'),
819 '$indent' => $indent,
820 '$sourceapp' => L10n::t($a->sourcename),
821 '$ww' => $conv->getMode() === 'network' ? $ww : '',
822 '$rand_num' => Crypto::randomDigits(12)
832 private function getRedirectUrl()
834 return $this->redirect_url;
838 * Check if we are a wall to wall item and set the relevant properties
842 protected function checkWallToWall()
845 $conv = $this->getThread();
846 $this->wall_to_wall = false;
848 if ($this->isToplevel()) {
849 if ($conv->getMode() !== 'profile') {
850 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
851 // On the network page, I am the owner. On the display page it will be the profile owner.
852 // This will have been stored in $a->page_contact by our calling page.
853 // Put this person as the wall owner of the wall-to-wall notice.
855 $this->owner_url = Contact::magicLink($a->page_contact['url']);
856 $this->owner_photo = $a->page_contact['thumb'];
857 $this->owner_name = $a->page_contact['name'];
858 $this->wall_to_wall = true;
859 } elseif ($this->getDataValue('owner-link')) {
860 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
861 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
862 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
864 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
865 // The author url doesn't match the owner (typically the contact)
866 // and also doesn't match the contact alias.
867 // The name match is a hack to catch several weird cases where URLs are
868 // all over the park. It can be tricked, but this prevents you from
869 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
870 // well that it's the same Bob Smith.
871 // But it could be somebody else with the same name. It just isn't highly likely.
874 $this->owner_photo = $this->getDataValue('owner-avatar');
875 $this->owner_name = $this->getDataValue('owner-name');
876 $this->wall_to_wall = true;
878 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
879 'network' => $this->getDataValue('owner-network'),
880 'url' => $this->getDataValue('owner-link')];
881 $this->owner_url = Contact::magicLinkbyContact($owner);
887 if (!$this->wall_to_wall) {
888 $this->setTemplate('wall');
889 $this->owner_url = '';
890 $this->owner_photo = '';
891 $this->owner_name = '';
898 private function isWallToWall()
900 return $this->wall_to_wall;
906 private function getOwnerUrl()
908 return $this->owner_url;
914 private function getOwnerName()
916 return $this->owner_name;
922 private function isVisiting()
924 return $this->visiting;