rcmail_output_html.php 97.0 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 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
<?php

/**
 +-----------------------------------------------------------------------+
 | This file is part of the Roundcube Webmail client                     |
 |                                                                       |
 | Copyright (C) The Roundcube Dev Team                                  |
 |                                                                       |
 | Licensed under the GNU General Public License version 3 or            |
 | any later version with exceptions for skins & plugins.                |
 | See the README file for a full license statement.                     |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Class to handle HTML page output using a skin template.             |
 +-----------------------------------------------------------------------+
 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
 +-----------------------------------------------------------------------+
*/

/**
 * Class to create HTML page output using a skin template
 *
 * @package    Webmail
 * @subpackage View
 */
class rcmail_output_html extends rcmail_output
{
    public $type = 'html';

    protected $message;
    protected $template_name;
    protected $objects      = [];
    protected $js_env       = [];
    protected $js_labels    = [];
    protected $js_commands  = [];
    protected $skin_paths   = [];
    protected $skin_name    = '';
    protected $scripts_path = '';
    protected $script_files = [];
    protected $css_files    = [];
    protected $scripts      = [];
    protected $meta_tags    = [];
    protected $link_tags    = ['shortcut icon' => ''];
    protected $header       = '';
    protected $footer       = '';
    protected $body         = '';
    protected $base_path    = '';
    protected $assets_path;
    protected $assets_dir   = RCUBE_INSTALL_PATH;
    protected $devel_mode   = false;
    protected $default_template = "<html>\n<head><meta name='generator' content='Roundcube'></head>\n<body></body>\n</html>";

    // deprecated names of templates used before 0.5
    protected $deprecated_templates = [
        'contact'      => 'showcontact',
        'contactadd'   => 'addcontact',
        'contactedit'  => 'editcontact',
        'identityedit' => 'editidentity',
        'messageprint' => 'printmessage',
    ];

    // deprecated names of template objects used before 1.4
    protected $deprecated_template_objects = [
        'addressframe'        => 'contentframe',
        'messagecontentframe' => 'contentframe',
        'prefsframe'          => 'contentframe',
        'folderframe'         => 'contentframe',
        'identityframe'       => 'contentframe',
        'responseframe'       => 'contentframe',
        'keyframe'            => 'contentframe',
        'filterframe'         => 'contentframe',
    ];

    /**
     * Constructor
     */
    public function __construct($task = null, $framed = false)
    {
        parent::__construct();

        $this->devel_mode = $this->config->get('devel_mode');

        $this->set_env('task', $task);
        $this->set_env('standard_windows', (bool) $this->config->get('standard_windows'));
        $this->set_env('locale', !empty($_SESSION['language']) ? $_SESSION['language'] : 'en_US');
        $this->set_env('devel_mode', $this->devel_mode);

        // Version number e.g. 1.4.2 will be 10402
        $version = explode('.', preg_replace('/[^0-9.].*/', '', RCMAIL_VERSION));
        $this->set_env('rcversion', $version[0] * 10000 + $version[1] * 100 + (isset($version[2]) ? $version[2] : 0));

        // add cookie info
        $this->set_env('cookie_domain', ini_get('session.cookie_domain'));
        $this->set_env('cookie_path', ini_get('session.cookie_path'));
        $this->set_env('cookie_secure', filter_var(ini_get('session.cookie_secure'), FILTER_VALIDATE_BOOLEAN));

        // Easy way to change skin via GET argument, for developers
        if ($this->devel_mode && !empty($_GET['skin']) && preg_match('/^[a-z0-9-_]+$/i', $_GET['skin'])) {
            if ($this->check_skin($_GET['skin'])) {
                $this->set_skin($_GET['skin']);
                $this->app->user->save_prefs(['skin' => $_GET['skin']]);
            }
        }

        // load and setup the skin
        $this->set_skin($this->config->get('skin'));
        $this->set_assets_path($this->config->get('assets_path'), $this->config->get('assets_dir'));

        if (!empty($_REQUEST['_extwin'])) {
            $this->set_env('extwin', 1);
        }

        if ($this->framed || $framed) {
            $this->set_env('framed', 1);
        }

        $lic = <<<EOF
/*
        @licstart  The following is the entire license notice for the 
        JavaScript code in this page.

        Copyright (C) The Roundcube Dev Team

        The JavaScript code in this page is free software: you can redistribute
        it and/or modify it under the terms of the GNU General Public License
        as published by the Free Software Foundation, either version 3 of
        the License, or (at your option) any later version.

        The code is distributed WITHOUT ANY WARRANTY; without even the implied
        warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
        See the GNU GPL for more details.

        @licend  The above is the entire license notice
        for the JavaScript code in this page.
*/
EOF;
        // add common javascripts
        $this->add_script($lic, 'head_top');
        $this->add_script('var '.self::JS_OBJECT_NAME.' = new rcube_webmail();', 'head_top');

        // don't wait for page onload. Call init at the bottom of the page (delayed)
        $this->add_script(self::JS_OBJECT_NAME.'.init();', 'docready');

        $this->scripts_path = 'program/js/';
        $this->include_script('jquery.min.js');
        $this->include_script('common.js');
        $this->include_script('app.js');

        // register common UI objects
        $this->add_handlers([
                'loginform'       => [$this, 'login_form'],
                'preloader'       => [$this, 'preloader'],
                'username'        => [$this, 'current_username'],
                'message'         => [$this, 'message_container'],
                'charsetselector' => [$this, 'charset_selector'],
                'aboutcontent'    => [$this, 'about_content'],
        ]);

        // set blankpage (watermark) url
        $blankpage = $this->config->get('blankpage_url', '/watermark.html');
        $this->set_env('blankpage', $blankpage);
    }

    /**
     * Set environment variable
     *
     * @param string $name    Property name
     * @param mixed  $value   Property value
     * @param bool   $addtojs True if this property should be added
     *                        to client environment
     */
    public function set_env($name, $value, $addtojs = true)
    {
        $this->env[$name] = $value;

        if ($addtojs || isset($this->js_env[$name])) {
            $this->js_env[$name] = $value;
        }
    }

    /**
     * Parse and set assets path
     *
     * @param string $path   Assets path URL (relative or absolute)
     * @param string $fs_dif Assets path in filesystem
     */
    public function set_assets_path($path, $fs_dir = null)
    {
        // set absolute path for assets if /index.php/foo/bar url is used
        if (empty($path) && !empty($_SERVER['PATH_INFO'])) {
            $path = preg_replace('/\?_task=[a-z]+/', '', $this->app->url([], true));
        }

        if (empty($path)) {
            return;
        }

        $path = rtrim($path, '/') . '/';

        // handle relative assets path
        if (!preg_match('|^https?://|', $path) && $path[0] != '/') {
            // save the path to search for asset files later
            $this->assets_dir = $path;

            $base = preg_replace('/[?#&].*$/', '', $_SERVER['REQUEST_URI']);
            $base = rtrim($base, '/');

            // remove url token if exists
            if ($len = intval($this->config->get('use_secure_urls'))) {
                $_base  = explode('/', $base);
                $last   = count($_base) - 1;
                $length = $len > 1 ? $len : 16; // as in rcube::get_secure_url_token()

                // we can't use real token here because it
                // does not exists in unauthenticated state,
                // hope this will not produce false-positive matches
                if ($last > -1 && preg_match('/^[a-f0-9]{' . $length . '}$/', $_base[$last])) {
                    $path = '../' . $path;
                }
            }
        }

        // set filesystem path for assets
        if ($fs_dir) {
            if ($fs_dir[0] != '/') {
                $fs_dir = realpath(RCUBE_INSTALL_PATH . $fs_dir);
            }
            // ensure the path ends with a slash
            $this->assets_dir = rtrim($fs_dir, '/') . '/';
        }

        $this->assets_path = $path;
        $this->set_env('assets_path', $path);
    }

    /**
     * Getter for the current page title
     *
     * @param bool $full Prepend title with product/user name
     *
     * @return string The page title
     */
    protected function get_pagetitle($full = true)
    {
        if (!empty($this->pagetitle)) {
            $title = $this->pagetitle;
        }
        else if (isset($this->env['task'])) {
            if ($this->env['task'] == 'login') {
                $title = $this->app->gettext([
                        'name' => 'welcome',
                        'vars' => ['product' => $this->config->get('product_name')]
                ]);
            }
            else {
                $title = ucfirst($this->env['task']);
            }
        }
        else {
            $title = '';
        }

        if ($full && $title) {
            if ($this->devel_mode && !empty($_SESSION['username'])) {
                $title = $_SESSION['username'] . ' :: ' . $title;
            }
            else if ($prod_name = $this->config->get('product_name')) {
                $title = $prod_name . ' :: ' . $title;
            }
        }

        return $title;
    }

    /**
     * Getter for the current skin path property
     */
    public function get_skin_path()
    {
        return $this->skin_paths[0];
    }

    /**
     * Set skin
     *
     * @param string $skin Skin name
     */
    public function set_skin($skin)
    {
        if (!$this->check_skin($skin)) {
            // If the skin does not exist (could be removed or invalid),
            // fallback to the skin set in the system configuration (#7271)
            $skin = $this->config->system_skin;
        }

        $skin_path = 'skins/' . $skin;

        $this->config->set('skin_path', $skin_path);
        $this->base_path = $skin_path;

        // register skin path(s)
        $this->skin_paths = [];
        $this->skins      = [];
        $this->load_skin($skin_path);

        $this->skin_name = $skin;
        $this->set_env('skin', $skin);
    }

    /**
     * Check skin validity/existence
     *
     * @param string $skin Skin name
     *
     * @return bool True if the skin exist and is readable, False otherwise
     */
    public function check_skin($skin)
    {
        // Sanity check to prevent from path traversal vulnerability (#1490620)
        if (strpos($skin, '/') !== false || strpos($skin, "\\") !== false) {
            rcube::raise_error([
                    'file'    => __FILE__,
                    'line'    => __LINE__,
                    'message' => 'Invalid skin name'
                ], true, false);

            return false;
        }

        $skins_allowed = $this->config->get('skins_allowed');

        if (!empty($skins_allowed) && !in_array($skin, (array) $skins_allowed)) {
            return false;
        }

        $path = RCUBE_INSTALL_PATH . 'skins/';

        return !empty($skin) && is_dir($path . $skin) && is_readable($path . $skin);
    }

