util.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /* XXX: break up into separate modules (HTTP, user, files) */
  17. defined('GNUSOCIAL') || die();
  18. /**
  19. * Show a server error.
  20. */
  21. function common_server_error($msg, $code=500)
  22. {
  23. $err = new ServerErrorAction($msg, $code);
  24. $err->showPage();
  25. }
  26. /**
  27. * Show a user error.
  28. */
  29. function common_user_error($msg, $code=400)
  30. {
  31. $err = new ClientErrorAction($msg, $code);
  32. $err->showPage();
  33. }
  34. /**
  35. * This should only be used at setup; processes switching languages
  36. * to send text to other users should use common_switch_locale().
  37. *
  38. * @param string $language Locale language code (optional; empty uses
  39. * current user's preference or site default)
  40. * @return mixed success
  41. */
  42. function common_init_locale($language=null)
  43. {
  44. if (!$language) {
  45. $language = common_language();
  46. }
  47. putenv('LANGUAGE='.$language);
  48. putenv('LANG='.$language);
  49. $ok = setlocale(
  50. LC_ALL,
  51. $language . '.utf8',
  52. $language . '.UTF8',
  53. $language . '.utf-8',
  54. $language . '.UTF-8',
  55. $language
  56. );
  57. return $ok;
  58. }
  59. /**
  60. * Initialize locale and charset settings and gettext with our message catalog,
  61. * using the current user's language preference or the site default.
  62. *
  63. * This should generally only be run at framework initialization; code switching
  64. * languages at runtime should call common_switch_language().
  65. *
  66. * @access private
  67. */
  68. function common_init_language()
  69. {
  70. mb_internal_encoding('UTF-8');
  71. // Note that this setlocale() call may "fail" but this is harmless;
  72. // gettext will still select the right language.
  73. $language = common_language();
  74. $locale_set = common_init_locale($language);
  75. if (!$locale_set) {
  76. // The requested locale doesn't exist on the system.
  77. //
  78. // gettext seems very picky... We first need to setlocale()
  79. // to a locale which _does_ exist on the system, and _then_
  80. // we can set in another locale that may not be set up
  81. // (say, ga_ES for Galego/Galician) it seems to take it.
  82. //
  83. // For some reason C and POSIX which are guaranteed to work
  84. // don't do the job. en_US.UTF-8 should be there most of the
  85. // time, but not guaranteed.
  86. $ok = common_init_locale("en_US");
  87. if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
  88. // Try to find a complete, working locale on Unix/Linux...
  89. // @fixme shelling out feels awfully inefficient
  90. // but I don't think there's a more standard way.
  91. $all = `locale -a`;
  92. foreach (explode("\n", $all) as $locale) {
  93. if (preg_match('/\.utf[-_]?8$/i', $locale)) {
  94. $ok = setlocale(LC_ALL, $locale);
  95. if ($ok) {
  96. break;
  97. }
  98. }
  99. }
  100. }
  101. if (!$ok) {
  102. common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
  103. }
  104. $locale_set = common_init_locale($language);
  105. }
  106. common_init_gettext();
  107. }
  108. /**
  109. * @access private
  110. */
  111. function common_init_gettext()
  112. {
  113. setlocale(LC_CTYPE, 'C');
  114. // So we do not have to make people install the gettext locales
  115. $path = common_config('site', 'locale_path');
  116. bindtextdomain("statusnet", $path);
  117. bind_textdomain_codeset("statusnet", "UTF-8");
  118. textdomain("statusnet");
  119. }
  120. /**
  121. * Switch locale during runtime, and poke gettext until it cries uncle.
  122. * Otherwise, sometimes it doesn't actually switch away from the old language.
  123. *
  124. * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
  125. */
  126. function common_switch_locale($language=null)
  127. {
  128. common_init_locale($language);
  129. setlocale(LC_CTYPE, 'C');
  130. // So we do not have to make people install the gettext locales
  131. $path = common_config('site', 'locale_path');
  132. bindtextdomain("statusnet", $path);
  133. bind_textdomain_codeset("statusnet", "UTF-8");
  134. textdomain("statusnet");
  135. }
  136. function common_timezone()
  137. {
  138. if (common_logged_in()) {
  139. $user = common_current_user();
  140. if ($user->timezone) {
  141. return $user->timezone;
  142. }
  143. }
  144. return common_config('site', 'timezone');
  145. }
  146. function common_valid_language($lang)
  147. {
  148. if ($lang) {
  149. // Validate -- we don't want to end up with a bogus code
  150. // left over from some old junk.
  151. foreach (common_config('site', 'languages') as $code => $info) {
  152. if ($info['lang'] == $lang) {
  153. return true;
  154. }
  155. }
  156. }
  157. return false;
  158. }
  159. function common_language()
  160. {
  161. // Allow ?uselang=xx override, very useful for debugging
  162. // and helping translators check usage and context.
  163. if (isset($_GET['uselang'])) {
  164. $uselang = strval($_GET['uselang']);
  165. if (common_valid_language($uselang)) {
  166. return $uselang;
  167. }
  168. }
  169. // If there is a user logged in and they've set a language preference
  170. // then return that one...
  171. if (_have_config() && common_logged_in()) {
  172. $user = common_current_user();
  173. if (common_valid_language($user->language)) {
  174. return $user->language;
  175. }
  176. }
  177. // Otherwise, find the best match for the languages requested by the
  178. // user's browser...
  179. if (common_config('site', 'langdetect')) {
  180. $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
  181. if (!empty($httplang)) {
  182. $language = client_preferred_language($httplang);
  183. if ($language) {
  184. return $language;
  185. }
  186. }
  187. }
  188. // Finally, if none of the above worked, use the site's default...
  189. return common_config('site', 'language');
  190. }
  191. /**
  192. * Salted, hashed passwords are stored in the DB.
  193. */
  194. function common_munge_password($password, Profile $profile=null)
  195. {
  196. $hashed = null;
  197. if (Event::handle('StartHashPassword', [&$hashed, $password, $profile])) {
  198. Event::handle('EndHashPassword', [&$hashed, $password, $profile]);
  199. }
  200. if (empty($hashed)) {
  201. throw new PasswordHashException();
  202. }
  203. return $hashed;
  204. }
  205. /**
  206. * Check if a username exists and has matching password.
  207. */
  208. function common_check_user($nickname, $password)
  209. {
  210. // empty nickname always unacceptable
  211. if (empty($nickname)) {
  212. return false;
  213. }
  214. $authenticatedUser = false;
  215. if (Event::handle('StartCheckPassword', [$nickname, $password, &$authenticatedUser])) {
  216. if (common_is_email($nickname)) {
  217. $user = User::getKV('email', common_canonical_email($nickname));
  218. } else {
  219. $user = User::getKV('nickname', Nickname::normalize($nickname));
  220. }
  221. if ($user instanceof User && !empty($password)) {
  222. if (0 == strcmp(common_munge_password($password, $user->getProfile()), $user->password)) {
  223. //internal checking passed
  224. $authenticatedUser = $user;
  225. }
  226. }
  227. }
  228. if (gettype($authenticatedUser) == "string") {
  229. throw new AuthorizationException(_("古いパスワードが不正です。"));
  230. }
  231. Event::handle('EndCheckPassword', [$nickname, $password, $authenticatedUser]);
  232. return $authenticatedUser;
  233. }
  234. /**
  235. * Is the current user logged in?
  236. */
  237. function common_logged_in()
  238. {
  239. return (!is_null(common_current_user()));
  240. }
  241. function common_local_referer()
  242. {
  243. return isset($_SERVER['HTTP_REFERER'])
  244. && parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) === common_config('site', 'server');
  245. }
  246. function common_have_session()
  247. {
  248. return (0 != strcmp(session_id(), ''));
  249. }
  250. /**
  251. * Make sure session is started and handled by
  252. * the correct handler.
  253. */
  254. function common_ensure_session()
  255. {
  256. if (!common_have_session()) {
  257. if (common_config('sessions', 'handle')) {
  258. session_set_save_handler(new InternalSessionHandler(), true);
  259. }
  260. $session_name = session_name();
  261. $id = null;
  262. foreach ([INPUT_COOKIE, INPUT_GET] as $input_type) {
  263. // PHP's session handler only accepts symbols from
  264. // "A" to "Z", "a" to "Z", the comma sign and the minus sign.
  265. $id = filter_input(
  266. $input_type,
  267. $session_name,
  268. FILTER_VALIDATE_REGEXP,
  269. ['options' => ['regexp' => '/^[,\-A-Za-z0-9]+$/D']]
  270. );
  271. // Found the session (null is suspicious, so stop at that also)
  272. if ($id !== false) {
  273. break;
  274. }
  275. }
  276. if (!is_null($id)) {
  277. session_id($id);
  278. }
  279. session_start();
  280. if (!array_key_exists('started', $_SESSION)) {
  281. $_SESSION['started'] = time();
  282. if (!is_null($id)) {
  283. common_debug(
  284. 'Session cookie "' . $id . '" is set but without a session'
  285. );
  286. }
  287. }
  288. }
  289. }
  290. // Three kinds of arguments:
  291. // 1) a user object
  292. // 2) a nickname
  293. // 3) null to clear
  294. // Initialize to false; set to null if none found
  295. $_cur = false;
  296. function common_set_user($user)
  297. {
  298. global $_cur;
  299. if (is_null($user) && common_have_session()) {
  300. $_cur = null;
  301. unset($_SESSION['userid']);
  302. return true;
  303. } elseif (is_string($user)) {
  304. $nickname = $user;
  305. $user = User::getKV('nickname', $nickname);
  306. } elseif (!$user instanceof User) {
  307. return false;
  308. }
  309. if ($user) {
  310. if (Event::handle('StartSetUser', [&$user])) {
  311. if (!empty($user)) {
  312. if (!$user->hasRight(Right::WEBLOGIN)) {
  313. // TRANS: Authorisation exception thrown when a user a not allowed to login.
  314. throw new AuthorizationException(_('Not allowed to log in.'));
  315. }
  316. common_ensure_session();
  317. $_SESSION['userid'] = $user->id;
  318. $_cur = $user;
  319. Event::handle('EndSetUser', [$user]);
  320. return $_cur;
  321. }
  322. }
  323. }
  324. return false;
  325. }
  326. function common_set_cookie($key, $value, $expiration=0)
  327. {
  328. $path = common_config('site', 'path');
  329. $server = common_config('site', 'server');
  330. if ($path && ($path != '/')) {
  331. $cookiepath = '/' . $path . '/';
  332. } else {
  333. $cookiepath = '/';
  334. }
  335. return setcookie(
  336. $key,
  337. $value,
  338. $expiration,
  339. $cookiepath,
  340. $server,
  341. GNUsocial::useHTTPS()
  342. );
  343. }
  344. define('REMEMBERME', 'rememberme');
  345. define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
  346. function common_rememberme($user=null)
  347. {
  348. if (!$user) {
  349. $user = common_current_user();
  350. if (!$user) {
  351. return false;
  352. }
  353. }
  354. $rm = new Remember_me();
  355. $rm->code = common_random_hexstr(16);
  356. $rm->user_id = $user->id;
  357. // Wrap the insert in some good ol' fashioned transaction code
  358. $rm->query('START TRANSACTION');
  359. $result = $rm->insert();
  360. if (!$result) {
  361. common_log_db_error($rm, 'INSERT', __FILE__);
  362. $rm->query('ROLLBACK');
  363. return false;
  364. }
  365. $rm->query('COMMIT');
  366. $cookieval = $rm->user_id . ':' . $rm->code;
  367. common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
  368. common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
  369. return true;
  370. }
  371. function common_remembered_user()
  372. {
  373. $user = null;
  374. $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
  375. if (!$packed) {
  376. return null;
  377. }
  378. list($id, $code) = explode(':', $packed);
  379. if (!$id || !$code) {
  380. common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
  381. common_forgetme();
  382. return null;
  383. }
  384. $rm = Remember_me::getKV('code', $code);
  385. if (!$rm) {
  386. common_log(LOG_WARNING, 'No such remember code: ' . $code);
  387. common_forgetme();
  388. return null;
  389. }
  390. if ($rm->user_id != $id) {
  391. common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
  392. common_forgetme();
  393. return null;
  394. }
  395. $user = User::getKV('id', $rm->user_id);
  396. if (!$user instanceof User) {
  397. common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
  398. common_forgetme();
  399. return null;
  400. }
  401. // successful!
  402. $result = $rm->delete();
  403. if (!$result) {
  404. common_log_db_error($rm, 'DELETE', __FILE__);
  405. common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
  406. common_forgetme();
  407. return null;
  408. }
  409. common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
  410. common_set_user($user);
  411. common_real_login(false);
  412. // We issue a new cookie, so they can log in
  413. // automatically again after this session
  414. common_rememberme($user);
  415. return $user;
  416. }
  417. /**
  418. * must be called with a valid user!
  419. */
  420. function common_forgetme()
  421. {
  422. common_set_cookie(REMEMBERME, '', 0);
  423. }
  424. /**
  425. * Who is the current user?
  426. */
  427. function common_current_user()
  428. {
  429. global $_cur;
  430. if (!_have_config()) {
  431. return null;
  432. }
  433. if ($_cur === false) {
  434. if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
  435. || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
  436. common_ensure_session();
  437. $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
  438. if ($id) {
  439. $user = User::getKV('id', $id);
  440. if ($user instanceof User) {
  441. $_cur = $user;
  442. return $_cur;
  443. }
  444. }
  445. }
  446. // that didn't work; try to remember; will init $_cur to null on failure
  447. $_cur = common_remembered_user();
  448. if ($_cur) {
  449. // XXX: Is this necessary?
  450. $_SESSION['userid'] = $_cur->id;
  451. }
  452. }
  453. return $_cur;
  454. }
  455. /**
  456. * Logins that are 'remembered' aren't 'real' -- they're subject to
  457. * cookie-stealing. So, we don't let them do certain things. New reg,
  458. * OpenID, and password logins _are_ real.
  459. */
  460. function common_real_login($real=true)
  461. {
  462. common_ensure_session();
  463. $_SESSION['real_login'] = $real;
  464. }
  465. function common_is_real_login()
  466. {
  467. return common_logged_in() && $_SESSION['real_login'];
  468. }
  469. /**
  470. * Get a hash portion for HTTP caching Etags and such including
  471. * info on the current user's session. If login/logout state changes,
  472. * or we've changed accounts, or we've renamed the current user,
  473. * we'll get a new hash value.
  474. *
  475. * This should not be considered secure information.
  476. *
  477. * @param User $user (optional; uses common_current_user() if left out)
  478. * @return string
  479. */
  480. function common_user_cache_hash($user=false)
  481. {
  482. if ($user === false) {
  483. $user = common_current_user();
  484. }
  485. if ($user) {
  486. return crc32($user->id . ':' . $user->nickname);
  487. } else {
  488. return '0';
  489. }
  490. }
  491. /**
  492. * get canonical version of nickname for comparison
  493. *
  494. * @param string $nickname
  495. * @return string
  496. *
  497. * @throws NicknameException on invalid input
  498. * @deprecated call Nickname::normalize() directly.
  499. */
  500. function common_canonical_nickname($nickname)
  501. {
  502. return Nickname::normalize($nickname);
  503. }
  504. /**
  505. * get canonical version of email for comparison
  506. *
  507. * @fixme actually normalize
  508. * @fixme reject invalid input
  509. *
  510. * @param string $email
  511. * @return string
  512. */
  513. function common_canonical_email($email)
  514. {
  515. // XXX: canonicalize UTF-8
  516. // XXX: lcase the domain part
  517. return $email;
  518. }
  519. function common_to_alphanumeric($str)
  520. {
  521. $filtered = preg_replace('/[^A-Za-z0-9]\s*/', '', $str);
  522. if (strlen($filtered) < 1) {
  523. throw new Exception('Filtered string was zero-length.');
  524. }
  525. return $filtered;
  526. }
  527. function common_purify($html, array $args=[])
  528. {
  529. $cfg = \HTMLPurifier_Config::createDefault();
  530. /**
  531. * rel values that should be avoided since they can be used to infer
  532. * information about the _current_ page, not the h-entry:
  533. *
  534. * directory, home, license, payment
  535. *
  536. * Source: http://microformats.org/wiki/rel
  537. */
  538. $cfg->set('Attr.AllowedRel', ['bookmark', 'enclosure', 'nofollow', 'tag', 'noreferrer']);
  539. $cfg->set('HTML.ForbiddenAttributes', ['style']); // id, on* etc. are already filtered by default
  540. $cfg->set('URI.AllowedSchemes', array_fill_keys(common_url_schemes(), true));
  541. if (isset($args['URI.Base'])) {
  542. $cfg->set('URI.Base', $args['URI.Base']); // if null this is like unsetting it I presume
  543. $cfg->set('URI.MakeAbsolute', !is_null($args['URI.Base'])); // if we have a URI base, convert relative URLs to absolute ones.
  544. }
  545. if (common_config('cache', 'dir')) {
  546. $cfg->set('Cache.SerializerPath', common_config('cache', 'dir'));
  547. }
  548. // if you don't want to use the default cache dir for htmlpurifier, set it specifically as $config['htmlpurifier']['Cache.SerializerPath'] = '/tmp'; or something.
  549. foreach (common_config('htmlpurifier') as $key=>$val) {
  550. $cfg->set($key, $val);
  551. }
  552. // Remove more elements than what the default filter removes, default in GNU social are remotely
  553. // linked resources such as img, video, audio
  554. $forbiddenElements = [];
  555. foreach (common_config('htmlfilter') as $tag=>$filter) {
  556. if ($filter === true) {
  557. $forbiddenElements[] = $tag;
  558. }
  559. }
  560. $cfg->set('HTML.ForbiddenElements', $forbiddenElements);
  561. $html = common_remove_unicode_formatting($html);
  562. $purifier = new HTMLPurifier($cfg);
  563. $purified = $purifier->purify($html);
  564. Event::handle('EndCommonPurify', [&$purified, $html]);
  565. return $purified;
  566. }
  567. function common_remove_unicode_formatting($text)
  568. {
  569. // Strip Unicode text formatting/direction codes
  570. // this is pretty dangerous for visualisation of text and can be used for mischief
  571. return $text !== null ? preg_replace('/[\\x{200b}-\\x{200f}\\x{202a}-\\x{202e}]/u', '', $text) : null;
  572. }
  573. /**
  574. * Partial notice markup rendering step: build links to !group references.
  575. *
  576. * @param string $text partially rendered HTML
  577. * @param Profile $author the Profile that is composing the current notice
  578. * @param Notice $parent the Notice this is sent in reply to, if any
  579. * @return string partially rendered HTML
  580. */
  581. function common_render_content($text, Profile $author, Notice $parent=null)
  582. {
  583. $text = common_render_text($text);
  584. $text = common_linkify_mentions($text, $author, $parent);
  585. return $text;
  586. }
  587. /**
  588. * Finds @-mentions within the partially-rendered text section and
  589. * turns them into live links.
  590. *
  591. * Should generally not be called except from common_render_content().
  592. *
  593. * @param string $text partially-rendered HTML
  594. * @param Profile $author the Profile that is composing the current notice
  595. * @param Notice $parent the Notice this is sent in reply to, if any
  596. * @return string partially-rendered HTML
  597. */
  598. function common_linkify_mentions($text, Profile $author, Notice $parent=null)
  599. {
  600. $mentions = common_find_mentions($text, $author, $parent);
  601. // We need to go through in reverse order by position,
  602. // so our positions stay valid despite our fudging with the
  603. // string!
  604. $points = [];
  605. foreach ($mentions as $mention) {
  606. $points[$mention['position']] = $mention;
  607. }
  608. krsort($points);
  609. foreach ($points as $position => $mention) {
  610. $linkText = common_linkify_mention($mention);
  611. $text = substr_replace($text, $linkText, $position, $mention['length']);
  612. }
  613. return $text;
  614. }
  615. function common_linkify_mention(array $mention)
  616. {
  617. $output = null;
  618. if (Event::handle('StartLinkifyMention', [$mention, &$output])) {
  619. $xs = new XMLStringer(false);
  620. $attrs = ['href' => $mention['url'],
  621. 'class' => 'h-card u-url p-nickname '.$mention['type']];
  622. if (!empty($mention['title'])) {
  623. $attrs['title'] = $mention['title'];
  624. }
  625. $xs->element('a', $attrs, $mention['text']);
  626. $output = $xs->getString();
  627. Event::handle('EndLinkifyMention', [$mention, &$output]);
  628. }
  629. return $output;
  630. }
  631. function common_get_attentions($text, Profile $sender, Notice $parent=null)
  632. {
  633. $mentions = common_find_mentions($text, $sender, $parent);
  634. $atts = [];
  635. foreach ($mentions as $mention) {
  636. foreach ($mention['mentioned'] as $mentioned) {
  637. $atts[$mentioned->getUri()] = $mentioned->getObjectType();
  638. }
  639. }
  640. if ($parent instanceof Notice) {
  641. $parentAuthor = $parent->getProfile();
  642. // afaik groups can't be authors
  643. $atts[$parentAuthor->getUri()] = ActivityObject::PERSON;
  644. }
  645. return $atts;
  646. }
  647. /**
  648. * Find @-mentions in the given text, using the given notice object as context.
  649. * References will be resolved with common_relative_profile() against the user
  650. * who posted the notice.
  651. *
  652. * Note the return data format is internal, to be used for building links and
  653. * such. Should not be used directly; rather, call common_linkify_mentions().
  654. *
  655. * @param string $text
  656. * @param Profile $sender the Profile that is sending the current text
  657. * @param Notice $parent the Notice this text is in reply to, if any
  658. *
  659. * @return array
  660. *
  661. * @access private
  662. */
  663. function common_find_mentions($text, Profile $sender, Notice $parent=null)
  664. {
  665. $mentions = [];
  666. if (Event::handle('StartFindMentions', [$sender, $text, &$mentions])) {
  667. // Get the context of the original notice, if any
  668. $origMentions = [];
  669. // Does it have a parent notice for context?
  670. if ($parent instanceof Notice) {
  671. foreach ($parent->getAttentionProfiles() as $repliedTo) {
  672. if (!$repliedTo->isPerson()) {
  673. continue;
  674. }
  675. $origMentions[$repliedTo->id] = $repliedTo;
  676. }
  677. }
  678. $matches = common_find_mentions_raw($text, '@');
  679. foreach ($matches as $match) {
  680. try {
  681. $nickname = Nickname::normalize($match[0]);
  682. } catch (NicknameException $e) {
  683. // Bogus match? Drop it.
  684. continue;
  685. }
  686. // primarily mention the profiles mentioned in the parent
  687. $mention_found_in_origMentions = false;
  688. foreach ($origMentions as $origMentionsId=>$origMention) {
  689. if ($origMention->getNickname() == $nickname) {
  690. $mention_found_in_origMentions = $origMention;
  691. // don't mention same twice! the parent might have mentioned
  692. // two users with same nickname on different instances
  693. unset($origMentions[$origMentionsId]);
  694. break;
  695. }
  696. }
  697. // Try to get a profile for this nickname.
  698. // Start with parents mentions, then go to parents sender context
  699. if ($mention_found_in_origMentions) {
  700. $mentioned = $mention_found_in_origMentions;
  701. } elseif ($parent instanceof Notice && $parent->getProfile()->getNickname() === $nickname) {
  702. $mentioned = $parent->getProfile();
  703. } else {
  704. // sets to null if no match
  705. $mentioned = common_relative_profile($sender, $nickname);
  706. }
  707. if ($mentioned instanceof Profile) {
  708. try {
  709. $url = $mentioned->getUri(); // prefer the URI as URL, if it is one.
  710. if (!common_valid_http_url($url)) {
  711. $url = $mentioned->getUrl();
  712. }
  713. } catch (InvalidUrlException $e) {
  714. $url = common_local_url('userbyid', ['id' => $mentioned->getID()]);
  715. }
  716. $mention = ['mentioned' => [$mentioned],
  717. 'type' => 'mention',
  718. 'text' => $match[0],
  719. 'position' => $match[1],
  720. 'length' => mb_strlen($match[0]),
  721. 'title' => $mentioned->getFullname(),
  722. 'url' => $url];
  723. $mentions[] = $mention;
  724. }
  725. }
  726. // @#tag => mention of all subscriptions tagged 'tag'
  727. preg_match_all(
  728. '/'.Nickname::BEFORE_MENTIONS.'@#([\pL\pN_\-\.]{1,64})/',
  729. $text,
  730. $hmatches,
  731. PREG_OFFSET_CAPTURE
  732. );
  733. foreach ($hmatches[1] as $hmatch) {
  734. $tag = common_canonical_tag($hmatch[0]);
  735. $plist = Profile_list::getByTaggerAndTag($sender->getID(), $tag);
  736. if (!$plist instanceof Profile_list || $plist->private) {
  737. continue;
  738. }
  739. $tagged = $sender->getTaggedSubscribers($tag);
  740. $url = common_local_url(
  741. 'showprofiletag',
  742. ['nickname' => $sender->getNickname(), 'tag' => $tag]
  743. );
  744. $mentions[] = ['mentioned' => $tagged,
  745. 'type' => 'list',
  746. 'text' => $hmatch[0],
  747. 'position' => $hmatch[1],
  748. 'length' => mb_strlen($hmatch[0]),
  749. 'url' => $url];
  750. }
  751. $hmatches = common_find_mentions_raw($text, '!');
  752. foreach ($hmatches as $hmatch) {
  753. $nickname = Nickname::normalize($hmatch[0]);
  754. $group = User_group::getForNickname($nickname, $sender);
  755. if (!$group instanceof User_group || !$sender->isMember($group)) {
  756. continue;
  757. }
  758. $profile = $group->getProfile();
  759. $mentions[] = ['mentioned' => [$profile],
  760. 'type' => 'group',
  761. 'text' => $hmatch[0],
  762. 'position' => $hmatch[1],
  763. 'length' => mb_strlen($hmatch[0]),
  764. 'url' => $group->permalink(),
  765. 'title' => $group->getFancyName()];
  766. }
  767. Event::handle('EndFindMentions', [$sender, $text, &$mentions]);
  768. }
  769. return $mentions;
  770. }
  771. /**
  772. * Does the actual regex pulls to find @-mentions in text.
  773. * Should generally not be called directly; for use in common_find_mentions.
  774. *
  775. * @param string $text
  776. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  777. * @return array of PCRE match arrays
  778. */
  779. function common_find_mentions_raw($text, $preMention='@')
  780. {
  781. $tmatches = [];
  782. preg_match_all(
  783. '/^T (' . Nickname::DISPLAY_FMT . ') /',
  784. $text,
  785. $tmatches,
  786. PREG_OFFSET_CAPTURE
  787. );
  788. $atmatches = [];
  789. // the regexp's "(?!\@)" makes sure it doesn't matches the single "@remote" in "@remote@server.com"
  790. preg_match_all(
  791. '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . Nickname::DISPLAY_FMT . ')\b(?!\@)/',
  792. $text,
  793. $atmatches,
  794. PREG_OFFSET_CAPTURE
  795. );
  796. $matches = array_merge($tmatches[1], $atmatches[1]);
  797. return $matches;
  798. }
  799. function common_render_text($text)
  800. {
  801. $text = common_remove_unicode_formatting($text);
  802. $text = nl2br(htmlspecialchars($text));
  803. $text = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $text);
  804. $text = common_replace_urls_callback($text, 'common_linkify');
  805. $text = preg_replace_callback(
  806. '/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/u',
  807. function ($m) {
  808. return "{$m[1]}#".common_tag_link($m[2]);
  809. },
  810. $text
  811. );
  812. // XXX: machine tags
  813. return $text;
  814. }
  815. define('_URL_SCHEME_COLON_DOUBLE_SLASH', 1);
  816. define('_URL_SCHEME_SINGLE_COLON', 2);
  817. define('_URL_SCHEME_NO_DOMAIN', 4);
  818. define('_URL_SCHEME_COLON_COORDINATES', 8);
  819. function common_url_schemes($filter = null)
  820. {
  821. // TODO: move these to $config
  822. $schemes = ['http' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  823. 'https' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  824. 'ftp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  825. 'ftps' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  826. 'mms' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  827. 'rtsp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  828. 'gopher' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  829. 'news' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  830. 'nntp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  831. 'telnet' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  832. 'wais' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  833. 'file' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  834. 'prospero' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  835. 'webcal' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  836. 'irc' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  837. 'ircs' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  838. 'aim' => _URL_SCHEME_SINGLE_COLON,
  839. 'bitcoin' => _URL_SCHEME_SINGLE_COLON,
  840. 'fax' => _URL_SCHEME_SINGLE_COLON,
  841. 'jabber' => _URL_SCHEME_SINGLE_COLON,
  842. 'mailto' => _URL_SCHEME_SINGLE_COLON,
  843. 'tel' => _URL_SCHEME_SINGLE_COLON,
  844. 'xmpp' => _URL_SCHEME_SINGLE_COLON,
  845. 'magnet' => _URL_SCHEME_NO_DOMAIN,
  846. 'geo' => _URL_SCHEME_COLON_COORDINATES,];
  847. return array_keys(
  848. array_filter(
  849. $schemes,
  850. function ($scheme) use ($filter) {
  851. return is_null($filter) || ($scheme & $filter);
  852. }
  853. )
  854. );
  855. }
  856. /**
  857. * Find links in the given text and pass them to the given callback function.
  858. *
  859. * @param string $text
  860. * @param function($text, $arg) $callback: return replacement text
  861. * @param mixed $arg: optional argument will be passed on to the callback
  862. */
  863. function common_replace_urls_callback($text, $callback, $arg = null)
  864. {
  865. $geouri_labeltext_regex = '\pN\pL\-';
  866. $geouri_mark_regex = '\-\_\.\!\~\*\\\'\(\)'; // the \\\' is really pretty
  867. $geouri_unreserved_regex = '\pN\pL' . $geouri_mark_regex;
  868. $geouri_punreserved_regex = '\[\]\:\&\+\$';
  869. $geouri_pctencoded_regex = '(?:\%[0-9a-fA-F][0-9a-fA-F])';
  870. $geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
  871. // Start off with a regex
  872. $regex = '#'.
  873. '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
  874. '('.
  875. '(?:'.
  876. '(?:'. //Known protocols
  877. '(?:'.
  878. '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'.
  879. '|'.
  880. '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_SINGLE_COLON)) . '):)'.
  881. ')'.
  882. '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  883. '(?:'.
  884. '(?:'.
  885. '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
  886. ')|(?:'.
  887. '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
  888. ')'.
  889. ')'.
  890. ')'.
  891. '|(?:'.
  892. '(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_COORDINATES)) . '):'.
  893. // There's an order that must be followed here too, if ;crs= is used, it must precede ;u=
  894. // Also 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
  895. // Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+
  896. '(?:'.
  897. '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})'. // 1(.23)?(,4(.56)){1,2}
  898. '(?:\;(?:['.$geouri_labeltext_regex.']+)(?:\=['.$geouri_paramchar_regex.']+)*)*'.
  899. ')'.
  900. ')'.
  901. // URLs without domain name, like magnet:?xt=...
  902. '|(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_NO_DOMAIN)) . '):(?=\?))'. // zero-length lookahead requires ? after :
  903. (common_config('linkify', 'bare_ipv4') // Convert IPv4 addresses to hyperlinks
  904. ? '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
  905. : '').
  906. (common_config('linkify', 'bare_ipv6') // Convert IPv6 addresses to hyperlinks
  907. ? '|(?:'. //IPv6
  908. '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'.
  909. ')'
  910. : '').
  911. (common_config('linkify', 'bare_domains')
  912. ? '|(?:'. //DNS
  913. '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  914. '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
  915. //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
  916. '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZONE|ZW|local|loc|onion)'.
  917. ')(?![\pN\pL\-\_])'
  918. : '') . // if common_config('linkify', 'bare_domains') is false, don't add anything here
  919. ')'.
  920. '(?:'.
  921. '(?:\:\d+)?'. //:port
  922. '(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?'. // path
  923. '(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?'. // ?query string
  924. '(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?'. // #fragment
  925. ')(?<!['. URL_REGEX_EXCLUDED_END_CHARS .'])'.
  926. ')'.
  927. '#ixu';
  928. //preg_match_all($regex,$text,$matches);
  929. //print_r($matches);
  930. return preg_replace_callback($regex, callableLeftCurry('callback_helper', $callback, $arg), $text);
  931. }
  932. /**
  933. * Intermediate callback for common_replace_links(), helps resolve some
  934. * ambiguous link forms before passing on to the final callback.
  935. *
  936. * @param array $matches
  937. * @param callable $callback
  938. * @param mixed $arg optional argument to pass on as second param to callback
  939. * @return string
  940. *
  941. * @access private
  942. */
  943. function callback_helper($matches, $callback, $arg = null)
  944. {
  945. $url = $matches[1];
  946. $left = strpos($matches[0], $url);
  947. $right = $left + strlen($url);
  948. $groupSymbolSets=[
  949. [
  950. 'left'=>'(',
  951. 'right'=>')'
  952. ],
  953. [
  954. 'left'=>'[',
  955. 'right'=>']'
  956. ],
  957. [
  958. 'left'=>'{',
  959. 'right'=>'}'
  960. ],
  961. [
  962. 'left'=>'<',
  963. 'right'=>'>'
  964. ]
  965. ];
  966. $cannotEndWith = ['.','?',',','#'];
  967. do {
  968. $original_url = $url;
  969. foreach ($groupSymbolSets as $groupSymbolSet) {
  970. if (substr($url, -1) == $groupSymbolSet['right']) {
  971. $group_left_count = substr_count($url, $groupSymbolSet['left']);
  972. $group_right_count = substr_count($url, $groupSymbolSet['right']);
  973. if ($group_left_count < $group_right_count) {
  974. $right -= 1;
  975. $url = substr($url, 0, -1);
  976. }
  977. }
  978. }
  979. if (in_array(substr($url, -1), $cannotEndWith)) {
  980. $right -= 1;
  981. $url=substr($url, 0, -1);
  982. }
  983. } while ($original_url != $url);
  984. $result = call_user_func_array($callback, [$url, $arg]);
  985. return substr($matches[0], 0, $left) . $result . substr($matches[0], $right);
  986. }
  987. require_once INSTALLDIR . '/lib/util/callableleftcurry.php';
  988. function common_linkify($url)
  989. {
  990. // It comes in special'd, so we unspecial it before passing to the stringifying
  991. // functions
  992. $url = htmlspecialchars_decode($url);
  993. if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
  994. //url is an email address without the mailto: protocol
  995. $canon = "mailto:$url";
  996. $longurl = "mailto:$url";
  997. } else {
  998. $canon = File_redirection::_canonUrl($url);
  999. $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
  1000. if (isset($longurl_data->redir_url)) {
  1001. $longurl = $longurl_data->redir_url;
  1002. } else {
  1003. // e.g. local files
  1004. $longurl = $longurl_data->url;
  1005. }
  1006. }
  1007. $attrs = ['href' => $longurl, 'title' => $longurl];
  1008. $is_attachment = false;
  1009. $attachment_id = null;
  1010. $has_thumb = false;
  1011. // Check to see whether this is a known "attachment" URL.
  1012. try {
  1013. $f = File::getByUrl($longurl);
  1014. } catch (NoResultException $e) {
  1015. if (common_config('attachments', 'process_links')) {
  1016. // XXX: this writes to the database. :<
  1017. try {
  1018. $f = File::processNew($longurl);
  1019. } catch (ServerException $e) {
  1020. $f = null;
  1021. }
  1022. }
  1023. }
  1024. if ($f instanceof File) {
  1025. try {
  1026. $enclosure = $f->getEnclosure();
  1027. $is_attachment = true;
  1028. $attachment_id = $f->id;
  1029. $thumb = File_thumbnail::getKV('file_id', $f->id);
  1030. $has_thumb = ($thumb instanceof File_thumbnail);
  1031. } catch (ServerException $e) {
  1032. // There was not enough metadata available
  1033. }
  1034. }
  1035. // Whether to nofollow
  1036. $nf = common_config('nofollow', 'external');
  1037. if ($nf == 'never') {
  1038. $attrs['rel'] = 'external';
  1039. } else {
  1040. $attrs['rel'] = 'nofollow external';
  1041. }
  1042. // Add clippy
  1043. if ($is_attachment) {
  1044. $attrs['class'] = 'attachment';
  1045. if ($has_thumb) {
  1046. $attrs['class'] = 'attachment thumbnail';
  1047. }
  1048. $attrs['id'] = "attachment-{$attachment_id}";
  1049. $attrs['rel'] .= ' noreferrer';
  1050. }
  1051. return XMLStringer::estring('a', $attrs, $url);
  1052. }
  1053. /**
  1054. * Find and shorten links in a given chunk of text if it's longer than the
  1055. * configured notice content limit (or unconditionally).
  1056. *
  1057. * Side effects: may save file and file_redirection records for referenced URLs.
  1058. *
  1059. * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
  1060. * user's options are used; otherwise the current web session user's setitngs
  1061. * will be used or ur1.ca if there is no active web login.
  1062. *
  1063. * @param string $text
  1064. * @param boolean $always (optional)
  1065. * @param User $user (optional)
  1066. *
  1067. * @return string
  1068. */
  1069. function common_shorten_links($text, $always = false, User $user=null)
  1070. {
  1071. if ($user === null) {
  1072. $user = common_current_user();
  1073. }
  1074. $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
  1075. if ($always || ($maxLength != -1 && mb_strlen($text) > $maxLength)) {
  1076. return common_replace_urls_callback($text, ['File_redirection', 'forceShort'], $user);
  1077. } else {
  1078. return common_replace_urls_callback($text, ['File_redirection', 'makeShort'], $user);
  1079. }
  1080. }
  1081. /**
  1082. * Make sure an arbitrary string is safe for output in XML as a single line.
  1083. *
  1084. * @param string $str
  1085. * @return string
  1086. */
  1087. function common_xml_safe_str($str)
  1088. {
  1089. // Replace common eol and extra whitespace input chars
  1090. $unWelcome = ["\t", // tab
  1091. "\n", // newline
  1092. "\r", // cr
  1093. "\0", // null byte eos
  1094. "\x0B"]; // vertical tab
  1095. $replacement = [' ', // single space
  1096. ' ',
  1097. '', // nothing
  1098. '',
  1099. ' '];
  1100. $str = str_replace($unWelcome, $replacement, $str);
  1101. // Neutralize any additional control codes and UTF-16 surrogates
  1102. // (Twitter uses '*')
  1103. return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
  1104. }
  1105. function common_slugify($str)
  1106. {
  1107. // php5-intl is highly recommended...
  1108. if (!function_exists('transliterator_transliterate')) {
  1109. $str = preg_replace('/[^\pL\pN]/u', '', $str);
  1110. $str = mb_convert_case($str, MB_CASE_LOWER, 'UTF-8');
  1111. $str = substr($str, 0, 64);
  1112. return $str;
  1113. }
  1114. $str = transliterator_transliterate('Any-Latin;' . // any charset to latin compatible
  1115. 'NFD;' . // decompose
  1116. '[:Nonspacing Mark:] Remove;' . // remove nonspacing marks (accents etc.)
  1117. 'NFC;' . // composite again
  1118. '[:Punctuation:] Remove;' . // remove punctuation (.,¿? etc.)
  1119. 'Lower();' . // turn into lowercase
  1120. 'Latin-ASCII;', // get ASCII equivalents (ð to d for example)
  1121. $str);
  1122. return preg_replace('/[^\pL\pN]/', '', $str);
  1123. }
  1124. function common_tag_link($tag)
  1125. {
  1126. $canonical = common_canonical_tag($tag);
  1127. if (common_config('singleuser', 'enabled')) {
  1128. // regular TagAction isn't set up in 1user mode
  1129. $nickname = User::singleUserNickname();
  1130. $url = common_local_url('showstream', ['nickname' => $nickname, 'tag' => $canonical]);
  1131. } else {
  1132. $url = common_local_url('tag', ['tag' => $canonical]);
  1133. }
  1134. $xs = new XMLStringer();
  1135. $xs->elementStart('span', 'tag');
  1136. $xs->element('a', ['href' => $url, 'rel' => 'tag'], $tag);
  1137. $xs->elementEnd('span');
  1138. return $xs->getString();
  1139. }
  1140. function common_canonical_tag($tag)
  1141. {
  1142. $tag = common_slugify($tag);
  1143. $tag = substr($tag, 0, 64);
  1144. return $tag;
  1145. }
  1146. function common_valid_profile_tag($str)
  1147. {
  1148. return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
  1149. }
  1150. /**
  1151. * Resolve an ambiguous profile nickname reference, checking in following order:
  1152. * - profiles that $sender subscribes to
  1153. * - profiles that subscribe to $sender
  1154. * - local user profiles
  1155. *
  1156. * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
  1157. * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
  1158. * ESCAPE SQL.
  1159. *
  1160. * @fixme validate input
  1161. * @fixme escape SQL
  1162. * @fixme fix or remove mystery third parameter
  1163. * @fixme is $sender a User or Profile?
  1164. *
  1165. * @param <type> $sender the user or profile in whose context we're looking
  1166. * @param string $nickname validated nickname of
  1167. * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
  1168. *
  1169. * @return Profile or null
  1170. */
  1171. function common_relative_profile($sender, $nickname, $dt=null)
  1172. {
  1173. // Will throw exception on invalid input.
  1174. $nickname = Nickname::normalize($nickname);
  1175. // Try to find profiles this profile is subscribed to that have this nickname
  1176. $recipient = new Profile();
  1177. $recipient->whereAdd(
  1178. sprintf('id IN (SELECT subscribed FROM subscription WHERE subscriber = %d)', $sender->id),
  1179. 'AND'
  1180. );
  1181. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1182. if ($recipient->find(true)) {
  1183. // XXX: should probably differentiate between profiles with
  1184. // the same name by date of most recent update
  1185. return $recipient;
  1186. }
  1187. // Try to find profiles that listen to this profile and that have this nickname
  1188. $recipient = new Profile();
  1189. $recipient->whereAdd(
  1190. sprintf('id IN (SELECT subscriber FROM subscription WHERE subscribed = %d)', $sender->id),
  1191. 'AND'
  1192. );
  1193. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1194. if ($recipient->find(true)) {
  1195. // XXX: should probably differentiate between profiles with
  1196. // the same name by date of most recent update
  1197. return $recipient;
  1198. }
  1199. // If this is a local user, try to find a local user with that nickname.
  1200. $sender = User::getKV('id', $sender->id);
  1201. if ($sender instanceof User) {
  1202. $recipient_user = User::getKV('nickname', $nickname);
  1203. if ($recipient_user instanceof User) {
  1204. return $recipient_user->getProfile();
  1205. }
  1206. }
  1207. // Otherwise, no links. @messages from local users to remote users,
  1208. // or from remote users to other remote users, are just
  1209. // outside our ability to make intelligent guesses about
  1210. return null;
  1211. }
  1212. function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true, $defancy = false)
  1213. {
  1214. if (Event::handle('StartLocalURL', [&$action, &$params, &$fragment, &$addSession, &$url])) {
  1215. $r = Router::get();
  1216. $path = $r->build($action, $args, $params, $fragment);
  1217. $ssl = GNUsocial::useHTTPS();
  1218. if (common_config('site', 'fancy') && !$defancy) {
  1219. $url = common_path($path, $ssl, $addSession);
  1220. } else {
  1221. if (mb_strpos($path, '/index.php') === 0) {
  1222. $url = common_path($path, $ssl, $addSession);
  1223. } else {
  1224. $url = common_path('index.php/'.$path, $ssl, $addSession);
  1225. }
  1226. }
  1227. Event::handle('EndLocalURL', [&$action, &$params, &$fragment, &$addSession, &$url]);
  1228. }
  1229. return $url;
  1230. }
  1231. function common_path($relative, $ssl=false, $addSession=true)
  1232. {
  1233. $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
  1234. if ($ssl && GNUsocial::useHTTPS()) {
  1235. $proto = 'https';
  1236. if (is_string(common_config('site', 'sslserver')) &&
  1237. mb_strlen(common_config('site', 'sslserver')) > 0) {
  1238. $serverpart = common_config('site', 'sslserver');
  1239. } elseif (common_config('site', 'server')) {
  1240. $serverpart = common_config('site', 'server');
  1241. } else {
  1242. throw new ServerException('Site server not configured, unable to determine site name.');
  1243. }
  1244. } else {
  1245. $proto = 'http';
  1246. if (common_config('site', 'server')) {
  1247. $serverpart = common_config('site', 'server');
  1248. } else {
  1249. throw new ServerException('Site server not configured, unable to determine site name.');
  1250. }
  1251. }
  1252. if ($addSession) {
  1253. $relative = common_inject_session($relative, $serverpart);
  1254. }
  1255. return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
  1256. }
  1257. // FIXME: Maybe this should also be able to handle non-fancy URLs with index.php?p=...
  1258. function common_fake_local_fancy_url($url)
  1259. {
  1260. /**
  1261. * This is a hacky fix to make URIs generated with "index.php/" match against
  1262. * locally stored URIs without that. So for example if the remote site is looking
  1263. * up the webfinger for some user and for some reason knows about https://some.example/user/1
  1264. * but we locally store and report only https://some.example/index.php/user/1 then they would
  1265. * dismiss the profile for not having an identified alias.
  1266. *
  1267. * There are various live instances where these issues occur, for various reasons.
  1268. * Most of them being users fiddling with configuration while already having
  1269. * started federating (distributing the URI to other servers) or maybe manually
  1270. * editing the local database.
  1271. */
  1272. if (!preg_match(
  1273. // [1] protocol part, we can only rewrite http/https anyway.
  1274. '/^(https?:\/\/)' .
  1275. // [2] site name.
  1276. // FIXME: Dunno how this acts if we're aliasing ourselves with a .onion domain etc.
  1277. '('.preg_quote(common_config('site', 'server'), '/').')' .
  1278. // [3] site path, or if that is empty just '/' (to retain the /)
  1279. '('.preg_quote(common_config('site', 'path') ?: '/', '/').')' .
  1280. // [4] + [5] extract index.php (+ possible leading double /) and the rest of the URL separately.
  1281. '(\/?index\.php\/)(.*)$/',
  1282. $url,
  1283. $matches
  1284. )) {
  1285. // if preg_match failed to match
  1286. throw new Exception('No known change could be made to the URL.');
  1287. }
  1288. // now reconstruct the URL with everything except the "index.php/" part
  1289. $fancy_url = '';
  1290. foreach ([1,2,3,5] as $idx) {
  1291. $fancy_url .= $matches[$idx];
  1292. }
  1293. return $fancy_url;
  1294. }
  1295. // FIXME: Maybe this should also be able to handle non-fancy URLs with index.php?p=...
  1296. function common_fake_local_nonfancy_url($url)
  1297. {
  1298. /**
  1299. * This is a hacky fix to make URIs NOT generated with "index.php/" match against
  1300. * locally stored URIs WITH that. The reverse from the above.
  1301. *
  1302. * It will also "repair" index.php URLs with multiple / prepended. Like https://some.example///index.php/user/1
  1303. */
  1304. if (!preg_match(
  1305. // [1] protocol part, we can only rewrite http/https anyway.
  1306. '/^(https?:\/\/)' .
  1307. // [2] site name.
  1308. // FIXME: Dunno how this acts if we're aliasing ourselves with a .onion domain etc.
  1309. '('.preg_quote(common_config('site', 'server'), '/').')' .
  1310. // [3] site path, or if that is empty just '/' (to retain the /)
  1311. '('.preg_quote(common_config('site', 'path') ?: '/', '/').')' .
  1312. // [4] should be empty (might contain one or more / and then maybe also index.php). Will be overwritten.
  1313. // [5] will have the extracted actual URL part (besides site path)
  1314. '((?!index.php\/)\/*(?:index.php\/)?)(.*)$/',
  1315. $url,
  1316. $matches
  1317. )) {
  1318. // if preg_match failed to match
  1319. throw new Exception('No known change could be made to the URL.');
  1320. }
  1321. $matches[4] = 'index.php/'; // inject the index.php/ rewritethingy
  1322. // remove the first element, which is the full matching string
  1323. array_shift($matches);
  1324. return implode('', $matches);
  1325. }
  1326. function common_inject_session($url, $serverpart = null)
  1327. {
  1328. if (!common_have_session()) {
  1329. return $url;
  1330. }
  1331. if (empty($serverpart)) {
  1332. $serverpart = parse_url($url, PHP_URL_HOST);
  1333. }
  1334. $currentServer = (array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['HTTP_HOST'] : null;
  1335. // Are we pointing to another server (like an SSL server?)
  1336. if (!empty($currentServer) && 0 != strcasecmp($currentServer, $serverpart)) {
  1337. // Pass the session ID as a GET parameter
  1338. $sesspart = session_name() . '=' . session_id();
  1339. $i = strpos($url, '?');
  1340. if ($i === false) { // no GET params, just append
  1341. $url .= '?' . $sesspart;
  1342. } else {
  1343. $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
  1344. }
  1345. }
  1346. return $url;
  1347. }
  1348. function common_date_string($dt)
  1349. {
  1350. // XXX: do some sexy date formatting
  1351. // return date(DATE_RFC822, $dt);
  1352. $t = strtotime($dt);
  1353. $now = time();
  1354. $diff = $now - $t;
  1355. if ($now < $t) { // that shouldn't happen!
  1356. return common_exact_date($dt);
  1357. } elseif ($diff < 60) {
  1358. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1359. return _('a few seconds ago');
  1360. } elseif ($diff < 92) {
  1361. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1362. return _('about a minute ago');
  1363. } elseif ($diff < 3300) {
  1364. $minutes = round($diff/60);
  1365. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1366. return sprintf(_m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
  1367. } elseif ($diff < 5400) {
  1368. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1369. return _('about an hour ago');
  1370. } elseif ($diff < 22 * 3600) {
  1371. $hours = round($diff/3600);
  1372. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1373. return sprintf(_m('about one hour ago', 'about %d hours ago', $hours), $hours);
  1374. } elseif ($diff < 37 * 3600) {
  1375. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1376. return _('about a day ago');
  1377. } elseif ($diff < 24 * 24 * 3600) {
  1378. $days = round($diff/(24*3600));
  1379. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1380. return sprintf(_m('about one day ago', 'about %d days ago', $days), $days);
  1381. } elseif ($diff < 46 * 24 * 3600) {
  1382. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1383. return _('about a month ago');
  1384. } elseif ($diff < 330 * 24 * 3600) {
  1385. $months = round($diff/(30*24*3600));
  1386. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1387. return sprintf(_m('about one month ago', 'about %d months ago', $months), $months);
  1388. } elseif ($diff < 480 * 24 * 3600) {
  1389. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1390. return _('about a year ago');
  1391. } else {
  1392. return common_exact_date($dt);
  1393. }
  1394. }
  1395. function common_exact_date($dt)
  1396. {
  1397. static $_utc;
  1398. static $_siteTz;
  1399. if (!$_utc) {
  1400. $_utc = new DateTimeZone('UTC');
  1401. $_siteTz = new DateTimeZone(common_timezone());
  1402. }
  1403. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1404. $d = new DateTime($dateStr, $_utc);
  1405. $d->setTimezone($_siteTz);
  1406. // TRANS: Human-readable full date-time specification (formatting on http://php.net/date)
  1407. return $d->format(_('l, d-M-Y H:i:s T'));
  1408. }
  1409. function common_date_w3dtf($dt)
  1410. {
  1411. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1412. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1413. $d->setTimezone(new DateTimeZone(common_timezone()));
  1414. return $d->format(DATE_W3C);
  1415. }
  1416. function common_date_rfc2822($dt)
  1417. {
  1418. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1419. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1420. $d->setTimezone(new DateTimeZone(common_timezone()));
  1421. return $d->format('r');
  1422. }
  1423. function common_date_iso8601($dt)
  1424. {
  1425. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1426. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1427. $d->setTimezone(new DateTimeZone(common_timezone()));
  1428. return $d->format('c');
  1429. }
  1430. function common_sql_now()
  1431. {
  1432. return common_sql_date(time());
  1433. }
  1434. function common_sql_date($datetime)
  1435. {
  1436. $date = new DateTime();
  1437. $date->setTimestamp((int)$datetime);
  1438. return $date->format("Y-m-d H:i:s");
  1439. }
  1440. /**
  1441. * Return an SQL fragment to calculate an age-based weight from a given
  1442. * timestamp or datetime column.
  1443. *
  1444. * @param string $column name of field we're comparing against current time
  1445. * @param integer $dropoff divisor for age in seconds before exponentiation
  1446. * @return string SQL fragment
  1447. */
  1448. function common_sql_weight($column, $dropoff)
  1449. {
  1450. if (common_config('db', 'type') !== 'mysql') {
  1451. $expr = sprintf(
  1452. '(((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + '
  1453. . 'EXTRACT(MINUTE %1$s)) * 60 + EXTRACT(SECOND %1$s))',
  1454. "FROM ({$column} - CURRENT_TIMESTAMP)"
  1455. );
  1456. } else {
  1457. $expr = "timestampdiff(SECOND, CURRENT_TIMESTAMP, {$column})";
  1458. }
  1459. return "SUM(EXP({$expr} / {$dropoff}))";
  1460. }
  1461. function common_redirect(string $url, int $code = 307): void
  1462. {
  1463. if (!in_array($code, [301, 302, 303, 307])) {
  1464. doom($code."は転送コードではありません。", __FILE__, __LINE__);
  1465. }
  1466. http_response_code($code);
  1467. header("Location: {$url}");
  1468. header("Connection: close");
  1469. $xo = new XMLOutputter();
  1470. $xo->startXML(
  1471. 'a',
  1472. '-//W3C//DTD XHTML 1.0 Strict//EN',
  1473. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
  1474. );
  1475. $xo->element('a', ['href' => $url], $url);
  1476. $xo->endXML();
  1477. die();
  1478. }
  1479. // Stick the notice on the queue
  1480. function common_enqueue_notice($notice)
  1481. {
  1482. static $localTransports = ['ping'];
  1483. $transports = [];
  1484. if (common_config('sms', 'enabled')) {
  1485. $transports[] = 'sms';
  1486. }
  1487. if (Event::hasHandler('HandleQueuedNotice')) {
  1488. $transports[] = 'Module';
  1489. }
  1490. // We can skip these for gatewayed notices.
  1491. if ($notice->isLocal()) {
  1492. $transports = array_merge($transports, $localTransports);
  1493. }
  1494. if (Event::handle('StartEnqueueNotice', [$notice, &$transports])) {
  1495. $qm = QueueManager::get();
  1496. foreach ($transports as $transport) {
  1497. $qm->enqueue($notice, $transport);
  1498. }
  1499. Event::handle('EndEnqueueNotice', [$notice, $transports]);
  1500. }
  1501. return true;
  1502. }
  1503. function common_profile_url($nickname)
  1504. {
  1505. return common_local_url(
  1506. 'showstream',
  1507. ['nickname' => $nickname],
  1508. null,
  1509. null,
  1510. false
  1511. );
  1512. }
  1513. /**
  1514. * Should make up a reasonable root URL
  1515. *
  1516. * @param bool $tls true or false to force TLS scheme, null to use server configuration
  1517. */
  1518. function common_root_url($tls=null)
  1519. {
  1520. if (is_null($tls)) {
  1521. $tls = GNUsocial::useHTTPS();
  1522. }
  1523. $url = common_path('', $tls, false);
  1524. $i = strpos($url, '?');
  1525. if ($i !== false) {
  1526. $url = substr($url, 0, $i);
  1527. }
  1528. return $url;
  1529. }
  1530. /**
  1531. * returns $bytes bytes of raw random data
  1532. */
  1533. function common_random_rawstr($bytes)
  1534. {
  1535. $rawstr = @file_exists('/dev/urandom')
  1536. ? common_urandom($bytes)
  1537. : common_mtrand($bytes);
  1538. return $rawstr;
  1539. }
  1540. /**
  1541. * returns $bytes bytes of random data as a hexadecimal string
  1542. */
  1543. function common_random_hexstr($bytes)
  1544. {
  1545. return bin2hex(random_bytes($bytes));
  1546. }
  1547. function common_urandom($bytes)
  1548. {
  1549. $h = fopen('/dev/urandom', 'rb');
  1550. // should not block
  1551. $src = fread($h, $bytes);
  1552. fclose($h);
  1553. return $src;
  1554. }
  1555. function common_mtrand($bytes)
  1556. {
  1557. $str = '';
  1558. for ($i = 0; $i < $bytes; $i++) {
  1559. $str .= chr(mt_rand(0, 255));
  1560. }
  1561. return $str;
  1562. }
  1563. /**
  1564. * Record the given URL as the return destination for a future
  1565. * form submission, to be read by common_get_returnto().
  1566. *
  1567. * @param string $url
  1568. *
  1569. * @fixme as a session-global setting, this can allow multiple forms
  1570. * to conflict and overwrite each others' returnto destinations if
  1571. * the user has multiple tabs or windows open.
  1572. *
  1573. * Should refactor to index with a token or otherwise only pass the
  1574. * data along its intended path.
  1575. */
  1576. function common_set_returnto($url)
  1577. {
  1578. common_ensure_session();
  1579. $_SESSION['returnto'] = $url;
  1580. }
  1581. /**
  1582. * Fetch a return-destination URL previously recorded by
  1583. * common_set_returnto().
  1584. *
  1585. * @return mixed URL string or null
  1586. *
  1587. * @fixme as a session-global setting, this can allow multiple forms
  1588. * to conflict and overwrite each others' returnto destinations if
  1589. * the user has multiple tabs or windows open.
  1590. *
  1591. * Should refactor to index with a token or otherwise only pass the
  1592. * data along its intended path.
  1593. */
  1594. function common_get_returnto()
  1595. {
  1596. common_ensure_session();
  1597. return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
  1598. }
  1599. function common_timestamp()
  1600. {
  1601. return date('YmdHis');
  1602. }
  1603. function common_ensure_syslog()
  1604. {
  1605. static $initialized = false;
  1606. if (!$initialized) {
  1607. openlog(
  1608. common_config('syslog', 'appname'),
  1609. 0,
  1610. common_config('syslog', 'facility')
  1611. );
  1612. $initialized = true;
  1613. }
  1614. }
  1615. function common_log_line($priority, $msg)
  1616. {
  1617. static $syslog_priorities = ['LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
  1618. 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'];
  1619. return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
  1620. }
  1621. function common_request_id()
  1622. {
  1623. $pid = getmypid();
  1624. $server = common_config('site', 'server');
  1625. if (php_sapi_name() == 'cli') {
  1626. $script = basename($_SERVER['PHP_SELF']);
  1627. return "$server:$script:$pid";
  1628. } else {
  1629. static $req_id = null;
  1630. if (!isset($req_id)) {
  1631. $req_id = substr(md5(mt_rand()), 0, 8);
  1632. }
  1633. if (isset($_SERVER['REQUEST_URI'])) {
  1634. $url = $_SERVER['REQUEST_URI'];
  1635. }
  1636. $method = $_SERVER['REQUEST_METHOD'];
  1637. return "$server:$pid.$req_id $method $url";
  1638. }
  1639. }
  1640. function common_log($priority, $msg, $filename=null)
  1641. {
  1642. // Don't write LOG_DEBUG if that's not wanted
  1643. if ($priority === LOG_DEBUG && !common_config('site', 'logdebug')) {
  1644. return;
  1645. }
  1646. if (Event::handle('StartLog', [&$priority, &$msg, &$filename])) {
  1647. $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
  1648. $msg = '[' . common_request_id() . '] ' . $msg;
  1649. $logfile = common_config('site', 'logfile');
  1650. if ($logfile) {
  1651. $log = fopen($logfile, "a");
  1652. if ($log) {
  1653. $output = common_log_line($priority, $msg);
  1654. fwrite($log, $output);
  1655. fclose($log);
  1656. }
  1657. } else {
  1658. common_ensure_syslog();
  1659. syslog($priority, $msg);
  1660. }
  1661. Event::handle('EndLog', [$priority, $msg, $filename]);
  1662. }
  1663. }
  1664. function common_debug($msg, $filename=null)
  1665. {
  1666. if ($filename) {
  1667. common_log(LOG_DEBUG, basename($filename).' - '.$msg);
  1668. } else {
  1669. common_log(LOG_DEBUG, $msg);
  1670. }
  1671. }
  1672. function common_log_db_error(&$object, $verb, $filename=null)
  1673. {
  1674. global $_PEAR;
  1675. $objstr = common_log_objstring($object);
  1676. $last_error = &$_PEAR->getStaticProperty('DB_DataObject', 'lastError');
  1677. if (is_object($last_error)) {
  1678. $msg = $last_error->message;
  1679. } else {
  1680. $msg = 'Unknown error (' . var_export($last_error, true) . ')';
  1681. }
  1682. common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
  1683. }
  1684. function common_log_objstring(&$object)
  1685. {
  1686. if (is_null($object)) {
  1687. return "null";
  1688. }
  1689. if (!($object instanceof DB_DataObject)) {
  1690. return "(unknown)";
  1691. }
  1692. $arr = $object->toArray();
  1693. $fields = [];
  1694. foreach ($arr as $k => $v) {
  1695. if (is_object($v)) {
  1696. $fields[] = "$k='".get_class($v)."'";
  1697. } else {
  1698. $fields[] = "$k='$v'";
  1699. }
  1700. }
  1701. $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
  1702. return $objstring;
  1703. }
  1704. function common_valid_http_url($url, $secure=false)
  1705. {
  1706. if (empty($url)) {
  1707. return false;
  1708. }
  1709. // If $secure is true, only allow https URLs to pass
  1710. // (if false, we use '?' in 'https?' to say the 's' is optional)
  1711. $regex = $secure ? '/^https$/' : '/^https?$/';
  1712. return filter_var($url, FILTER_VALIDATE_URL)
  1713. && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
  1714. }
  1715. function common_valid_tag($tag)
  1716. {
  1717. if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
  1718. return (Validate::email($matches[1]) ||
  1719. preg_match('/^([\w-\.]+)$/', $matches[1]));
  1720. }
  1721. return false;
  1722. }
  1723. /**
  1724. * Determine if given domain or address literal is valid
  1725. * eg for use in JIDs and URLs. Does not check if the domain
  1726. * exists!
  1727. *
  1728. * @param string $domain
  1729. * @return boolean valid or not
  1730. */
  1731. function common_valid_domain($domain)
  1732. {
  1733. $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
  1734. $ipv4 = "(?:$octet(?:\.$octet){3})";
  1735. if (preg_match("/^$ipv4$/u", $domain)) {
  1736. return true;
  1737. }
  1738. $group = "(?:[0-9a-f]{1,4})";
  1739. $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
  1740. if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
  1741. $before = explode(":", $matches[1]);
  1742. $zeroes = $matches[2];
  1743. $after = explode(":", $matches[3]);
  1744. if ($zeroes) {
  1745. $min = 0;
  1746. $max = 7;
  1747. } else {
  1748. $min = 1;
  1749. $max = 8;
  1750. }
  1751. $explicit = count($before) + count($after);
  1752. if ($explicit < $min || $explicit > $max) {
  1753. return false;
  1754. }
  1755. return true;
  1756. }
  1757. try {
  1758. require_once "Net/IDNA2.php";
  1759. $idn = Net_IDNA2::getInstance();
  1760. $domain = $idn->encode($domain);
  1761. } catch (Exception $e) {
  1762. return false;
  1763. }
  1764. $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
  1765. $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
  1766. return preg_match("/^$fqdn$/ui", $domain);
  1767. }
  1768. /* Following functions are copied from MediaWiki GlobalFunctions.php
  1769. * and written by Evan Prodromou. */
  1770. function common_accept_to_prefs($accept, $def = '*/*')
  1771. {
  1772. // No arg means accept anything (per HTTP spec)
  1773. if (!$accept) {
  1774. return [$def => 1];
  1775. }
  1776. $prefs = [];
  1777. $parts = explode(',', $accept);
  1778. foreach ($parts as $part) {
  1779. // FIXME: doesn't deal with params like 'text/html; level=1'
  1780. $p = explode(';', trim($part));
  1781. $value = 0;
  1782. if (count($p) >= 2) {
  1783. list($value, $qpart) = $p;
  1784. }
  1785. $match = [];
  1786. if (!isset($qpart)) {
  1787. $prefs[$value] = 1;
  1788. } elseif (preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
  1789. $prefs[$value] = $match[1];
  1790. }
  1791. }
  1792. return $prefs;
  1793. }
  1794. // Match by our supported file extensions
  1795. function common_supported_filename_to_mime($filename)
  1796. {
  1797. // Accept a filename and take out the extension
  1798. if (strpos($filename, '.') === false) {
  1799. throw new ServerException(sprintf('No extension on filename: %1$s', _ve($filename)));
  1800. }
  1801. $fileext = substr(strrchr($filename, '.'), 1);
  1802. return common_supported_ext_to_mime($fileext);
  1803. }
  1804. function common_supported_ext_to_mime($fileext)
  1805. {
  1806. $supported = common_config('attachments', 'supported');
  1807. if ($supported === true) {
  1808. // FIXME: Should we just accept the extension straight off when supported === true?
  1809. throw new UnknownExtensionMimeException($fileext);
  1810. }
  1811. foreach ($supported as $type => $ext) {
  1812. if ($ext === $fileext) {
  1813. return $type;
  1814. }
  1815. }
  1816. throw new ServerException('Unsupported file extension');
  1817. }
  1818. // Match by our supported mime types
  1819. function common_supported_mime_to_ext($mimetype)
  1820. {
  1821. $supported = common_config('attachments', 'supported');
  1822. if (is_array($supported)) {
  1823. foreach ($supported as $type => $ext) {
  1824. if ($mimetype === $type) {
  1825. return $ext;
  1826. }
  1827. }
  1828. }
  1829. throw new UnknownMimeExtensionException($mimetype);
  1830. }
  1831. // The MIME "media" is the part before the slash (video in video/webm)
  1832. function common_get_mime_media($type)
  1833. {
  1834. $tmp = explode('/', $type);
  1835. return strtolower($tmp[0]);
  1836. }
  1837. // Get only the mimetype and not additional info (separated from bare mime with semi-colon)
  1838. function common_bare_mime($mimetype)
  1839. {
  1840. $mimetype = mb_strtolower($mimetype ?? "");
  1841. if (($semicolon = mb_strpos($mimetype, ';')) !== false) {
  1842. $mimetype = mb_substr($mimetype, 0, $semicolon);
  1843. }
  1844. return trim($mimetype);
  1845. }
  1846. function common_mime_type_match($type, $avail)
  1847. {
  1848. if (array_key_exists($type, $avail)) {
  1849. return $type;
  1850. } else {
  1851. $parts = explode('/', $type);
  1852. if (array_key_exists($parts[0] . '/*', $avail)) {
  1853. return $parts[0] . '/*';
  1854. } elseif (array_key_exists('*/*', $avail)) {
  1855. return '*/*';
  1856. } else {
  1857. return null;
  1858. }
  1859. }
  1860. }
  1861. function common_negotiate_type($cprefs, $sprefs)
  1862. {
  1863. $combine = [];
  1864. foreach (array_keys($sprefs) as $type) {
  1865. $parts = explode('/', $type);
  1866. if (isset($parts[1]) && $parts[1] != '*') {
  1867. $ckey = common_mime_type_match($type, $cprefs);
  1868. if ($ckey) {
  1869. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1870. }
  1871. }
  1872. }
  1873. foreach (array_keys($cprefs) as $type) {
  1874. $parts = explode('/', $type);
  1875. if (isset($parts[1]) && $parts[1] != '*' && !array_key_exists($type, $sprefs)) {
  1876. $skey = common_mime_type_match($type, $sprefs);
  1877. if ($skey) {
  1878. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1879. }
  1880. }
  1881. }
  1882. $bestq = 0;
  1883. $besttype = 'text/html';
  1884. foreach (array_keys($combine) as $type) {
  1885. if ($combine[$type] > $bestq) {
  1886. $besttype = $type;
  1887. $bestq = $combine[$type];
  1888. }
  1889. }
  1890. if ('text/html' === $besttype) {
  1891. return "text/html; charset=utf-8";
  1892. }
  1893. return $besttype;
  1894. }
  1895. function common_config($main, $sub=null)
  1896. {
  1897. global $config;
  1898. if (is_null($config)) {
  1899. throw new ServerException('common_config was invoked before config.php was read');
  1900. }
  1901. if (is_null($sub)) {
  1902. // Return the config category array
  1903. return array_key_exists($main, $config) ? $config[$main] : [];
  1904. }
  1905. // Return the config value
  1906. return (array_key_exists($main, $config) &&
  1907. array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
  1908. }
  1909. function common_config_set($main, $sub, $value)
  1910. {
  1911. global $config;
  1912. if (!array_key_exists($main, $config)) {
  1913. $config[$main] = [];
  1914. }
  1915. $config[$main][$sub] = $value;
  1916. }
  1917. function common_config_append($main, $sub, $value)
  1918. {
  1919. global $config;
  1920. if (!array_key_exists($main, $config)) {
  1921. $config[$main] = [];
  1922. }
  1923. if (!array_key_exists($sub, $config[$main])) {
  1924. $config[$main][$sub] = [];
  1925. }
  1926. if (!is_array($config[$main][$sub])) {
  1927. $config[$main][$sub] = [$config[$main][$sub]];
  1928. }
  1929. array_push($config[$main][$sub], $value);
  1930. }
  1931. /**
  1932. * Pull arguments from a GET/POST/REQUEST array and replace invalid in UTF-8
  1933. * sequences with question marks.
  1934. *
  1935. * @param array $from
  1936. * @return array
  1937. */
  1938. function common_copy_args(array $from): array
  1939. {
  1940. return array_map(function ($v) {
  1941. return is_array($v) ? common_copy_args($v) : mb_scrub($v);
  1942. }, $from);
  1943. }
  1944. function common_user_uri(&$user)
  1945. {
  1946. return common_local_url(
  1947. 'userbyid',
  1948. ['id' => $user->id],
  1949. null,
  1950. null,
  1951. false,
  1952. true
  1953. );
  1954. }
  1955. /**
  1956. * Generates cryptographically secure pseudo-random strings out of a allowed chars string
  1957. *
  1958. * @param $bits int strength of the confirmation code
  1959. * @param $codechars allowed characters to be used in the confirmation code, by default we use 36 upper case
  1960. * alphanums and remove lookalikes (0, O, 1, I) = 32 chars = 5 bits to make it easy for the user to type in
  1961. * @return string confirmation_code of length $bits/5
  1962. */
  1963. function common_confirmation_code($bits, $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ')
  1964. {
  1965. $chars = ceil($bits/5);
  1966. $codechars_length = strlen($codechars)-1;
  1967. $code = '';
  1968. for ($i = 0; $i < $chars; ++$i) {
  1969. $random_char = $codechars[random_int(0, $codechars_length)];
  1970. $code .= $random_char;
  1971. }
  1972. return $code;
  1973. }
  1974. // convert markup to HTML
  1975. function common_markup_to_html($c, $args=null)
  1976. {
  1977. if ($c === null) {
  1978. return '';
  1979. }
  1980. if (is_null($args)) {
  1981. $args = [];
  1982. }
  1983. // XXX: not very efficient
  1984. foreach ($args as $name => $value) {
  1985. $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
  1986. }
  1987. $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) {
  1988. return common_user_property($m[1]);
  1989. }, $c);
  1990. $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) {
  1991. return common_local_url($m[1]);
  1992. }, $c);
  1993. $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) {
  1994. return common_local_url('doc', ['title'=>$m[1]]);
  1995. }, $c);
  1996. $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) {
  1997. return common_config($m[1], $m[2]);
  1998. }, $c);
  1999. return \Michelf\Markdown::defaultTransform($c);
  2000. }
  2001. function common_user_property($property)
  2002. {
  2003. $profile = Profile::current();
  2004. if (empty($profile)) {
  2005. return null;
  2006. }
  2007. switch ($property) {
  2008. case 'profileurl':
  2009. case 'nickname':
  2010. case 'fullname':
  2011. case 'location':
  2012. case 'bio':
  2013. return $profile->$property;
  2014. break;
  2015. case 'avatar':
  2016. try {
  2017. return $profile->getAvatar(AVATAR_STREAM_SIZE);
  2018. } catch (Exception $e) {
  2019. return null;
  2020. }
  2021. break;
  2022. case 'bestname':
  2023. return $profile->getBestName();
  2024. break;
  2025. default:
  2026. return null;
  2027. }
  2028. }
  2029. function common_profile_uri($profile)
  2030. {
  2031. $uri = null;
  2032. if (!empty($profile)) {
  2033. if (Event::handle('StartCommonProfileURI', [$profile, &$uri])) {
  2034. $user = User::getKV('id', $profile->id);
  2035. if ($user instanceof User) {
  2036. $uri = $user->getUri();
  2037. } // FIXME: might be a remote profile, by this function name, I would guess it would be fine to call this
  2038. // On the other hand, there's Profile->getUri
  2039. Event::handle('EndCommonProfileURI', [$profile, &$uri]);
  2040. }
  2041. }
  2042. // XXX: this is a very bad profile!
  2043. return $uri;
  2044. }
  2045. function common_canonical_sms($sms)
  2046. {
  2047. // strip non-digits
  2048. preg_replace('/\D/', '', $sms);
  2049. return $sms;
  2050. }
  2051. function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
  2052. {
  2053. switch ($errno) {
  2054. case E_ERROR:
  2055. case E_COMPILE_ERROR:
  2056. case E_CORE_ERROR:
  2057. case E_USER_ERROR:
  2058. case E_PARSE:
  2059. case E_RECOVERABLE_ERROR:
  2060. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
  2061. die();
  2062. break;
  2063. case E_WARNING:
  2064. case E_COMPILE_WARNING:
  2065. case E_CORE_WARNING:
  2066. case E_USER_WARNING:
  2067. common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
  2068. break;
  2069. case E_NOTICE:
  2070. case E_USER_NOTICE:
  2071. common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
  2072. break;
  2073. case E_STRICT:
  2074. case E_DEPRECATED:
  2075. case E_USER_DEPRECATED:
  2076. // XXX: config variable to log this stuff, too
  2077. break;
  2078. default:
  2079. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
  2080. die();
  2081. break;
  2082. }
  2083. // FIXME: show error page if we're on the Web
  2084. /* Don't execute PHP internal error handler */
  2085. return true;
  2086. }
  2087. function common_session_token()
  2088. {
  2089. common_ensure_session();
  2090. if (!array_key_exists('token', $_SESSION)) {
  2091. $_SESSION['token'] = common_random_hexstr(64);
  2092. }
  2093. return $_SESSION['token'];
  2094. }
  2095. function common_license_terms($uri)
  2096. {
  2097. if (preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
  2098. return explode('-', $matches[1]);
  2099. }
  2100. return [$uri];
  2101. }
  2102. function common_compatible_license($from, $to)
  2103. {
  2104. $from_terms = common_license_terms($from);
  2105. // public domain and cc-by are compatible with everything
  2106. if (count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
  2107. return true;
  2108. }
  2109. $to_terms = common_license_terms($to);
  2110. // sa is compatible across versions. IANAL
  2111. if (in_array('sa', $from_terms) || in_array('sa', $to_terms)) {
  2112. return count(array_diff($from_terms, $to_terms)) == 0;
  2113. }
  2114. // XXX: better compatibility check needed here!
  2115. // Should at least normalise URIs
  2116. return ($from == $to);
  2117. }
  2118. /**
  2119. * returns the character set name used for the current DBMS
  2120. */
  2121. function common_database_charset(): string
  2122. {
  2123. $schema = Schema::get();
  2124. return $schema->charset();
  2125. }
  2126. /**
  2127. * returns a quoted table name
  2128. */
  2129. function common_database_tablename($tablename)
  2130. {
  2131. $schema = Schema::get();
  2132. // table prefixes could be added here later
  2133. return $schema->quoteIdentifier($tablename);
  2134. }
  2135. /**
  2136. * Shorten a URL with the current user's configured shortening service,
  2137. * or ur1.ca if configured, or not at all if no shortening is set up.
  2138. *
  2139. * @param string $long_url original URL
  2140. * @param User $user to specify a particular user's options
  2141. * @param boolean $force Force shortening (used when notice is too long)
  2142. * @return string may return the original URL if shortening failed
  2143. *
  2144. * @fixme provide a way to specify a particular shortener
  2145. */
  2146. function common_shorten_url($long_url, User $user=null, $force = false)
  2147. {
  2148. $long_url = trim($long_url);
  2149. $user = common_current_user();
  2150. $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
  2151. // $force forces shortening even if it's not strictly needed
  2152. // I doubt URL shortening is ever 'strictly' needed. - ESP
  2153. if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
  2154. return $long_url;
  2155. }
  2156. $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
  2157. if (Event::handle(
  2158. 'StartShortenUrl',
  2159. [$long_url, $shortenerName, &$shortenedUrl]
  2160. )) {
  2161. if ($shortenerName == 'internal') {
  2162. try {
  2163. $f = File::processNew($long_url);
  2164. $shortenedUrl = common_local_url('redirecturl', ['id' => $f->id]);
  2165. if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
  2166. return $shortenedUrl;
  2167. } else {
  2168. return $long_url;
  2169. }
  2170. } catch (ServerException $e) {
  2171. return $long_url;
  2172. }
  2173. } else {
  2174. return $long_url;
  2175. }
  2176. } else {
  2177. //URL was shortened, so return the result
  2178. return trim($shortenedUrl);
  2179. }
  2180. }
  2181. /**
  2182. * @return mixed array($proxy, $ip) for web requests; proxy may be null
  2183. * null if not a web request
  2184. *
  2185. * @fixme X-Forwarded-For can be chained by multiple proxies;
  2186. we should parse the list and provide a cleaner array
  2187. * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
  2188. * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
  2189. * use function to get exact request headers from Apache if possible.
  2190. */
  2191. function common_client_ip()
  2192. {
  2193. if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
  2194. return null;
  2195. }
  2196. if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
  2197. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2198. $proxy = $_SERVER['HTTP_CLIENT_IP'];
  2199. } else {
  2200. $proxy = $_SERVER['REMOTE_ADDR'];
  2201. }
  2202. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  2203. } else {
  2204. $proxy = null;
  2205. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2206. $ip = $_SERVER['HTTP_CLIENT_IP'];
  2207. } else {
  2208. $ip = $_SERVER['REMOTE_ADDR'];
  2209. }
  2210. }
  2211. return [$proxy, $ip];
  2212. }
  2213. function common_url_to_nickname($url)
  2214. {
  2215. static $bad = ['query', 'user', 'password', 'port', 'fragment'];
  2216. $parts = parse_url($url);
  2217. // If any of these parts exist, this won't work
  2218. foreach ($bad as $badpart) {
  2219. if (array_key_exists($badpart, $parts)) {
  2220. return null;
  2221. }
  2222. }
  2223. // We just have host and/or path
  2224. // If it's just a host...
  2225. if (array_key_exists('host', $parts) &&
  2226. (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) {
  2227. $hostparts = explode('.', $parts['host']);
  2228. // Try to catch common idiom of nickname.service.tld
  2229. if ((count($hostparts) > 2) &&
  2230. (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
  2231. (strcmp($hostparts[0], 'www') != 0)) {
  2232. return common_nicknamize($hostparts[0]);
  2233. } else {
  2234. // Do the whole hostname
  2235. return common_nicknamize($parts['host']);
  2236. }
  2237. } else {
  2238. if (array_key_exists('path', $parts)) {
  2239. // Strip starting, ending slashes
  2240. $path = preg_replace('@/$@', '', $parts['path']);
  2241. $path = preg_replace('@^/@', '', $path);
  2242. $path = basename($path);
  2243. // Hack for MediaWiki user pages, in the form:
  2244. // http://example.com/wiki/User:Myname
  2245. // ('User' may be localized.)
  2246. if (strpos($path, ':')) {
  2247. $parts = array_filter(explode(':', $path));
  2248. $path = $parts[count($parts) - 1];
  2249. }
  2250. if ($path) {
  2251. return common_nicknamize($path);
  2252. }
  2253. }
  2254. }
  2255. return null;
  2256. }
  2257. function common_nicknamize($str)
  2258. {
  2259. try {
  2260. return Nickname::normalize($str);
  2261. } catch (NicknameException $e) {
  2262. return null;
  2263. }
  2264. }
  2265. function common_perf_counter($key, $val=null)
  2266. {
  2267. global $_perfCounters;
  2268. if (isset($_perfCounters)) {
  2269. if (common_config('site', 'logperf')) {
  2270. if (array_key_exists($key, $_perfCounters)) {
  2271. $_perfCounters[$key][] = $val;
  2272. } else {
  2273. $_perfCounters[$key] = [$val];
  2274. }
  2275. if (common_config('site', 'logperf_detail')) {
  2276. common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
  2277. }
  2278. }
  2279. }
  2280. }
  2281. function common_log_perf_counters()
  2282. {
  2283. if (common_config('site', 'logperf')) {
  2284. global $_startCpuTime, $_perfCounters;
  2285. if (isset($_startCpuTime)) {
  2286. $end_cpu_time = hrtime(true);
  2287. $diff = round(($end_cpu_time - $_startCpuTime) / 1000000);
  2288. common_log(LOG_DEBUG, "PERF runtime: {$diff}ms");
  2289. }
  2290. $counters = $_perfCounters;
  2291. ksort($counters);
  2292. foreach ($counters as $key => $values) {
  2293. $count = count($values);
  2294. $unique = count(array_unique($values));
  2295. common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
  2296. }
  2297. }
  2298. }
  2299. function common_is_email($str)
  2300. {
  2301. return (strpos($str, '@') !== false);
  2302. }
  2303. function common_init_stats()
  2304. {
  2305. global $_mem, $_ts;
  2306. $_mem = memory_get_usage(true);
  2307. $_ts = microtime(true);
  2308. }
  2309. function common_log_delta($comment=null)
  2310. {
  2311. global $_mem, $_ts;
  2312. $mold = $_mem;
  2313. $told = $_ts;
  2314. $_mem = memory_get_usage(true);
  2315. $_ts = microtime(true);
  2316. $mtotal = $_mem - $mold;
  2317. $ttotal = $_ts - $told;
  2318. if (empty($comment)) {
  2319. $comment = 'Delta';
  2320. }
  2321. common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));
  2322. }
  2323. function common_strip_html($html, $trim=true, $save_whitespace=false)
  2324. {
  2325. // first replace <br /> with \n
  2326. $html = preg_replace('/\<(\s*)?br(\s*)?\/?(\s*)?\>/i', "\n", $html);
  2327. // then, unless explicitly avoided, remove excessive whitespace
  2328. if (!$save_whitespace) {
  2329. $html = preg_replace('/\s+/', ' ', $html);
  2330. }
  2331. $text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
  2332. return $trim ? trim($text) : $text;
  2333. }
  2334. /**
  2335. * An internal helper function that converts a $size from php.ini for
  2336. * file size limit from the 'human-readable' shorthand into a int. If
  2337. * $size is empty (the value is not set in php.ini), returns a default
  2338. * value (5000000)
  2339. *
  2340. * @param string|bool $size
  2341. * @return int the php.ini upload limit in machine-readable format
  2342. */
  2343. function _common_size_str_to_int($size): int
  2344. {
  2345. // `memory_limit` can be -1 and `post_max_size` can be 0
  2346. // for unlimited. Consistency.
  2347. if (empty($size) || $size === '-1' || $size === '0') {
  2348. return 5000000;
  2349. }
  2350. $suffix = substr($size, -1);
  2351. $size = substr($size, 0, -1);
  2352. switch (strtoupper($suffix)) {
  2353. case 'P':
  2354. $size *= 1024;
  2355. // no break
  2356. case 'T':
  2357. $size *= 1024;
  2358. // no break
  2359. case 'G':
  2360. $size *= 1024;
  2361. // no break
  2362. case 'M':
  2363. $size *= 1024;
  2364. // no break
  2365. case 'K':
  2366. $size *= 1024;
  2367. break;
  2368. }
  2369. return $size;
  2370. }
  2371. /**
  2372. * Uses `_common_size_str_to_int()` to find the smallest value for uploads in php.ini
  2373. *
  2374. * @return int
  2375. */
  2376. function common_get_preferred_php_upload_limit(): int
  2377. {
  2378. return min(
  2379. _common_size_str_to_int(ini_get('post_max_size')),
  2380. _common_size_str_to_int(ini_get('upload_max_filesize')),
  2381. _common_size_str_to_int(ini_get('memory_limit'))
  2382. );
  2383. }
  2384. /**
  2385. * Send a file to the client.
  2386. *
  2387. * @param string $filepath
  2388. * @param string $mimetype
  2389. * @param string $filename
  2390. * @param string $disposition
  2391. * @param int $expires header browser cache expires in milliseconds (defaults to 30 days)
  2392. * @throws ServerException
  2393. */
  2394. function common_send_file(string $filepath, string $mimetype, string $filename, string $disposition = 'inline', int $expires = 30 * 24 * 3600): void
  2395. {
  2396. header("Content-Type: {$mimetype}");
  2397. header("Content-Disposition: {$disposition}; filename=\"{$filename}\"");
  2398. header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
  2399. if (is_string(common_config('site', 'x-static-delivery'))) {
  2400. handleStaticDelivery($filepath);
  2401. } else {
  2402. handleDynamicDelivery($filepath);
  2403. }
  2404. }
  2405. function handleStaticDelivery(string $filepath): void
  2406. {
  2407. $tmp = explode(INSTALLDIR, $filepath);
  2408. $relative_path = array_pop($tmp);
  2409. common_debug("Using Static Delivery with header: '".common_config('site', 'x-static-delivery') . ": {$relative_path}'");
  2410. header(common_config('site', 'x-static-delivery').": {$relative_path}");
  2411. }
  2412. function handleDynamicDelivery(string $filepath): void
  2413. {
  2414. header("Content-Description: File Transfer");
  2415. header('Content-Transfer-Encoding: binary');
  2416. if (file_exists($filepath)) {
  2417. http_response_code(HTTP_OK);
  2418. header("Content-Length: ".filesize($filepath));
  2419. // header('Cache-Control: private, no-transform, no-store, must-revalidate');
  2420. $ret = readfile($filepath);
  2421. if ($ret === false) {
  2422. http_response_code(HTTP_NOT_FOUND);
  2423. throw new ServerException("Couldn't read file at {$filepath}.");
  2424. } elseif ($ret !== filesize($filepath)) {
  2425. http_response_code(HTTP_INTERNAL_SERVER_ERROR);
  2426. throw new ServerException("The lengths of the file as recorded on the DB (or on disk) for the file {$filepath}.");
  2427. }
  2428. } else {
  2429. http_response_code(HTTP_NOT_FOUND);
  2430. throw new ServerException("File doesn't exist at {$filepath}.");
  2431. }
  2432. }
  2433. function html_sprintf()
  2434. {
  2435. $args = func_get_args();
  2436. for ($i=1; $i<count($args); $i++) {
  2437. $args[$i] = htmlspecialchars($args[$i]);
  2438. }
  2439. return call_user_func_array('sprintf', $args);
  2440. }
  2441. function _ve($var)
  2442. {
  2443. return var_export($var, true);
  2444. }