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\PConfig;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
15 require_once 'include/dba.php';
16 require_once 'include/text.php';
17 require_once 'boot.php';
18 require_once 'include/conversation.php';
23 class Post extends BaseObject
25 private $data = array();
26 private $template = null;
27 private $available_templates = array(
28 'wall' => 'wall_thread.tpl',
29 'wall2wall' => 'wallwall_thread.tpl'
31 private $comment_box_template = 'comment_item.tpl';
32 private $toplevel = false;
33 private $writable = false;
34 private $children = array();
35 private $parent = null;
36 private $thread = null;
37 private $redirect_url = null;
38 private $owner_url = '';
39 private $owner_photo = '';
40 private $owner_name = '';
41 private $wall_to_wall = false;
42 private $threaded = false;
43 private $visiting = false;
48 * @param array $data data array
50 public function __construct(array $data)
55 $this->setTemplate('wall');
56 $this->toplevel = $this->getId() == $this->getDataValue('parent');
58 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
59 foreach ($_SESSION['remote'] as $visitor) {
60 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
61 $this->visiting = true;
67 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
68 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
70 if (!$this->isToplevel()) {
71 $this->threaded = true;
74 // Prepare the children
75 if (count($data['children'])) {
76 foreach ($data['children'] as $item) {
77 // Only add will be displayed
78 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
80 } elseif (!visible_activity($item)) {
84 // You can always comment on Diaspora items
85 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
86 $item['writable'] = true;
89 $item['pagedrop'] = $data['pagedrop'];
90 $child = new Post($item);
91 $this->addChild($child);
97 * Get data in a form usable by a conversation template
99 * @param object $conv_responses conversation responses
100 * @param integer $thread_level default = 1
102 * @return mixed The data requested on success
105 public function getTemplateData($conv_responses, $thread_level = 1)
107 require_once "mod/proxy.php";
113 $item = $this->getData();
115 // If the time between "created" and "edited" differs we add
116 // a notice that the post was edited.
117 // Note: In some networks reshared items seem to have (sometimes) a difference
118 // between creation time and edit time of a second. Thats why we add the notice
119 // only if the difference is more than 1 second.
120 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
122 'label' => t('This entry was edited'),
123 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
124 'relative' => relative_date($item['edited'])
133 $isstarred = "unstarred";
137 $total_children = $this->countDescendants();
139 $conv = $this->getThread();
141 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
142 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
143 ? t('Private Message')
145 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
147 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
148 if ($item["event-id"] != 0) {
149 $edpost = array("events/event/" . $item['event-id'], t("Edit"));
151 $edpost = array("editpost/" . $item['id'], t("Edit"));
153 $dropping = in_array($item['uid'], [0, local_user()]);
158 // Editing on items of not subscribed users isn't currently possible
159 // There are some issues on editing that prevent this.
160 // But also it is an issue of the supported protocols that doesn't allow editing at all.
161 if ($item['uid'] == 0) {
165 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
170 'dropping' => $dropping,
171 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
172 'select' => t('Select'),
173 'delete' => t('Delete'),
176 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
178 $diff_author = !link_compare($item['url'], $item['author-link']);
179 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
180 if ($item['author-link'] && (!$item['author-name'])) {
181 $profile_name = $item['author-link'];
185 $profile_link = best_link_url($item, $sp);
186 if ($profile_link === 'mailbox') {
191 $sparkle = ' sparkle';
193 $profile_link = zrl($profile_link);
196 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
197 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
198 if ($author_contact["thumb"]) {
199 $item['author-thumb'] = $author_contact["thumb"];
201 $item['author-thumb'] = $item['author-avatar'];
205 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
206 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
207 if ($owner_contact["thumb"]) {
208 $item['owner-thumb'] = $owner_contact["thumb"];
210 $item['owner-thumb'] = $item['owner-avatar'];
214 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
215 call_hooks('render_location', $locate);
216 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
218 // process action responses - e.g. like/dislike/attend/agree/whatever
219 $response_verbs = array('like', 'dislike');
223 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
224 $response_verbs[] = 'attendyes';
225 $response_verbs[] = 'attendno';
226 $response_verbs[] = 'attendmaybe';
227 if ($conv->isWritable()) {
229 $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
233 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
235 foreach ($response_verbs as $value => $verbs) {
236 $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']) : '';
240 * We should avoid doing this all the time, but it depends on the conversation mode
241 * And the conv mode may change when we change the conv, or it changes its mode
242 * Maybe we should establish a way to be notified about conversation changes
244 $this->checkWallToWall();
246 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
247 $osparkle = ' sparkle';
252 if ($this->isToplevel()) {
253 if ($conv->getProfileOwner() == local_user()) {
254 $isstarred = (($item['starred']) ? "starred" : "unstarred");
257 'do' => t("add star"),
258 'undo' => t("remove star"),
259 'toggle' => t("toggle star status"),
260 'classdo' => $item['starred'] ? "hidden" : "",
261 'classundo' => $item['starred'] ? "" : "hidden",
262 'starred' => t('starred'),
264 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
265 if (DBM::is_result($r)) {
267 'do' => t("ignore thread"),
268 'undo' => t("unignore thread"),
269 'toggle' => t("toggle ignore status"),
270 'classdo' => $r['ignored'] ? "hidden" : "",
271 'classundo' => $r['ignored'] ? "" : "hidden",
272 'ignored' => t('ignored'),
276 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
278 'add' => t("add tag"),
287 if ($conv->isWritable()) {
289 'like' => array(t("I like this \x28toggle\x29"), t("like")),
290 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
293 $buttons['share'] = array(t('Share this'), t('share'));
296 // If a contact isn't writable, we cannot send a like or dislike to it
297 if (!$item['writable']) {
298 unset($buttons["like"]);
299 unset($buttons["dislike"]);
303 $comment = $this->getCommentBox($indent);
305 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
309 localize_item($item);
311 $body = prepare_body($item, true);
313 list($categories, $folders) = get_cats_and_terms($item);
316 $text_e = strip_tags($body);
317 $name_e = $profile_name;
318 $title_e = $item['title'];
319 $location_e = $location;
320 $owner_name_e = $this->getOwnerName();
322 // Disable features that aren't available in several networks
323 /// @todo Add NETWORK_DIASPORA when it will pass this information
324 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
325 unset($buttons["dislike"]);
330 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
331 unset($buttons["like"]);
334 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
335 unset($buttons["like"]);
339 'template' => $this->getTemplate(),
340 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
341 'tags' => $item['tags'],
342 'hashtags' => $item['hashtags'],
343 'mentions' => $item['mentions'],
344 'txt_cats' => t('Categories:'),
345 'txt_folders' => t('Filed under:'),
346 'has_cats' => ((count($categories)) ? 'true' : ''),
347 'has_folders' => ((count($folders)) ? 'true' : ''),
348 'categories' => $categories,
349 'folders' => $folders,
352 'id' => $this->getId(),
353 'guid' => urlencode($item['guid']),
354 'isevent' => $isevent,
356 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
357 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
360 'wall' => t('Wall-to-Wall'),
361 'vwall' => t('via Wall-To-Wall:'),
362 'profile_url' => $profile_link,
363 'item_photo_menu' => item_photo_menu($item),
365 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
366 'osparkle' => $osparkle,
367 'sparkle' => $sparkle,
369 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
370 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
371 'app' => $item['app'],
372 'created' => relative_date($item['created']),
374 'location' => $location_e,
377 'owner_url' => $this->getOwnerUrl(),
378 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
379 'owner_name' => htmlentities($owner_name_e),
380 'plink' => get_plink($item),
381 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
382 'isstarred' => $isstarred,
383 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
384 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
386 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
389 'like' => $responses['like']['output'],
390 'dislike' => $responses['dislike']['output'],
391 'responses' => $responses,
392 'switchcomment' => t('Comment'),
393 'comment' => $comment,
394 'previewing' => $conv->isPreview() ? ' preview ' : '',
395 'wait' => t('Please wait'),
396 'thread_level' => $thread_level,
398 'network' => $item["item_network"],
399 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
400 'received' => $item['received'],
401 'commented' => $item['commented'],
402 'created_date' => $item['created'],
405 $arr = array('item' => $item, 'output' => $tmp_item);
406 call_hooks('display_item', $arr);
408 $result = $arr['output'];
410 $result['children'] = array();
411 $children = $this->getChildren();
412 $nb_children = count($children);
413 if ($nb_children > 0) {
414 foreach ($children as $child) {
415 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
418 if (($nb_children > 2) || ($thread_level > 1)) {
419 $result['children'][0]['comment_firstcollapsed'] = true;
420 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
421 $result['children'][0]['hidden_comments_num'] = $total_children;
422 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
423 $result['children'][0]['hide_text'] = t('show more');
424 if ($thread_level > 1) {
425 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
427 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
432 if ($this->isToplevel()) {
433 $result['total_comments_num'] = "$total_children";
434 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
437 $result['private'] = $item['private'];
438 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
440 if ($this->isThreaded()) {
441 $result['flatten'] = false;
442 $result['threaded'] = true;
444 $result['flatten'] = true;
445 $result['threaded'] = false;
454 public function getId()
456 return $this->getDataValue('id');
462 public function isThreaded()
464 return $this->threaded;
470 * @param object $item The child item to add
474 public function addChild(Post $item)
476 $item_id = $item->getId();
478 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
480 } elseif ($this->getChild($item->getId())) {
481 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
485 * Only add what will be displayed
487 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
489 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
493 $item->setParent($this);
494 $this->children[] = $item;
496 return end($this->children);
500 * Get a child by its ID
502 * @param integer $id The child id
506 public function getChild($id)
508 foreach ($this->getChildren() as $child) {
509 if ($child->getId() == $id) {
518 * Get all our children
522 public function getChildren()
524 return $this->children;
530 * @param object $item The item to set as parent
534 protected function setParent($item)
536 $parent = $this->getParent();
538 $parent->removeChild($this);
541 $this->parent = $item;
542 $this->setThread($item->getThread());
550 protected function removeParent()
552 $this->parent = null;
553 $this->thread = null;
559 * @param object $item The child to be removed
561 * @return boolean Success or failure
563 public function removeChild($item)
565 $id = $item->getId();
566 foreach ($this->getChildren() as $key => $child) {
567 if ($child->getId() == $id) {
568 $child->removeParent();
569 unset($this->children[$key]);
570 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
571 $this->children = array_values($this->children);
575 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
584 protected function getParent()
586 return $this->parent;
592 * @param object $conv The conversation
596 public function setThread($conv)
598 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
600 $this->thread = $conv;
602 // Set it on our children too
603 foreach ($this->getChildren() as $child) {
604 $child->setThread($conv);
613 public function getThread()
615 return $this->thread;
621 * We shouldn't need this
625 public function getData()
633 * @param object $name key
635 * @return mixed value on success
638 public function getDataValue($name)
640 if (!isset($this->data[$name])) {
641 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
645 return $this->data[$name];
651 * @param object $name template name
655 private function setTemplate($name)
657 if (!x($this->available_templates, $name)) {
658 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
662 $this->template = $this->available_templates[$name];
670 private function getTemplate()
672 return $this->template;
676 * Check if this is a toplevel post
680 private function isToplevel()
682 return $this->toplevel;
686 * Check if this is writable
690 private function isWritable()
692 $conv = $this->getThread();
695 // This will allow us to comment on wall-to-wall items owned by our friends
696 // and community forums even if somebody else wrote the post.
697 // bug #517 - this fixes for conversation owner
698 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
702 // this fixes for visitors
703 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
705 return $this->writable;
709 * Count the total of our descendants
713 private function countDescendants()
715 $children = $this->getChildren();
716 $total = count($children);
718 foreach ($children as $child) {
719 $total += $child->countDescendants();
727 * Get the template for the comment box
731 private function getCommentBoxTemplate()
733 return $this->comment_box_template;
737 * Get the comment box
739 * @param string $indent Indent value
741 * @return mixed The comment box string (empty if no comment box)
744 private function getCommentBox($indent)
749 $conv = $this->getThread();
751 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
755 if ($conv->isWritable() && $this->isWritable()) {
756 $qc = $qcomment = null;
759 * Hmmm, code depending on the presence of a particular plugin?
760 * This should be better if done by a hook
762 if (in_array('qcomment', $a->plugins)) {
763 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
764 $qcomment = (($qc) ? explode("\n", $qc) : null);
767 // Fetch the user id from the parent when the owner user is empty
768 $uid = $conv->getProfileOwner();
769 $parent_uid = $this->getDataValue('uid');
771 if (!empty($parent_uid) && empty($uid) && ($uid != $parent_uid)) {
775 $template = get_markup_template($this->getCommentBoxTemplate());
776 $comment_box = replace_macros($template, array(
777 '$return_path' => $a->query_string,
778 '$threaded' => $this->isThreaded(),
780 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
781 '$id' => $this->getId(),
782 '$parent' => $this->getId(),
783 '$qcomment' => $qcomment,
784 '$profile_uid' => $uid,
785 '$mylink' => $a->remove_baseurl($a->contact['url']),
786 '$mytitle' => t('This is you'),
787 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
788 '$comment' => t('Comment'),
789 '$submit' => t('Submit'),
790 '$edbold' => t('Bold'),
791 '$editalic' => t('Italic'),
792 '$eduline' => t('Underline'),
793 '$edquote' => t('Quote'),
794 '$edcode' => t('Code'),
795 '$edimg' => t('Image'),
796 '$edurl' => t('Link'),
797 '$edvideo' => t('Video'),
798 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
799 '$indent' => $indent,
800 '$sourceapp' => t($a->sourcename),
801 '$ww' => $conv->getMode() === 'network' ? $ww : '',
802 '$rand_num' => random_digits(12)
812 private function getRedirectUrl()
814 return $this->redirect_url;
818 * Check if we are a wall to wall item and set the relevant properties
822 protected function checkWallToWall()
825 $conv = $this->getThread();
826 $this->wall_to_wall = false;
828 if ($this->isToplevel()) {
829 if ($conv->getMode() !== 'profile') {
830 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
831 // On the network page, I am the owner. On the display page it will be the profile owner.
832 // This will have been stored in $a->page_contact by our calling page.
833 // Put this person as the wall owner of the wall-to-wall notice.
835 $this->owner_url = zrl($a->page_contact['url']);
836 $this->owner_photo = $a->page_contact['thumb'];
837 $this->owner_name = $a->page_contact['name'];
838 $this->wall_to_wall = true;
839 } elseif ($this->getDataValue('owner-link')) {
840 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
841 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
842 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
844 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
845 // The author url doesn't match the owner (typically the contact)
846 // and also doesn't match the contact alias.
847 // The name match is a hack to catch several weird cases where URLs are
848 // all over the park. It can be tricked, but this prevents you from
849 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
850 // well that it's the same Bob Smith.
851 // But it could be somebody else with the same name. It just isn't highly likely.
854 $this->owner_photo = $this->getDataValue('owner-avatar');
855 $this->owner_name = $this->getDataValue('owner-name');
856 $this->wall_to_wall = true;
857 // If it is our contact, use a friendly redirect link
858 if ($this->getDataValue('network') === NETWORK_DFRN
859 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
861 $this->owner_url = $this->getRedirectUrl();
863 $this->owner_url = zrl($this->getDataValue('owner-link'));
870 if (!$this->wall_to_wall) {
871 $this->setTemplate('wall');
872 $this->owner_url = '';
873 $this->owner_photo = '';
874 $this->owner_name = '';
881 private function isWallToWall()
883 return $this->wall_to_wall;
889 private function getOwnerUrl()
891 return $this->owner_url;
897 private function getOwnerName()
899 return $this->owner_name;
905 private function isVisiting()
907 return $this->visiting;