    /**
     * Helper method to recursively read skin meta files and register search paths
     */
    private function load_skin($skin_path)
    {
        $this->skin_paths[] = $skin_path;

        // read meta file and check for dependencies
        $meta = @file_get_contents(RCUBE_INSTALL_PATH . $skin_path . '/meta.json');
        $meta = @json_decode($meta, true);

        $meta['path']  = $skin_path;
        $path_elements = explode('/', $skin_path);
        $skin_id       = end($path_elements);

        if (empty($meta['name'])) {
            $meta['name'] = $skin_id;
        }

        $this->skins[$skin_id] = $meta;

        // Keep skin config for ajax requests (#6613)
        $_SESSION['skin_config'] = [];

        if (!empty($meta['extends'])) {
            $path = RCUBE_INSTALL_PATH . 'skins/';
            if (is_dir($path . $meta['extends']) && is_readable($path . $meta['extends'])) {
                $_SESSION['skin_config'] = $this->load_skin('skins/' . $meta['extends']);
            }
        }

        if (!empty($meta['config'])) {
            foreach ($meta['config'] as $key => $value) {
                $this->config->set($key, $value, true);
                $_SESSION['skin_config'][$key] = $value;
            }

            $value = array_merge((array) $this->config->get('dont_override'), array_keys($meta['config']));
            $this->config->set('dont_override', $value, true);
        }

        if (!empty($meta['localization'])) {
            $locdir = $meta['localization'] === true ? 'localization' : $meta['localization'];
            if ($texts = $this->app->read_localization(RCUBE_INSTALL_PATH . $skin_path . '/' . $locdir)) {
                $this->app->load_language($_SESSION['language'], $texts);
            }
        }

        // Use array_merge() here to allow for global default and extended skins
        if (!empty($meta['meta'])) {
            $this->meta_tags = array_merge($this->meta_tags, (array) $meta['meta']);
        }
        if (!empty($meta['links'])) {
            $this->link_tags = array_merge($this->link_tags, (array) $meta['links']);
        }

        $this->set_env('dark_mode_support', (bool) $this->config->get('dark_mode_support'));

        return $_SESSION['skin_config'];
    }

