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\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Term;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Proxy as ProxyUtils;
20 use Friendica\Util\Temporal;
22 require_once 'include/dba.php';
23 require_once 'include/text.php';
24 require_once 'boot.php';
25 require_once 'include/conversation.php';
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 (x($_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'] === NETWORK_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'], [NETWORK_OSTATUS, NETWORK_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;
155 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
156 if ($item["event-id"] != 0) {
157 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
159 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
161 $dropping = in_array($item['uid'], [0, local_user()]);
166 // Editing on items of not subscribed users isn't currently possible
167 // There are some issues on editing that prevent this.
168 // But also it is an issue of the supported protocols that doesn't allow editing at all.
169 if ($item['uid'] == 0) {
173 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
177 $origin = $item['origin'];
180 /// @todo This shouldn't be done as query here, but better during the data creation.
181 // it is now done here, since during the RC phase we shouldn't make to intense changes.
182 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
183 if (DBA::isResult($parent)) {
184 $origin = $parent['origin'];
188 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
189 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
192 'dropping' => $dropping,
193 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
194 'select' => L10n::t('Select'),
198 if (!local_user() || ($item['uid'] == 0)) {
202 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
204 $profile_name = htmlentities($item['author-name']);
205 if (!empty($item['author-link']) && empty($item['author-name'])) {
206 $profile_name = $item['author-link'];
209 $author = ['uid' => 0, 'id' => $item['author-id'],
210 'network' => $item['author-network'], 'url' => $item['author-link']];
211 $profile_link = Contact::magicLinkbyContact($author);
212 if (strpos($profile_link, 'redir/') === 0) {
213 $sparkle = ' sparkle';
216 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
217 Addon::callHooks('render_location', $locate);
218 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
220 // process action responses - e.g. like/dislike/attend/agree/whatever
221 $response_verbs = ['like', 'dislike'];
225 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
226 $response_verbs[] = 'attendyes';
227 $response_verbs[] = 'attendno';
228 $response_verbs[] = 'attendmaybe';
229 if ($conv->isWritable()) {
231 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
235 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
237 foreach ($response_verbs as $value => $verbs) {
238 $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']) : '';
242 * We should avoid doing this all the time, but it depends on the conversation mode
243 * And the conv mode may change when we change the conv, or it changes its mode
244 * Maybe we should establish a way to be notified about conversation changes
246 $this->checkWallToWall();
248 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
249 $osparkle = ' sparkle';
254 if ($this->isToplevel()) {
255 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
256 if (DBA::isResult($thread)) {
258 'do' => L10n::t("ignore thread"),
259 'undo' => L10n::t("unignore thread"),
260 'toggle' => L10n::t("toggle ignore status"),
261 'classdo' => $thread['ignored'] ? "hidden" : "",
262 'classundo' => $thread['ignored'] ? "" : "hidden",
263 'ignored' => L10n::t('ignored'),
267 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
268 $isstarred = (($item['starred']) ? "starred" : "unstarred");
271 'do' => L10n::t("add star"),
272 'undo' => L10n::t("remove star"),
273 'toggle' => L10n::t("toggle star status"),
274 'classdo' => $item['starred'] ? "hidden" : "",
275 'classundo' => $item['starred'] ? "" : "hidden",
276 'starred' => L10n::t('starred'),
279 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
281 'add' => L10n::t("add tag"),
290 if ($conv->isWritable()) {
292 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
293 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
296 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
300 $comment = $this->getCommentBox($indent);
302 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
306 localize_item($item);
308 $body = prepare_body($item, true);
310 list($categories, $folders) = get_cats_and_terms($item);
313 $text_e = strip_tags($body);
314 $name_e = $profile_name;
316 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
317 $title_e = ucfirst($item['content-warning']);
319 $title_e = $item['title'];
322 $location_e = $location;
323 $owner_name_e = $this->getOwnerName();
325 // Disable features that aren't available in several networks
326 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
327 unset($buttons["dislike"]);
332 if (($item["network"] == NETWORK_FEED) && isset($buttons["like"])) {
333 unset($buttons["like"]);
336 if (($item["network"] == NETWORK_MAIL) && isset($buttons["like"])) {
337 unset($buttons["like"]);
340 $tags = Term::populateTagsFromItem($item);
343 'template' => $this->getTemplate(),
344 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
345 'suppress_tags' => Config::get('system', 'suppress_tags'),
346 'tags' => $tags['tags'],
347 'hashtags' => $tags['hashtags'],
348 'mentions' => $tags['mentions'],
349 'txt_cats' => L10n::t('Categories:'),
350 'txt_folders' => L10n::t('Filed under:'),
351 'has_cats' => ((count($categories)) ? 'true' : ''),
352 'has_folders' => ((count($folders)) ? 'true' : ''),
353 'categories' => $categories,
354 'folders' => $folders,
357 'id' => $this->getId(),
358 'guid' => urlencode($item['guid']),
359 'isevent' => $isevent,
361 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
362 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), $item['owner-link']),
363 'to' => L10n::t('to'),
364 'via' => L10n::t('via'),
365 'wall' => L10n::t('Wall-to-Wall'),
366 'vwall' => L10n::t('via Wall-To-Wall:'),
367 'profile_url' => $profile_link,
368 'item_photo_menu' => item_photo_menu($item),
370 'thumb' => $a->remove_baseurl(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
371 'osparkle' => $osparkle,
372 'sparkle' => $sparkle,
374 'localtime' => DateTimeFormat::local($item['created'], 'r'),
375 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
376 'app' => $item['app'],
377 'created' => Temporal::getRelativeDate($item['created']),
379 'location' => $location_e,
382 'owner_url' => $this->getOwnerUrl(),
383 'owner_photo' => $a->remove_baseurl(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
384 'owner_name' => htmlentities($owner_name_e),
385 'plink' => get_plink($item),
386 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
387 'isstarred' => $isstarred,
388 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
389 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
391 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
394 'like' => $responses['like']['output'],
395 'dislike' => $responses['dislike']['output'],
396 'responses' => $responses,
397 'switchcomment' => L10n::t('Comment'),
398 'comment' => $comment,
399 'previewing' => $conv->isPreview() ? ' preview ' : '',
400 'wait' => L10n::t('Please wait'),
401 'thread_level' => $thread_level,
403 'network' => $item["network"],
404 'network_name' => ContactSelector::networkToName($item['network'], $profile_link),
405 'received' => $item['received'],
406 'commented' => $item['commented'],
407 'created_date' => $item['created'],
410 $arr = ['item' => $item, 'output' => $tmp_item];
411 Addon::callHooks('display_item', $arr);
413 $result = $arr['output'];
415 $result['children'] = [];
416 $children = $this->getChildren();
417 $nb_children = count($children);
418 if ($nb_children > 0) {
419 foreach ($children as $child) {
420 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
423 if (($nb_children > 2) || ($thread_level > 1)) {
424 $result['children'][0]['comment_firstcollapsed'] = true;
425 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
426 $result['children'][0]['hidden_comments_num'] = $total_children;
427 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
428 $result['children'][0]['hide_text'] = L10n::t('show more');
429 if ($thread_level > 1) {
430 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
432 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
437 if ($this->isToplevel()) {
438 $result['total_comments_num'] = "$total_children";
439 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
442 $result['private'] = $item['private'];
443 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
445 if ($this->isThreaded()) {
446 $result['flatten'] = false;
447 $result['threaded'] = true;
449 $result['flatten'] = true;
450 $result['threaded'] = false;
459 public function getId()
461 return $this->getDataValue('id');
467 public function isThreaded()
469 return $this->threaded;
475 * @param object $item The child item to add
479 public function addChild(Post $item)
481 $item_id = $item->getId();
483 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
485 } elseif ($this->getChild($item->getId())) {
486 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
490 * Only add what will be displayed
492 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
494 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
498 $item->setParent($this);
499 $this->children[] = $item;
501 return end($this->children);
505 * Get a child by its ID
507 * @param integer $id The child id
511 public function getChild($id)
513 foreach ($this->getChildren() as $child) {
514 if ($child->getId() == $id) {
523 * Get all our children
527 public function getChildren()
529 return $this->children;
535 * @param object $item The item to set as parent
539 protected function setParent($item)
541 $parent = $this->getParent();
543 $parent->removeChild($this);
546 $this->parent = $item;
547 $this->setThread($item->getThread());
555 protected function removeParent()
557 $this->parent = null;
558 $this->thread = null;
564 * @param object $item The child to be removed
566 * @return boolean Success or failure
568 public function removeChild($item)
570 $id = $item->getId();
571 foreach ($this->getChildren() as $key => $child) {
572 if ($child->getId() == $id) {
573 $child->removeParent();
574 unset($this->children[$key]);
575 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
576 $this->children = array_values($this->children);
580 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
589 protected function getParent()
591 return $this->parent;
597 * @param object $conv The conversation
601 public function setThread($conv)
603 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
605 $this->thread = $conv;
607 // Set it on our children too
608 foreach ($this->getChildren() as $child) {
609 $child->setThread($conv);
618 public function getThread()
620 return $this->thread;
626 * We shouldn't need this
630 public function getData()
638 * @param object $name key
640 * @return mixed value on success
643 public function getDataValue($name)
645 if (!isset($this->data[$name])) {
646 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
650 return $this->data[$name];
656 * @param object $name template name
660 private function setTemplate($name)
662 if (!x($this->available_templates, $name)) {
663 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
667 $this->template = $this->available_templates[$name];
675 private function getTemplate()
677 return $this->template;
681 * Check if this is a toplevel post
685 private function isToplevel()
687 return $this->toplevel;
691 * Check if this is writable
695 private function isWritable()
697 $conv = $this->getThread();
700 // This will allow us to comment on wall-to-wall items owned by our friends
701 // and community forums even if somebody else wrote the post.
702 // bug #517 - this fixes for conversation owner
703 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
707 // this fixes for visitors
708 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
710 return $this->writable;
714 * Count the total of our descendants
718 private function countDescendants()
720 $children = $this->getChildren();
721 $total = count($children);
723 foreach ($children as $child) {
724 $total += $child->countDescendants();
732 * Get the template for the comment box
736 private function getCommentBoxTemplate()
738 return $this->comment_box_template;
742 * Get the comment box
744 * @param string $indent Indent value
746 * @return mixed The comment box string (empty if no comment box)
749 private function getCommentBox($indent)
754 $conv = $this->getThread();
756 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
760 if ($conv->isWritable() && $this->isWritable()) {
761 $qc = $qcomment = null;
764 * Hmmm, code depending on the presence of a particular addon?
765 * This should be better if done by a hook
767 if (in_array('qcomment', $a->addons)) {
768 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
769 $qcomment = (($qc) ? explode("\n", $qc) : null);
772 // Fetch the user id from the parent when the owner user is empty
773 $uid = $conv->getProfileOwner();
774 $parent_uid = $this->getDataValue('uid');
776 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
780 $template = get_markup_template($this->getCommentBoxTemplate());
781 $comment_box = replace_macros($template, [
782 '$return_path' => $a->query_string,
783 '$threaded' => $this->isThreaded(),
785 '$wall' => ($conv->getMode() === 'profile'),
786 '$id' => $this->getId(),
787 '$parent' => $this->getId(),
788 '$qcomment' => $qcomment,
789 '$profile_uid' => $uid,
790 '$mylink' => $a->remove_baseurl($a->contact['url']),
791 '$mytitle' => L10n::t('This is you'),
792 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
793 '$comment' => L10n::t('Comment'),
794 '$submit' => L10n::t('Submit'),
795 '$edbold' => L10n::t('Bold'),
796 '$editalic' => L10n::t('Italic'),
797 '$eduline' => L10n::t('Underline'),
798 '$edquote' => L10n::t('Quote'),
799 '$edcode' => L10n::t('Code'),
800 '$edimg' => L10n::t('Image'),
801 '$edurl' => L10n::t('Link'),
802 '$edvideo' => L10n::t('Video'),
803 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
804 '$indent' => $indent,
805 '$sourceapp' => L10n::t($a->sourcename),
806 '$ww' => $conv->getMode() === 'network' ? $ww : '',
807 '$rand_num' => random_digits(12)
817 private function getRedirectUrl()
819 return $this->redirect_url;
823 * Check if we are a wall to wall item and set the relevant properties
827 protected function checkWallToWall()
830 $conv = $this->getThread();
831 $this->wall_to_wall = false;
833 if ($this->isToplevel()) {
834 if ($conv->getMode() !== 'profile') {
835 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
836 // On the network page, I am the owner. On the display page it will be the profile owner.
837 // This will have been stored in $a->page_contact by our calling page.
838 // Put this person as the wall owner of the wall-to-wall notice.
840 $this->owner_url = Contact::magicLink($a->page_contact['url']);
841 $this->owner_photo = $a->page_contact['thumb'];
842 $this->owner_name = $a->page_contact['name'];
843 $this->wall_to_wall = true;
844 } elseif ($this->getDataValue('owner-link')) {
845 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
846 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
847 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
849 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
850 // The author url doesn't match the owner (typically the contact)
851 // and also doesn't match the contact alias.
852 // The name match is a hack to catch several weird cases where URLs are
853 // all over the park. It can be tricked, but this prevents you from
854 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
855 // well that it's the same Bob Smith.
856 // But it could be somebody else with the same name. It just isn't highly likely.
859 $this->owner_photo = $this->getDataValue('owner-avatar');
860 $this->owner_name = $this->getDataValue('owner-name');
861 $this->wall_to_wall = true;
863 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
864 'network' => $this->getDataValue('owner-network'),
865 'url' => $this->getDataValue('owner-link')];
866 $this->owner_url = Contact::magicLinkbyContact($owner);
872 if (!$this->wall_to_wall) {
873 $this->setTemplate('wall');
874 $this->owner_url = '';
875 $this->owner_photo = '';
876 $this->owner_name = '';
883 private function isWallToWall()
885 return $this->wall_to_wall;
891 private function getOwnerUrl()
893 return $this->owner_url;
899 private function getOwnerName()
901 return $this->owner_name;
907 private function isVisiting()
909 return $this->visiting;