Post.php 76 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
<?php
// Dobrado Content Management System
// Copyright (C) 2017 Malcolm Blaney
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

class Post extends Base {

  public function Add($id) {
    // Add default content here so that SetContent doesn't need to check if
    // a table row already exists.
    $this->Insert($id, $this->user->name, $this->user->page);
  }

  public function Callback() {
    // This is called after SetContent and NewComment return.
    if (isset($_POST['action'])) {
      $updated = false;
      if ($_POST['action'] === 'updated') {
        $updated = true;
      }
      else if ($_POST['action'] !== 'newComment') {
        return ['error' => 'Unknown action'];
      }

      $status = '';
      $key = $this->owner.'-'.$this->user->page;
      if (isset($_SESSION['post-update'][$key])) {
        $post = $_SESSION['post-update'][$key];
        $status = $this->ContentUpdated($post['content'], $post['category'],
                                        $post['feed'], $post['permalink'],
                                        $updated);
        $_SESSION['post-update'][$key] = NULL;
      }
      else if (isset($_SESSION['micropub-status'])) {
        $status = $_SESSION['micropub-status'];
        $_SESSION['micropub-status'] = NULL;
      }
      return ['status' => $status];
    }

    // 'mode' is used by the Extended module, which calls this function.
    if (!isset($_POST['mode']) || $_POST['mode'] !== 'box') {
      return ['error' => 'Unknown mode'];
    }

    $object = [];
    $mysqli = connect_db();
    $id = (int)substr($_POST['id'], 9);
    $query = 'SELECT title, description, author, category, enclosure, '.
      'permalink FROM post WHERE user = "'.$this->owner.'" AND box_id = '.$id;
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $object['editor'] = true;
        $object['source'] = $post['description'];
        // When notify is set to false, it's possible that the current version
        // of the post will be saved without sending notifications. In this
        // case create a notify flag to ignore the content check done later.
        if (isset($_POST['notify']) && $_POST['notify'] === 'false') {
          $object['notify'] = true;
        }
        $object['permalink'] = $post['permalink'];
        // Check the 'Send to Twitter' or 'Send to Facebook' boxes if a link
        // was added previously.
        $twitter_checked = '';
        $twitter_link = 'https://brid.gy/publish/twitter';
        if (strpos($post['description'], $twitter_link) !== false) {
          $twitter_checked = ' checked="checked"';
        }
        $facebook_checked = '';
        $facebook_link = 'https://brid.gy/publish/facebook';
        if (strpos($post['description'], $facebook_link) !== false) {
          $facebook_checked = ' checked="checked"';
        }
        // Set Webaction if a class name is found in the description.
        $class = '';
        $url = '';
        $options = '<option></option><option>like</option>'.
          '<option>reply</option><option>share</option>';
        if (strpos($post['description'], 'u-like-of') !== false) {
          $class = 'u-like-of';
          $options = '<option></option>'.
            '<option selected="selected">like</option>'.
            '<option>reply</option><option>share</option>';
        }
        else if (strpos($post['description'], 'u-repost-of') !== false) {
          $class = 'u-repost-of';
          $options = '<option></option><option>like</option>'.
            '<option>reply</option>'.
            '<option selected="selected">share</option>';
        }
        else if (strpos($post['description'], 'u-in-reply-to') !== false) {
          $class = 'u-in-reply-to';
          $options = '<option></option><option>like</option>'.
            '<option selected="selected">reply</option>'.
            '<option>share</option>';
        }
        if ($class !== '') {
          $regex = '/<a href="(.*)" class="'.$class.'"/i';
          if (preg_match($regex, $post['description'], $match)) {
            $url = $match[1];
          }
        }
        // The Extended module uses the name attribute to assign content.
        $object['custom'] = '<form id="extended-custom-settings">'.
          '<div class="form-spacing">'.
            '<label for="post-title-input">Title:</label>'.
            '<input id="post-title-input" name="title" type="text" '.
              'value="'.htmlspecialchars($post['title']).'" maxlength="180">'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-author-input">Author:</label>'.
            '<input id="post-author-input" name="author" type="text" '.
              'value="'.htmlspecialchars($post['author']).'" maxlength="50">'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-category-input">Category:</label>'.
            '<input id="post-category-input" name="category" type="text" '.
              'value="'.htmlspecialchars($post['category']).'" '.
              'maxlength="200">'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-action-url-input">Webaction Url:</label>'.
            '<input id="post-action-url-input" name="webactionUrl" '.
              'type="text" value="'.htmlspecialchars($url).'" maxlength="200">'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-action-type-input">Webaction Type:</label>'.
            '<select id="post-action-type-input" name="webactionType">'.
              $options.'</select>'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-twitter-input">Send to Twitter:</label>'.
            '<input id="post-twitter-input" name="twitter" type="checkbox"'.
              $twitter_checked.'>'.
          '</div>'.
          '<div class="form-spacing">'.
            '<label for="post-facebook-input">Send to Facebook:</label>'.
            '<input id="post-facebook-input" name="facebook" type="checkbox"'.
              $facebook_checked.'>'.
          '</div>'.
          '<button type="submit">Submit</button>'.
          '</form>';
      }
      $result->close();
    }
    else {
      $this->Log('Post->Callback: '.$mysqli->error);
    }
    $mysqli->close();
    return $object;
  }

  public function CanAdd($page) {
    return true;
  }

  public function CanRemove($id) {
    return true;
  }

  public function CanEdit($id) {
    return true;
  }

  public function Content($id) {
    // If the reader module is on the page, it is responsible for aggregating
    // post module content, so return false here.
    if ($this->AlreadyOnPage('reader')) {
      return false;
    }

    $title = '';
    $description = '';
    $author = '';
    $category = '';
    $media = '';
    $permalink = '';
    $feed = '';
    $timestamp = 0;
    $base_url = $this->user->config->Secure() ? 'https://' : 'http://';
    $base_url .= $this->user->config->ServerName();
    $mysqli = connect_db();
    $query = 'SELECT title, description, author, category, enclosure, '.
      'permalink, feed, timestamp FROM post WHERE user = "'.$this->owner.'" '.
      'AND box_id = '.$id;
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        // Allow the title to be stored with literal special chars as this
        // simplifies creating permalinks, but it must be escaped here.
        $title = htmlspecialchars($post['title']);
        $description = $post['description'];
        // The author is escaped in SetContent.
        $author = $post['author'];
        $prev_tag = '';
        // Category can be comma separated values.
        if (strpos($post['category'], ',') !== false) {
          foreach (explode(',', $post['category']) as $tag) {
            if (preg_match('/^reposted by (.+)$/', $prev_tag, $match)) {
              // Reposted items get their original author, which is stored in
              // the nickname cache when the repost is created.
              $author = $this->LookupAuthor($author, $tag).
                ' <span class="post-reposted-by">reposted by '.
                  $this->LookupUser($match[1], $base_url).'</span>';
              $category .= category_markup(htmlspecialchars($tag));
            }
            else {
              $category .= category_markup(htmlspecialchars($tag),
                                           $this->LookupName($tag));
            }
            $prev_tag = $tag;
          }
        }
        else {
          $category .= category_markup(htmlspecialchars($post['category']),
                                       $this->LookupName($post['category']));
        }
        if ($category !== '') {
          $category = '<span class="post-tag-label">tags: </span>'.$category;
        }
        $permalink = $post['permalink'];
        $feed = $post['feed'];
        $timestamp = (int)$post['timestamp'];
      }
      $result->close();
    }
    else {
      $this->Log('Post->Content 1: '.$mysqli->error);
    }
    $formatted_date = date('j F Y, g:i a', $timestamp);
    $atom_date = date(DATE_ATOM, $timestamp);
    $date = '<time class="dt-published" datetime="'.$atom_date.'">'.
      $formatted_date.'</time>';
    $permalink_url = $this->Url('', $permalink);
    $permalink_page = $this->user->page === $permalink;

    // Check if this is a tombstone post.
    if ($description === $this->Tombstone()) {
      if ($permalink_page) {
        header('HTTP/1.1 410 Gone');
        return '<article class="h-entry">'.
            '<div class="published">'.
              '<time class="dt-deleted" datetime="'.$atom_date.'">'.
                '<a href="'.$permalink_url.'" class="u-url">'.
                $formatted_date.'</a>'.
              '</time></div>'.
            '<div class="p-name e-content">'.$description.'</div>'.
          '</article>';
      }
      else {
        // Show an empty h-entry on the feed page so that readers can remove
        // cached entries.
        return '<article class="h-entry">'.
          '<time class="dt-deleted" datetime="'.$atom_date.'">'.
            '<a href="'.$permalink_url.'" class="u-url"></a>'.
          '</time></article>';
      }
    }

    // When creating a new post, the writer module can designate a different
    // page, so only return content when on this post's feed or permalink page.
    if (!$permalink_page &&
        !preg_match('/^'.$feed.'(-p[0-9]+)?$/', $this->user->page)) {
      return false;
    }

    // Link to previous and next posts on permalink pages.
    $navigation = '';
    if ($permalink_page) {
      // When a post is copied it keeps the same permalink, so don't show
      // duplicate posts in this case.
      $duplicate = false;
      $query = 'SELECT box_id FROM post WHERE user = "'.$this->owner.'" AND '.
        'permalink = "'.$permalink.'" ORDER BY box_id LIMIT 1';
      if ($result = $mysqli->query($query)) {
        if ($post = $result->fetch_assoc()) {
          $duplicate = (int)$post['box_id'] !== $id;
        }
        $result->close();
      }
      else {
        $this->Log('Post->Content 2: '.$mysqli->error);
      }
      if ($duplicate) {
        $mysqli->close();
        return false;
      }

      // Show the webmention endpoint on permalink pages.
      header('Link: <'.$base_url.'/php/webmention.php>; rel="webmention"');
      // Also specify that this is the canonical version of the content.
      header('Link: <'.$base_url.$permalink_url.'>; rel="canonical"', false);
      $navigation = $this->Navigation($feed, $timestamp);
    }
    $mysqli->close();

    // If title and description are both empty, assume this post module
    // should not be shown yet and return false so that it's hidden.
    if ($title === '' && $description === '') return false;

    $author = $this->LookupUser($author, $base_url);
    // Permalink page requires h-entry class on the parent group div so that
    // comments can be nested. This is handled by the Page class.
    $post_format = $permalink_page ? 'permalink-' : '';
    // When there is no title, link the permalink to the date.
    if ($title === '') {
      $post_format .= 'post-no-title';
      $date = '<time class="dt-published" datetime="'.$atom_date.'">'.
        '<a href="'.$permalink_url.'" class="u-url">'.$formatted_date.'</a>'.
        '</time>';
    }
    else {
      $post_format .= 'post-with-title';
      if ($permalink_page) {
        $title = '<h2 class="title"><a href="'.$permalink_url.'" '.
          'class="p-name u-url">'.$title.'</a></h2>';
      }
      else {
        $title = '<h4 class="title"><a href="'.$permalink_url.'" '.
          'class="p-name u-url">'.$title.'</a></h4>';
      }
    }
    $patterns = ['/!title/', '/!description/', '/!author/', '/!category/',
                 '/!media/', '/!date/', '/!navigation/'];
    $replacements = [$title, $description, $author, $category, $media, $date,
                     $navigation];
    $content = $this->Substitute($post_format, $patterns, $replacements);
    if ($this->Substitute('post-web-actions') === 'true') {
      // Add the base url to the permalink url for web actions.
      $permalink_url = $base_url.$permalink_url;
      $content .= '<div class="post-web-actions">'.
        '<indie-action do="like" with="'.$permalink_url.'">'.
          '<a href="#" class="action">'.
            '<span class="ui-icon ui-icon-star"></span>like</a>'.
        '</indie-action>'.
        '<indie-action do="repost" with="'.$permalink_url.'">'.
          '<a href="#" class="action">'.
            '<span class="ui-icon ui-icon-refresh"></span>share</a>'.
        '</indie-action>'.
        '<indie-action do="reply" with="'.$permalink_url.'">'.
          '<a href="#" class="action">'.
            '<span class="ui-icon ui-icon-arrowreturnthick-1-w"></span>'.
            'reply</a>'.
        '</indie-action>'.
        '<span class="indie-config-info">'.
          'Want to share this? Click to choose a site:</span>'.
        '<a href="#" class="indie-config" title="web action settings">'.
          '<span class="ui-icon ui-icon-gear"></span>settings</a></div>';
    }
    return $content;
  }

  public function Copy($id, $new_page, $old_owner, $old_id) {
    $title = '';
    $description = '';
    $category = '';
    $enclosure = '';
    $permalink = '';
    $timestamp = 0;
    $mysqli = connect_db();
    $query = 'SELECT title, description, author, category, enclosure, '.
      'permalink, timestamp FROM post WHERE user = "'.$old_owner.'" AND '.
      'box_id = '.$old_id;
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $title = $mysqli->escape_string($post['title']);
        $description = $mysqli->escape_string($post['description']);
        $author = $mysqli->escape_string($post['author']);
        $category = $mysqli->escape_string($post['category']);
        $enclosure = $mysqli->escape_string($post['enclosure']);
        $permalink = $mysqli->escape_string($post['permalink']);
        $timestamp = (int)$post['timestamp'];
      }
      $result->close();
    }
    else {
      $this->Log('Post->Copy 1: '.$mysqli->error);
    }
    // Point the new module at the existing permalink page.
    $query = 'INSERT INTO modules VALUES ("'.$this->owner.'", '.
      '"'.$permalink.'", '.$id.', "post", "'.$this->Group().'", '.
      $this->user->config->PermalinkOrder().', "'.$this->Placement().'", 0)';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Copy 2: '.$mysqli->error);
    }
    $mysqli->close();

    $this->Insert($id, $author, $new_page, $title, $description, $category,
                  $enclosure, $permalink, $timestamp, true);
    $this->CopyStyle($id, $old_owner, $old_id);
    $this->Notify($id, 'post', 'feed', $new_page, $this->Published($new_page));
  }

  public function Cron() {
    set_time_limit(0);
    $receive = [];
    $send = [];
    $mysqli = connect_db();
    $query = 'SELECT source, target FROM post_queue WHERE source != ""';
    if ($result = $mysqli->query($query)) {
      while ($post_queue = $result->fetch_assoc()) {
        $receive[] = $post_queue;
      }
      $result->close();
    }
    else {
      $this->Log('Post->Cron 1: '.$mysqli->error);
    }
    $base_url = $this->user->config->Secure() ? 'https://' : 'http://';
    $base_url .= $this->user->config->ServerName();
    foreach ($receive as $webmention) {
      $us_source = $webmention['source'];
      $us_target = $webmention['target'];
      $full_target = $us_target;
      if (stripos($full_target, 'http') !== 0) {
        $full_target = $base_url.$us_target;
      }
      list($this->user->page, $this->owner) = page_owner($full_target);
      $result = $this->ProcessReceivedWebmention($us_source, $us_target);
      // The third result parameter indicates if a comment was updated,
      // in which case webmentions are resent for all links in the post.
      if ($result[2]) $send[] = $us_target;
    }
    $already_sent = [];
    foreach ($send as $us_target) {
      if (!in_array($us_target, $already_sent)) {
        $full_target = $us_target;
        if (stripos($full_target, 'http') !== 0) {
          $full_target = $base_url.$us_target;
        }
        list($this->user->page, $this->owner) = page_owner($full_target);
        if ($this->IsPermalink()) {
          $query = 'SELECT description, category, feed FROM post WHERE '.
            'user = "'.$this->owner.'" AND permalink = "'.$this->user->page.'"';
          if ($result = $mysqli->query($query)) {
            if ($post = $result->fetch_assoc()) {
              $this->ContentUpdated($post['description'], $post['category'],
                                    $post['feed'], $this->user->page, false);
            }
            $result->close();
          }
          else {
            $this->Log('Post->Cron 2: '.$mysqli->error);
          }
        }
        $already_sent[] = $us_target;
      }
    }
    $query = 'DELETE FROM post_queue';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Cron 3: '.$mysqli->error);
    }

    // Tombstone posts are removed from the feed here after a week, which
    // should've given readers time to update their cache.
    $tombstone = $mysqli->escape_string($this->Tombstone());
    $query = 'UPDATE modules LEFT JOIN post ON modules.box_id = post.box_id '.
      'SET deleted = 1 WHERE description = "'.$tombstone.'" '.
      'AND timestamp < '.strtotime('-7 days');
    if (!$mysqli->query($query)) {
      $this->Log('Post->Cron 4: '.$mysqli->error);
    }
    $mysqli->close();
  }

  public function Factory($fn, $p = NULL) {
    if ($fn === 'Status') {
      return $this->Status($p);
    }
    if ($fn === 'NewComment') {
      return $this->NewComment();
    }
  }

  public function Group() {
    return 'post-comment';
  }

  public function IncludeScript() {
    return false;
  }

  public function Install($path) {
    $mysqli = connect_db();
    $query = 'CREATE TABLE IF NOT EXISTS post ('.
      'user VARCHAR(50) NOT NULL,'.
      'box_id INT UNSIGNED NOT NULL,'.
      'title VARCHAR(180),'.
      'description TEXT,'.
      'author VARCHAR(50),'.
      'category VARCHAR(200),'.
      'enclosure TEXT,'.
      'permalink VARCHAR(200),'.
      'feed VARCHAR(200),'.
      'timestamp INT(10) UNSIGNED NOT NULL,'.
      'PRIMARY KEY(user, box_id)'.
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Install 1: '.$mysqli->error);
    }

    $query = 'CREATE TABLE IF NOT EXISTS post_history ('.
      'user VARCHAR(50) NOT NULL,'.
      'box_id INT UNSIGNED NOT NULL,'.
      'title VARCHAR(180),'.
      'description TEXT,'.
      'author VARCHAR(50),'.
      'category VARCHAR(200),'.
      'enclosure TEXT,'.
      'permalink VARCHAR(200),'.
      'feed VARCHAR(200),'.
      'timestamp INT(10) UNSIGNED NOT NULL,'.
      'modified_by VARCHAR(50) NOT NULL,'.
      'PRIMARY KEY(user, box_id, timestamp)'.
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Install 2: '.$mysqli->error);
    }

    $query = 'CREATE TABLE IF NOT EXISTS post_queue ('.
      'source VARCHAR(200),'.
      'target VARCHAR(200),'.
      'timestamp INT(10) UNSIGNED NOT NULL,'.
      'PRIMARY KEY(source, target)'.
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Install 3: '.$mysqli->error);
    }

    $site_style = ['"",".post .thumb","width","20px"',
                   '"",".post .thumb","border-radius","2px"',
                   '"",".post .options > *","padding","5px"',
                   '"",".post .navigation .next","float","right"',
                   '"",".post-web-actions","padding-top","10px"',
                   '"",".post-web-actions a","padding","10px"',
                   '"",".post-web-actions a.highlight","font-weight","bold"'];
    $this->AddSiteStyle($site_style);

    // The two formats are required because p-name needs to be either on the
    // title or on the same div as e-content.
    $post_no_title = '<article class="h-entry">'.
      '<div class="published">'.
        'By <span class="h-card p-author">!author</span> on !date</div>'.
      '<div class="editable p-name e-content">!description</div>'.
      '<div class="options">!category</div>!navigation</article>';
    $post_with_title = '<article class="h-entry">!title'.
      '<div class="published">'.
        'By <span class="h-card p-author">!author</span> on !date</div>'.
      '<div class="editable e-content">!description</div>'.
      '<div class="options">!category</div>!navigation</article>';
    $permalink_no_title = '<article>'.
      '<div class="published">'.
        'By <span class="h-card p-author">!author</span> on !date</div>'.
      '<div class="editable p-name e-content">!description</div>'.
      '<div class="options">!category</div>!navigation</article>';
    $permalink_with_title = '<article>!title'.
      '<div class="published">'.
        'By <span class="h-card p-author">!author</span> on !date</div>'.
      '<div class="editable e-content">!description</div>'.
      '<div class="options">!category</div>!navigation</article>';
    $template = ['"post-no-title", "", '.
                   '"'.$mysqli->escape_string($post_no_title).'"',
                 '"post-with-title", "", '.
                   '"'.$mysqli->escape_string($post_with_title).'"',
                 '"permalink-post-no-title", "", '.
                   '"'.$mysqli->escape_string($permalink_no_title).'"',
                 '"permalink-post-with-title", "", '.
                   '"'.$mysqli->escape_string($permalink_with_title).'"'];
    $mysqli->close();
    $this->AddTemplate($template);
  }

  public function Placement() {
    return 'middle';
  }

  public function Publish($id, $update) {
    if (isset($id)) {
      $this->Notify($id, 'post', 'feed', $this->user->page, $update);
    }
    else {
      // When $id is not set the page has been made private. Remove users from
      // any post notifications groups if they don't have access permission.
      $this->RemoveNotification('post', $this->user->page);
    }
  }

  public function Remove($id) {
    $mysqli = connect_db();
    if (isset($id)) {
      // Copies of this post can point to the same permalink page, so only
      // remove it when there's only one reference left.
      $query = 'SELECT permalink FROM post WHERE user = "'.$this->owner.'" '.
        'AND permalink = (SELECT permalink FROM post WHERE '.
        'user = "'.$this->owner.'" AND box_id = '.$id.')';
      if ($result = $mysqli->query($query)) {
        if ($result->num_rows === 1) {
          $this->RemovePermalinkPage($id);
        }
        else if ($post = $result->fetch_assoc()) {
          $permalink = $post['permalink'];
          // Otherwise just set this module as deleted on the permalink page.
          $query = 'UPDATE modules SET deleted = 1 WHERE box_id = '.$id.
            ' AND page = "'.$permalink.'" AND user = "'.$this->owner.'"';
          if (!$mysqli->query($query)) {
            $this->Log('Post->Remove 1: '.$mysqli->error);
          }
        }
        $result->close();
      }
      else {
        $this->Log('Post->Remove 2: '.$mysqli->error);
      }
      $this->RemoveNotify($id);
      $this->UpdatePager($id);
      $tombstone = $mysqli->escape_string($this->Tombstone());
      $query = 'UPDATE post SET title = "", description = "'.$tombstone.'", '.
        'author = "", category = "", enclosure = "" WHERE '.
        'user = "'.$this->owner.'" AND box_id = '.$id;
      if (!$mysqli->query($query)) {
        $this->Log('Post->Remove 3: '.$mysqli->error);
      }
    }
    else {
      $query = 'DELETE FROM post WHERE user = "'.$this->owner.'"';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Remove 4: '.$mysqli->error);
      }
      $query = 'DELETE FROM post_history WHERE user = "'.$this->owner.'"';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Remove 5: '.$mysqli->error);
      }
    }
    $mysqli->close();
  }

  public function SetContent($id, $us_content) {
    $micropub = isset($_SESSION['micropub-endpoint']);
    $us_data = $micropub ? ['type' => ['h-entry'], 'properties' => []] : '';
    if (isset($us_content['data']) && $us_content['data'] !== '') {
      if ($this->owner === 'admin') {
        if ($micropub) {
          $us_data['properties']['content'] = [['html' => $us_content['data']]];
        }
        else {
          $us_data .= $us_content['data'];
        }
      }
      else {
        include_once 'library/HTMLPurifier.auto.php';
        $config = HTMLPurifier_Config::createDefault();
        $config->set('Attr.EnableID', true);
        $config->set('Attr.IDPrefix', 'anchor-');
        // Allow iframes from youtube and vimeo.
        $config->set('HTML.SafeIframe', true);
        $config->set('URI.SafeIframeRegexp',
                     '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|'.
                     'player\.vimeo\.com/video/)%');
        $purifier = new HTMLPurifier($config);
        if ($micropub) {
          $us_data['properties']['content'] =
            [['html' => $purifier->purify($us_content['data'])]];
        }
        else {
          $us_data .= $purifier->purify($us_content['data']);
        }
      }
    }
    $us_title = isset($us_content['title']) ? $us_content['title'] : '';
    $mp_syndicate_to = '';
    // If the user has chosen to send the post to twitter or facebook, add a
    // link in the post to brid.gy to enable webmentions.
    if (isset($us_content['twitter']) && (int)$us_content['twitter'] === 1) {
      if ($micropub) {
        $mp_syndicate_to .= 'https://twitter.com';
      }
      else {
        $twitter_link = 'https://brid.gy/publish/twitter';
        if (strpos($us_data, $twitter_link) === false) {
          // A link back to the user's site is omitted when the post is less
          // than 140 characters and it doesn't have a title (when a title is
          // given, only that and the link back are shown).
          if (strlen(strip_tags($us_data)) < 140 && $us_title === '') {
            $twitter_link .= '?bridgy_omit_link=true';
          }
          $us_data .= '<a href="'.$twitter_link.'"></a>';
        }
        // Also add u-photo to any images so that brid.gy posts them too.
        if (strpos($us_data, '<img') !== false) {
          $regex = '/<img .*src="(.+)".*>/U';
          $replacement = '<img src="$1" class="u-photo">';
          $us_data = preg_replace($regex, $replacement, $us_data);
        }
      }
    }
    if (isset($us_content['facebook']) && (int)$us_content['facebook'] === 1) {
      if ($micropub) {
        if ($mp_syndicate_to !== '') $mp_syndicate_to .= ',';
        $mp_syndicate_to .= 'https://facebook.com';
      }
      else {
        // Don't need the link back on Facebook as it shows the full content.
        $facebook_link =
          'https://brid.gy/publish/facebook?bridgy_omit_link=true';
        if (strpos($us_data, $facebook_link) === false) {
          $us_data .= '<a href="'.$facebook_link.'"></a>';
        }
        if (strpos($us_data, '<img') !== false) {
          $regex = '/<img .*src="(.+)".*>/U';
          $replacement = '<img src="$1" class="u-photo">';
          $us_data = preg_replace($regex, $replacement, $us_data);
        }
      }
    }
    if ($mp_syndicate_to !== '') {
      $us_data['properties']['mp-syndicate-to'] = $mp_syndicate_to;
    }
    // If a webaction is set, make sure it's marked up correctly.
    if (isset($us_content['webactionType']) &&
        isset($us_content['webactionUrl'])) {
      $us_type = $us_content['webactionType'];
      $us_url = $us_content['webactionUrl'];
      $class = '';
      if ($us_type === 'like') {
        $class = 'like-of';
      }
      else if ($us_type === 'share') {
        $class = 'repost-of';
        if (!$micropub) {
          // The author is kept as that of the original post, so show the user
          // who is sharing it as a category.
          if (!isset($us_content['category'])) $us_content['category'] = '';
          $us_content['category'] .= ',reposted by '.$this->user->name.','.
            $us_url;
        }
      }
      else if ($us_type === 'reply' || $us_type === 'reply to') {
        $class = 'in-reply-to';
        if (!$micropub) {
          // Add the url as a category for our permalink post so that it doesn't
          // need to be visible in the content of the comment.
          if (!isset($us_content['category'])) $us_content['category'] = '';
          $us_content['category'] .= ',In reply to,'.$us_url;
        }
      }
      // Mark up the existing content or add a link if the url wasn't found.
      if ($class !== '') {
        if ($micropub) {
          $us_data['properties'][$class] = $us_url;
        }
        else {
          if (strpos($us_data, $us_url) !== false &&
              strpos($us_data, $class) === false) {
            $regex = '/<a .*href="'.preg_quote($us_url, '/').'".*>/iU';
            $replacement = '<a href="'.$us_url.'" class="u-'.$class.'">';
            $us_data = preg_replace($regex, $replacement, $us_data);
          }
          else {
            $us_data .= '<a href="'.$us_url.'" class="u-'.$class.'"></a>';
          }
        }
      }
    }
    if ($micropub) {
      if ($us_title !== '') $us_data['properties']['name'] = $us_title;
      if (isset($us_content['category']) && $us_content['category'] !== '') {
        foreach (explode(',', $us_content['category']) as $tag) {
          $us_data['properties']['category'][] = $tag;
        }
      }
      $this->Micropub($us_data);
      return;
    }

    $mysqli = connect_db();
    // Titles can be a maximum of 180 characters when stored in the database.
    $title = $mysqli->escape_string(substr($us_title, 0, 180));
    $description = $mysqli->escape_string($us_data);
    $author = isset($us_content['author']) ?
      $mysqli->escape_string(htmlspecialchars($us_content['author'])) :
      $this->user->name;
    $us_category = isset($us_content['category']) ?
      $us_content['category'] : '';
    $category = $mysqli->escape_string($us_category);
    $enclosure = isset($us_content['enclosure']) ?
      $mysqli->escape_string($us_content['enclosure']) : '';
    $permalink = '';
    $old_title = '';
    $us_old_description = '';
    $old_author = '';
    $old_category = '';
    $us_old_category = '';
    $old_enclosure = '';
    $old_permalink = '';
    $feed = '';
    $query = 'SELECT title, description, author, category, enclosure, '.
      'permalink, feed FROM post WHERE user = "'.$this->owner.'" AND '.
      'box_id = '.$id;
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $old_title = $mysqli->escape_string($post['title']);
        $us_old_description = $post['description'];
        $old_author = $mysqli->escape_string($post['author']);
        $us_old_category = $post['category'];
        $old_category = $mysqli->escape_string($us_old_category);
        $old_enclosure = $mysqli->escape_string($post['enclosure']);
        $old_permalink = $mysqli->escape_string($post['permalink']);
        $permalink = $old_permalink;
        $feed = $mysqli->escape_string($post['feed']);
      }
      $result->close();
    }
    else {
      $this->Log('Post->SetContent 1: '.$mysqli->error);
    }
    // If only data was sent, use the previous values for other fields.
    if (!isset($us_content['dataOnly']) || $us_content['dataOnly'] !== false) {
      $title = $old_title;
      $author = $old_author;
      $category = $old_category;
      $enclosure = $old_enclosure;
    }
    // Only create a new permalink if the title was changed, or if a new post.
    // Otherwise don't update the timestamp for the post.
    $time = time();
    $timestamp_query = '';
    $empty_post = '<i>empty post.</i>';
    if ($permalink === '' || $title !== $old_title) {
      $timestamp_query = ', timestamp = '.$time;
      $date = date('Y-m-d', $time);
      // Remove characters from the title or description that don't belong in
      // permalinks, but replace spaces with underscores.
      $patterns = ['/[^a-z0-9\s_-]/i', '/ /'];
      $replacements = ['', '_'];
      // When the title is empty, use the start of description as the peramlink.
      if ($title === '') {
        if (strip_tags($description) === '') {
          $permalink = $date.'-'.mt_rand();
          // Having both an empty title and description is really bad because
          // Content will return false, which means the post can't be removed.
          if ($description === '') {
            $description = $empty_post;
          }
        }
        else {
          $start = substr(strip_tags($description), 0, 50);
          // description has entities encoded, want to decode them so they
          // can be removed.
          $start = html_entity_decode($start, ENT_QUOTES);
          // it can also have escaped newlines because of calling
          // mysqli escape_string above, replace them with underscores.
          $start = preg_replace('/\\\n/', '_', $start);
          $permalink = $date.'-'.preg_replace($patterns, $replacements, $start);
        }
      }
      else {
        $permalink = $date.'-'.preg_replace($patterns, $replacements, $title);
      }
      // Now check if this permalink already exists as a page name, and
      // increment a suffix if there's a conflict.
      $query = 'SELECT DISTINCT page FROM modules WHERE '.
        'user = "'.$this->owner.'" AND page LIKE "'.$permalink.'%"';
      if ($result = $mysqli->query($query)) {
        if ($result->num_rows > 0) {
          $permalink .= '-'.($result->num_rows + 1);
        }
        $result->close();
      }
      else {
        $this->Log('Post->SetContent 2: '.$mysqli->error);
      }
      // The permalink may not have changed just because the title has
      // (due to characters that are removed), so compare first.
      if ($permalink !== $old_permalink) {
        $this->Permalink($id, $permalink, $old_permalink, $feed);
      }
    }
    // Otherwise check if anything else has changed and return if not.
    // Note that having a notify flag set to true overrides the content check.
    else if ((!isset($us_content['notify']) ||
              $us_content['notify'] === false) &&
             $us_data === $us_old_description && $author === $old_author &&
             $category === $old_category && $enclosure === $old_enclosure) {
      $mysqli->close();
      return;
    }

    $query = 'UPDATE post SET title = "'.$title.'", '.
      'description = "'.$description.'", author = "'.$author.'", '.
      'category = "'.$category.'", enclosure = "'.$enclosure.'", '.
      'permalink = "'.$permalink.'", feed = "'.$feed.'"'.$timestamp_query.
      ' WHERE user = "'.$this->owner.'" AND box_id = '.$id;
    if (!$mysqli->query($query)) {
      $this->Log('Post->SetContent 3: '.$mysqli->error);
    }
    $query = 'INSERT INTO post_history VALUES ("'.$this->owner.'", '.
      $id.', "'.$title.'", "'.$description.'", "'.$author.'", '.
      '"'.$category.'", "'.$enclosure.'", "'.$permalink.'", "'.$feed.'", '.
      $time.', "'.$this->user->name.'")';
    if (!$mysqli->query($query)) {
      $this->Log('Post->SetContent 4: '.$mysqli->error);
    }
    $mysqli->close();

    // When a post has been updated, the only time Notify is not called is
    // when notify is set and the given value is set to false.
    if (isset($_POST['notify']) && $_POST['notify'] === 'false') return;

    // If a post is still empty the second time SetContent is called, remove
    // it before any notifications are sent. (SetContent is first called from
    // an Extended Editor callback, where notify is set to false.)
    if ($description === $empty_post) {
      // Passing the permalink in here means a tombstone post isn't created.
      $this->RemovePermalinkPage($id, $permalink);
      $this->RemoveNotify($id);
      $this->UpdatePager($id);
      $mysqli = connect_db();
      $query = 'DELETE FROM post WHERE user = "'.$this->owner.'" AND '.
        'box_id = '.$id;
      if (!$mysqli->query($query)) {
        $this->Log('Post->SetContent 5: '.$mysqli->error);
      }
      $mysqli->close();
      return;
    }

    $published = $this->Published($feed);
    // Note that modules need to decide what notifications they want to give.
    // Not bothering with add or edit notifications here, instead just
    // pushing all changes into the main page feed when the page is published.
    $this->Notify($id, 'post', 'feed', $feed, $published);
    // Also create individual notifications for users that request them.
    // Note that the feed name is also passed in as the description here.
    $this->Notification('post', $author, $feed, 'feed', $feed, $permalink);
    if ($published === 0) return $this->Url('', $permalink);

    // Webmentions will be sent to any links in the description and categories.
    // Also check for links in the old content because they might have been
    // removed, in which case we still send a webmention to notify the target
    // of the removal. (The data is stored here and processed from a callback.)
    $us_data .= $us_old_description;
    $us_category .= $old_category;
    $key = $this->owner.'-'.$this->user->page;
    if (isset($_SESSION['post-update'])) {
      $_SESSION['post-update'][$key] = ['content' => $us_data,
                                        'category' => $us_category,
                                        'feed' => $feed,
                                        'permalink' => $permalink];
    }
    else {
      $_SESSION['post-update'] = [$key => ['content' => $us_data,
                                           'category' => $us_category,
                                           'feed' => $feed,
                                           'permalink' => $permalink]];
    }
    // This is returned for our own micropub endpoint.
    return $this->Url('', $permalink);
  }

  public function Update() {
    $mysqli = connect_db();
    $query = 'CREATE TABLE IF NOT EXISTS post_queue ('.
      'source VARCHAR(200),'.
      'target VARCHAR(200),'.
      'timestamp INT(10) UNSIGNED NOT NULL,'.
      'PRIMARY KEY(source, target)'.
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Update: '.$mysqli->error);
    }
    $mysqli->close();
  }

  public function UpdateScript($path) {

  }

  // Public functions that aren't part of interface here /////////////////////

  public function ReceiveWebmention($us_source, $us_target) {
    // The server name is required by page_owner, but it doesn't have to be
    // matched in the source if given a relative url (ie by our own server).
    $full_target = $us_target;
    if (stripos($full_target, 'http') !== 0) {
      $full_target = $this->user->config->Secure() ? 'https://' : 'http://';
      $full_target .= $this->user->config->ServerName().$us_target;
    }
    list($this->user->page, $this->owner) = page_owner($full_target);
    // Check that target is an existing page on this server, and that it's a
    // permalink for a post module, or a page containing a detail module. The
    // latter case assumes there is a representative h-card on the page.
    if (!$this->IsPermalink() && !$this->AlreadyOnPage('detail')) {
      return ['HTTP/1.1 400 Bad Request',
              'Target URL does not accept webmentions: '.$us_target];
    }

    $recent = false;
    $mysqli = connect_db();
    $target = $mysqli->escape_string($us_target);
    $query = 'SELECT timestamp FROM post_queue WHERE target = "'.$target.'" '.
      'ORDER BY timestamp LIMIT 1';
    if ($result = $mysqli->query($query)) {
      if ($post_queue = $result->fetch_assoc()) {
        // This is the oldest item in the queue, so continue waiting if it's
        // less than 5 minutes old.
        $recent = $post_queue['timestamp'] > strtotime('-5 minuntes');
      }
      $result->close();
    }
    else {
      $this->Log('Post->ReceiveWebmention 1: '.$mysqli->error);
    }
    if ($recent) {
      $source = $mysqli->escape_string($us_source);
      $query = 'INSERT INTO post_queue VALUES ("'.$source.'", "'.$target.'", '.
        time().') ON DUPLICATE KEY UPDATE timestamp = '.time();
      if (!$mysqli->query($query)) {
        $this->Log('Post->ReceiveWebmention 2: '.$mysqli->error);
      }
      $mysqli->close();
      return ['HTTP/1.1 202 Accepted',
              'Thanks! Your webmention has been queued for processing.'];
    }

    $updated = false;
    // Process all queued webmentions for this target.
    $query = 'SELECT source FROM post_queue WHERE target = "'.$target.'" '.
      'AND source != "" ORDER BY timestamp';
    if ($result = $mysqli->query($query)) {
      while ($post_queue = $result->fetch_assoc()) {
        $received = $this->ProcessReceivedWebmention($post_queue['source'],
                                                     $us_target);
        if ($received[2]) $updated = true;
      }
      $result->close();
    }
    else {
      $this->Log('Post->ReceiveWebmention 3: '.$mysqli->error);
    }
    // Clear the queue for the target, but add back in a row with an empty
    // source so that the timestamp can be checked by the next webmention.
    $query = 'DELETE FROM post_queue WHERE target = "'.$target.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->ReceiveWebmention 4: '.$mysqli->error);
    }
    $query = 'INSERT INTO post_queue VALUES ("", "'.$target.'", '.time().')';
    if (!$mysqli->query($query)) {
      $this->Log('Post->ReceiveWebmention 5: '.$mysqli->error);
    }
    // Lastly process received webmention for the most recent source.
    $received = $this->ProcessReceivedWebmention($us_source, $us_target);
    // If any of the received webmentions updated comments, resend webmentions
    // for this page.
    if (($updated || $received[2]) && $this->IsPermalink()) {
      $query = 'SELECT description, category, feed FROM post WHERE '.
        'user = "'.$this->owner.'" AND permalink = "'.$this->user->page.'"';
      if ($result = $mysqli->query($query)) {
        if ($post = $result->fetch_assoc()) {
          $this->ContentUpdated($post['desccription'], $post['category'],
                                $post['feed'], $this->user->page, false);
        }
        $result->close();
      }
      else {
        $this->Log('Post->ReceiveWebmention 6: '.$mysqli->error);
      }
    }
    $mysqli->close();
    return [$received[0], $received[1]];
  }

  // Private functions below here ////////////////////////////////////////////

  private function AddSyndicationLink($us_url, $permalink) {
    $mysqli = connect_db();
    $us_url = '<a href="'.$us_url.'" class="u-syndication"></a>';
    $url = $mysqli->escape_string($us_url);
    $query = 'UPDATE post SET description = CONCAT(description, "'.$url.'") '.
      'WHERE user = "'.$this->owner.'" AND permalink = "'.$permalink.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->AddSyndicationLink: '.$mysqli->error);
    }
    $mysqli->close();
  }

  private function ContentUpdated($data, $category, $feed,
                                  $permalink, $updated = true) {
    $status = '';
    $already_sent = [];
    $doc = new DOMDocument();
    @$doc->loadHTML($data);
    $xpath = new DOMXpath($doc);
    foreach ($xpath->query('//a[@href]') as $link) {
      $url = $link->getAttribute('href');
      if (!in_array($url, $already_sent)) {
        $status .= $this->SendWebmention($url, $permalink);
        $already_sent[] = $url;
      }
    }
    // Also check for links in category. Note that the anchor is created in the
    // Content method, so need to match only the url.
    if (preg_match_all('/https?:\/\/[^,]+/', $category, $match)) {
      foreach (array_unique($match[0]) as $url) {
        // Links can be added to both the content and as a category, so check
        // if a webmention has just been sent.
        if (!in_array($url, $already_sent)) {
          $status .= $this->SendWebmention($url, $permalink);
        }
      }
    }
    // Only update the feeds when the post content is updated (which is false
    // here when sending webmentions for a new comment).
    if ($updated) {
      // Update the feed, which will also notify subscribers.
      $reader = new Module($this->user, $this->owner, 'reader');
      if ($reader->IsInstalled()) {
        $page = 'rss/index.php?page='.$feed;
        $url = $this->user->config->Secure() ? 'https://' : 'http://';
        $url .= $this->user->config->ServerName();
        $path = $this->owner === 'admin' ? $page : $this->owner.'/'.$page;
        $reader->Factory('UpdateFeed', $url.'/'.$path);
        // Also update the microformats feed.
        $reader->Factory('UpdateFeed', $url.$this->Url('', $feed));
      }
    }
    return $status;
  }

  private function Endpoint($url) {
    $_SESSION['endpoint'] = '';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) {
      if (stripos($header, 'Link:') === 0 && stripos($header, 'webmention')) {
        $regex = '/<([^>]+)>; rel="?(([^"]* )?webmention( [^"]*)?)"?/i';
        if (preg_match($regex, $header, $match)) {
          if (in_array('webmention', explode(' ', strtolower($match[2])))) {
            // This makes sure the first discovered endpoint is used.
            if ($_SESSION['endpoint'] === '') $_SESSION['endpoint'] = $match[1];
          }
        }
      }
      return strlen($header);
    });
    $body = curl_exec($ch);
    curl_close($ch);
    $endpoint = $_SESSION['endpoint'];
    if ($endpoint === '') {
      $doc = new DOMDocument();
      @$doc->loadHTML($body);
      $xpath = new DOMXpath($doc);
      $query = '//a[@rel and @href] | //link[@rel and @href]';
      foreach ($xpath->query($query) as $link) {
        $rel_values = explode(' ', strtolower($link->getAttribute('rel')));
        if (in_array('webmention', $rel_values)) {
          $endpoint = trim($link->getAttribute('href'));
          if ($endpoint === '') $endpoint = $url;
          break;
        }
      }
    }
    $regex = '/^(?:https?:\/\/)?[\/]*([^\/]+)/i';
    if ($endpoint === '') {
      if ($this->Substitute('post-webmention-debug') === 'true') {
        $this->Log('Post->Endpoint: No endpoint found at '.$url);
      }
    }
    else if (preg_match($regex, $endpoint, $match)) {
      if (strpos($match[1], '127.') === 0 ||
          strtolower($match[1]) === 'localhost') {
        if ($this->Substitute('post-webmention-debug') === 'true') {
          $this->Log('Post->Endpoint: Invalid endpoint found at '.$url);
        }
        $endpoint = '';
      }
    }
    include_once 'library/Mf2/Parser.php';
    // Look for a canonical h-card to add to the nickname cache.
    $mf = Mf2\parse($body, $url);
    foreach ($mf['items'] as $hcard) {
      // Only interested in an h-card by itself in this case and must have a
      // url property matching the url provided as a parameter.
      if (in_array('h-card', $hcard['type']) &&
          isset($hcard['properties']['url']) &&
          (in_array($url, $hcard['properties']['url']))) {
        $properties = $hcard['properties'];
        $mysqli = connect_db();
        $name = isset($properties['name'][0]) ?
          $mysqli->escape_string($properties['name'][0]) : '';
        $nickname = isset($properties['nickname'][0]) ?
          $mysqli->escape_string($properties['nickname'][0]) : '';
        $photo = isset($properties['photo'][0]) ?
          $mysqli->escape_string($properties['photo'][0]) : '';
        $reachable = $endpoint === '' ? '0' : '1';
        $query = 'INSERT INTO nickname VALUES ("'.$name.'", '.
          '"'.$mysqli->escape_string($url).'", "'.$photo.'", "'.$nickname.'", '.
          $reachable.') ON DUPLICATE KEY UPDATE name = "'.$name.'", photo = '.
          '"'.$photo.'", nickname = "'.$nickname.'", reachable = '.$reachable;
        if (!$mysqli->query($query)) {
          $this->Log('Post->Endpoint: '.$mysqli->error);
        }
        $mysqli->close();
        break;
      }
    }
    if ($endpoint === '') return '';

    // Turn relative endpoints into absolute ones using the given url.
    if (stripos($endpoint, 'http') !== 0) {
      if (preg_match('/^(https?:\/\/[^\/]+)/i', $url, $match)) {
        if (strpos($endpoint, '/') === 0) {
          $endpoint = $match[1].$endpoint;
        }
        else {
          // No leading slash means the endpoint is relative to the url path,
          // so match everything except for the last path segment.
          if (preg_match('/^(https?:\/\/.+\/)[^\/]*$/i', $url, $match)) {
            $endpoint = $match[1].$endpoint;
          }
          else {
            // This catches a url without any path.
            $endpoint = $url.'/'.$endpoint;
          }
        }
      }
    }
    if (strpos($url, '?bridgy_omit_link=true') !== false) {
      // The bridgy_omit_link query parameter needs to be on the request to the
      // endpoint, not the url of the target, but the current method of marking
      // up the content provides an easy way to know when to add it here.
      $endpoint .= '?bridgy_omit_link=true';
    }
    return $endpoint;
  }

  private function Hide($id, $page, $deleted) {
    $mysqli = connect_db();
    $query = 'UPDATE modules SET deleted = '.$deleted.' WHERE '.
      'user = "'.$this->owner.'" AND box_id = '.$id.' AND page = "'.$page.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Hide: '.$mysqli->error);
    }
    $mysqli->close();
  }

  private function Insert($id, $author, $feed, $title = '',
                          $description = '', $category = '',
                          $enclosure = '', $permalink = '',
                          $timestamp = 0, $history = false) {
    if ($timestamp === 0) {
      $timestamp = time();
    }
    $mysqli = connect_db();
    $query = 'INSERT INTO post VALUES ("'.$this->owner.'", '.$id.', '.
      '"'.$title.'", "'.$description.'", "'.$author.'", "'.$category.'", '.
      '"'.$enclosure.'", "'.$permalink.'", "'.$feed.'", '.$timestamp.')';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Insert 1: '.$mysqli->error);
    }
    // Don't copy into history unless specified. Need to be careful due to
    // the way new posts are created and then immediately saved with their
    // new content, both Insert and SetContent can be called within a
    // second which will duplicate the primary key.
    if ($history) {
      $query = 'INSERT INTO post_history VALUES ("'.$this->owner.'", '.
        $id.', "'.$title.'", "'.$description.'", "'.$category.'", '.
        '"'.$author.'", "'.$enclosure.'", "'.$permalink.'", "'.$feed.'", '.
        $timestamp.', "'.$this->user->name.'")';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Insert 2: '.$mysqli->error);
      }
    }
    else {
      // If using the pager module, older posts are moved to a new page when
      // the posts per page limit is reached. (Note: this isn't used when
      // copying pages of posts).
      $pager = new Module($this->user, $this->owner, 'pager');
      if ($pager->IsInstalled()) {
        $pager->Factory('Move', $feed);
      }
    }
    $mysqli->close();
  }

  private function IsPermalink() {
    if ($this->Published() === 0) return false;

    $permalink = false;
    $mysqli = connect_db();
    $query = 'SELECT permalink FROM post WHERE user = "'.$this->owner.'" AND '.
      'permalink = "'.$this->user->page.'"';
    if ($result = $mysqli->query($query)) {
      if ($result->num_rows === 1) {
        $permalink = true;
      }
      $result->close();
    }
    else {
      $this->Log('Post->IsPermalink: '.$mysqli->error);
    }
    $mysqli->close();
    return $permalink;
  }

  private function LookupAuthor($name, $url) {
    if ($name === '') $name = 'unknown';
    // If just name is returned, make sure it at least gets marked up properly.
    // Note that a u-url is required here because in the case of reposts, the
    // url of the user making the repost will be used if not found previously.
    $author = '<a class="p-name u-url" href="'.$url.'">'.$name.'</a>';
    $mysqli = connect_db();
    $name = $mysqli->escape_string($name);
    // The url provided here is ther permalink, want to use the domain to
    // make sure we have the right name in case there are collisions.
    if (preg_match('/^https?:\/\/([^\/]+)/i', $url, $match)) {
      $url = $match[1];
    }
    $url = $mysqli->escape_string($url);
    $query = 'SELECT url, photo FROM nickname WHERE name = "'.$name.'" AND '.
      'url LIKE "%'.$url.'%"';
    if ($result = $mysqli->query($query)) {
      if ($nickname = $result->fetch_assoc()) {
        $author = '';
        $url = $nickname['url'];
        if ($nickname['photo'] !== '') {
          $author = '<a href="'.$url.'">'.
            '<img class="thumb u-photo" src="'.$nickname['photo'].'"></a> ';
        }
        $author .= '<a class="p-name u-url" href="'.$url.'">'.$name.'</a>';
      }
      $result->close();
    }
    else {
      $this->Log('Post->LookupAuthor: '.$mysqli->error);
    }
    $mysqli->close();
    return $author;
  }

  private function LookupName($tag) {
    $name = '';
    $tag = trim($tag);
    if (stripos($tag, 'http') === 0) {
      if (preg_match('/^https?:\/\/([^\/]+\/?[^\/]*)/i', $tag, $match)) {
        $tag = $match[1];
      }
      $mysqli = connect_db();
      $tag = $mysqli->escape_string($tag);
      $query = 'SELECT name FROM nickname WHERE url LIKE "%'.$tag.'%"';
      if ($result = $mysqli->query($query)) {
        if ($nickname = $result->fetch_assoc()) {
          $name = $nickname['name'];
        }
        $result->close();
      }
      else {
        $this->Log('Post->LookupName: '.$mysqli->error);
      }
      $mysqli->close();
    }
    return $name;
  }

  private function LookupUser($user, $base_url) {
    $detail = new Module($this->user, $this->owner, 'detail');
    if ($detail->IsInstalled()) {
      $user_detail = $detail->Factory('User', $user);
      $name = '';
      if ($user_detail['first'] !== '') {
        $name = $user_detail['first'];
      }
      if ($user_detail['last'] !== '') {
        if ($name !== '') $name .= ' ';
        $name .= $user_detail['last'];
      }
      // If name is empty, the current value for user is used with the Detail
      // module didn't match an existing user.
      if ($name !== '') {
        $url = $base_url;
        if ($user !== 'admin') {
          $url .= '/'.$user;
        }
        $user = '';
        if ($user_detail['thumbnail'] !== '') {
          $user = '<a href="'.$url.'">'.$user_detail['thumbnail'].'</a> ';
        }
        $user .= '<a class="p-name u-url" href="'.$url.'">'.$name.'</a>';
      }
    }
    return $user;
  }

  private function Micropub($us_data) {
    $micropub = $_SESSION['micropub-endpoint'];
    $curl_headers = ['Authorization: Bearer '.$_SESSION['access-token'],
                     'Content-Type: application/json'];
    $ch = curl_init($micropub);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($us_data));
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) {
      if (preg_match('/^Location:(.+)$/', $header, $match)) {
        $_SESSION['micropub-status'] = 'Published to: '.$match[1];
      }
      return strlen($header);
    });
    $body = curl_exec($ch);
    if (curl_errno($ch) === 0) {
      $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if ($http_code !== 201 && $http_code !== 202) {
        $_SESSION['micropub-status'] = 'Publish error. HTTP code: '.$http_code;
        $this->Log('Post->Micropub 1: Error posting to '.$micropub.
               "\nHTTP code: ".$http_code."\nBody: ".$body);
      }
    }
    else {
      $_SESSION['micropub-status'] = 'Couldn\'t connect to '.$micropub;
      $this->Log('Post->Micropub 2: Error connecting to '.$micropub.
                 "\nCurl error: ".curl_error($ch));
    }
    curl_close($ch);
  }

  private function Navigation($feed, $timestamp) {
    $mysqli = connect_db();
    $navigation = '';
    $tombstone = $mysqli->escape_string($this->Tombstone());
    $query = 'SELECT title, permalink FROM post WHERE '.
      'user = "'.$this->owner.'" AND description != "'.$tombstone.'" AND '.
      'feed = "'.$feed.'" AND timestamp < '.$timestamp.' ORDER BY timestamp '.
      'DESC LIMIT 1';
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $navigation = '<div class="navigation">'.
          '<a href="'.$this->Url('', $post['permalink']).'" class="prev">';
        $navigation .= '&lt; ';
        if ($post['title'] === '') {
          $navigation .= 'older';
        }
        else {
          $navigation .= $post['title'];
        }
        $navigation .= '</a>';
      }
      $result->close();
    }
    else {
      $this->Log('Post->Navigation 1: '.$mysqli->error);
    }
    $query = 'SELECT title, permalink FROM post WHERE '.
      'user = "'.$this->owner.'" AND description != "'.$tombstone.'" AND '.
      'feed = "'.$feed.'" AND timestamp > '.$timestamp.' ORDER BY timestamp '.
      'LIMIT 1';
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        if ($navigation === '') {
          $navigation = '<div class="navigation">';
        }
        $navigation .=
          '<a href="'.$this->Url('', $post['permalink']).'" class="next">';
        if ($post['title'] === '') {
          $navigation .= 'newer';
        }
        else {
          $navigation .= $post['title'];
        }
        $navigation .= ' &gt;</a>';
      }
      $result->close();
    }
    else {
      $this->Log('Post->Navigation 2: '.$mysqli->error);
    }
    if ($navigation !== '') {
      $navigation .= '</div>';
    }
    $mysqli->close();
    return $navigation;
  }

  private function NewComment() {
    if (!$this->IsPermalink()) return;

    $mysqli = connect_db();
    $query = 'SELECT description, category, feed FROM post WHERE '.
      'user = "'.$this->owner.'" AND permalink = "'.$this->user->page.'"';
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $key = $this->owner.'-'.$this->user->page;
        if (isset($_SESSION['post-update'])) {
          $_SESSION['post-update'][$key] = ['content' => $post['description'],
                                            'category' => $post['category'],
                                            'feed' => $post['feed'],
                                            'permalink' => $this->user->page];
        }
        else {
          $_SESSION['post-update'] =
            [$key => ['content' => $post['description'],
                      'category' => $post['category'],
                      'feed' => $post['feed'],
                      'permalink' => $this->user->page]];
        }
      }
      $result->close();
    }
    else {
      $this->Log('Post->NewComment: '.$mysqli->error);
    }
    $mysqli->close();
  }

  private function Permalink($id, $permalink, $old_permalink, $feed) {
    $this->RemovePermalinkPage($id, $old_permalink);

    // Need to override the user set in config to match the current page owner.
    if ($this->user->name !== $this->owner) {
      $this->user->config->SetUser($this->owner);
    }
    // The box_order for the post module on the permalink page is configurable.
    $order = $this->user->config->PermalinkOrder();
    $placement = $this->Placement();
    $group = $this->Group();
    copy_page($this->user->config->PermalinkDefault(), $this->owner,
              $permalink, $this->owner, $feed, $order, $placement);
    if ($this->user->name !== $this->owner) {
      $this->user->config->SetUser($this->user->name);
    }

    $mysqli = connect_db();
    $query = 'INSERT INTO modules VALUES ("'.$this->owner.'", '.
      '"'.$permalink.'", '.$id.', "post", "'.$group.'", '.$order.', '.
      '"'.$placement.'", 0)';
    if (!$mysqli->query($query)) {
      $this->Log('Post->Permalink 1: '.$mysqli->error);
    }
    // If the current user is not the owner of the page, give them edit
    // permission for the permalink page. (They may have only had view
    // permission for the page containing the writer module, so this gives
    // them a way to edit their post).
    if ($this->user->name !== $this->owner) {
      $query = 'INSERT INTO user_permission VALUES ("'.$this->owner.'", '.
        '"'.$permalink.'", "'.$this->user->name.'", 1, 0, 0) '.
        'ON DUPLICATE KEY UPDATE edit = 1';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Permalink 2: '.$mysqli->error);
      }
    }
    // Update the comment notifications group for this page if the permalink
    // has changed, otherwise add the current user to the group if it's a new
    // permalink.
    if ($old_permalink === '') {
      $query = 'INSERT INTO groups VALUES ("'.$this->owner.'", '.
        '"comment-notifications-'.$permalink.'", "'.$this->user->name.'", 0)';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Permalink 3: '.$mysqli->error);
      }
    }
    else {
      $query = 'UPDATE groups SET '.
        'name = "comment-notifications-'.$permalink.'" WHERE '.
        'user = "'.$this->owner.'" AND '.
        'name = "comment-notifications-'.$old_permalink.'"';
      if (!$mysqli->query($query)) {
        $this->Log('Post->Permalink 4: '.$mysqli->error);
      }
    }
    $mysqli->close();
  }

  private function ProcessReceivedWebmention($us_source, $us_target) {
    $comment = new Module($this->user, $this->owner, 'comment');
    $comment_installed = $comment->IsInstalled();
    // Next check that a link to the target is found in the source (or that
    // the source has been removed, in which case try and delete a comment).
    $ch = curl_init($us_source);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $body = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 410) {
      $message = '';
      if ($comment_installed) {
        $id = $comment->Factory('MatchUrl', $us_source);
        if ($id !== 0) {
          $comment->Factory('RemoveWebmention', $id);
          $message = 'Thanks! Your webmention has been removed.';
        }
      }
      return ['HTTP/1.1 200 OK', $message, true];
    }

    // Look for meta http-equiv to support deleted static posts.
    if ($http_code === 200 && $position = stripos($body, '<meta http-equiv')) {
      $start = $position < 200 ? 0 : $position - 200;
      $check = substr($body, $start, 400);
      $regex = '/<meta http-equiv="([^"]+)" content="([0-9]{3})[^"]*"\/>/i';
      if (preg_match($regex, $check, $match)) {
        if (strtolower($match[1]) === 'status' && $match[2] === '410') {
          $message = '';
          if ($comment_installed) {
            $id = $comment->Factory('MatchUrl', $us_source);
            if ($id !== 0) {
              $comment->Factory('RemoveWebmention', $id);
              $message = 'Thanks! Your webmention has been removed.';
            }
          }
          return ['HTTP/1.1 200 OK', $message, true];
        }
      }
    }

    $result = parse_microformats($us_source, $us_target, $body);
    if (strpos($body, $us_target) === false) {
      if ($comment_installed) {
        $id = $comment->Factory('MatchUrl', $result['url']);
        if ($id !== 0) $comment->Factory('RemoveWebmention', $id);
      }
      return ['HTTP/1.1 400 Bad Request',
              'Source URL does not contain a link to the target: '.$us_source,
              false];
    }

    if ($this->Substitute('post-webmention-debug') === 'true') {
      $this->Log('Post->ProcessReceivedWebmention: Accepted webmention from '.
                 $us_source);
    }
    $commenteditor = new Module($this->user, $this->owner, 'commenteditor');
    if ($commenteditor->IsInstalled() &&
        $commenteditor->Factory('Blocked', $result['url'])) {
      $this->Log('Post->ProcessReceivedWebmention: Blocking webmention from '.
                 $result['url']);
      return ['HTTP/1.1 200 OK', 'Thanks! Your webmention has been accepted.',
              false];
    }

    include_once 'library/HTMLPurifier.auto.php';
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    $url = $purifier->purify($result['url']);
    $content = $purifier->purify($result['content']);
    $author = $purifier->purify($result['author-name']);
    $author_photo = $purifier->purify($result['author-photo']);
    $author_url = $purifier->purify($result['author-url']);
    $resend = false;
    $id = '';
    if ($comment_installed && $result['mention'] === 'comment') {
      $us_content = ['author' => $author, 'author_photo' => $author_photo,
                     'author_url' => $author_url, 'url' => $url,
                     'description' => $content,
                     'permalink' => $this->user->page.'#'.$id];
      $id = $comment->Factory('MatchUrl', $url);
      if ($id !== 0) {
        if ($comment->Factory('Modified', [$id, $content])) {
          $resend = true;
          if ($content === '') {
            $comment->Factory('RemoveWebmention', $id);
          }
          else {
            // SetContent will create a Notification for the updated comment.
            $comment->SetContent($id, $us_content);
          }
        }
      }
      else if ($content !== '') {
        $id = new_module($this->user, $this->owner, 'comment',
                         $this->user->page, $comment->Group(),
                         $comment->Placement());
        $comment->Add($id);
        // SetContent will create a Notification for the new comment.
        $comment->SetContent($id, $us_content);
        $resend = true;
      }
    }
    else {
      $this->Notification('comment', [$author, $author_photo, $author_url],
                          $url, $result['mention'], $this->user->page,
                          $this->user->page);
    }
    if ($id !== '') $id = '#'.$id;
    // Process any responses to the webmention parsed in the microformats.
    foreach (['comment', 'like', 'share'] as $action) {
      foreach ($result[$action] as $response) {
        $author = $purifier->purify($response['author-name']);
        $author_photo = $purifier->purify($response['author-photo']);
        $author_url = $purifier->purify($response['author-url']);
        $url = $purifier->purify($response['url']);
        $this->Notification('comment', [$author, $author_photo, $author_url],
                            $url, $action.'-mention', $this->user->page,
                            $this->user->page.$id);
      }
    }
    return ['HTTP/1.1 200 OK', 'Thanks! Your webmention has been accepted.',
            $resend];
  }

  private function RemovePermalinkPage($id, $permalink = '') {
    $mysqli = connect_db();
    $tombstone = false;
    $feed = '';
    if ($permalink === '') {
      $query = 'SELECT permalink, feed FROM post WHERE '.
        'user = "'.$this->owner.'" AND box_id = '.$id;
      if ($result = $mysqli->query($query)) {
        if ($post = $result->fetch_assoc()) {
          $permalink = $mysqli->escape_string($post['permalink']);
          $feed = $mysqli->escape_string($post['feed']);
        }
        $result->close();
      }
      else {
        $this->Log('Post->RemovePermalinkPage 1: '.$mysqli->error);
      }
      if ($permalink === '') {
        $mysqli->close();
        return;
      }
      // When a permalink is not given the post is being removed, in which case
      // we'll replace it with a tombstone post.
      $tombstone = true;
    }

    // Call the Remove method for all other modules on the page.
    $query = 'SELECT box_id, label FROM modules WHERE '.
      'user = "'.$this->owner.'" AND box_id != '.$id.' AND '.
      'page = "'.$permalink.'" AND deleted = 0';
    if ($result = $mysqli->query($query)) {
      while ($module_list = $result->fetch_assoc()) {
        $module = new Module($this->user, $this->owner, $module_list['label']);
        $module->Remove($module_list['box_id']);
      }
      $result->close();
    }
    else {
      $this->Log('Post->RemovePermalinkPage 2: '.$mysqli->error);
    }
    $query = 'UPDATE modules SET deleted = 1 WHERE page = "'.$permalink.'" '.
      'AND user = "'.$this->owner.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->RemovePermalinkPage 3: '.$mysqli->error);
    }
    $query = 'DELETE FROM page_style WHERE name = "'.$permalink.'" '.
      'AND user = "'.$this->owner.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->RemovePermalinkPage 4: '.$mysqli->error);
    }
    $path = $this->owner === 'admin' ? '../' : '../'.$this->owner.'/';
    if (file_exists($path.$permalink.'.css')) unlink($path.$permalink.'.css');
    $query = 'DELETE FROM user_permission WHERE page = "'.$permalink.'" '.
      'AND user = "'.$this->owner.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->RemovePermalinkPage 5: '.$mysqli->error);
    }
    $query = 'DELETE FROM group_permission WHERE page = "'.$permalink.'" '.
      'AND user = "'.$this->owner.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->RemovePermalinkPage 6: '.$mysqli->error);
    }
    $query = 'DELETE FROM notify WHERE page = "'.$permalink.'" '.
      'AND user = "'.$this->owner.'"';
    if (!$mysqli->query($query)) {
      $this->Log('Post->RemovePermalinkPage 7: '.$mysqli->error);
    }
    if ($tombstone) {
      $description = $mysqli->escape_string($this->Tombstone());
      $new_id = new_module($this->user, $this->owner, 'post', $permalink,
                           $this->Group(), $this->Placement());
      $query = 'INSERT INTO post VALUES ("'.$this->owner.'", '.$new_id.', '.
        '"", "'.$description.'", "", "", "", "'.$permalink.'", '.
        '"'.$feed.'", '.time().')';
      if (!$mysqli->query($query)) {
        $this->Log('Post->RemovePermalinkPage 8: '.$mysqli->error);
      }
      // Use SetContent to notify others that the feed has changed.
      $this->SetContent($new_id, ['data' => $description, 'notify' => true]);
    }
    $mysqli->close();
  }

  private function SendWebmention($url, $permalink, $endpoint = '') {
    $base_url = $this->user->config->Secure() ? 'https://' : 'http://';
    $base_url .= $this->user->config->ServerName();
    // Use our own endpoint for relative urls.
    if (stripos($url, 'http') !== 0) {
      $endpoint = $base_url.'/php/webmention.php';
    }
    else if ($endpoint === '') {
      // Do discovery on the url if an endpoint isn't provided.
      $endpoint = $this->Endpoint($url);
      if ($endpoint === '') return '';
    }

    $status = '';
    $source = $base_url.$this->Url('', $permalink);
    $post_fields = 'source='.urlencode($source).'&target='.urlencode($url);
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    $body = curl_exec($ch);
    if (curl_errno($ch) === 0) {
      $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if ($http_code === 200 || $http_code === 201 || $http_code === 202) {
        if ($this->Substitute('post-webmention-debug') === 'true') {
          $this->Log('Post->SendWebmention: Success posting to '.$endpoint.
                     "\HTTP code: ".$http_code."\nBody: ".$body);
          if (strpos($endpoint, 'https://brid.gy') === 0) {
            $result = json_decode($body, true);
            if (isset($result['url'])) {
              $this->AddSyndicationLink($result['url'], $permalink);
              $status = 'brid.gy published to: <a href="'.$result['url'].'">'.
                $result['url'].'</a><br>';
            }
          }
        }
      }
      else {
        $this->Log('Post->SendWebmention: Error posting to '.$endpoint.
                   "\nHTTP code: ".$http_code."\nBody: ".$body);
        if (strpos($endpoint, 'https://brid.gy') === 0) {
          $result = json_decode($body, true);
          if (isset($result['error'])) {
            $status = 'brid.gy error: '.$result['error'];
          }
        }
      }
    }
    else {
      $this->Log('Post->SendWebmention: Error connecting to endpoint '.
                 $endpoint."\nCurl error: ".curl_error($ch));
    }
    curl_close($ch);
    return $status;
  }

  private function Status($target) {
    $target_status = [];
    $mysqli = connect_db();
    $query = 'SELECT description, permalink FROM post WHERE '.
      'user = "'.$this->owner.'" AND description LIKE "%'.$target.'%"';
    if ($result = $mysqli->query($query)) {
      while ($post = $result->fetch_assoc()) {
        $description = $post['description'];
        $check = '<a href="'.$target.'" class=';
        if (strpos($description, $check.'"u-like-of"') !== false) {
          $target_status['like'] = $post['permalink'];
        }
        else if (strpos($description, $check.'"u-repost-of"') !== false) {
          $target_status['repost'] = $post['permalink'];
        }
        else if (strpos($description, $check.'"u-in-reply-to"') !== false) {
          $target_status['reply'] = $post['permalink'];
        }
      }
      $result->close();
    }
    else {
      $this->Log('Post->Status: '.$mysqli->error);
    }
    $mysqli->close();
    return $target_status;
  }

  private function Tombstone() {
    return 'This post has been removed.';
  }

  private function UpdatePager($id) {
    // If the Pager module is installed it requires the feed name to move
    // posts back to previous pages when required.
    $pager = new Module($this->user, $this->owner, 'pager');
    if (!$pager->IsInstalled()) return;

    $feed = '';
    $mysqli = connect_db();
    $query = 'SELECT feed FROM post WHERE user = "'.$this->owner.'" '.
      'AND box_id = '.$id;
    if ($result = $mysqli->query($query)) {
      if ($post = $result->fetch_assoc()) {
        $feed = $mysqli->escape_string($post['feed']);
      }
      $result->close();
    }
    else {
      $this->Log('Post->UpdatePager 1: '.$mysqli->error);
    }
    // Move posts on pages after the the page containing the post being
    // removed. This requires giving the Pager the starting page, so look
    // up the page this post is on and add 1 to give it the next page.
    $page = '';
    $query = 'SELECT page FROM modules WHERE user = "'.$this->owner.'" '.
      'AND box_id = '.$id.' AND deleted = 0';
    if ($result = $mysqli->query($query)) {
      if ($modules = $result->fetch_assoc()) {
        $page = $mysqli->escape_string($modules['page']);
      }
      $result->close();
    }
    else {
      $this->Log('Post->UpdatePager 2: '.$mysqli->error);
    }
    $mysqli->close();

    // If the page doesn't have a pager suffix, then the module is being
    // removed from the first page and the next page starts at 2.
    $count = 2;
    if (preg_match('/-p([0-9]+)$/', $page, $match)) {
      $count = (int)$match[1] + 1;
    }
    if ($count >= 2) {
      // The pager expects this post to already be deleted, so flag it
      // first and then reinstate it once Move has been called.
      $this->Hide($id, $page, 1);
      $pager->Factory('Move', [$feed, $count, false]);
      $this->Hide($id, $page, 0);
    }
  }

}