3 * @file src/Object/Post.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
14 require_once 'include/dba.php';
15 require_once 'include/text.php';
16 require_once 'boot.php';
17 require_once 'include/conversation.php';
22 class Post extends BaseObject
24 private $data = array();
25 private $template = null;
26 private $available_templates = array(
27 'wall' => 'wall_thread.tpl',
28 'wall2wall' => 'wallwall_thread.tpl'
30 private $comment_box_template = 'comment_item.tpl';
31 private $toplevel = false;
32 private $writable = false;
33 private $children = array();
34 private $parent = null;
35 private $thread = null;
36 private $redirect_url = null;
37 private $owner_url = '';
38 private $owner_photo = '';
39 private $owner_name = '';
40 private $wall_to_wall = false;
41 private $threaded = false;
42 private $visiting = false;
47 * @param array $data data array
49 public function __construct(array $data)
54 $this->setTemplate('wall');
55 $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
57 if (is_array($_SESSION['remote'])) {
58 foreach ($_SESSION['remote'] as $visitor) {
59 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
60 $this->visiting = true;
66 $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
68 $ssl_state = ((local_user()) ? true : false);
69 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
71 if (!$this->isToplevel()) {
72 $this->threaded = true;
75 // Prepare the children
76 if (count($data['children'])) {
77 foreach ($data['children'] as $item) {
79 * Only add will be displayed
81 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
83 } elseif (! visible_activity($item)) {
87 // You can always comment on Diaspora items
88 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
89 $item['writable'] = true;
92 $item['pagedrop'] = $data['pagedrop'];
93 $child = new Post($item);
94 $this->addChild($child);
100 * Get data in a form usable by a conversation template
102 * @param object $conv_responses conversation responses
103 * @param integer $thread_level default = 1
105 * @return mixed The data requested on success
108 public function getTemplateData($conv_responses, $thread_level = 1)
110 require_once "mod/proxy.php";
116 $item = $this->getData();
118 // If the time between "created" and "edited" differs we add
119 // a notice that the post was edited.
120 // Note: In some networks reshared items seem to have (sometimes) a difference
121 // between creation time and edit time of a second. Thats why we add the notice
122 // only if the difference is more than 1 second.
123 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
125 'label' => t('This entry was edited'),
126 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
127 'relative' => relative_date($item['edited'])
136 $isstarred = "unstarred";
140 $total_children = $this->countDescendants();
142 $conv = $this->getThread();
144 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
145 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
146 ? t('Private Message')
148 $shareable = ((($conv->getProfileOwner() == local_user()) && ($item['private'] != 1)) ? true : false);
149 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
150 if ($item["event-id"] != 0) {
151 $edpost = array("events/event/".$item['event-id'], t("Edit"));
153 $edpost = array("editpost/".$item['id'], t("Edit"));
159 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
164 'dropping' => $dropping,
165 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
166 'select' => t('Select'),
167 'delete' => t('Delete'),
170 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
172 $diff_author = ((link_compare($item['url'], $item['author-link'])) ? false : true);
173 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
174 if ($item['author-link'] && (! $item['author-name'])) {
175 $profile_name = $item['author-link'];
179 $profile_link = best_link_url($item, $sp);
180 if ($profile_link === 'mailbox') {
185 $sparkle = ' sparkle';
187 $profile_link = zrl($profile_link);
190 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
191 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
192 if ($author_contact["thumb"]) {
193 $item['author-thumb'] = $author_contact["thumb"];
195 $item['author-thumb'] = $item['author-avatar'];
199 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
200 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
201 if ($owner_contact["thumb"]) {
202 $item['owner-thumb'] = $owner_contact["thumb"];
204 $item['owner-thumb'] = $item['owner-avatar'];
208 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
209 call_hooks('render_location', $locate);
210 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
216 /*foreach(explode(',',$item['tag']) as $tag){
228 // process action responses - e.g. like/dislike/attend/agree/whatever
229 $response_verbs = array('like', 'dislike');
231 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
232 $response_verbs[] = 'attendyes';
233 $response_verbs[] = 'attendno';
234 $response_verbs[] = 'attendmaybe';
235 if ($conv->isWritable()) {
237 $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
241 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
243 foreach ($response_verbs as $value => $verbs) {
244 $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']) : '');
248 * We should avoid doing this all the time, but it depends on the conversation mode
249 * And the conv mode may change when we change the conv, or it changes its mode
250 * Maybe we should establish a way to be notified about conversation changes
252 $this->checkWallToWall();
254 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
255 $osparkle = ' sparkle';
258 if ($this->isToplevel()) {
259 if ($conv->getProfileOwner() == local_user()) {
260 $isstarred = (($item['starred']) ? "starred" : "unstarred");
263 'do' => t("add star"),
264 'undo' => t("remove star"),
265 'toggle' => t("toggle star status"),
266 'classdo' => (($item['starred']) ? "hidden" : ""),
267 'classundo' => (($item['starred']) ? "" : "hidden"),
268 'starred' => t('starred'),
270 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
271 if (DBM::is_result($r)) {
273 'do' => t("ignore thread"),
274 'undo' => t("unignore thread"),
275 'toggle' => t("toggle ignore status"),
276 'classdo' => (($r['ignored']) ? "hidden" : ""),
277 'classundo' => (($r['ignored']) ? "" : "hidden"),
278 'ignored' => t('ignored'),
283 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
285 'add' => t("add tag"),
294 if ($conv->isWritable()) {
296 'like' => array( t("I like this \x28toggle\x29"), t("like")),
297 'dislike' => ((Feature::isEnabled($conv->getProfileOwner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
300 $buttons['share'] = array( t('Share this'), t('share'));
304 $comment = $this->getCommentBox($indent);
306 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
310 localize_item($item);
312 $body = prepare_body($item, true);
314 list($categories, $folders) = get_cats_and_terms($item);
317 $text_e = strip_tags($body);
318 $name_e = $profile_name;
319 $title_e = $item['title'];
320 $location_e = $location;
321 $owner_name_e = $this->getOwnerName();
323 // Disable features that aren't available in several networks
325 /// @todo Add NETWORK_DIASPORA when it will pass this information
326 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
327 unset($buttons["dislike"], $isevent);
331 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
332 unset($buttons["like"]);
335 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
336 unset($buttons["like"]);
340 'template' => $this->getTemplate(),
341 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
342 'tags' => $item['tags'],
343 'hashtags' => $item['hashtags'],
344 'mentions' => $item['mentions'],
345 'txt_cats' => t('Categories:'),
346 'txt_folders' => t('Filed under:'),
347 'has_cats' => ((count($categories)) ? 'true' : ''),
348 'has_folders' => ((count($folders)) ? 'true' : ''),
349 'categories' => $categories,
350 'folders' => $folders,
353 'id' => $this->getId(),
354 'guid' => urlencode($item['guid']),
355 'isevent' => $isevent,
357 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
358 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
361 'wall' => t('Wall-to-Wall'),
362 'vwall' => t('via Wall-To-Wall:'),
363 'profile_url' => $profile_link,
364 'item_photo_menu' => item_photo_menu($item),
366 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
367 'osparkle' => $osparkle,
368 'sparkle' => $sparkle,
370 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
371 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
372 'app' => $item['app'],
373 'created' => relative_date($item['created']),
375 'location' => $location_e,
378 'owner_url' => $this->getOwnerUrl(),
379 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
380 'owner_name' => htmlentities($owner_name_e),
381 'plink' => get_plink($item),
382 'edpost' => ((Feature::isEnabled($conv->getProfileOwner(), 'edit_posts')) ? $edpost : ''),
383 'isstarred' => $isstarred,
384 'star' => ((Feature::isEnabled($conv->getProfileOwner(), 'star_posts')) ? $star : ''),
385 'ignore' => ((Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts')) ? $ignore : ''),
387 'filer' => ((Feature::isEnabled($conv->getProfileOwner(), 'filing')) ? $filer : ''),
390 'like' => $responses['like']['output'],
391 'dislike' => $responses['dislike']['output'],
392 'responses' => $responses,
393 'switchcomment' => t('Comment'),
394 'comment' => $comment,
395 'previewing' => ($conv->isPreview() ? ' preview ' : ''),
396 'wait' => t('Please wait'),
397 'thread_level' => $thread_level,
399 'network' => $item["item_network"],
400 'network_name' => network_to_name($item['item_network'], $profile_link),
401 'received' => $item['received'],
402 'commented' => $item['commented'],
403 'created_date' => $item['created'],
406 $arr = array('item' => $item, 'output' => $tmp_item);
407 call_hooks('display_item', $arr);
409 $result = $arr['output'];
411 $result['children'] = array();
412 $children = $this->getChildren();
413 $nb_children = count($children);
414 if ($nb_children > 0) {
415 foreach ($children as $child) {
416 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
419 if (($nb_children > 2) || ($thread_level > 1)) {
420 $result['children'][0]['comment_firstcollapsed'] = true;
421 $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
422 $result['children'][0]['hidden_comments_num'] = $total_children;
423 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
424 $result['children'][0]['hide_text'] = t('show more');
425 if ($thread_level > 1) {
426 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
428 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
433 if ($this->isToplevel()) {
434 $result['total_comments_num'] = "$total_children";
435 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
438 $result['private'] = $item['private'];
439 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
441 if ($this->isThreaded()) {
442 $result['flatten'] = false;
443 $result['threaded'] = true;
445 $result['flatten'] = true;
446 $result['threaded'] = false;
455 public function getId()
457 return $this->getDataValue('id');
463 public function isThreaded()
465 return $this->threaded;
471 * @param object $item The child item to add
475 public function addChild(Post $item)
477 $item_id = $item->getId();
479 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
481 } elseif ($this->getChild($item->getId())) {
482 logger('[WARN] Post::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
486 * Only add what will be displayed
488 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
490 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
494 $item->setParent($this);
495 $this->children[] = $item;
497 return end($this->children);
501 * Get a child by its ID
503 * @param integer $id The child id
507 public function getChild($id)
509 foreach ($this->getChildren() as $child) {
510 if ($child->getId() == $id) {
519 * Get all our children
523 public function getChildren()
525 return $this->children;
531 * @param object $item The item to set as parent
535 protected function setParent($item)
537 $parent = $this->getParent();
539 $parent->removeChild($this);
542 $this->parent = $item;
543 $this->setThread($item->getThread());
551 protected function removeParent()
553 $this->parent = null;
554 $this->thread = null;
560 * @param object $item The child to be removed
562 * @return boolean Success or failure
564 public function removeChild($item)
566 $id = $item->getId();
567 foreach ($this->getChildren() as $key => $child) {
568 if ($child->getId() == $id) {
569 $child->removeParent();
570 unset($this->children[$key]);
571 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
572 $this->children = array_values($this->children);
576 logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
585 protected function getParent()
587 return $this->parent;
593 * @param object $conv The conversation
597 public function setThread($conv)
599 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
601 $this->thread = $conv;
603 // Set it on our children too
604 foreach ($this->getChildren() as $child) {
605 $child->setThread($conv);
614 public function getThread()
616 return $this->thread;
622 * We shouldn't need this
626 public function getData()
634 * @param object $name key
636 * @return mixed value on success
639 public function getDataValue($name)
641 if (!isset($this->data[$name])) {
642 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
646 return $this->data[$name];
652 * @param object $name template name
656 private function setTemplate($name)
658 if (!x($this->available_templates, $name)) {
659 logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
663 $this->template = $this->available_templates[$name];
671 private function getTemplate()
673 return $this->template;
677 * Check if this is a toplevel post
681 private function isToplevel()
683 return $this->toplevel;
687 * Check if this is writable
691 private function isWritable()
693 $conv = $this->getThread();
696 // This will allow us to comment on wall-to-wall items owned by our friends
697 // and community forums even if somebody else wrote the post.
699 // bug #517 - this fixes for conversation owner
700 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
704 // this fixes for visitors
705 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
707 return $this->writable;
711 * Count the total of our descendants
715 private function countDescendants()
717 $children = $this->getChildren();
718 $total = count($children);
720 foreach ($children as $child) {
721 $total += $child->countDescendants();
729 * Get the template for the comment box
733 private function getCommentBoxTemplate()
735 return $this->comment_box_template;
739 * Get the comment box
741 * @param string $indent Indent value
743 * @return mixed The comment box string (empty if no comment box)
746 private function getCommentBox($indent)
751 $conv = $this->getThread();
752 $template = get_markup_template($this->getCommentBoxTemplate());
754 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
758 if ($conv->isWritable() && $this->isWritable()) {
759 $qc = $qcomment = null;
762 * Hmmm, code depending on the presence of a particular plugin?
763 * This should be better if done by a hook
765 if (in_array('qcomment', $a->plugins)) {
766 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
767 $qcomment = (($qc) ? explode("\n", $qc) : null);
770 $comment_box = replace_macros(
773 '$return_path' => $a->query_string,
774 '$threaded' => $this->isThreaded(),
775 // '$jsreload' => (($conv->getMode() === 'display') ? $_SESSION['return_url'] : ''),
777 '$type' => (($conv->getMode() === 'profile') ? 'wall-comment' : 'net-comment'),
778 '$id' => $this->getId(),
779 '$parent' => $this->getId(),
780 '$qcomment' => $qcomment,
781 '$profile_uid' => $conv->getProfileOwner(),
782 '$mylink' => $a->remove_baseurl($a->contact['url']),
783 '$mytitle' => t('This is you'),
784 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
785 '$comment' => t('Comment'),
786 '$submit' => t('Submit'),
787 '$edbold' => t('Bold'),
788 '$editalic' => t('Italic'),
789 '$eduline' => t('Underline'),
790 '$edquote' => t('Quote'),
791 '$edcode' => t('Code'),
792 '$edimg' => t('Image'),
793 '$edurl' => t('Link'),
794 '$edvideo' => t('Video'),
795 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
796 '$indent' => $indent,
797 '$sourceapp' => t($a->sourcename),
798 '$ww' => (($conv->getMode() === 'network') ? $ww : ''),
799 '$rand_num' => random_digits(12))
809 private function getRedirectUrl()
811 return $this->redirect_url;
815 * Check if we are a wall to wall item and set the relevant properties
819 protected function checkWallToWall()
822 $conv = $this->getThread();
823 $this->wall_to_wall = false;
825 if ($this->isToplevel()) {
826 if ($conv->getMode() !== 'profile') {
827 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
828 // On the network page, I am the owner. On the display page it will be the profile owner.
829 // This will have been stored in $a->page_contact by our calling page.
830 // Put this person as the wall owner of the wall-to-wall notice.
832 $this->owner_url = zrl($a->page_contact['url']);
833 $this->owner_photo = $a->page_contact['thumb'];
834 $this->owner_name = $a->page_contact['name'];
835 $this->wall_to_wall = true;
836 } elseif ($this->getDataValue('owner-link')) {
837 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
838 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
839 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
841 if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
842 // The author url doesn't match the owner (typically the contact)
843 // and also doesn't match the contact alias.
844 // The name match is a hack to catch several weird cases where URLs are
845 // all over the park. It can be tricked, but this prevents you from
846 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
847 // well that it's the same Bob Smith.
849 // But it could be somebody else with the same name. It just isn't highly likely.
852 $this->owner_photo = $this->getDataValue('owner-avatar');
853 $this->owner_name = $this->getDataValue('owner-name');
854 $this->wall_to_wall = true;
855 // If it is our contact, use a friendly redirect link
856 if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
857 && ($this->getDataValue('network') === NETWORK_DFRN)
859 $this->owner_url = $this->getRedirectUrl();
861 $this->owner_url = zrl($this->getDataValue('owner-link'));
868 if (!$this->wall_to_wall) {
869 $this->setTemplate('wall');
870 $this->owner_url = '';
871 $this->owner_photo = '';
872 $this->owner_name = '';
879 private function isWallToWall()
881 return $this->wall_to_wall;
887 private function getOwnerUrl()
889 return $this->owner_url;
895 private function getOwnerName()
897 return $this->owner_name;
903 private function isVisiting()
905 return $this->visiting;