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;
27 require_once 'include/dba.php';
28 require_once 'include/text.php';
29 require_once 'boot.php';
30 require_once 'include/conversation.php';
35 class Post extends BaseObject
38 private $template = null;
39 private $available_templates = [
40 'wall' => 'wall_thread.tpl',
41 'wall2wall' => 'wallwall_thread.tpl'
43 private $comment_box_template = 'comment_item.tpl';
44 private $toplevel = false;
45 private $writable = false;
46 private $children = [];
47 private $parent = null;
48 private $thread = null;
49 private $redirect_url = null;
50 private $owner_url = '';
51 private $owner_photo = '';
52 private $owner_name = '';
53 private $wall_to_wall = false;
54 private $threaded = false;
55 private $visiting = false;
60 * @param array $data data array
62 public function __construct(array $data)
67 $this->setTemplate('wall');
68 $this->toplevel = $this->getId() == $this->getDataValue('parent');
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;
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;
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']) {
94 } elseif (!visible_activity($item)) {
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;
103 $item['pagedrop'] = $data['pagedrop'];
104 $child = new Post($item);
105 $this->addChild($child);
111 * Get data in a form usable by a conversation template
113 * @param object $conv_responses conversation responses
114 * @param integer $thread_level default = 1
116 * @return mixed The data requested on success
119 public function getTemplateData($conv_responses, $thread_level = 1)
125 $item = $this->getData();
127 // If the time between "created" and "edited" differs we add
128 // a notice that the post was edited.
129 // Note: In some networks reshared items seem to have (sometimes) a difference
130 // between creation time and edit time of a second. Thats why we add the notice
131 // only if the difference is more than 1 second.
132 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
134 'label' => L10n::t('This entry was edited'),
135 'date' => DateTimeFormat::local($item['edited'], 'r'),
136 'relative' => Temporal::getRelativeDate($item['edited'])
145 $isstarred = "unstarred";
149 $total_children = $this->countDescendants();
151 $conv = $this->getThread();
153 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
154 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
155 ? L10n::t('Private Message')
158 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
163 if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
164 if ($item["event-id"] != 0) {
165 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
167 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
170 $dropping = in_array($item['uid'], [0, local_user()]);
173 // Editing on items of not subscribed users isn't currently possible
174 // There are some issues on editing that prevent this.
175 // But also it is an issue of the supported protocols that doesn't allow editing at all.
176 if ($item['uid'] == 0) {
180 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
184 $origin = $item['origin'];
187 /// @todo This shouldn't be done as query here, but better during the data creation.
188 // it is now done here, since during the RC phase we shouldn't make to intense changes.
189 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
190 if (DBA::isResult($parent)) {
191 $origin = $parent['origin'];
195 if ($origin && ($item['id'] != $item['parent']) && ($item['network'] == Protocol::ACTIVITYPUB)) {
196 // ActivityPub doesn't allow removal of remote comments
197 $delete = L10n::t('Delete locally');
199 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
200 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
204 'dropping' => $dropping,
205 'pagedrop' => $item['pagedrop'],
206 'select' => L10n::t('Select'),
214 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
216 $profile_name = $item['author-name'];
217 if (!empty($item['author-link']) && empty($item['author-name'])) {
218 $profile_name = $item['author-link'];
221 $author = ['uid' => 0, 'id' => $item['author-id'],
222 'network' => $item['author-network'], 'url' => $item['author-link']];
224 if (local_user() || remote_user()) {
225 $profile_link = Contact::magicLinkbyContact($author);
227 $profile_link = $item['author-link'];
230 if (strpos($profile_link, 'redir/') === 0) {
231 $sparkle = ' sparkle';
234 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
235 Addon::callHooks('render_location', $locate);
236 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
238 // process action responses - e.g. like/dislike/attend/agree/whatever
239 $response_verbs = ['like', 'dislike'];
243 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
244 $response_verbs[] = 'attendyes';
245 $response_verbs[] = 'attendno';
246 $response_verbs[] = 'attendmaybe';
247 if ($conv->isWritable()) {
249 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
253 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
255 foreach ($response_verbs as $value => $verbs) {
256 $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']) : '';
260 * We should avoid doing this all the time, but it depends on the conversation mode
261 * And the conv mode may change when we change the conv, or it changes its mode
262 * Maybe we should establish a way to be notified about conversation changes
264 $this->checkWallToWall();
266 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
267 $osparkle = ' sparkle';
272 if ($this->isToplevel()) {
274 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
275 if (DBA::isResult($thread)) {
277 'do' => L10n::t("ignore thread"),
278 'undo' => L10n::t("unignore thread"),
279 'toggle' => L10n::t("toggle ignore status"),
280 'classdo' => $thread['ignored'] ? "hidden" : "",
281 'classundo' => $thread['ignored'] ? "" : "hidden",
282 'ignored' => L10n::t('ignored'),
286 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
287 $isstarred = (($item['starred']) ? "starred" : "unstarred");
290 'do' => L10n::t("add star"),
291 'undo' => L10n::t("remove star"),
292 'toggle' => L10n::t("toggle star status"),
293 'classdo' => $item['starred'] ? "hidden" : "",
294 'classundo' => $item['starred'] ? "" : "hidden",
295 'starred' => L10n::t('starred'),
299 'add' => L10n::t("add tag"),
308 if ($conv->isWritable()) {
310 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
311 'dislike' => [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")],
314 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
318 $comment = $this->getCommentBox($indent);
320 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
324 localize_item($item);
326 $body = Item::prepareBody($item, true);
328 list($categories, $folders) = get_cats_and_terms($item);
331 $text_e = strip_tags($body);
332 $name_e = $profile_name;
334 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
335 $title_e = ucfirst($item['content-warning']);
337 $title_e = $item['title'];
340 $location_e = $location;
341 $owner_name_e = $this->getOwnerName();
343 // Disable features that aren't available in several networks
344 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
345 unset($buttons["dislike"]);
350 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
351 unset($buttons["like"]);
354 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
355 unset($buttons["like"]);
358 $tags = Term::populateTagsFromItem($item);
361 'template' => $this->getTemplate(),
362 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
363 'suppress_tags' => Config::get('system', 'suppress_tags'),
364 'tags' => $tags['tags'],
365 'hashtags' => $tags['hashtags'],
366 'mentions' => $tags['mentions'],
367 'txt_cats' => L10n::t('Categories:'),
368 'txt_folders' => L10n::t('Filed under:'),
369 'has_cats' => ((count($categories)) ? 'true' : ''),
370 'has_folders' => ((count($folders)) ? 'true' : ''),
371 'categories' => $categories,
372 'folders' => $folders,
375 'id' => $this->getId(),
376 'guid' => urlencode($item['guid']),
377 'isevent' => $isevent,
379 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
380 'olinktitle' => L10n::t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
381 'to' => L10n::t('to'),
382 'via' => L10n::t('via'),
383 'wall' => L10n::t('Wall-to-Wall'),
384 'vwall' => L10n::t('via Wall-To-Wall:'),
385 'profile_url' => $profile_link,
386 'item_photo_menu' => item_photo_menu($item),
388 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
389 'osparkle' => $osparkle,
390 'sparkle' => $sparkle,
392 'localtime' => DateTimeFormat::local($item['created'], 'r'),
393 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
394 'app' => $item['app'],
395 'created' => Temporal::getRelativeDate($item['created']),
397 'location' => $location_e,
400 'owner_url' => $this->getOwnerUrl(),
401 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
402 'owner_name' => $owner_name_e,
403 'plink' => Item::getPlink($item),
405 'isstarred' => $isstarred,
412 'like' => $responses['like']['output'],
413 'dislike' => $responses['dislike']['output'],
414 'responses' => $responses,
415 'switchcomment' => L10n::t('Comment'),
416 'comment' => $comment,
417 'previewing' => $conv->isPreview() ? ' preview ' : '',
418 'wait' => L10n::t('Please wait'),
419 'thread_level' => $thread_level,
421 'network' => $item["network"],
422 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
423 'received' => $item['received'],
424 'commented' => $item['commented'],
425 'created_date' => $item['created'],
426 'return' => ($a->cmd) ? bin2hex($a->cmd) : '',
429 $arr = ['item' => $item, 'output' => $tmp_item];
430 Addon::callHooks('display_item', $arr);
432 $result = $arr['output'];
434 $result['children'] = [];
435 $children = $this->getChildren();
436 $nb_children = count($children);
437 if ($nb_children > 0) {
438 foreach ($children as $child) {
439 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
442 if (($nb_children > 2) || ($thread_level > 1)) {
443 $result['children'][0]['comment_firstcollapsed'] = true;
444 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
445 $result['children'][0]['hidden_comments_num'] = $total_children;
446 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
447 $result['children'][0]['hide_text'] = L10n::t('show more');
448 if ($thread_level > 1) {
449 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
451 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
456 if ($this->isToplevel()) {
457 $result['total_comments_num'] = "$total_children";
458 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
461 $result['private'] = $item['private'];
462 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
464 if ($this->isThreaded()) {
465 $result['flatten'] = false;
466 $result['threaded'] = true;
468 $result['flatten'] = true;
469 $result['threaded'] = false;
478 public function getId()
480 return $this->getDataValue('id');
486 public function isThreaded()
488 return $this->threaded;
494 * @param object $item The child item to add
498 public function addChild(Post $item)
500 $item_id = $item->getId();
502 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
504 } elseif ($this->getChild($item->getId())) {
505 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
509 * Only add what will be displayed
511 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
513 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
517 $item->setParent($this);
518 $this->children[] = $item;
520 return end($this->children);
524 * Get a child by its ID
526 * @param integer $id The child id
530 public function getChild($id)
532 foreach ($this->getChildren() as $child) {
533 if ($child->getId() == $id) {
542 * Get all our children
546 public function getChildren()
548 return $this->children;
554 * @param object $item The item to set as parent
558 protected function setParent($item)
560 $parent = $this->getParent();
562 $parent->removeChild($this);
565 $this->parent = $item;
566 $this->setThread($item->getThread());
574 protected function removeParent()
576 $this->parent = null;
577 $this->thread = null;
583 * @param object $item The child to be removed
585 * @return boolean Success or failure
587 public function removeChild($item)
589 $id = $item->getId();
590 foreach ($this->getChildren() as $key => $child) {
591 if ($child->getId() == $id) {
592 $child->removeParent();
593 unset($this->children[$key]);
594 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
595 $this->children = array_values($this->children);
599 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
608 protected function getParent()
610 return $this->parent;
616 * @param object $conv The conversation
620 public function setThread($conv)
622 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
624 $this->thread = $conv;
626 // Set it on our children too
627 foreach ($this->getChildren() as $child) {
628 $child->setThread($conv);
637 public function getThread()
639 return $this->thread;
645 * We shouldn't need this
649 public function getData()
657 * @param object $name key
659 * @return mixed value on success
662 public function getDataValue($name)
664 if (!isset($this->data[$name])) {
665 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
669 return $this->data[$name];
675 * @param object $name template name
679 private function setTemplate($name)
681 if (empty($this->available_templates[$name])) {
682 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
686 $this->template = $this->available_templates[$name];
694 private function getTemplate()
696 return $this->template;
700 * Check if this is a toplevel post
704 private function isToplevel()
706 return $this->toplevel;
710 * Check if this is writable
714 private function isWritable()
716 $conv = $this->getThread();
719 // This will allow us to comment on wall-to-wall items owned by our friends
720 // and community forums even if somebody else wrote the post.
721 // bug #517 - this fixes for conversation owner
722 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
726 // this fixes for visitors
727 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
729 return $this->writable;
733 * Count the total of our descendants
737 private function countDescendants()
739 $children = $this->getChildren();
740 $total = count($children);
742 foreach ($children as $child) {
743 $total += $child->countDescendants();
751 * Get the template for the comment box
755 private function getCommentBoxTemplate()
757 return $this->comment_box_template;
761 * Get the comment box
763 * @param string $indent Indent value
765 * @return mixed The comment box string (empty if no comment box)
768 private function getCommentBox($indent)
773 $conv = $this->getThread();
775 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
779 if ($conv->isWritable() && $this->isWritable()) {
780 $qc = $qcomment = null;
783 * Hmmm, code depending on the presence of a particular addon?
784 * This should be better if done by a hook
786 if (Addon::isEnabled('qcomment')) {
787 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
788 $qcomment = (($qc) ? explode("\n", $qc) : null);
791 // Fetch the user id from the parent when the owner user is empty
792 $uid = $conv->getProfileOwner();
793 $parent_uid = $this->getDataValue('uid');
795 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
799 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
800 $comment_box = Renderer::replaceMacros($template, [
801 '$return_path' => $a->query_string,
802 '$threaded' => $this->isThreaded(),
804 '$wall' => ($conv->getMode() === 'profile'),
805 '$id' => $this->getId(),
806 '$parent' => $this->getId(),
807 '$qcomment' => $qcomment,
808 '$profile_uid' => $uid,
809 '$mylink' => $a->removeBaseURL($a->contact['url']),
810 '$mytitle' => L10n::t('This is you'),
811 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
812 '$comment' => L10n::t('Comment'),
813 '$submit' => L10n::t('Submit'),
814 '$edbold' => L10n::t('Bold'),
815 '$editalic' => L10n::t('Italic'),
816 '$eduline' => L10n::t('Underline'),
817 '$edquote' => L10n::t('Quote'),
818 '$edcode' => L10n::t('Code'),
819 '$edimg' => L10n::t('Image'),
820 '$edurl' => L10n::t('Link'),
821 '$edattach' => L10n::t('Link or Media'),
822 '$prompttext' => L10n::t('Please enter a image/video/audio/webpage URL:'),
823 '$preview' => L10n::t('Preview'),
824 '$indent' => $indent,
825 '$sourceapp' => L10n::t($a->sourcename),
826 '$ww' => $conv->getMode() === 'network' ? $ww : '',
827 '$rand_num' => Crypto::randomDigits(12)
837 private function getRedirectUrl()
839 return $this->redirect_url;
843 * Check if we are a wall to wall item and set the relevant properties
847 protected function checkWallToWall()
850 $conv = $this->getThread();
851 $this->wall_to_wall = false;
853 if ($this->isToplevel()) {
854 if ($conv->getMode() !== 'profile') {
855 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
856 // On the network page, I am the owner. On the display page it will be the profile owner.
857 // This will have been stored in $a->page_contact by our calling page.
858 // Put this person as the wall owner of the wall-to-wall notice.
860 $this->owner_url = Contact::magicLink($a->page_contact['url']);
861 $this->owner_photo = $a->page_contact['thumb'];
862 $this->owner_name = $a->page_contact['name'];
863 $this->wall_to_wall = true;
864 } elseif ($this->getDataValue('owner-link')) {
865 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
866 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
867 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
869 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
870 // The author url doesn't match the owner (typically the contact)
871 // and also doesn't match the contact alias.
872 // The name match is a hack to catch several weird cases where URLs are
873 // all over the park. It can be tricked, but this prevents you from
874 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
875 // well that it's the same Bob Smith.
876 // But it could be somebody else with the same name. It just isn't highly likely.
879 $this->owner_photo = $this->getDataValue('owner-avatar');
880 $this->owner_name = $this->getDataValue('owner-name');
881 $this->wall_to_wall = true;
883 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
884 'network' => $this->getDataValue('owner-network'),
885 'url' => $this->getDataValue('owner-link')];
886 $this->owner_url = Contact::magicLinkbyContact($owner);
892 if (!$this->wall_to_wall) {
893 $this->setTemplate('wall');
894 $this->owner_url = '';
895 $this->owner_photo = '';
896 $this->owner_name = '';
903 private function isWallToWall()
905 return $this->wall_to_wall;
911 private function getOwnerUrl()
913 return $this->owner_url;
919 private function getOwnerName()
921 return $this->owner_name;
927 private function isVisiting()
929 return $this->visiting;