    /**
     * Check if a specific template exists
     *
     * @param string $name Template name
     *
     * @return bool True if template exists, False otherwise
     */
    public function template_exists($name)
    {
        foreach ($this->skin_paths as $skin_path) {
            $filename = RCUBE_INSTALL_PATH . $skin_path . '/templates/' . $name . '.html';
            if (
                (is_file($filename) && is_readable($filename))
                || (!empty($this->deprecated_templates[$name]) && $this->template_exists($this->deprecated_templates[$name]))
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Find the given file in the current skin path stack
     *
     * @param string $file       File name/path to resolve (starting with /)
     * @param string &$skin_path Reference to the base path of the matching skin
     * @param string $add_path   Additional path to search in
     * @param bool   $minified   Fallback to a minified version of the file
     *
     * @return string|false Relative path to the requested file or False if not found
     */
    public function get_skin_file($file, &$skin_path = null, $add_path = null, $minified = false)
    {
        $skin_paths = $this->skin_paths;

        if ($add_path) {
            array_unshift($skin_paths, $add_path);
            $skin_paths = array_unique($skin_paths);
        }

        if ($file[0] != '/') {
            $file = '/' . $file;
        }

        if ($skin_path = $this->find_file_path($file, $skin_paths)) {
            return $skin_path . $file;
        }

        if ($minified && preg_match('/(?<!\.min)\.(js|css)$/', $file)) {
            $file = preg_replace('/\.(js|css)$/', '.min.\\1', $file);

            if ($skin_path = $this->find_file_path($file, $skin_paths)) {
                return $skin_path . $file;
            }
        }

        return false;
    }

    /**
     * Find path of the asset file
     */
    protected function find_file_path($file, $skin_paths)
    {
        foreach ($skin_paths as $skin_path) {
            if ($this->assets_dir != RCUBE_INSTALL_PATH) {
                if (realpath($this->assets_dir . $skin_path . $file)) {
                    return $skin_path;
                }
            }

            if (realpath(RCUBE_INSTALL_PATH . $skin_path . $file)) {
                return $skin_path;
            }
        }
    }

    /**
     * Register a GUI object to the client script
     *
     * @param string $obj Object name
     * @param string $id  Object ID
     */
    public function add_gui_object($obj, $id)
    {
        $this->add_script(self::JS_OBJECT_NAME.".gui_object('$obj', '$id');");
    }

    /**
     * Call a client method
     *
     * @param string Method to call
     * @param ... Additional arguments
     */
    public function command()
    {
        $cmd = func_get_args();

        if (strpos($cmd[0], 'plugin.') !== false) {
            $this->js_commands[] = ['triggerEvent', $cmd[0], $cmd[1]];
        }
        else {
            $this->js_commands[] = $cmd;
        }
    }

    /**
     * Add a localized label to the client environment
     */
    public function add_label()
    {
        $args = func_get_args();

        if (count($args) == 1 && is_array($args[0])) {
            $args = $args[0];
        }

        foreach ($args as $name) {
            $this->js_labels[$name] = $this->app->gettext($name);
        }
    }

    /**
     * Invoke display_message command
     *
     * @param string  $message  Message to display
     * @param string  $type     Message type [notice|confirm|error]
     * @param array   $vars     Key-value pairs to be replaced in localized text
     * @param bool    $override Override last set message
     * @param int     $timeout  Message display time in seconds
     *
     * @uses self::command()
     */
    public function show_message($message, $type = 'notice', $vars = null, $override = true, $timeout = 0)
    {
        if ($override || !$this->message) {
            if ($this->app->text_exists($message)) {
                if (!empty($vars)) {
                    $vars = array_map(['rcube','Q'], $vars);
                }

                $msgtext = $this->app->gettext(['name' => $message, 'vars' => $vars]);
            }
            else {
                $msgtext = $message;
            }

            $this->message = $message;
            $this->command('display_message', $msgtext, $type, $timeout * 1000);
        }
    }

    /**
     * Delete all stored env variables and commands
     *
     * @param bool $all Reset all env variables (including internal)
     */
    public function reset($all = false)
    {
        $framed = $this->framed;
        $task   = isset($this->env['task']) ? $this->env['task'] : '';
        $env    = $all ? null : array_intersect_key($this->env, ['extwin' => 1, 'framed' => 1]);

        // keep jQuery-UI files
        $css_files = $script_files = [];

        foreach ($this->css_files as $file) {
            if (strpos($file, 'plugins/jqueryui') === 0) {
                $css_files[] = $file;
            }
        }

        foreach ($this->script_files as $position => $files) {
            foreach ($files as $file) {
                if (strpos($file, 'plugins/jqueryui') === 0) {
                    $script_files[$position][] = $file;
                }
            }
        }

        parent::reset();

        // let some env variables survive
        $this->env          = $this->js_env = $env;
        $this->framed       = $framed || !empty($this->env['framed']);
        $this->js_labels    = [];
        $this->js_commands  = [];
        $this->scripts      = [];
        $this->header       = '';
        $this->footer       = '';
        $this->body         = '';
        $this->css_files    = [];
        $this->script_files = [];

        // load defaults
        if (!$all) {
            $this->__construct();
        }

        // Note: we merge jQuery-UI scripts after jQuery...
        $this->css_files    = array_merge($this->css_files, $css_files);
        $this->script_files = array_merge_recursive($this->script_files, $script_files);

        $this->set_env('orig_task', $task);
    }

    /**
     * Redirect to a certain url
     *
     * @param mixed $p      Either a string with the action or url parameters as key-value pairs
     * @param int   $delay  Delay in seconds
     * @param bool  $secure Redirect to secure location (see rcmail::url())
     */
    public function redirect($p = [], $delay = 1, $secure = false)
    {
        if (!empty($this->env['extwin']) && !(is_string($p) && preg_match('#^https?://#', $p))) {
            if (!is_array($p)) {
                $p = ['_action' => $p];
            }

            $p['_extwin'] = 1;
        }

        $location = $this->app->url($p, false, false, $secure);
        $this->header('Location: ' . $location);
        exit;
    }

    /**
     * Send the request output to the client.
     * This will either parse a skin template.
     *
     * @param string $templ Template name
     * @param bool   $exit  True if script should terminate (default)
     */
    public function send($templ = null, $exit = true)
    {
        if ($templ != 'iframe') {
            // prevent from endless loops
            if ($exit != 'recur' && $this->app->plugins->is_processing('render_page')) {
                rcube::raise_error([
                        'code'    => 505,
                        'file'    => __FILE__,
                        'line'    => __LINE__,
                        'message' => 'Recursion alert: ignoring output->send()'
                    ], true, false
                );

                return;
            }

            $this->parse($templ, false);
        }
        else {
            $this->framed = true;
            $this->write();
        }

        // set output asap
        ob_flush();
        flush();

        if ($exit) {
            exit;
        }
    }

    /**
     * Process template and write to stdOut
     *
     * @param string $template HTML template content
     */
    public function write($template = '')
    {
        if (!empty($this->script_files)) {
            $this->set_env('request_token', $this->app->get_request_token());
        }

        // Fix assets path on blankpage
        if (!empty($this->js_env['blankpage'])) {
            $this->js_env['blankpage'] = $this->asset_url($this->js_env['blankpage'], true);
        }

        $commands = $this->get_js_commands($framed);

        // if all js commands go to parent window we can ignore all
        // script files and skip rcube_webmail initialization (#1489792)
        // but not on error pages where skins may need jQuery, etc.
        if ($framed && empty($this->js_env['server_error'])) {
            $this->scripts      = [];
            $this->script_files = [];
            $this->header       = '';
            $this->footer       = '';
        }

        // write all javascript commands
        if (!empty($commands)) {
            $this->add_script($commands, 'head_top');
        }

        $this->page_headers();

        // call super method
        $this->_write($template);
    }

    /**
     * Send common page headers
     * For now it only (re)sets X-Frame-Options when needed
     */
    public function page_headers()
    {
        if (headers_sent()) {
            return;
        }

        // allow (legal) iframe content to be loaded
        $framed = $this->framed || !empty($this->env['framed']);
        if ($framed && ($xopt = $this->app->config->get('x_frame_options', 'sameorigin'))) {
            if (strtolower($xopt) === 'deny') {
                $this->header('X-Frame-Options: sameorigin', true);
            }
        }
    }

    /**
     * Parse a specific skin template and deliver to stdout (or return)
     *
     * @param string $name  Template name
     * @param bool   $exit  Exit script
     * @param bool   $write Don't write to stdout, return parsed content instead
     *
     * @link http://php.net/manual/en/function.exit.php
     */
    function parse($name = 'main', $exit = true, $write = true)
    {
        $plugin   = false;
        $realname = $name;
        $skin_dir = '';
        $plugin_skin_paths = [];

        $this->template_name = $realname;

        $temp = explode('.', $name, 2);
        if (count($temp) > 1) {
            $plugin   = $temp[0];
            $name     = $temp[1];
            $skin_dir = $plugin . '/skins/' . $this->config->get('skin');

            // apply skin search escalation list to plugin directory
            foreach ($this->skin_paths as $skin_path) {
                // skin folder in plugin dir
                $plugin_skin_paths[] = $this->app->plugins->url . $plugin . '/' . $skin_path;
                // plugin folder in skin dir
                $plugin_skin_paths[] = $skin_path . '/plugins/' . $plugin;
            }

            // prepend plugin skin paths to search list
            $this->skin_paths = array_merge($plugin_skin_paths, $this->skin_paths);
        }

        // find skin template
        $path = false;
        foreach ($this->skin_paths as $skin_path) {
            // when requesting a plugin template ignore global skin path(s)
            if ($plugin && strpos($skin_path, $this->app->plugins->url) === false) {
                continue;
            }

            $path = RCUBE_INSTALL_PATH . "$skin_path/templates/$name.html";

            // fallback to deprecated template names
            if (!is_readable($path) && !empty($this->deprecated_templates[$realname])) {
                $dname = $this->deprecated_templates[$realname];
                $path  = RCUBE_INSTALL_PATH . "$skin_path/templates/$dname.html";

                if (is_readable($path)) {
                    rcube::raise_error([
                            'code' => 502, 'file' => __FILE__, 'line' => __LINE__,
                            'message' => "Using deprecated template '$dname' in $skin_path/templates. Please rename to '$realname'"
                        ], true, false
                    );
                }
            }

            if (is_readable($path)) {
                $this->config->set('skin_path', $skin_path);
                // set base_path to core skin directory (not plugin's skin)
                $this->base_path = preg_replace('!plugins/\w+/!', '', $skin_path);
                $skin_dir        = preg_replace('!^plugins/!', '', $skin_path);
                break;
            }
            else {
                $path = false;
            }
        }

        // read template file
        if (!$path || ($templ = @file_get_contents($path)) === false) {
            rcube::raise_error([
                    'code' => 404,
                    'line' => __LINE__,
                    'file' => __FILE__,
                    'message' => 'Error loading template for '.$realname
                ], true, $write);

            $this->skin_paths = array_slice($this->skin_paths, count($plugin_skin_paths));
            return false;
        }

        // replace all path references to plugins/... with the configured plugins dir
        // and /this/ to the current plugin skin directory
        if ($plugin) {
            $templ = preg_replace(
                ['/\bplugins\//', '/(["\']?)\/this\//'],
                [$this->app->plugins->url, '\\1' . $this->app->plugins->url . $skin_dir . '/'],
                $templ
            );
        }

        // parse for special tags
        $output = $this->parse_conditions($templ);
        $output = $this->parse_xml($output);

        // trigger generic hook where plugins can put additional content to the page
        $hook = $this->app->plugins->exec_hook("render_page", [
                'template' => $realname,
                'content'  => $output,
                'write'    => $write
        ]);

        // save some memory
        $output = $hook['content'];
        unset($hook['content']);

        // remove plugin skin paths from current context
        $this->skin_paths = array_slice($this->skin_paths, count($plugin_skin_paths));

        if (!$write) {
            return $this->postrender($output);
        }

        $this->write(trim($output));

        if ($exit) {
            exit;
        }
    }

    /**
     * Return executable javascript code for all registered commands
     */
    protected function get_js_commands(&$framed = null)
    {
        $out             = '';
        $parent_commands = 0;
        $parent_prefix   = '';
        $top_commands    = [];

        // these should be always on top,
        // e.g. hide_message() below depends on env.framed
        if (!$this->framed && !empty($this->js_env)) {
            $top_commands[] = ['set_env', $this->js_env];
        }
        if (!empty($this->js_labels)) {
            $top_commands[] = ['add_label', $this->js_labels];
        }

        // unlock interface after iframe load
        $unlock = isset($_REQUEST['_unlock']) ? preg_replace('/[^a-z0-9]/i', '', $_REQUEST['_unlock']) : 0;
        if ($this->framed) {
            $top_commands[] = ['iframe_loaded', $unlock];
        }
        else if ($unlock) {
            $top_commands[] = ['hide_message', $unlock];
        }

        $commands = array_merge($top_commands, $this->js_commands);

        foreach ($commands as $i => $args) {
            $method = array_shift($args);
            $parent = $this->framed || preg_match('/^parent\./', $method);

            foreach ($args as $i => $arg) {
                $args[$i] = self::json_serialize($arg, $this->devel_mode);
            }

            if ($parent) {
                $parent_commands++;
                $method        = preg_replace('/^parent\./', '', $method);
                $parent_prefix = 'if (window.parent && parent.' . self::JS_OBJECT_NAME . ') parent.';
                $method        = $parent_prefix . self::JS_OBJECT_NAME . '.' . $method;
            }
            else {
                $method = self::JS_OBJECT_NAME . '.' . $method;
            }

            $out .= sprintf("%s(%s);\n", $method, implode(',', $args));
        }

        $framed = $parent_prefix && $parent_commands == count($commands);

        // make the output more compact if all commands go to parent window
        if ($framed) {
            $out = "if (window.parent && parent." . self::JS_OBJECT_NAME . ") {\n"
                . str_replace($parent_prefix, "\tparent.", $out)
                . "}\n";
        }

        return $out;
    }

    /**
     * Make URLs starting with a slash point to skin directory
     *
     * @param string $str         Input string
     * @param bool   $search_path True if URL should be resolved using the current skin path stack
     *
     * @return string URL
     */
    public function abs_url($str, $search_path = false)
    {
        if (isset($str[0]) && $str[0] == '/') {
            if ($search_path && ($file_url = $this->get_skin_file($str))) {
                return $file_url;
            }

            return $this->base_path . $str;
        }

        return $str;
    }

    /**
     * Show error page and terminate script execution
     *
     * @param int    $code    Error code
     * @param string $message Error message
     */
    public function raise_error($code, $message)
    {
        $args = [
            'code'    => $code,
            'message' => $message,
        ];

        $page = new rcmail_action_utils_error;
        $page->run($args);
    }

    /**
     * Modify path by adding URL prefix if configured
     *
     * @param string $path    Asset path
     * @param bool   $abs_url Pass to self::abs_url() first
     *
     * @return string Asset path
     */
    public function asset_url($path, $abs_url = false)
    {
        // iframe content can't be in a different domain
        // @TODO: check if assets are on a different domain

        if ($abs_url) {
            $path = $this->abs_url($path, true);
        }

        if (!$this->assets_path || in_array($path[0], ['?', '/', '.']) || strpos($path, '://')) {
            return $path;
        }

        return $this->assets_path . $path;
    }


    /*****  Template parsing methods  *****/

    /**
     * Replace all strings ($varname)
     * with the content of the according global variable.
     */
    protected function parse_with_globals($input)
    {
        $GLOBALS['__version']   = html::quote(RCMAIL_VERSION);
        $GLOBALS['__comm_path'] = html::quote($this->app->comm_path);
        $GLOBALS['__skin_path'] = html::quote($this->base_path);

        return preg_replace_callback('/\$(__[a-z0-9_\-]+)/', [$this, 'globals_callback'], $input);
    }

    /**
     * Callback function for preg_replace_callback() in parse_with_globals()
     */
    protected function globals_callback($matches)
    {
        return $GLOBALS[$matches[1]];
    }

    /**
     * Correct absolute paths in images and other tags (add cache busters)
     */
    protected function fix_paths($output)
    {
        $regexp = '!(src|href|background|data-src-[a-z]+)=(["\']?)([a-z0-9/_.-]+)(["\'\s>])!i';

        return preg_replace_callback($regexp, [$this, 'file_callback'], $output);
    }

    /**
     * Callback function for preg_replace_callback in fix_paths()
     *
     * @return string Parsed string
     */
    protected function file_callback($matches)
    {
        $file = $matches[3];
        $file = preg_replace('!^/this/!', '/', $file);

        // correct absolute paths
        if ($file[0] == '/') {
            $this->get_skin_file($file, $skin_path, $this->base_path);
            $file = ($skin_path ?: $this->base_path) . $file;
        }

        // add file modification timestamp
        if (preg_match('/\.(js|css|less|ico|png|svg|jpeg)$/', $file)) {
            $file = $this->file_mod($file);
        }

        return $matches[1] . '=' . $matches[2] . $file . $matches[4];
    }

    /**
     * Correct paths of asset files according to assets_path
     */
    protected function fix_assets_paths($output)
    {
        $regexp = '!(src|href|background)=(["\']?)([a-z0-9/_.?=-]+)(["\'\s>])!i';

        return preg_replace_callback($regexp, [$this, 'assets_callback'], $output);
    }

    /**
     * Callback function for preg_replace_callback in fix_assets_paths()
     *
     * @return string Parsed string
     */
    protected function assets_callback($matches)
    {
        $file = $this->asset_url($matches[3]);

        return $matches[1] . '=' . $matches[2] . $file . $matches[4];
    }

    /**
     * Modify file by adding mtime indicator
     */
    protected function file_mod($file)
    {
        $fs  = false;
        $ext = substr($file, strrpos($file, '.') + 1);

        // use minified file if exists (not in development mode)
        if (!$this->devel_mode && !preg_match('/\.min\.' . $ext . '$/', $file)) {
            $minified_file = substr($file, 0, strlen($ext) * -1) . 'min.' . $ext;
            if ($fs = @filemtime($this->assets_dir . $minified_file)) {
                return $minified_file . '?s=' . $fs;
            }
        }

        if ($fs = @filemtime($this->assets_dir . $file)) {
            $file .= '?s=' . $fs;
        }

        return $file;
    }

    /**
     * Public wrapper to dip into template parsing.
     *
     * @param string $input Template content
     *
     * @return string
     * @uses   rcmail_output_html::parse_xml()
     * @since  0.1-rc1
     */
    public function just_parse($input)
    {
        $input = $this->parse_conditions($input);
        $input = $this->parse_xml($input);
        $input = $this->postrender($input);

        return $input;
    }

    /**
     * Parse for conditional tags
     */
    protected function parse_conditions($input)
    {
        $regexp1 = '/<roundcube:if\s+([^>]+)>/is';
        $regexp2 = '/<roundcube:(if|elseif|else|endif)\s*([^>]*)>/is';

        $pos = 0;

        // Find IF tags and process them
        while ($pos < strlen($input) && preg_match($regexp1, $input, $conditions, PREG_OFFSET_CAPTURE, $pos)) {
            $pos = $start = $conditions[0][1];

            // Process the 'condition' attribute
            $attrib  = html::parse_attrib_string($conditions[1][0]);
            $condmet = isset($attrib['condition']) && $this->check_condition($attrib['condition']);

            // Define start/end position of the content to pass into the output
            $content_start = $condmet ? $pos + strlen($conditions[0][0]) : null;
            $content_end   = null;

            $level = 0;
            $endif = null;
            $n = $pos + 1;

            // Process the code until the closing tag (for the processed IF tag)
            while (preg_match($regexp2, $input, $matches, PREG_OFFSET_CAPTURE, $n)) {
                $tag_start = $matches[0][1];
                $tag_end   = $tag_start + strlen($matches[0][0]);
                $tag_name  = strtolower($matches[1][0]);

                switch ($tag_name) {
                case 'if':
                    $level++;
                    break;

                case 'endif':
                    if (!$level--) {
                        $endif = $tag_end;
                        if ($content_end === null) {
                            $content_end = $tag_start;
                        }
                        break 2;
                    }
                    break;

                case 'elseif':
                    if (!$level) {
                        if ($condmet) {
                            if ($content_end === null) {
                                $content_end = $tag_start;
                            }
                        }
                        else {
                            // Process the 'condition' attribute
                            $attrib  = html::parse_attrib_string($matches[2][0]);
                            $condmet = isset($attrib['condition']) && $this->check_condition($attrib['condition']);

                            if ($condmet) {
                                $content_start = $tag_end;
                            }
                        }
                    }
                    break;

                case 'else':
                    if (!$level) {
                        if ($condmet) {
                            if ($content_end === null) {
                                $content_end = $tag_start;
                            }
                        }
                        else {
                            $content_start = $tag_end;
                        }
                    }
                    break;
                }

                $n = $tag_end;
            }

            // No ending tag found
            if ($endif === null) {
                $pos = strlen($input);
                if ($content_end === null) {
                    $content_end = $pos;
                }
            }

            if ($content_start === null) {
                $content = '';
            }
            else {
                $content = substr($input, $content_start, $content_end - $content_start);
            }

            // Replace the whole IF statement with the output content
            $input = substr_replace($input, $content, $start, max($endif, $content_end, $pos) - $start);
            $pos   = $start;
        }

        return $input;
    }

    /**
     * Determines if a given condition is met
     *
     * @param string $condition Condition statement
     *
     * @return bool True if condition is met, False if not
     * @todo Extend this to allow real conditions, not just "set"
     */
    protected function check_condition($condition)
    {
        return $this->eval_expression($condition);
    }

    /**
     * Inserts hidden field with CSRF-prevention-token into POST forms
     */
    protected function alter_form_tag($matches)
    {
        $out    = $matches[0];
        $attrib = html::parse_attrib_string($matches[1]);

        if (!empty($attrib['method']) && strtolower($attrib['method']) == 'post') {
            $hidden = new html_hiddenfield(['name' => '_token', 'value' => $this->app->get_request_token()]);
            $out .= "\n" . $hidden->show();
        }

        return $out;
    }

    /**
     * Parse & evaluate a given expression and return its result.
     *
     * @param string $expression Expression statement
     *
     * @return mixed Expression result
     */
    protected function eval_expression($expression)
    {
        $expression = preg_replace(
            [
                '/session:([a-z0-9_]+)/i',
                '/config:([a-z0-9_]+)(:([a-z0-9_]+))?/i',
                '/env:([a-z0-9_]+)/i',
                '/request:([a-z0-9_]+)/i',
                '/cookie:([a-z0-9_]+)/i',
                '/browser:([a-z0-9_]+)/i',
                '/template:name/i',
            ],
            [
                "(isset(\$_SESSION['\\1']) ? \$_SESSION['\\1'] : null)",
                "\$this->app->config->get('\\1',rcube_utils::get_boolean('\\3'))",
                "(isset(\$this->env['\\1']) ? \$this->env['\\1'] : null)",
                "rcube_utils::get_input_value('\\1', rcube_utils::INPUT_GPC)",
                "(isset(\$_COOKIE['\\1']) ? \$_COOKIE['\\1'] : null)",
                "(isset(\$this->browser->{'\\1'}) ? \$this->browser->{'\\1'} : null)",
                "'{$this->template_name}'",
            ],
            $expression
        );

        // Note: We used create_function() before but it's deprecated in PHP 7.2
        //       and really it was just a wrapper on eval().
        return eval("return ($expression);");
    }

    /**
     * Parse variable strings
     *
     * @param string $type Variable type (env, config etc)
     * @param string $name Variable name
     *
     * @return mixed Variable value
     */
    protected function parse_variable($type, $name)
    {
        $value = '';

        switch ($type) {
            case 'env':
                $value = isset($this->env[$name]) ? $this->env[$name] : null;
                break;
            case 'config':
                $value = $this->config->get($name);
                if (is_array($value) && !empty($value[$_SESSION['storage_host']])) {
                    $value = $value[$_SESSION['storage_host']];
                }
                break;
            case 'request':
                $value = rcube_utils::get_input_value($name, rcube_utils::INPUT_GPC);
                break;
            case 'session':
                $value = isset($_SESSION[$name]) ? $_SESSION[$name] : '';
                break;
            case 'cookie':
                $value = htmlspecialchars($_COOKIE[$name], ENT_COMPAT | ENT_HTML401, RCUBE_CHARSET);
                break;
            case 'browser':
                $value = isset($this->browser->{$name}) ? $this->browser->{$name} : '';
                break;
        }

        return $value;
    }

    /**
     * Search for special tags in input and replace them
     * with the appropriate content
     *
     * @param string $input Input string to parse
     *
     * @return string Altered input string
     * @todo   Use DOM-parser to traverse template HTML
     * @todo   Maybe a cache.
     */
    protected function parse_xml($input)
    {
        $regexp = '/<roundcube:([-_a-z]+)\s+((?:[^>]|\\\\>)+)(?<!\\\\)>/Ui';

        return preg_replace_callback($regexp, [$this, 'xml_command'], $input);
    }

    /**
     * Callback function for parsing an xml command tag
     * and turn it into real html content
     *
     * @param array $matches Matches array of preg_replace_callback
     *
     * @return string Tag/Object content
     */
    protected function xml_command($matches)
    {
        $command = strtolower($matches[1]);
        $attrib  = html::parse_attrib_string($matches[2]);

        // empty output if required condition is not met
        if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
            return '';
        }

        // localize title and summary attributes
        if ($command != 'button' && !empty($attrib['title']) && $this->app->text_exists($attrib['title'])) {
            $attrib['title'] = $this->app->gettext($attrib['title']);
        }
        if ($command != 'button' && !empty($attrib['summary']) && $this->app->text_exists($attrib['summary'])) {
            $attrib['summary'] = $this->app->gettext($attrib['summary']);
        }

        // execute command
        switch ($command) {
            // return a button
            case 'button':
                if (!empty($attrib['name']) || !empty($attrib['command'])) {
                    return $this->button($attrib);
                }
                break;

            // frame
            case 'frame':
                return $this->frame($attrib);
                break;

            // show a label
            case 'label':
                if (!empty($attrib['expression'])) {
                    $attrib['name'] = $this->eval_expression($attrib['expression']);
                }

                if (!empty($attrib['name']) || !empty($attrib['command'])) {
                    $vars = $attrib + ['product' => $this->config->get('product_name')];
                    unset($vars['name'], $vars['command']);

                    $label   = $this->app->gettext($attrib + ['vars' => $vars]);
                    $quoting = null;

                    if (!empty($attrib['quoting'])) {
                        $quoting = strtolower($attrib['quoting']);
                    }
                    else if (isset($attrib['html'])) {
                        $quoting = rcube_utils::get_boolean((string) $attrib['html']) ? 'no' : '';
                    }

                    // 'noshow' can be used in skins to define new labels
                    if (!empty($attrib['noshow'])) {
                        return '';
                    }

                    switch ($quoting) {
                        case 'no':
                        case 'raw':
                            break;
                        case 'javascript':
                        case 'js':
                            $label = rcube::JQ($label);
                            break;
                        default:
                            $label = html::quote($label);
                            break;
                    }

                    return $label;
                }
                break;

            case 'add_label':
                $this->add_label($attrib['name']);
                break;

            // include a file
            case 'include':
                if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
                    break;
                }

                if ($attrib['file'][0] != '/') {
                    $attrib['file'] = '/templates/' . $attrib['file'];
                }

                $old_base_path   = $this->base_path;
                $include         = '';
                $attr_skin_path = !empty($attrib['skinpath']) ? $attrib['skinpath'] : null;

                if (!empty($attrib['skin_path'])) {
                    $attr_skin_path = $attrib['skin_path'];
                }

                if ($path = $this->get_skin_file($attrib['file'], $skin_path, $attr_skin_path)) {
                    // set base_path to core skin directory (not plugin's skin)
                    $this->base_path = preg_replace('!plugins/\w+/!', '', $skin_path);
                    $path = realpath(RCUBE_INSTALL_PATH . $path);
                }

                if (is_readable($path)) {
                    $allow_php = $this->config->get('skin_include_php');
                    $include   = $allow_php ? $this->include_php($path) : file_get_contents($path);
                    $include   = $this->parse_conditions($include);
                    $include   = $this->parse_xml($include);
                    $include   = $this->fix_paths($include);
                }

                $this->base_path = $old_base_path;

                return $include;

            case 'plugin.include':
                $hook = $this->app->plugins->exec_hook("template_plugin_include", $attrib + ['content' => '']);
                return $hook['content'];

            // define a container block
            case 'container':
                if (!empty($attrib['name']) && !empty($attrib['id'])) {
                    $this->command('gui_container', $attrib['name'], $attrib['id']);
                    // let plugins insert some content here
                    $hook = $this->app->plugins->exec_hook("template_container", $attrib + ['content' => '']);
                    return $hook['content'];
                }
                break;

            // return code for a specific application object
            case 'object':
                $object  = strtolower($attrib['name']);
                $content = '';
                $handler = null;

                // correct deprecated object names
                if (!empty($this->deprecated_template_objects[$object])) {
                    $object = $this->deprecated_template_objects[$object];
                }

                if (!empty($this->object_handlers[$object])) {
                    $handler = $this->object_handlers[$object];
                }

                // execute object handler function
                if (is_callable($handler)) {
                    $this->prepare_object_attribs($attrib);

                    // We assume that objects with src attribute are internal (in most
                    // cases this is a watermark frame). We need this to make sure assets_path
                    // is added to the internal assets paths
                    $external = empty($attrib['src']);
                    $content  = call_user_func($handler, $attrib);
                }
                else if ($object == 'doctype') {
                    $content = html::doctype($attrib['value']);
                }
                else if ($object == 'logo') {
                    $attrib += ['alt' => $this->xml_command(['', 'object', 'name="productname"'])];

                    // 'type' attribute added in 1.4 was renamed 'logo-type' in 1.5
                    // check both for backwards compatibility
                    $logo_type  = !empty($attrib['logo-type']) ? $attrib['logo-type'] : null;
                    $logo_match = !empty($attrib['logo-match']) ? $attrib['logo-match'] : null;
                    if (!empty($attrib['type']) && empty($logo_type)) {
                        $logo_type = $attrib['type'];
                    }

                    if (($template_logo = $this->get_template_logo($logo_type, $logo_match)) !== null) {
                        $attrib['src'] = $template_logo;
                    }

                    $additional_logos = [];
                    $logo_types       = (array) $this->config->get('additional_logo_types');

                    foreach ($logo_types as $type) {
                        if (($template_logo = $this->get_template_logo($type)) !== null) {
                            $additional_logos[$type] = $this->abs_url($template_logo);
                        }
                        else if (!empty($attrib['data-src-' . $type])) {
                            $additional_logos[$type] = $this->abs_url($attrib['data-src-' . $type]);
                        }
                    }

                    if (!empty($additional_logos)) {
                        $this->set_env('additional_logos', $additional_logos);
                    }

                    if (!empty($attrib['src'])) {
                        $content = html::img($attrib);
                    }
                }
                else if ($object == 'productname') {
                    $name    = $this->config->get('product_name', 'Roundcube Webmail');
                    $content = html::quote($name);
                }
                else if ($object == 'version') {
                    $ver = (string) RCMAIL_VERSION;
                    if (is_file(RCUBE_INSTALL_PATH . '.svn/entries')) {
                        if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
                          $ver .= ' [SVN r'.$regs[1].']';
                    }
                    else if (is_file(RCUBE_INSTALL_PATH . '.git/index')) {
                        if (preg_match('/Date:\s+([^\n]+)/', @shell_exec('git log -1'), $regs)) {
                            if ($date = date('Ymd.Hi', strtotime($regs[1]))) {
                                $ver .= ' [GIT '.$date.']';
                            }
                        }
                    }
                    $content = html::quote($ver);
                }
                else if ($object == 'steptitle') {
                    $content = html::quote($this->get_pagetitle(false));
                }
                else if ($object == 'pagetitle') {
                    // Deprecated, <title> will be added automatically
                    $content = html::quote($this->get_pagetitle());
                }
                else if ($object == 'contentframe') {
                    if (empty($attrib['id'])) {
                        $attrib['id'] = 'rcm' . $this->env['task'] . 'frame';
                    }

                    // parse variables
                    if (preg_match('/^(config|env):([a-z0-9_]+)$/i', $attrib['src'], $matches)) {
                        $attrib['src'] = $this->parse_variable($matches[1], $matches[2]);
                    }

                    $content = $this->frame($attrib, true);
                }
                else if ($object == 'meta' || $object == 'links') {
                    if ($object == 'meta') {
                        $source = 'meta_tags';
                        $tag    = 'meta';
                        $key    = 'name';
                        $param  = 'content';
                    }
                    else {
                        $source = 'link_tags';
                        $tag    = 'link';
                        $key    = 'rel';
                        $param  = 'href';
                    }

                    foreach ($this->$source as $name => $vars) {
                        // $vars can be in many forms:
                        // - string
                        // - array('key' => 'val')
                        // - array(string, string)
                        // - array(array(), string)
                        // - array(array('key' => 'val'), array('key' => 'val'))
                        // normalise this for processing by checking for string array keys
                        $vars = is_array($vars) ? (count(array_filter(array_keys($vars), 'is_string')) > 0 ? [$vars] : $vars) : [$vars];

                        foreach ($vars as $args) {
                            // skip unset headers e.g. when extending a skin and removing a header defined in the parent
                            if ($args === false) {
                                continue;
                            }

                            $args = is_array($args) ? $args : [$param => $args];

                            // special handling for favicon
                            if ($object == 'links' && $name == 'shortcut icon' && empty($args[$param])) {
                                if ($href = $this->get_template_logo('favicon')) {
                                    $args[$param] = $href;
                                }
                                else if ($href = $this->config->get('favicon', '/images/favicon.ico')) {
                                    $args[$param] = $href;
                                }
                            }

                            $content .= html::tag($tag, [$key => $name, 'nl' => true] + $args);
                        }
                    }
                }

                // exec plugin hooks for this template object
                $hook = $this->app->plugins->exec_hook("template_object_$object", $attrib + ['content' => $content]);

                if (strlen($hook['content']) && !empty($external)) {
                    $object_id                 = uniqid('TEMPLOBJECT:', true);
                    $this->objects[$object_id] = $hook['content'];
                    $hook['content']           = $object_id;
                }

                return $hook['content'];

            // return <link> element
            case 'link':
                if ($attrib['condition'] && !$this->check_condition($attrib['condition'])) {
                    break;
                }

                unset($attrib['condition']);

                return html::tag('link', $attrib);


            // return code for a specified eval expression
            case 'exp':
                return html::quote($this->eval_expression($attrib['expression']));

            // return variable
            case 'var':
                $var = explode(':', $attrib['name']);
                $value = $this->parse_variable($var[0], $var[1]);

                if (is_array($value)) {
                    $value = implode(', ', $value);
                }

                return html::quote($value);

            case 'form':
                return $this->form_tag($attrib);
        }

        return '';
    }

    /**
     * Prepares template object attributes
     *
     * @param array &$attribs Attributes
     */
    protected function prepare_object_attribs(&$attribs)
    {
        foreach ($attribs as $key => &$value) {
            if (strpos($key, 'data-label-') === 0) {
                // Localize data-label-* attributes
                $value = $this->app->gettext($value);
            }
            elseif ($key[0] == ':') {
                // Evaluate attributes with expressions and remove special character from attribute name
                $attribs[substr($key, 1)] = $this->eval_expression($value);
                unset($attribs[$key]);
            }
        }
    }

    /**
     * Include a specific file and return it's contents
     *
     * @param string $file File path
     *
     * @return string Contents of the processed file
     */
    protected function include_php($file)
    {
        ob_start();
        include $file;
        $out = ob_get_contents();
        ob_end_clean();

        return $out;
    }

    /**
     * Put objects' content back into template output
     */
    protected function postrender($output)
    {
        // insert objects' contents
        foreach ($this->objects as $key => $val) {
            $output = str_replace($key, $val, $output, $count);
            if ($count) {
                $this->objects[$key] = null;
            }
        }

        // make sure all <form> tags have a valid request token
        $output = preg_replace_callback('/<form\s+([^>]+)>/Ui', [$this, 'alter_form_tag'], $output);

        return $output;
    }

    /**
     * Create and register a button
     *
     * @param array $attrib Named button attributes
     *
     * @return string HTML button
     * @todo   Remove all inline JS calls and use jQuery instead.
     * @todo   Remove all sprintf()'s - they are pretty, but also slow.
     */
    public function button($attrib)
    {
        static $s_button_count = 100;

        // these commands can be called directly via url
        $a_static_commands = ['compose', 'list', 'preferences', 'folders', 'identities'];

        if (empty($attrib['command']) && empty($attrib['name']) && empty($attrib['href'])) {
            return '';
        }

        $command = !empty($attrib['command']) ? $attrib['command'] : null;
        $action  = $command ?: (!empty($attrib['name']) ? $attrib['name'] : null);

        if (!empty($attrib['task'])) {
            $command = $attrib['task'] . '.' . $command;
            $element = $attrib['task'] . '.' . $action;
        }
        else {
            $element = (!empty($this->env['task']) ? $this->env['task'] . '.' : '') . $action;
        }

        $disabled_actions = (array) $this->config->get('disabled_actions');

        // remove buttons for disabled actions
        if (in_array($element, $disabled_actions) || in_array($action, $disabled_actions)) {
            return '';
        }

        // try to find out the button type
        if (!empty($attrib['type'])) {
            $attrib['type'] = strtolower($attrib['type']);
            if (strpos($attrib['type'], '-menuitem')) {
                $attrib['type'] = substr($attrib['type'], 0, -9);
                $menuitem = true;
            }
        }
        else if (!empty($attrib['image']) || !empty($attrib['imagepas']) || !empty($attrib['imageact'])) {
            $attrib['type'] = 'image';
        }
        else {
            $attrib['type'] = 'button';
        }

        if (empty($attrib['image'])) {
            if (!empty($attrib['imagepas'])) {
                $attrib['image'] = $attrib['imagepas'];
            }
            else if (!empty($attrib['imageact'])) {
                $attrib['image'] = $attrib['imageact'];
            }
        }

        if (empty($attrib['id'])) {
            // ensure auto generated IDs are unique between main window and content frame
            // Elastic skin duplicates buttons between the two on smaller screens (#7618)
            $prefix       = ($this->framed || !empty($this->env['framed'])) ? 'frm' : '';
            $attrib['id'] = sprintf('rcmbtn%s%d', $prefix, $s_button_count++);
        }

        // get localized text for labels and titles
        $domain = !empty($attrib['domain']) ? $attrib['domain'] : null;
        if (!empty($attrib['title'])) {
            $attrib['title'] = html::quote($this->app->gettext($attrib['title'], $domain));
        }
        if (!empty($attrib['label'])) {
            $attrib['label'] = html::quote($this->app->gettext($attrib['label'], $domain));
        }
        if (!empty($attrib['alt'])) {
            $attrib['alt'] = html::quote($this->app->gettext($attrib['alt'], $domain));
        }

        // set accessibility attributes
        if (empty($attrib['role'])) {
            $attrib['role'] = 'button';
        }

        if (!empty($attrib['class']) && !empty($attrib['classact']) || !empty($attrib['imagepas']) && !empty($attrib['imageact'])) {
            if (array_key_exists('tabindex', $attrib)) {
                $attrib['data-tabindex'] = $attrib['tabindex'];
            }
            $attrib['tabindex']      = '-1';  // disable button by default
            $attrib['aria-disabled'] = 'true';
        }

        // set title to alt attribute for IE browsers
        if ($this->browser->ie && empty($attrib['title']) && !empty($attrib['alt'])) {
            $attrib['title'] = $attrib['alt'];
        }

        // add empty alt attribute for XHTML compatibility
        if (!isset($attrib['alt'])) {
            $attrib['alt'] = '';
        }

        // register button in the system
        if (!empty($attrib['command'])) {
            $this->add_script(sprintf(
                "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
                self::JS_OBJECT_NAME,
                $command,
                $attrib['id'],
                $attrib['type'],
                !empty($attrib['imageact']) ? $this->abs_url($attrib['imageact']) : (!empty($attrib['classact']) ? $attrib['classact'] : ''),
                !empty($attrib['imagesel']) ? $this->abs_url($attrib['imagesel']) : (!empty($attrib['classsel']) ? $attrib['classsel'] : ''),
                !empty($attrib['imageover']) ? $this->abs_url($attrib['imageover']) : ''
            ));

            // make valid href to specific buttons
            if (in_array($attrib['command'], rcmail::$main_tasks)) {
                $attrib['href']    = $this->app->url(['task' => $attrib['command']]);
                $attrib['onclick'] = sprintf("return %s.command('switch-task','%s',this,event)", self::JS_OBJECT_NAME, $attrib['command']);
            }
            else if (!empty($attrib['task']) && in_array($attrib['task'], rcmail::$main_tasks)) {
                $attrib['href'] = $this->app->url(['action' => $attrib['command'], 'task' => $attrib['task']]);
            }
            else if (in_array($attrib['command'], $a_static_commands)) {
                $attrib['href'] = $this->app->url(['action' => $attrib['command']]);
            }
            else if (($attrib['command'] == 'permaurl' || $attrib['command'] == 'extwin') && !empty($this->env['permaurl'])) {
              $attrib['href'] = $this->env['permaurl'];
            }
        }

        // overwrite attributes
        if (empty($attrib['href'])) {
            $attrib['href'] = '#';
        }

        if (!empty($attrib['task'])) {
            if (!empty($attrib['classact'])) {
                $attrib['class'] = $attrib['classact'];
            }
        }
        else if ($command && empty($attrib['onclick'])) {
            $attrib['onclick'] = sprintf(
                "return %s.command('%s','%s',this,event)",
                self::JS_OBJECT_NAME,
                $command,
                !empty($attrib['prop']) ? $attrib['prop'] : ''
            );
        }

        $out         = '';
        $btn_content = null;
        $link_attrib = [];

        // generate image tag
        if ($attrib['type'] == 'image') {
            $attrib_str = html::attrib_string(
                $attrib,
                [
                    'style', 'class', 'id', 'width', 'height', 'border', 'hspace',
                    'vspace', 'align', 'alt', 'tabindex', 'title'
                ]
            );
            $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
            if (!empty($attrib['label'])) {
                $btn_content .= ' '.$attrib['label'];
            }
            $link_attrib = ['href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'target'];
        }
        else if ($attrib['type'] == 'link') {
            $btn_content = isset($attrib['content']) ? $attrib['content'] : (!empty($attrib['label']) ? $attrib['label'] : $attrib['command']);
            $link_attrib = array_merge(html::$common_attrib, ['href', 'onclick', 'tabindex', 'target', 'rel']);
            if (!empty($attrib['innerclass'])) {
                $btn_content = html::span($attrib['innerclass'], $btn_content);
            }
        }
        else if ($attrib['type'] == 'input') {
            $attrib['type'] = 'button';

            if (!empty($attrib['label'])) {
                $attrib['value'] = $attrib['label'];
            }
            if (!empty($attrib['command'])) {
                $attrib['disabled'] = 'disabled';
            }

            $out = html::tag('input', $attrib, null, ['type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex', 'disabled']);
        }
        else {
            if (!empty($attrib['label'])) {
                $attrib['value'] = $attrib['label'];
            }
            if (!empty($attrib['command'])) {
                $attrib['disabled'] = 'disabled';
            }

            $content = isset($attrib['content']) ? $attrib['content'] : $attrib['label'];
            $out = html::tag('button', $attrib, $content, ['type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex', 'disabled']);
        }

        // generate html code for button
        if ($btn_content) {
            $attrib_str = html::attrib_string($attrib, $link_attrib);
            $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
        }

        if (!empty($attrib['wrapper'])) {
            $out = html::tag($attrib['wrapper'], null, $out);
        }

        if (!empty($menuitem)) {
            $class = !empty($attrib['menuitem-class']) ? ' class="' . $attrib['menuitem-class'] . '"' : '';
            $out   = '<li role="menuitem"' . $class . '>' . $out . '</li>';
        }

        return $out;
    }

    /**
     * Link an external script file
     *
     * @param string $file     File URL
     * @param string $position Target position [head|head_bottom|foot]
     */
    public function include_script($file, $position = 'head', $add_path = true)
    {
        if ($add_path && !preg_match('|^https?://|i', $file) && $file[0] != '/') {
            $file = $this->file_mod($this->scripts_path . $file);
        }

        if (!isset($this->script_files[$position]) || !is_array($this->script_files[$position])) {
            $this->script_files[$position] = [];
        }

        if (!in_array($file, $this->script_files[$position])) {
            $this->script_files[$position][] = $file;
        }
    }

    /**
     * Add inline javascript code
     *
     * @param string $script   JS code snippet
     * @param string $position Target position [head|head_top|foot|docready]
     */
    public function add_script($script, $position = 'head')
    {
        if (!isset($this->scripts[$position])) {
            $this->scripts[$position] = rtrim($script);
        }
        else {
            $this->scripts[$position] .= "\n" . rtrim($script);
        }
    }

    /**
     * Link an external css file
     *
     * @param string $file File URL
     */
    public function include_css($file)
    {
        $this->css_files[] = $file;
    }

    /**
     * Add HTML code to the page header
     *
     * @param string $str HTML code
     */
    public function add_header($str)
    {
        $this->header .= "\n" . $str;
    }

    /**
     * Add HTML code to the page footer
     * To be added right before </body>
     *
     * @param string $str HTML code
     */
    public function add_footer($str)
    {
        $this->footer .= "\n" . $str;
    }

    /**
     * Process template and write to stdOut
     *
     * @param string $output HTML output
     */
    protected function _write($output = '')
    {
        $output = trim($output);

        if (empty($output)) {
            $output   = html::doctype('html5') . "\n" . $this->default_template;
            $is_empty = true;
        }

        $merge_script_files = function($output, $script) {
            return $output . html::script($script);
        };

        $merge_scripts = function($output, $script) {
            return $output . html::script([], $script);
        };

        // put docready commands into page footer
        if (!empty($this->scripts['docready'])) {
            $this->add_script("\$(function() {\n" . $this->scripts['docready'] . "\n});", 'foot');
        }

        $page_header = '';
        $page_footer = '';
        $meta        = '';

        // declare page language
        if (!empty($_SESSION['language'])) {
            $lang   = substr($_SESSION['language'], 0, 2);
            $output = preg_replace('/<html/', '<html lang="' . html::quote($lang) . '"', $output, 1);

            if (!headers_sent()) {
                $this->header('Content-Language: ' . $lang);
            }
        }

        // include meta tag with charset
        if (!empty($this->charset)) {
            if (!headers_sent()) {
                $this->header('Content-Type: text/html; charset=' . $this->charset);
            }

            $meta .= html::tag('meta', [
                    'http-equiv' => 'content-type',
                    'content'    => "text/html; charset={$this->charset}",
                    'nl'         => true
            ]);
        }

        // include page title (after charset specification)
        $meta .= '<title>' . html::quote($this->get_pagetitle()) . "</title>\n";

        $output = preg_replace('/(<head[^>]*>)\n*/i', "\\1\n{$meta}", $output, 1, $count);
        if (!$count) {
            $page_header .= $meta;
        }

        // include scripts into header/footer
        if (!empty($this->script_files['head'])) {
            $page_header .= array_reduce((array) $this->script_files['head'], $merge_script_files);
        }

        $head  = isset($this->scripts['head_top']) ? $this->scripts['head_top'] : '';
        $head .= isset($this->scripts['head']) ? $this->scripts['head'] : '';

        $page_header .= array_reduce((array) $head, $merge_scripts);
        $page_header .= $this->header . "\n";

        if (!empty($this->script_files['head_bottom'])) {
            $page_header .= array_reduce((array) $this->script_files['head_bottom'], $merge_script_files);
        }

        if (!empty($this->script_files['foot'])) {
            $page_footer .= array_reduce((array) $this->script_files['foot'], $merge_script_files);
        }

        $page_footer .= $this->footer . "\n";

        if (!empty($this->scripts['foot'])) {
            $page_footer .= array_reduce((array) $this->scripts['foot'], $merge_scripts);
        }

        // find page header
        if ($hpos = stripos($output, '</head>')) {
            $page_header .= "\n";
        }
        else {
            if (!is_numeric($hpos)) {
                $hpos = stripos($output, '<body');
            }
            if (!is_numeric($hpos) && ($hpos = stripos($output, '<html'))) {
                while ($output[$hpos] != '>') {
                    $hpos++;
                }
                $hpos++;
            }
            $page_header = "<head>\n$page_header\n</head>\n";
        }

        // add page header
        if ($hpos) {
            $output = substr_replace($output, $page_header, $hpos, 0);
        }
        else {
            $output = $page_header . $output;
        }

        // add page footer
        if (($fpos = strripos($output, '</body>')) || ($fpos = strripos($output, '</html>'))) {
            // for Elastic: put footer content before "footer scripts"
            while (($npos = strripos($output, "\n", -strlen($output) + $fpos - 1))
                && $npos != $fpos
                && ($chunk = substr($output, $npos, $fpos - $npos)) !== ''
                && (trim($chunk) === '' || preg_match('/\s*<script[^>]+><\/script>\s*/', $chunk))
            ) {
                $fpos = $npos;
            }

            $output = substr_replace($output, $page_footer."\n", $fpos, 0);
        }
        else {
            $output .= "\n".$page_footer;
        }

        // add css files in head, before scripts, for speed up with parallel downloads
        if (!empty($this->css_files) && empty($is_empty)
            && (($pos = stripos($output, '<script ')) || ($pos = stripos($output, '</head>')))
        ) {
            $css = '';
            foreach ($this->css_files as $file) {
                $is_less = substr_compare($file, '.less', -5, 5, true) === 0;
                $css    .= html::tag('link', [
                        'rel'  => $is_less ? 'stylesheet/less' : 'stylesheet',
                        'type' => 'text/css',
                        'href' => $file,
                        'nl'   => true,
                ]);
            }
            $output = substr_replace($output, $css, $pos, 0);
        }

        $output = $this->parse_with_globals($this->fix_paths($output));

        if ($this->assets_path) {
            $output = $this->fix_assets_paths($output);
        }

        $output = $this->postrender($output);

        // trigger hook with final HTML content to be sent
        $hook = $this->app->plugins->exec_hook("send_page", ['content' => $output]);
        if (!$hook['abort']) {
            if ($this->charset != RCUBE_CHARSET) {
                echo rcube_charset::convert($hook['content'], RCUBE_CHARSET, $this->charset);
            }
            else {
                echo $hook['content'];
            }
        }
    }

    /**
     * Returns iframe object, registers some related env variables
     *
     * @param array $attrib          HTML attributes
     * @param bool  $is_contentframe Register this iframe as the 'contentframe' gui object
     *
     * @return string IFRAME element
     */
    public function frame($attrib, $is_contentframe = false)
    {
        static $idcount = 0;

        if (empty($attrib['id'])) {
            $attrib['id'] = 'rcmframe' . ++$idcount;
        }

        $attrib['name'] = $attrib['id'];
        $attrib['src']  = !empty($attrib['src']) ? $this->abs_url($attrib['src'], true) : 'about:blank';

        // register as 'contentframe' object
        if ($is_contentframe || !empty($attrib['contentframe'])) {
            $this->set_env('contentframe', !empty($attrib['contentframe']) ? $attrib['contentframe'] : $attrib['name']);
        }

        return html::iframe($attrib);
    }


    /*  ************* common functions delivering gui objects **************  */

    /**
     * Create a form tag with the necessary hidden fields
     *
     * @param array  $attrib  Named tag parameters
     * @param string $content HTML content of the form
     *
     * @return string HTML code for the form
     */
    public function form_tag($attrib, $content = null)
    {
        $hidden = '';

        if (!empty($this->env['extwin'])) {
            $hiddenfield = new html_hiddenfield(['name' => '_extwin', 'value' => '1']);
            $hidden = $hiddenfield->show();
        }
        else if ($this->framed || !empty($this->env['framed'])) {
            $hiddenfield = new html_hiddenfield(['name' => '_framed', 'value' => '1']);
            $hidden = $hiddenfield->show();
        }

        if (!$content) {
            $attrib['noclose'] = true;
        }

        return html::tag('form',
            $attrib + ['action' => $this->app->comm_path, 'method' => 'get'],
            $hidden . $content,
            ['id', 'class', 'style', 'name', 'method', 'action', 'enctype', 'onsubmit']
        );
    }

    /**
     * Build a form tag with a unique request token
     *
     * @param array  $attrib  Named tag parameters including 'action' and 'task' values
     *                        which will be put into hidden fields
     * @param string $content Form content
     *
     * @return string HTML code for the form
     */
    public function request_form($attrib, $content = '')
    {
        $hidden = new html_hiddenfield();

        if (!empty($attrib['task'])) {
            $hidden->add(['name' => '_task', 'value' => $attrib['task']]);
        }

        if (!empty($attrib['action'])) {
            $hidden->add(['name' => '_action', 'value' => $attrib['action']]);
        }

        // we already have a <form> tag
        if (!empty($attrib['form'])) {
            if ($this->framed || !empty($this->env['framed'])) {
                $hidden->add(['name' => '_framed', 'value' => '1']);
            }

            return $hidden->show() . $content;
        }

        unset($attrib['task'], $attrib['request']);
        $attrib['action'] = './';

        return $this->form_tag($attrib, $hidden->show() . $content);
    }

    /**
     * GUI object 'username'
     * Showing IMAP username of the current session
     *
     * @param array $attrib Named tag parameters (currently not used)
     *
     * @return string HTML code for the gui object
     */
    public function current_username($attrib)
    {
        static $username;

        // already fetched
        if (!empty($username)) {
            return $username;
        }

        // Current username is an e-mail address
        if (isset($_SESSION['username']) && strpos($_SESSION['username'], '@')) {
            $username = $_SESSION['username'];
        }
        // get e-mail address from default identity
        else if ($sql_arr = $this->app->user->get_identity()) {
            $username = $sql_arr['email'];
        }
        else {
            $username = $this->app->user->get_username();
        }

        $username = rcube_utils::idn_to_utf8($username);

        return html::quote($username);
    }

    /**
     * GUI object 'loginform'
     * Returns code for the webmail login form
     *
     * @param array $attrib Named parameters
     *
     * @return string HTML code for the gui object
     */
    protected function login_form($attrib)
    {
        $default_host     = $this->config->get('default_host');
        $autocomplete     = (int) $this->config->get('login_autocomplete');
        $username_filter  = $this->config->get('login_username_filter');
        $_SESSION['temp'] = true;

        // save original url
        $url = rcube_utils::get_input_value('_url', rcube_utils::INPUT_POST);
        if (
            empty($url)
            && !empty($_SERVER['QUERY_STRING'])
            && !preg_match('/_(task|action)=logout/', $_SERVER['QUERY_STRING'])
        ) {
            $url = $_SERVER['QUERY_STRING'];
        }

        // Disable autocapitalization on iPad/iPhone (#1488609)
        $attrib['autocapitalize'] = 'off';

        $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';

        // set autocomplete attribute
        $user_attrib = $autocomplete > 0 ? [] : ['autocomplete' => 'off'];
        $host_attrib = $autocomplete > 0 ? [] : ['autocomplete' => 'off'];
        $pass_attrib = $autocomplete > 1 ? [] : ['autocomplete' => 'off'];

        if ($username_filter && strtolower($username_filter) == 'email') {
            $user_attrib['type'] = 'email';
        }

        $input_task   = new html_hiddenfield(['name' => '_task', 'value' => 'login']);
        $input_action = new html_hiddenfield(['name' => '_action', 'value' => 'login']);
        $input_tzone  = new html_hiddenfield(['name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_']);
        $input_url    = new html_hiddenfield(['name' => '_url', 'id' => 'rcmloginurl', 'value' => $url]);
        $input_user   = new html_inputfield(['name' => '_user', 'id' => 'rcmloginuser', 'required' => 'required']
            + $attrib + $user_attrib);
        $input_pass   = new html_passwordfield(['name' => '_pass', 'id' => 'rcmloginpwd', 'required' => 'required']
            + $attrib + $pass_attrib);
        $input_host   = null;
        $hide_host    = false;

        // 调整为手动输入模式
//        if (is_array($default_host) && count($default_host) > 1) {
//            $input_host = new html_select(['name' => '_host', 'id' => 'rcmloginhost', 'class' => 'custom-select']);
//
//            foreach ($default_host as $key => $value) {
//                if (!is_array($value)) {
//                    $input_host->add($value, (is_numeric($key) ? $value : $key));
//                }
//                else {
//                    $input_host = null;
//                    break;
//                }
//            }
//        }
//        else if (is_array($default_host) && ($host = key($default_host)) !== null) {
//            $hide_host = true;
//            $input_host = new html_hiddenfield([
//                'name' => '_host', 'id' => 'rcmloginhost', 'value' => is_numeric($host) ? $default_host[$host] : $host] + $attrib);
//        }
//        else if (empty($default_host)) {
            $input_host = new html_inputfield(['name' => '_host', 'id' => 'rcmloginhost', 'class' => 'form-control']
                + $attrib + $host_attrib);
//        }
        // 加入js来控制
        $js_default_host = rcube_email_server_address::getKeyValue();
        $_script = "<script>
var _default_hosts = ".json_encode($js_default_host,JSON_UNESCAPED_UNICODE).";
$(\"#rcmloginuser\").change(function() {auto_host($(this).val());});
$(\"#rcmloginuser\").keyup(function() {auto_host($(this).val());});
$(\"#rcmloginuser\").blur(function() {auto_host($(this).val());});
$('body').mousedown(function() {auto_host($(\"#rcmloginuser\").val());});
function auto_host(_user){
    _user = _user.trim().split('@');
    if(_user[1] && _default_hosts[_user[1]]){
        $(\"#rcmloginhost\").val(_default_hosts[_user[1]]);
    }
}
</script>";
        $this->add_script(mb_substr($_script,8,-9),'foot');

        $this->add_gui_object('loginform', $form_name);

        // create HTML table with two cols
        $table = new html_table(['cols' => 2]);

        $table->add('title', html::label('rcmloginuser', html::quote($this->app->gettext('username'))));
        $table->add('input', $input_user->show(rcube_utils::get_input_value('_user', rcube_utils::INPUT_GPC)));

        $table->add('title', html::label('rcmloginpwd', html::quote($this->app->gettext('password'))));
        $table->add('input', $input_pass->show());

        // add host selection row
        if (is_object($input_host) && !$hide_host) {
            $table->add('title', html::label('rcmloginhost', html::quote('imap '.$this->app->gettext('server'))));
            $table->add('input', $input_host->show(rcube_utils::get_input_value('_host', rcube_utils::INPUT_GPC)));
        }

        $out  = $input_task->show();
        $out .= $input_action->show();
        $out .= $input_tzone->show();
        $out .= $input_url->show();
        $out .= $table->show();

        if ($hide_host) {
            $out .= $input_host->show();
        }

        if (rcube_utils::get_boolean($attrib['submit'])) {
            $button_attr = ['type' => 'submit', 'id' => 'rcmloginsubmit', 'class' => 'button mainaction submit'];
            $out .= html::p('formbuttons', html::tag('button', $button_attr, $this->app->gettext('login')));
        }

        // add oauth login button
        if ($this->config->get('oauth_auth_uri') && $this->config->get('oauth_provider')) {
            // hide login form fields when `oauth_login_redirect` is configured
            if ($this->config->get('oauth_login_redirect')) {
                $out = '';
            }

            $link_attr = ['href' => $this->app->url(['action' => 'oauth']), 'id' => 'rcmloginoauth', 'class' => 'button oauth ' . $this->config->get('oauth_provider')];
            $out .= html::p('oauthlogin', html::a($link_attr, $this->app->gettext(['name' => 'oauthlogin', 'vars' => ['provider' => $this->config->get('oauth_provider_name', 'OAuth')]])));
        }

        // surround html output with a form tag
        if (empty($attrib['form'])) {
            $out = $this->form_tag(['name' => $form_name, 'method' => 'post'], $out);
        }

        // include script for timezone detection
        $this->include_script('jstz.min.js');

        return $out;
    }

    /**
     * GUI object 'preloader'
     * Loads javascript code for images preloading
     *
     * @param array $attrib Named parameters
     * @return void
     */
    protected function preloader($attrib)
    {
        $images = preg_split('/[\s\t\n,]+/', $attrib['images'], -1, PREG_SPLIT_NO_EMPTY);
        $images = array_map([$this, 'abs_url'], $images);
        $images = array_map([$this, 'asset_url'], $images);

        if (empty($images) || $_REQUEST['_task'] == 'logout') {
            return;
        }

        $this->add_script('var images = ' . self::json_serialize($images, $this->devel_mode) .';
            for (var i=0; i<images.length; i++) {
                img = new Image();
                img.src = images[i];
            }', 'docready');
    }

    /**
     * GUI object 'searchform'
     * Returns code for search function
     *
     * @param array $attrib Named parameters
     *
     * @return string HTML code for the gui object
     */
    public function search_form($attrib)
    {
        // add some labels to client
        $this->add_label('searching');

        $attrib['name']  = '_q';
        $attrib['class'] = trim((!empty($attrib['class']) ? $attrib['class'] : '') . ' no-bs');

        if (empty($attrib['id'])) {
            $attrib['id'] = 'rcmqsearchbox';
        }
        if (isset($attrib['type']) && $attrib['type'] == 'search' && !$this->browser->khtml) {
            unset($attrib['type'], $attrib['results']);
        }
        if (empty($attrib['placeholder'])) {
            $attrib['placeholder'] = $this->app->gettext('searchplaceholder');
        }

        $label   = html::label(['for' => $attrib['id'], 'class' => 'voice'], rcube::Q($this->app->gettext('arialabelsearchterms')));
        $input_q = new html_inputfield($attrib);
        $out     = $label . $input_q->show();
        $name    = 'qsearchbox';

        // Support for multiple searchforms on the same page
        if (isset($attrib['gui-object']) && $attrib['gui-object'] !== false && $attrib['gui-object'] !== 'false') {
            $name = $attrib['gui-object'];
        }

        $this->add_gui_object($name, $attrib['id']);

        // add form tag around text field
        if (empty($attrib['form']) && empty($attrib['no-form'])) {
            $out = $this->form_tag([
                    'name'     => !empty($attrib['form-name']) ? $attrib['form-name'] : 'rcmqsearchform',
                    'onsubmit' => sprintf(
                        "%s.command('%s'); return false",
                        self::JS_OBJECT_NAME,
                        !empty($attrib['command']) ? $attrib['command'] : 'search'
                    ),
                    // 'style'    => "display:inline"
                ], $out);
        }

        if (!empty($attrib['wrapper'])) {
            $options_button = '';

            $ariatag = !empty($attrib['ariatag']) ? $attrib['ariatag'] : 'h2';
            $domain  = !empty($attrib['label-domain']) ? $attrib['label-domain'] : null;
            $options = !empty($attrib['options']) ? $attrib['options'] : null;

            $header_label = $this->app->gettext('arialabel' . $attrib['label'], $domain);
            $header_attrs = [
                'id'    => 'aria-label-' . $attrib['label'],
                'class' => 'voice'
            ];

            $header = html::tag($ariatag, $header_attrs, rcube::Q($header_label));

            if (!empty($attrib['options'])) {
                $options_button = $this->button([
                        'type'       => 'link',
                        'href'       => '#search-filter',
                        'class'      => 'button options',
                        'label'      => 'options',
                        'title'      => 'options',
                        'tabindex'   => '0',
                        'innerclass' => 'inner',
                        'data-target' => $options
                ]);
            }

            $search_button = $this->button([
                    'type'       => 'link',
                    'href'       => '#search',
                    'class'      => 'button search',
                    'label'      => $attrib['buttontitle'],
                    'title'      => $attrib['buttontitle'],
                    'tabindex'   => '0',
                    'innerclass' => 'inner',
            ]);

            $reset_button = $this->button([
                    'type'       => 'link',
                    'command'    => !empty($attrib['reset-command']) ? $attrib['reset-command'] : 'reset-search',
                    'class'      => 'button reset',
                    'label'      => 'resetsearch',
                    'title'      => 'resetsearch',
                    'tabindex'   => '0',
                    'innerclass' => 'inner',
            ]);

            $out = html::div([
                    'role'            => 'search',
                    'aria-labelledby' => !empty($attrib['label']) ? 'aria-label-' . $attrib['label'] : null,
                    'class'           => $attrib['wrapper'],
                ],
                "$header$out\n$reset_button\n$options_button\n$search_button"
            );
        }

        return $out;
    }

    /**
     * Builder for GUI object 'message'
     *
     * @param array Named tag parameters
     * @return string HTML code for the gui object
     */
    protected function message_container($attrib)
    {
        if (isset($attrib['id']) === false) {
            $attrib['id'] = 'rcmMessageContainer';
        }

        $this->add_gui_object('message', $attrib['id']);

        return html::div($attrib, '');
    }

    /**
     * GUI object 'charsetselector'
     *
     * @param array $attrib Named parameters for the select tag
     *
     * @return string HTML code for the gui object
     */
    public function charset_selector($attrib)
    {
        // pass the following attributes to the form class
        $field_attrib = ['name' => '_charset'];
        foreach ($attrib as $attr => $value) {
            if (in_array($attr, ['id', 'name', 'class', 'style', 'size', 'tabindex'])) {
                $field_attrib[$attr] = $value;
            }
        }

        $charsets = [
            'UTF-8'        => 'UTF-8 ('.$this->app->gettext('unicode').')',
            'US-ASCII'     => 'ASCII ('.$this->app->gettext('english').')',
            'ISO-8859-1'   => 'ISO-8859-1 ('.$this->app->gettext('westerneuropean').')',
            'ISO-8859-2'   => 'ISO-8859-2 ('.$this->app->gettext('easterneuropean').')',
            'ISO-8859-4'   => 'ISO-8859-4 ('.$this->app->gettext('baltic').')',
            'ISO-8859-5'   => 'ISO-8859-5 ('.$this->app->gettext('cyrillic').')',
            'ISO-8859-6'   => 'ISO-8859-6 ('.$this->app->gettext('arabic').')',
            'ISO-8859-7'   => 'ISO-8859-7 ('.$this->app->gettext('greek').')',
            'ISO-8859-8'   => 'ISO-8859-8 ('.$this->app->gettext('hebrew').')',
            'ISO-8859-9'   => 'ISO-8859-9 ('.$this->app->gettext('turkish').')',
            'ISO-8859-10'  => 'ISO-8859-10 ('.$this->app->gettext('nordic').')',
            'ISO-8859-11'  => 'ISO-8859-11 ('.$this->app->gettext('thai').')',
            'ISO-8859-13'  => 'ISO-8859-13 ('.$this->app->gettext('baltic').')',
            'ISO-8859-14'  => 'ISO-8859-14 ('.$this->app->gettext('celtic').')',
            'ISO-8859-15'  => 'ISO-8859-15 ('.$this->app->gettext('westerneuropean').')',
            'ISO-8859-16'  => 'ISO-8859-16 ('.$this->app->gettext('southeasterneuropean').')',
            'WINDOWS-1250' => 'Windows-1250 ('.$this->app->gettext('easterneuropean').')',
            'WINDOWS-1251' => 'Windows-1251 ('.$this->app->gettext('cyrillic').')',
            'WINDOWS-1252' => 'Windows-1252 ('.$this->app->gettext('westerneuropean').')',
            'WINDOWS-1253' => 'Windows-1253 ('.$this->app->gettext('greek').')',
            'WINDOWS-1254' => 'Windows-1254 ('.$this->app->gettext('turkish').')',
            'WINDOWS-1255' => 'Windows-1255 ('.$this->app->gettext('hebrew').')',
            'WINDOWS-1256' => 'Windows-1256 ('.$this->app->gettext('arabic').')',
            'WINDOWS-1257' => 'Windows-1257 ('.$this->app->gettext('baltic').')',
            'WINDOWS-1258' => 'Windows-1258 ('.$this->app->gettext('vietnamese').')',
            'ISO-2022-JP'  => 'ISO-2022-JP ('.$this->app->gettext('japanese').')',
            'ISO-2022-KR'  => 'ISO-2022-KR ('.$this->app->gettext('korean').')',
            'ISO-2022-CN'  => 'ISO-2022-CN ('.$this->app->gettext('chinese').')',
            'EUC-JP'       => 'EUC-JP ('.$this->app->gettext('japanese').')',
            'EUC-KR'       => 'EUC-KR ('.$this->app->gettext('korean').')',
            'EUC-CN'       => 'EUC-CN ('.$this->app->gettext('chinese').')',
            'BIG5'         => 'BIG5 ('.$this->app->gettext('chinese').')',
            'GB2312'       => 'GB2312 ('.$this->app->gettext('chinese').')',
            'KOI8-R'       => 'KOI8-R ('.$this->app->gettext('cyrillic').')',
        ];

        if ($post = rcube_utils::get_input_value('_charset', rcube_utils::INPUT_POST)) {
            $set = $post;
        }
        else if (!empty($attrib['selected'])) {
            $set = $attrib['selected'];
        }
        else {
            $set = $this->get_charset();
        }

        $set = strtoupper($set);
        if (!isset($charsets[$set]) && preg_match('/^[A-Z0-9-]+$/', $set)) {
            $charsets[$set] = $set;
        }

        $select = new html_select($field_attrib);
        $select->add(array_values($charsets), array_keys($charsets));

        return $select->show($set);
    }

    /**
     * Include content from config/about.<LANG>.html if available
     */
    protected function about_content($attrib)
    {
        $content = '';
        $filenames = [
            'about.' . $_SESSION['language'] . '.html',
            'about.' . substr($_SESSION['language'], 0, 2) . '.html',
            'about.html',
        ];

        foreach ($filenames as $file) {
            $fn = RCUBE_CONFIG_DIR . $file;
            if (is_readable($fn)) {
                $content = file_get_contents($fn);
                $content = $this->parse_conditions($content);
                $content = $this->parse_xml($content);
                break;
            }
        }

        return $content;
    }

    /**
     * Get logo URL for current template based on skin_logo config option
     *
     * @param string $type   Type of the logo to check for (e.g. 'print' or 'small')
     *                       default is null (no special type)
     * @param string $match  (optional) 'all' = type, template or wildcard, 'template' = type or template
     *                       Note: when type is specified matches are limited to type only unless $match is defined
     *
     * @return string image URL
     */
    protected function get_template_logo($type = null, $match = null)
    {
        $template_logo = null;

        if ($logo = $this->config->get('skin_logo')) {
            if (is_array($logo)) {
                $template_names = [
                    $this->skin_name . ':' . $this->template_name . '[' . $type . ']',
                    $this->skin_name . ':' . $this->template_name,
                    $this->skin_name . ':*[' . $type . ']',
                    $this->skin_name . ':[' . $type . ']',
                    $this->skin_name . ':*',
                    '*:' . $this->template_name . '[' . $type . ']',
                    '*:' . $this->template_name,
                    '*:*[' . $type . ']',
                    '*:[' . $type . ']',
                    $this->template_name . '[' . $type . ']',
                    $this->template_name,
                    '*[' . $type . ']',
                    '[' . $type . ']',
                    '*',
                ];

                if (empty($type)) {
                    // If no type provided then remove those options from the list
                    $template_names = preg_grep("/\]$/", $template_names, PREG_GREP_INVERT);
                }
                elseif ($match === null) {
                    // Type specified with no special matching requirements so remove all none type specific options from the list
                    $template_names = preg_grep("/\]$/", $template_names);
                }

                if ($match == 'template') {
                    // Match only specific type or template name
                    $template_names = preg_grep("/\*$/", $template_names, PREG_GREP_INVERT);
                }

                foreach ($template_names as $key) {
                    if (isset($logo[$key])) {
                        $template_logo = $logo[$key];
                        break;
                    }
                }
            }
            else {
                $template_logo = $logo;
            }
        }

        return $template_logo;
    }
}