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\PConfig;
14 use Friendica\Core\Protocol;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Item;
18 use Friendica\Model\Term;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Proxy as ProxyUtils;
21 use Friendica\Util\Temporal;
23 require_once 'include/dba.php';
24 require_once 'include/text.php';
25 require_once 'boot.php';
26 require_once 'include/conversation.php';
31 class Post extends BaseObject
34 private $template = null;
35 private $available_templates = [
36 'wall' => 'wall_thread.tpl',
37 'wall2wall' => 'wallwall_thread.tpl'
39 private $comment_box_template = 'comment_item.tpl';
40 private $toplevel = false;
41 private $writable = false;
42 private $children = [];
43 private $parent = null;
44 private $thread = null;
45 private $redirect_url = null;
46 private $owner_url = '';
47 private $owner_photo = '';
48 private $owner_name = '';
49 private $wall_to_wall = false;
50 private $threaded = false;
51 private $visiting = false;
56 * @param array $data data array
58 public function __construct(array $data)
63 $this->setTemplate('wall');
64 $this->toplevel = $this->getId() == $this->getDataValue('parent');
66 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
67 foreach ($_SESSION['remote'] as $visitor) {
68 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
69 $this->visiting = true;
75 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
76 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
77 'network' => $this->getDataValue('author-network'),
78 'url' => $this->getDataValue('author-link')];
79 $this->redirect_url = Contact::magicLinkbyContact($author);
80 if (!$this->isToplevel()) {
81 $this->threaded = true;
84 // Prepare the children
85 if (!empty($data['children'])) {
86 foreach ($data['children'] as $item) {
87 // Only add will be displayed
88 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
90 } elseif (!visible_activity($item)) {
94 // You can always comment on Diaspora and OStatus items
95 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
96 $item['writable'] = true;
99 $item['pagedrop'] = $data['pagedrop'];
100 $child = new Post($item);
101 $this->addChild($child);
107 * Get data in a form usable by a conversation template
109 * @param object $conv_responses conversation responses
110 * @param integer $thread_level default = 1
112 * @return mixed The data requested on success
115 public function getTemplateData($conv_responses, $thread_level = 1)
121 $item = $this->getData();
123 // If the time between "created" and "edited" differs we add
124 // a notice that the post was edited.
125 // Note: In some networks reshared items seem to have (sometimes) a difference
126 // between creation time and edit time of a second. Thats why we add the notice
127 // only if the difference is more than 1 second.
128 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
130 'label' => L10n::t('This entry was edited'),
131 'date' => DateTimeFormat::local($item['edited'], 'r'),
132 'relative' => Temporal::getRelativeDate($item['edited'])
141 $isstarred = "unstarred";
145 $total_children = $this->countDescendants();
147 $conv = $this->getThread();
149 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
150 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
151 ? L10n::t('Private Message')
154 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
156 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
157 if ($item["event-id"] != 0) {
158 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
160 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
162 $dropping = in_array($item['uid'], [0, local_user()]);
167 // Editing on items of not subscribed users isn't currently possible
168 // There are some issues on editing that prevent this.
169 // But also it is an issue of the supported protocols that doesn't allow editing at all.
170 if ($item['uid'] == 0) {
174 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
178 $origin = $item['origin'];
181 /// @todo This shouldn't be done as query here, but better during the data creation.
182 // it is now done here, since during the RC phase we shouldn't make to intense changes.
183 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
184 if (DBA::isResult($parent)) {
185 $origin = $parent['origin'];
189 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
190 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
193 'dropping' => $dropping,
194 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
195 'select' => L10n::t('Select'),
199 if (!local_user() || ($item['uid'] == 0)) {
203 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
205 $profile_name = htmlentities($item['author-name']);
206 if (!empty($item['author-link']) && empty($item['author-name'])) {
207 $profile_name = $item['author-link'];
210 $author = ['uid' => 0, 'id' => $item['author-id'],
211 'network' => $item['author-network'], 'url' => $item['author-link']];
213 if (local_user() || remote_user()) {
214 $profile_link = Contact::magicLinkbyContact($author);
216 $profile_link = $item['author-link'];
219 if (strpos($profile_link, 'redir/') === 0) {
220 $sparkle = ' sparkle';
223 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
224 Addon::callHooks('render_location', $locate);
225 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
227 // process action responses - e.g. like/dislike/attend/agree/whatever
228 $response_verbs = ['like', 'dislike'];
232 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
233 $response_verbs[] = 'attendyes';
234 $response_verbs[] = 'attendno';
235 $response_verbs[] = 'attendmaybe';
236 if ($conv->isWritable()) {
238 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
242 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
244 foreach ($response_verbs as $value => $verbs) {
245 $responses[$verbs]['output'] = x($conv_responses[$verbs], $item['uri']) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '';
249 * We should avoid doing this all the time, but it depends on the conversation mode
250 * And the conv mode may change when we change the conv, or it changes its mode
251 * Maybe we should establish a way to be notified about conversation changes
253 $this->checkWallToWall();
255 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
256 $osparkle = ' sparkle';
261 if ($this->isToplevel()) {
262 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
263 if (DBA::isResult($thread)) {
265 'do' => L10n::t("ignore thread"),
266 'undo' => L10n::t("unignore thread"),
267 'toggle' => L10n::t("toggle ignore status"),
268 'classdo' => $thread['ignored'] ? "hidden" : "",
269 'classundo' => $thread['ignored'] ? "" : "hidden",
270 'ignored' => L10n::t('ignored'),
274 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
275 $isstarred = (($item['starred']) ? "starred" : "unstarred");
278 'do' => L10n::t("add star"),
279 'undo' => L10n::t("remove star"),
280 'toggle' => L10n::t("toggle star status"),
281 'classdo' => $item['starred'] ? "hidden" : "",
282 'classundo' => $item['starred'] ? "" : "hidden",
283 'starred' => L10n::t('starred'),
286 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
288 'add' => L10n::t("add tag"),
297 if ($conv->isWritable()) {
299 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
300 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
303 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
307 $comment = $this->getCommentBox($indent);
309 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
313 localize_item($item);
315 $body = prepare_body($item, true);
317 list($categories, $folders) = get_cats_and_terms($item);
320 $text_e = strip_tags($body);
321 $name_e = $profile_name;
323 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
324 $title_e = ucfirst($item['content-warning']);
326 $title_e = $item['title'];
329 $location_e = $location;
330 $owner_name_e = $this->getOwnerName();
332 // Disable features that aren't available in several networks
333 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
334 unset($buttons["dislike"]);
339 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
340 unset($buttons["like"]);
343 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
344 unset($buttons["like"]);
347 $tags = Term::populateTagsFromItem($item);
350 'template' => $this->getTemplate(),
351 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
352 'suppress_tags' => Config::get('system', 'suppress_tags'),
353 'tags' => $tags['tags'],
354 'hashtags' => $tags['hashtags'],
355 'mentions' => $tags['mentions'],
356 'txt_cats' => L10n::t('Categories:'),
357 'txt_folders' => L10n::t('Filed under:'),
358 'has_cats' => ((count($categories)) ? 'true' : ''),
359 'has_folders' => ((count($folders)) ? 'true' : ''),
360 'categories' => $categories,
361 'folders' => $folders,
364 'id' => $this->getId(),
365 'guid' => urlencode($item['guid']),
366 'isevent' => $isevent,
368 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
369 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), $item['owner-link']),
370 'to' => L10n::t('to'),
371 'via' => L10n::t('via'),
372 'wall' => L10n::t('Wall-to-Wall'),
373 'vwall' => L10n::t('via Wall-To-Wall:'),
374 'profile_url' => $profile_link,
375 'item_photo_menu' => item_photo_menu($item),
377 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
378 'osparkle' => $osparkle,
379 'sparkle' => $sparkle,
381 'localtime' => DateTimeFormat::local($item['created'], 'r'),
382 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
383 'app' => $item['app'],
384 'created' => Temporal::getRelativeDate($item['created']),
386 'location' => $location_e,
389 'owner_url' => $this->getOwnerUrl(),
390 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
391 'owner_name' => htmlentities($owner_name_e),
392 'plink' => get_plink($item),
393 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
394 'isstarred' => $isstarred,
395 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
396 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
398 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
401 'like' => $responses['like']['output'],
402 'dislike' => $responses['dislike']['output'],
403 'responses' => $responses,
404 'switchcomment' => L10n::t('Comment'),
405 'comment' => $comment,
406 'previewing' => $conv->isPreview() ? ' preview ' : '',
407 'wait' => L10n::t('Please wait'),
408 'thread_level' => $thread_level,
410 'network' => $item["network"],
411 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
412 'received' => $item['received'],
413 'commented' => $item['commented'],
414 'created_date' => $item['created'],
417 $arr = ['item' => $item, 'output' => $tmp_item];
418 Addon::callHooks('display_item', $arr);
420 $result = $arr['output'];
422 $result['children'] = [];
423 $children = $this->getChildren();
424 $nb_children = count($children);
425 if ($nb_children > 0) {
426 foreach ($children as $child) {
427 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
430 if (($nb_children > 2) || ($thread_level > 1)) {
431 $result['children'][0]['comment_firstcollapsed'] = true;
432 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
433 $result['children'][0]['hidden_comments_num'] = $total_children;
434 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
435 $result['children'][0]['hide_text'] = L10n::t('show more');
436 if ($thread_level > 1) {
437 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
439 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
444 if ($this->isToplevel()) {
445 $result['total_comments_num'] = "$total_children";
446 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
449 $result['private'] = $item['private'];
450 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
452 if ($this->isThreaded()) {
453 $result['flatten'] = false;
454 $result['threaded'] = true;
456 $result['flatten'] = true;
457 $result['threaded'] = false;
466 public function getId()
468 return $this->getDataValue('id');
474 public function isThreaded()
476 return $this->threaded;
482 * @param object $item The child item to add
486 public function addChild(Post $item)
488 $item_id = $item->getId();
490 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
492 } elseif ($this->getChild($item->getId())) {
493 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
497 * Only add what will be displayed
499 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
501 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
505 $item->setParent($this);
506 $this->children[] = $item;
508 return end($this->children);
512 * Get a child by its ID
514 * @param integer $id The child id
518 public function getChild($id)
520 foreach ($this->getChildren() as $child) {
521 if ($child->getId() == $id) {
530 * Get all our children
534 public function getChildren()
536 return $this->children;
542 * @param object $item The item to set as parent
546 protected function setParent($item)
548 $parent = $this->getParent();
550 $parent->removeChild($this);
553 $this->parent = $item;
554 $this->setThread($item->getThread());
562 protected function removeParent()
564 $this->parent = null;
565 $this->thread = null;
571 * @param object $item The child to be removed
573 * @return boolean Success or failure
575 public function removeChild($item)
577 $id = $item->getId();
578 foreach ($this->getChildren() as $key => $child) {
579 if ($child->getId() == $id) {
580 $child->removeParent();
581 unset($this->children[$key]);
582 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
583 $this->children = array_values($this->children);
587 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
596 protected function getParent()
598 return $this->parent;
604 * @param object $conv The conversation
608 public function setThread($conv)
610 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
612 $this->thread = $conv;
614 // Set it on our children too
615 foreach ($this->getChildren() as $child) {
616 $child->setThread($conv);
625 public function getThread()
627 return $this->thread;
633 * We shouldn't need this
637 public function getData()
645 * @param object $name key
647 * @return mixed value on success
650 public function getDataValue($name)
652 if (!isset($this->data[$name])) {
653 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
657 return $this->data[$name];
663 * @param object $name template name
667 private function setTemplate($name)
669 if (!x($this->available_templates, $name)) {
670 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
674 $this->template = $this->available_templates[$name];
682 private function getTemplate()
684 return $this->template;
688 * Check if this is a toplevel post
692 private function isToplevel()
694 return $this->toplevel;
698 * Check if this is writable
702 private function isWritable()
704 $conv = $this->getThread();
707 // This will allow us to comment on wall-to-wall items owned by our friends
708 // and community forums even if somebody else wrote the post.
709 // bug #517 - this fixes for conversation owner
710 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
714 // this fixes for visitors
715 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
717 return $this->writable;
721 * Count the total of our descendants
725 private function countDescendants()
727 $children = $this->getChildren();
728 $total = count($children);
730 foreach ($children as $child) {
731 $total += $child->countDescendants();
739 * Get the template for the comment box
743 private function getCommentBoxTemplate()
745 return $this->comment_box_template;
749 * Get the comment box
751 * @param string $indent Indent value
753 * @return mixed The comment box string (empty if no comment box)
756 private function getCommentBox($indent)
761 $conv = $this->getThread();
763 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
767 if ($conv->isWritable() && $this->isWritable()) {
768 $qc = $qcomment = null;
771 * Hmmm, code depending on the presence of a particular addon?
772 * This should be better if done by a hook
774 if (Addon::isEnabled('qcomment')) {
775 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
776 $qcomment = (($qc) ? explode("\n", $qc) : null);
779 // Fetch the user id from the parent when the owner user is empty
780 $uid = $conv->getProfileOwner();
781 $parent_uid = $this->getDataValue('uid');
783 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
787 $template = get_markup_template($this->getCommentBoxTemplate());
788 $comment_box = replace_macros($template, [
789 '$return_path' => $a->query_string,
790 '$threaded' => $this->isThreaded(),
792 '$wall' => ($conv->getMode() === 'profile'),
793 '$id' => $this->getId(),
794 '$parent' => $this->getId(),
795 '$qcomment' => $qcomment,
796 '$profile_uid' => $uid,
797 '$mylink' => $a->removeBaseURL($a->contact['url']),
798 '$mytitle' => L10n::t('This is you'),
799 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
800 '$comment' => L10n::t('Comment'),
801 '$submit' => L10n::t('Submit'),
802 '$edbold' => L10n::t('Bold'),
803 '$editalic' => L10n::t('Italic'),
804 '$eduline' => L10n::t('Underline'),
805 '$edquote' => L10n::t('Quote'),
806 '$edcode' => L10n::t('Code'),
807 '$edimg' => L10n::t('Image'),
808 '$edurl' => L10n::t('Link'),
809 '$edvideo' => L10n::t('Video'),
810 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
811 '$indent' => $indent,
812 '$sourceapp' => L10n::t($a->sourcename),
813 '$ww' => $conv->getMode() === 'network' ? $ww : '',
814 '$rand_num' => random_digits(12)
824 private function getRedirectUrl()
826 return $this->redirect_url;
830 * Check if we are a wall to wall item and set the relevant properties
834 protected function checkWallToWall()
837 $conv = $this->getThread();
838 $this->wall_to_wall = false;
840 if ($this->isToplevel()) {
841 if ($conv->getMode() !== 'profile') {
842 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
843 // On the network page, I am the owner. On the display page it will be the profile owner.
844 // This will have been stored in $a->page_contact by our calling page.
845 // Put this person as the wall owner of the wall-to-wall notice.
847 $this->owner_url = Contact::magicLink($a->page_contact['url']);
848 $this->owner_photo = $a->page_contact['thumb'];
849 $this->owner_name = $a->page_contact['name'];
850 $this->wall_to_wall = true;
851 } elseif ($this->getDataValue('owner-link')) {
852 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
853 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
854 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
856 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
857 // The author url doesn't match the owner (typically the contact)
858 // and also doesn't match the contact alias.
859 // The name match is a hack to catch several weird cases where URLs are
860 // all over the park. It can be tricked, but this prevents you from
861 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
862 // well that it's the same Bob Smith.
863 // But it could be somebody else with the same name. It just isn't highly likely.
866 $this->owner_photo = $this->getDataValue('owner-avatar');
867 $this->owner_name = $this->getDataValue('owner-name');
868 $this->wall_to_wall = true;
870 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
871 'network' => $this->getDataValue('owner-network'),
872 'url' => $this->getDataValue('owner-link')];
873 $this->owner_url = Contact::magicLinkbyContact($owner);
879 if (!$this->wall_to_wall) {
880 $this->setTemplate('wall');
881 $this->owner_url = '';
882 $this->owner_photo = '';
883 $this->owner_name = '';
890 private function isWallToWall()
892 return $this->wall_to_wall;
898 private function getOwnerUrl()
900 return $this->owner_url;
906 private function getOwnerName()
908 return $this->owner_name;
914 private function isVisiting()
916 return $this->visiting;