3 * @file src/Object/Post.php
5 namespace Friendica\Object;
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;
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;
44 private $children = [];
45 private $parent = null;
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;
62 * @param array $data data array
64 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 array $conv_responses conversation responses
114 * @param integer $thread_level default = 1
116 * @return mixed The data requested on success
119 public function getTemplateData(array $conv_responses, $thread_level = 1)
123 $item = $this->getData();
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) {
132 'label' => L10n::t('This entry was edited'),
133 'date' => DateTimeFormat::local($item['edited'], 'r'),
134 'relative' => Temporal::getRelativeDate($item['edited'])
142 $isstarred = "unstarred";
146 $total_children = $this->countDescendants();
148 $conv = $this->getThread();
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')
155 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
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")];
164 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
167 $dropping = in_array($item['uid'], [0, local_user()]);
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) {
177 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
181 $origin = $item['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'];
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');
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');
201 'dropping' => $dropping,
202 'pagedrop' => $item['pagedrop'],
203 'select' => L10n::t('Select'),
211 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
213 $profile_name = $item['author-name'];
214 if (!empty($item['author-link']) && empty($item['author-name'])) {
215 $profile_name = $item['author-link'];
218 $author = ['uid' => 0, 'id' => $item['author-id'],
219 'network' => $item['author-network'], 'url' => $item['author-link']];
221 if (local_user() || remote_user()) {
222 $profile_link = Contact::magicLinkbyContact($author);
224 $profile_link = $item['author-link'];
227 if (strpos($profile_link, 'redir/') === 0) {
228 $sparkle = ' sparkle';
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));
235 // process action responses - e.g. like/dislike/attend/agree/whatever
236 $response_verbs = ['like', 'dislike'];
240 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
241 $response_verbs[] = 'attendyes';
242 $response_verbs[] = 'attendno';
243 $response_verbs[] = 'attendmaybe';
244 if ($conv->isWritable()) {
246 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
250 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
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']) : '';
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
261 $this->checkWallToWall();
263 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
264 $osparkle = ' sparkle';
269 if ($this->isToplevel()) {
271 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
272 if (DBA::isResult($thread)) {
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'),
283 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
284 $isstarred = (($item['starred']) ? "starred" : "unstarred");
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'),
296 'add' => L10n::t("add tag"),
305 if ($conv->isWritable()) {
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")],
311 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
315 $comment = $this->getCommentBox($indent);
317 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
321 localize_item($item);
323 $body = Item::prepareBody($item, true);
325 list($categories, $folders) = get_cats_and_terms($item);
328 $text_e = strip_tags($body);
329 $name_e = $profile_name;
331 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
332 $title_e = ucfirst($item['content-warning']);
334 $title_e = $item['title'];
337 $location_e = $location;
338 $owner_name_e = $this->getOwnerName();
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"]);
347 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
348 unset($buttons["like"]);
351 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
352 unset($buttons["like"]);
355 $tags = Term::populateTagsFromItem($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,
372 'id' => $this->getId(),
373 'guid' => urlencode($item['guid']),
374 'isevent' => $isevent,
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),
385 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
386 'osparkle' => $osparkle,
387 'sparkle' => $sparkle,
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']),
394 'location' => $location_e,
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),
403 'isstarred' => $isstarred,
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,
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) : '',
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'),
435 $arr = ['item' => $item, 'output' => $tmp_item];
436 Addon::callHooks('display_item', $arr);
438 $result = $arr['output'];
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);
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;
457 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
462 if ($this->isToplevel()) {
463 $result['total_comments_num'] = "$total_children";
464 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
467 $result['private'] = $item['private'];
468 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
470 if ($this->isThreaded()) {
471 $result['flatten'] = false;
472 $result['threaded'] = true;
474 $result['flatten'] = true;
475 $result['threaded'] = false;
484 public function getId()
486 return $this->getDataValue('id');
492 public function isThreaded()
494 return $this->threaded;
500 * @param Post $item The child item to add
504 public function addChild(Post $item)
506 $item_id = $item->getId();
508 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
510 } elseif ($this->getChild($item->getId())) {
511 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
515 * Only add what will be displayed
517 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
519 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
523 $item->setParent($this);
524 $this->children[] = $item;
526 return end($this->children);
530 * Get a child by its ID
532 * @param integer $id The child id
536 public function getChild($id)
538 foreach ($this->getChildren() as $child) {
539 if ($child->getId() == $id) {
548 * Get all our children
552 public function getChildren()
554 return $this->children;
560 * @param Post $item The item to set as parent
564 protected function setParent(Post $item)
566 $parent = $this->getParent();
568 $parent->removeChild($this);
571 $this->parent = $item;
572 $this->setThread($item->getThread());
580 protected function removeParent()
582 $this->parent = null;
583 $this->thread = null;
589 * @param Post $item The child to be removed
591 * @return boolean Success or failure
593 public function removeChild(Post $item)
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);
605 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
614 protected function getParent()
616 return $this->parent;
620 * Set conversation thread
622 * @param Thread $thread
626 public function setThread(Thread $thread = null)
628 $this->thread = $thread;
630 // Set it on our children too
631 foreach ($this->getChildren() as $child) {
632 $child->setThread($thread);
641 public function getThread()
643 return $this->thread;
649 * We shouldn't need this
653 public function getData()
661 * @param string $name key
663 * @return mixed value on success
666 public function getDataValue($name)
668 if (!isset($this->data[$name])) {
669 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
673 return $this->data[$name];
679 * @param string $name template name
682 private function setTemplate($name)
684 if (empty($this->available_templates[$name])) {
685 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
689 $this->template = $this->available_templates[$name];
699 private function getTemplate()
701 return $this->template;
705 * Check if this is a toplevel post
709 private function isToplevel()
711 return $this->toplevel;
715 * Check if this is writable
719 private function isWritable()
721 $conv = $this->getThread();
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()) {
731 // this fixes for visitors
732 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
734 return $this->writable;
738 * Count the total of our descendants
742 private function countDescendants()
744 $children = $this->getChildren();
745 $total = count($children);
747 foreach ($children as $child) {
748 $total += $child->countDescendants();
756 * Get the template for the comment box
760 private function getCommentBoxTemplate()
762 return $this->comment_box_template;
766 * Get the comment box
768 * @param string $indent Indent value
770 * @return mixed The comment box string (empty if no comment box)
773 private function getCommentBox($indent)
778 $conv = $this->getThread();
780 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
784 if ($conv->isWritable() && $this->isWritable()) {
785 $qc = $qcomment = null;
788 * Hmmm, code depending on the presence of a particular addon?
789 * This should be better if done by a hook
791 if (Addon::isEnabled('qcomment')) {
792 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
793 $qcomment = (($qc) ? explode("\n", $qc) : null);
796 // Fetch the user id from the parent when the owner user is empty
797 $uid = $conv->getProfileOwner();
798 $parent_uid = $this->getDataValue('uid');
800 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
804 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
805 $comment_box = Renderer::replaceMacros($template, [
806 '$return_path' => $a->query_string,
807 '$threaded' => $this->isThreaded(),
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)
842 private function getRedirectUrl()
844 return $this->redirect_url;
848 * Check if we are a wall to wall item and set the relevant properties
852 protected function checkWallToWall()
855 $conv = $this->getThread();
856 $this->wall_to_wall = false;
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.
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'));
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.
884 $this->owner_photo = $this->getDataValue('owner-avatar');
885 $this->owner_name = $this->getDataValue('owner-name');
886 $this->wall_to_wall = true;
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);
897 if (!$this->wall_to_wall) {
898 $this->setTemplate('wall');
899 $this->owner_url = '';
900 $this->owner_photo = '';
901 $this->owner_name = '';
908 private function isWallToWall()
910 return $this->wall_to_wall;
916 private function getOwnerUrl()
918 return $this->owner_url;
924 private function getOwnerName()
926 return $this->owner_name;
932 private function isVisiting()
934 return $this->visiting;