utils.inc.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_LINK_CLASS', 'bx-link'); ///< class to add to every link in user content
  10. define('BX_DATA_TEXT', 1); ///< regular text data type
  11. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  12. define('BX_DATA_INT', 3); ///< integer data type
  13. define('BX_DATA_FLOAT', 4); ///< float data type
  14. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  15. define('BX_DATA_HTML', 6); ///< HTML data type
  16. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  17. define('BX_DATA_DATETIME', 12); ///< date/time data type stored as yyyy-mm-dd hh:mm:ss
  18. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  19. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  20. define('BX_DATA_DATE_TS_UTC', 10); ///< date data type stored as unixtimestamp from UTC time
  21. define('BX_DATA_DATETIME_TS_UTC', 11); ///< date/time data type stored as unixtimestamp from UTC time
  22. define('BX_SLASHES_AUTO', 0);
  23. define('BX_SLASHES_ADD', 1);
  24. define('BX_SLASHES_STRIP', 2);
  25. define('BX_SLASHES_NO_ACTION', 3);
  26. define('BX_ESCAPE_STR_AUTO', 0); ///< turn apostropes and quote signs into html special chars, for use in @see bx_js_string and @see bx_html_attribute
  27. define('BX_ESCAPE_STR_APOS', 1); ///< escape apostrophes only, for js strings enclosed in apostrophes, for use in @see bx_js_string and @see bx_html_attribute
  28. define('BX_ESCAPE_STR_QUOTE', 2); ///< escape quotes only, for js strings enclosed in quotes, for use in @see bx_js_string and @see bx_html_attribute
  29. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  30. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  31. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  32. define('BX_MAINTENANCE_FILE', '.bx_maintenance'); ///< file name to use as mantenance mode indicator
  33. /**
  34. * The following two functions are needed to convert title to uri and back.
  35. * It usefull when titles are used in URLs, like in Categories and Tags.
  36. */
  37. function title2uri($sValue)
  38. {
  39. return str_replace(
  40. array('&', '/', '\\', '"', '+'),
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. $sValue
  43. );
  44. }
  45. function uri2title($sValue)
  46. {
  47. return str_replace(
  48. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  49. array('&', '/', '\\', '"', '+'),
  50. $sValue
  51. );
  52. }
  53. /*
  54. * functions for limiting maximal text length
  55. */
  56. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;')
  57. {
  58. $sTail = '';
  59. $s = trim(strip_tags($sInput));
  60. if (mb_strlen($s) > $iMaxLen) {
  61. $s = mb_substr($s, 0, $iMaxLen);
  62. $sTail = $sEllipsisSign;
  63. }
  64. return htmlspecialchars_adv($s) . $sTail;
  65. }
  66. function html2txt($content, $tags = "")
  67. {
  68. while($content != strip_tags($content, $tags)) {
  69. $content = strip_tags($content, $tags);
  70. }
  71. return $content;
  72. }
  73. /**
  74. * Functions to process user input.
  75. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  76. * It is ok to use bx_process_input and then db prepare.
  77. * @param $mixedData data to process
  78. * @param $iDataType how to handle data, possible valies:
  79. * @code
  80. * BX_DATA_INT - integer value
  81. * BX_DATA_FLOAT - float values
  82. * BX_DATA_CHECKBOX - 'on' or empty string
  83. * BX_DATA_TEXT - text data, single line (default)
  84. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  85. * BX_DATA_HTML - HTML data
  86. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  87. * BX_DATA_DATETIME - date/time data type stored as yyyy-mm-dd hh:mm:ss
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * BX_DATA_DATE_TS_UTC - date data type stored as unixtimestamp from UTC time
  91. * BX_DATA_DATETIME_TS_UTC - date/time data type stored as unixtimestamp from UTC time
  92. * @endcode
  93. * @param $mixedParams optional parameters to pass for validation
  94. * @param $isCheckMagicQuotes deprecated
  95. * @return the filtered data, or FALSE if the filter fails.
  96. */
  97. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  98. {
  99. if (is_array($mixedData)) {
  100. foreach ($mixedData as $k => $v)
  101. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  102. return $mixedData;
  103. }
  104. switch ($iDataType) {
  105. case BX_DATA_INT:
  106. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  107. case BX_DATA_FLOAT:
  108. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  109. case BX_DATA_CHECKBOX:
  110. return 'on' == trim($mixedData) ? 'on' : '';
  111. case BX_DATA_DATE:
  112. // maybe consider using strtotime
  113. $mixedData = trim($mixedData);
  114. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  115. return false;
  116. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  117. $iDay = intval($iDay);
  118. $iMonth = intval($iMonth);
  119. $iYear = intval($iYear);
  120. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  121. case BX_DATA_DATETIME:
  122. // maybe consider using strtotime
  123. $mixedData = trim($mixedData);
  124. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  125. return bx_process_input ($mixedData, BX_DATA_DATE, $mixedParams, $isCheckMagicQuotes);
  126. $iDay = intval($m[3]);
  127. $iMonth = intval($m[2]);
  128. $iYear = intval($m[1]);
  129. $iH = intval($m[4]);
  130. $iM = intval($m[5]);
  131. $iS = isset($m[6]) ? intval($m[6]) : 0;
  132. return sprintf("%04d-%02d-%02d %02d:%02d:%02d", $iYear, $iMonth, $iDay, $iH, $iM, $iS); // 1985-10-28 00:59:35
  133. case BX_DATA_DATE_TS:
  134. case BX_DATA_DATE_TS_UTC:
  135. $mixedData = trim($mixedData);
  136. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  137. return false;
  138. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  139. $iDay = intval($iDay);
  140. $iMonth = intval($iMonth);
  141. $iYear = intval($iYear);
  142. $sFunc = BX_DATA_DATE_TS_UTC == $iDataType ? 'gmmktime' : 'mktime';
  143. $iRet = $sFunc (0, 0, 0, $iMonth, $iDay, $iYear);
  144. return $iRet > 0 ? $iRet : false;
  145. case BX_DATA_DATETIME_TS:
  146. case BX_DATA_DATETIME_TS_UTC:
  147. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\s]{1}(\d+):(\d+):(\d+)[\s]{1}([+\-\d:Z]+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  148. return bx_process_input ($mixedData, BX_DATA_DATETIME_TS == $iDataType ? BX_DATA_DATE_TS : BX_DATA_DATE_TS_UTC, $mixedParams, $isCheckMagicQuotes);
  149. $iDay = $m[3];
  150. $iMonth = $m[2];
  151. $iYear = $m[1];
  152. $iH = $m[4];
  153. $iM = $m[5];
  154. $iS = isset($m[6]) ? $m[6] : 0;
  155. $iTimezoneOffset = 0;
  156. if (isset($m[7])) {
  157. $oTz = new DateTimeZone($m[7]);
  158. $oUtc = new DateTime(str_replace($m[7], '', $mixedData), new DateTimeZone('UTC'));
  159. if ($oTz && $oUtc)
  160. $iTimezoneOffset = $oTz->getOffset($oUtc);
  161. }
  162. $sFunc = BX_DATA_DATETIME_TS_UTC == $iDataType ? 'gmmktime' : 'mktime';
  163. $iRet = $sFunc ($iH, $iM, $iS, $iMonth, $iDay, $iYear) - $iTimezoneOffset;
  164. return $iRet > 0 ? $iRet : false;
  165. case BX_DATA_HTML:
  166. return clear_xss($mixedData);
  167. case BX_DATA_TEXT_MULTILINE:
  168. return nl2br(htmlspecialchars_adv($mixedData));
  169. case BX_DATA_TEXT:
  170. default:
  171. return $mixedData;
  172. }
  173. }
  174. /*
  175. * Functions to process user output.
  176. * Always use this function before output data which was entered by user before.
  177. * @param $mixedData string to process
  178. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  179. * @param $mixedParams optional parameters to pass for validation
  180. * @return the filtered data, or FALSE if the filter fails.
  181. */
  182. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false)
  183. {
  184. if (is_array($mixedData)) {
  185. foreach ($mixedData as $k => $v)
  186. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  187. return $mixedData;
  188. }
  189. switch ($iDataType) {
  190. case BX_DATA_INT:
  191. return filter_var($mixedData, FILTER_VALIDATE_INT);
  192. case BX_DATA_FLOAT:
  193. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  194. case BX_DATA_CHECKBOX:
  195. return 'on' == trim($mixedData) ? 'on' : '';
  196. case BX_DATA_DATE:
  197. case BX_DATA_DATETIME:
  198. return $mixedData;
  199. case BX_DATA_DATE_TS:
  200. return empty($mixedData) ? '' : date("Y-m-d", (int)$mixedData);
  201. case BX_DATA_DATE_TS_UTC:
  202. return empty($mixedData) ? '' : gmdate("Y-m-d", (int)$mixedData);
  203. case BX_DATA_DATETIME_TS:
  204. return empty($mixedData) ? '' : date("Y-m-d H:i", (int)$mixedData);
  205. case BX_DATA_DATETIME_TS_UTC:
  206. return empty($mixedData) ? '' : gmdate("Y-m-d H:i", (int)$mixedData);
  207. case BX_DATA_HTML:
  208. $s = bx_linkify_html($mixedData, 'class="' . BX_DOL_LINK_CLASS . '"');
  209. return $mixedParams && is_array($mixedParams) && in_array('no_process_macro', $mixedParams) ? $s : bx_process_macros($s);
  210. case BX_DATA_TEXT_MULTILINE:
  211. $s = $mixedData;
  212. return $mixedParams && is_array($mixedParams) && in_array('no_process_macros', $mixedParams) ? $s : bx_process_macros($s);
  213. case BX_DATA_TEXT:
  214. default:
  215. $s = htmlspecialchars_adv($mixedData);
  216. return $mixedParams && is_array($mixedParams) && in_array('no_process_macros', $mixedParams) ? $s : bx_process_macros($s);
  217. }
  218. }
  219. function bx_is_macros_in_content (&$s)
  220. {
  221. return false === strpos($s, '{{~') ? false : true;
  222. }
  223. /**
  224. * This function converts macros upon text output.
  225. * Macros represents constructions like this:
  226. * @code
  227. * {{!module_name:function[param1, "param2"]}}
  228. * @endcode
  229. * For example, to display some content from module Posts:
  230. * @code
  231. * {{!bx_posts:get_search_result_unit[3]}}
  232. * @endcode
  233. * Only users which have "use macros" ACL action enabled can use this functionlity.
  234. *
  235. * @param $s text to process
  236. * @return modified or not modified text
  237. */
  238. function bx_process_macros ($s)
  239. {
  240. if (!bx_is_macros_in_content($s))
  241. return $s;
  242. return preg_replace_callback(
  243. "/{{\~(.*?)\~}}/",
  244. function ($aMatches) {
  245. return BxDolService::callMacro($aMatches[1]);
  246. },
  247. $s);
  248. }
  249. /*
  250. * This function apply bx_process_input and then bx_process_output.
  251. * Use this function to output data immediately after receiving, without saving to database.
  252. * Patams are the same as bx_process_input function - @see bx_process_input
  253. */
  254. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  255. {
  256. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  257. }
  258. /**
  259. * DEPRECATED
  260. * use bx_process_input + bx_process_output instead
  261. * --------
  262. * function for processing pass data
  263. *
  264. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  265. * for data which should be outputed immediately after submit
  266. */
  267. /*
  268. function process_pass_data( $text, $strip_tags = 0 )
  269. {
  270. if ( $strip_tags )
  271. $text = strip_tags($text);
  272. if ( !get_magic_quotes_gpc() )
  273. return $text;
  274. else
  275. return stripslashes($text);
  276. }
  277. */
  278. /*
  279. * function for output data from database into html
  280. */
  281. function htmlspecialchars_adv( $string )
  282. {
  283. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
  284. }
  285. /**
  286. * Send mail to user by parsing email template
  287. */
  288. function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY, $bAddToQueue = false)
  289. {
  290. $oProfile = BxDolProfile::getInstance($iProfileId);
  291. $oAccount = $iAccountId ? BxDolAccount::getInstance($iAccountId) : ($oProfile ? $oProfile->getAccountObject() : null);
  292. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  293. if (!$oAccount || !$oProfile || !$oEmailTemplates)
  294. return false;
  295. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $oAccount ? $oAccount->id() : 0, (int)$iProfileId);
  296. if (!$aTemplate)
  297. return false;
  298. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  299. }
  300. /**
  301. * Send system email
  302. */
  303. function sendMailTemplateSystem($sTemplateName, $aReplaceVars = array(), $iEmailType = BX_EMAIL_SYSTEM, $bAddToQueue = false)
  304. {
  305. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  306. if (!$oEmailTemplates)
  307. return false;
  308. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars);
  309. if (!$aTemplate)
  310. return false;
  311. return sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  312. }
  313. /**
  314. * Send email function
  315. *
  316. * @param $sRecipientEmail - Email where email should be send
  317. * @param $sMailSubject - subject of the message
  318. * @param $sMailBody - Body of the message
  319. * @param $iRecipientID - ID of recipient profile
  320. * @param $aPlus - Array of additional information
  321. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  322. * @param $sEmailFlag - use 'html' for HTML email message
  323. * @param $isDisableAlert - disable alert
  324. * @param $aCustomHeaders - custom email headers
  325. * @param $bAddToQueue - add message to email queue
  326. * @return true if message was send or false otherwise
  327. */
  328. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false, $aCustomHeaders = array(), $bAddToQueue = false)
  329. {
  330. // make sure that recipient's email is valid and message isn't empty
  331. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  332. return false;
  333. // get recipient account
  334. $oAccount = !$isDisableAlert ? BxDolAccount::getInstance($sRecipientEmail) : null;
  335. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  336. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  337. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  338. return false;
  339. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  340. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  341. return false;
  342. if($bAddToQueue && BxDolQueueEmail::getInstance()->add($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID, $aPlus, $iEmailType, $sEmailFlag, $isDisableAlert, $aCustomHeaders))
  343. return true;
  344. // if profile id is provided - get profile's info
  345. $aRecipientInfo = false;
  346. if ($iRecipientID) {
  347. $oProfile = BxDolProfile::getInstance($iRecipientID);
  348. if ($oProfile)
  349. $aRecipientInfo = $oProfile->getInfo();
  350. }
  351. // get site vars
  352. $sEmailNotify = !$isDisableAlert ? getParam('site_email_notify') : $sRecipientEmail;
  353. $sSiteTitle = !$isDisableAlert ? getParam('site_title') : 'UNA ' . BX_DOL_VERSION;
  354. // add unsubscribe link
  355. if (!$isDisableAlert && empty($aPlus['unsubscribe'])) {
  356. $aPlus['unsubscribe'] = '';
  357. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  358. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  359. }
  360. // parse template
  361. if ($aPlus || $iRecipientID || $oAccount) {
  362. if(!is_array($aPlus))
  363. $aPlus = array();
  364. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  365. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  366. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  367. }
  368. // email message headers
  369. $sMailHeader = '';
  370. foreach ($aCustomHeaders as $sHeaderName => $sHeaderValue)
  371. $sMailHeader = "$sHeaderName: $sHeaderValue\r\n" . $sMailHeader;
  372. if (!isset($aCustomHeaders['From']))
  373. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  374. if (!isset($aCustomHeaders['MIME-Version']))
  375. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  376. $sMailParameters = isset($aCustomHeaders['Sender']) ? "-f{$aCustomHeaders['Sender']}" : "-f{$sEmailNotify}";
  377. if (isset($aCustomHeaders['Subject']))
  378. $sMailSubject = $aCustomHeaders['Subject'];
  379. // build data for alert handler
  380. $bResult = null;
  381. $aAlert = array(
  382. 'email' => $sRecipientEmail,
  383. 'subject' => $sMailSubject,
  384. 'body' => $sMailBody,
  385. 'header' => $sMailHeader,
  386. 'params' => $sMailParameters,
  387. 'recipient' => $aRecipientInfo,
  388. 'html' => 'html' == $sEmailFlag ? true : false,
  389. 'custom_headers' => $aCustomHeaders,
  390. 'override_result' => &$bResult,
  391. );
  392. // system alert
  393. if (!$isDisableAlert) {
  394. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  395. if ($bResult !== null)
  396. return $bResult;
  397. unset($aAlert['override_result']);
  398. }
  399. // prepare HTML/Plain message
  400. if($sEmailFlag == 'html')
  401. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  402. else {
  403. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  404. $sMailBody = html2txt($sMailBody);
  405. }
  406. // encode subject
  407. if (0 !== strncasecmp($sMailSubject, '=?UTF-8?B?', 10))
  408. $sMailSubject = '=?UTF-8?B?' . base64_encode($sMailSubject) . '?=';
  409. // send mail or put it into queue
  410. $bResult = mail($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters);
  411. // system alert
  412. if (!$isDisableAlert)
  413. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  414. return $bResult;
  415. }
  416. /*
  417. * Getting an array with Templates' Names
  418. */
  419. function get_templates_array($bEnabledOnly = true, $bShortInfo = true)
  420. {
  421. $oDb = BxDolDb::getInstance();
  422. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  423. if($bShortInfo)
  424. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  425. else
  426. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  427. }
  428. function bx_get_image_exif_and_size($oStorage, $oTranscoder, $iContentId){
  429. $sExif = '';
  430. $aExif = false;
  431. $aPhoto = $oStorage->getFile($iContentId);
  432. if ($oTranscoder->isMimeTypeSupported($aPhoto['mime_type'])) {
  433. $oImageReize = BxDolImageResize::getInstance();
  434. $a = $oImageReize->getImageSize($oTranscoder->getFileUrl($iContentId));
  435. $sData = isset($a['w']) && isset($a['h']) ? $a['w'] . 'x' . $a['h'] : '';
  436. if ($aExif = $oImageReize->getExifInfo($oStorage->getFileUrlById($iContentId))) {
  437. $a = array('Make', 'Model', 'FocalLength', 'ShutterSpeedValue', 'ExposureTime', 'ISOSpeedRatings', 'Orientation', 'Artist', 'Copyright', 'Flash', 'WhiteBalance', 'DateTimeOriginal', 'DateTimeDigitized', 'ExifVersion', 'COMPUTED', 'GPSLatitudeRef', 'GPSLatitude', 'GPSLongitudeRef', 'GPSLongitude', 'GPSAltitudeRef', 'GPSAltitude', 'GPSTimeStamp', 'GPSImgDirectionRef', 'GPSImgDirection', 'GPSDateStamp');
  438. $aExifFiltered = array();
  439. foreach ($a as $sIndex)
  440. if (isset($aExif[$sIndex]))
  441. $aExifFiltered[$sIndex] = $aExif[$sIndex];
  442. $sExif = serialize($aExifFiltered);
  443. }
  444. }
  445. return array('exif' => $sExif, 'size' => $sData);
  446. }
  447. function extFileExists( $sFileSrc )
  448. {
  449. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  450. }
  451. function getVisitorIP()
  452. {
  453. $ip = "0.0.0.0";
  454. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  455. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  456. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  457. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  458. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  459. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  460. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  461. $ip = $_SERVER['REMOTE_ADDR'];
  462. }
  463. return $ip;
  464. }
  465. function genFlag($sLang = '', $oTemplate = null)
  466. {
  467. if (!$oTemplate)
  468. $oTemplate = BxDolTemplate::getInstance();
  469. $oTemplate->addCss(BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'flag-icon-css/css/|flag-icon.min.css');
  470. $sFlag = BxDolLanguages::getInstance()->getLangFlag($sLang);
  471. return '<span title="' . $sFlag . '" class="flag-icon flag-icon-' . $sFlag . '"></span>';
  472. }
  473. // print debug information ( e.g. arrays )
  474. function echoDbg( $what, $desc = '' )
  475. {
  476. if ( $desc )
  477. echo "<b>$desc:</b> ";
  478. echo "<pre>";
  479. print_r( $what );
  480. echo "</pre>\n";
  481. }
  482. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log')
  483. {
  484. $sCont =
  485. '--- ' . date('r') . ' (' . BX_DOL_START . ") ---\n" .
  486. $sDesc . "\n" .
  487. print_r($mWhat, true) . "\n\n\n";
  488. $rFile = fopen(BX_DIRECTORY_PATH_LOGS . $sFileName, 'a');
  489. fwrite($rFile, $sCont);
  490. fclose($rFile);
  491. }
  492. function dbgTiming($sStartMicrotime)
  493. {
  494. $i1 = explode(' ', microtime ());
  495. $i2 = explode(' ', $sStartMicrotime);
  496. $iTime = ($i1[0]+$i1[1]) - ($i2[0]+$i2[1]);
  497. return round($iTime, 6) . ' sec';
  498. }
  499. function echoJson($a)
  500. {
  501. header('Content-type: text/html; charset=utf-8');
  502. echo json_encode($a);
  503. }
  504. function clear_xss($val)
  505. {
  506. // HTML Purifier plugin
  507. global $oHtmlPurifier;
  508. if (!isset($oHtmlPurifier) && !$GLOBALS['logged']['admin']) {
  509. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  510. HTMLPurifier_Bootstrap::registerAutoload();
  511. $oConfig = HTMLPurifier_Config::createDefault();
  512. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  513. $oConfig->set('Cache.SerializerPermissions', BX_DOL_DIR_RIGHTS);
  514. $oConfig->set('HTML.SafeObject', 'true');
  515. $oConfig->set('Output.FlashCompat', 'true');
  516. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  517. $oConfig->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top'));
  518. if (getParam('sys_add_nofollow')) {
  519. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  520. $oConfig->set('URI.Host', $sHost);
  521. $oConfig->set('HTML.Nofollow', 'true');
  522. }
  523. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe(), new HTMLPurifier_Filter_AddBxLinksClass(), new HTMLPurifier_Filter_LocalIframe()));
  524. $oConfig->set('HTML.DefinitionID', 'html5-definitions');
  525. $oConfig->set('HTML.DefinitionRev', 1);
  526. if ($def = $oConfig->maybeGetRawHTMLDefinition()) {
  527. $def->addElement('section', 'Block', 'Flow', 'Common');
  528. $def->addElement('nav', 'Block', 'Flow', 'Common');
  529. $def->addElement('article', 'Block', 'Flow', 'Common');
  530. $def->addElement('aside', 'Block', 'Flow', 'Common');
  531. $def->addElement('header', 'Block', 'Flow', 'Common');
  532. $def->addElement('footer', 'Block', 'Flow', 'Common');
  533. $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
  534. 'src' => 'URI',
  535. 'type' => 'Text',
  536. 'width' => 'Length',
  537. 'height' => 'Length',
  538. 'poster' => 'URI',
  539. 'preload' => 'Enum#auto,metadata,none',
  540. 'controls' => 'Bool',
  541. ));
  542. $def->addElement('source', 'Block', 'Flow', 'Common', array(
  543. 'src' => 'URI',
  544. 'type' => 'Text',
  545. ));
  546. $def->addAttribute('a', 'data-profile-id', 'Number');
  547. }
  548. $oHtmlPurifier = new HTMLPurifier($oConfig);
  549. }
  550. if (!$GLOBALS['logged']['admin'])
  551. $val = $oHtmlPurifier->purify($val);
  552. bx_alert('system', 'clear_xss', 0, 0, array('oHtmlPurifier' => $oHtmlPurifier, 'return_data' => &$val));
  553. return $val;
  554. }
  555. //--------------------------------------- friendly permalinks --------------------------------------//
  556. //------------------------------------------- main functions ---------------------------------------//
  557. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-', $sDivider = '-')
  558. {
  559. $s = uriFilter($s, $sEmpty, $sDivider);
  560. if(uriCheckUniq($s, $sTable, $sField))
  561. return $s;
  562. // cut off redundant part
  563. if(get_mb_len($s) > 240)
  564. $s = get_mb_substr($s, 0, 240);
  565. // try to add date
  566. $s .= $sDivider . date('Y-m-d');
  567. if(uriCheckUniq($s, $sTable, $sField))
  568. return $s;
  569. // try to add number
  570. for($i = 0 ; $i < 999 ; ++$i)
  571. if(uriCheckUniq($s . $sDivider . $i, $sTable, $sField))
  572. return ($s . $sDivider . $i);
  573. return rand(0, 999999999);
  574. }
  575. function uriFilter ($s, $sEmpty = '-', $sDivider = '-')
  576. {
  577. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  578. $s = get_mb_replace ('/[^\pL^\pN]+/u', $sDivider, $s); // unicode characters
  579. else
  580. $s = get_mb_replace ('/([^\d^\w]+)/u', $sDivider, $s); // latin characters only
  581. $s = get_mb_replace ('/([' . $sDivider . '^]+)/', $sDivider, $s);
  582. $s = get_mb_replace ('/([' . $sDivider . ']+)$/', '', $s); // remove trailing dash
  583. if (!$s) $s = $sEmpty;
  584. return $s;
  585. }
  586. function uriCheckUniq ($s, $sTable, $sField)
  587. {
  588. $oDb = BxDolDb::getInstance();
  589. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  590. return !$oDb->query($sSql);
  591. }
  592. function get_mb_replace ($sPattern, $sReplace, $s)
  593. {
  594. return preg_replace ($sPattern, $sReplace, $s);
  595. }
  596. function get_mb_len ($s)
  597. {
  598. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  599. }
  600. function get_mb_substr ($s, $iStart, $iLen)
  601. {
  602. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  603. }
  604. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
  605. {
  606. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  607. }
  608. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  609. {
  610. return mb_strpos($s, $sReplacement, $iStart);
  611. }
  612. /**
  613. * Import class file, it automatically detects class path by its prefix or module array/name
  614. *
  615. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  616. * @param $mixedModule - module array or module name in the case of module class
  617. */
  618. function bx_import($sClassName, $mixedModule = array())
  619. {
  620. if (class_exists($sClassName, false))
  621. return;
  622. $aModule = false;
  623. if ($mixedModule) {
  624. if (is_array($mixedModule)) {
  625. $aModule = $mixedModule;
  626. } elseif (is_string($mixedModule)) {
  627. $o = BxDolModule::getInstance($mixedModule);
  628. $aModule = $o->_aModule;
  629. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  630. $aModule = $GLOBALS['aModule'];
  631. }
  632. }
  633. if ($aModule) {
  634. if (class_exists($aModule['class_prefix'] . $sClassName, false))
  635. return;
  636. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  637. return;
  638. }
  639. if (0 === strncmp($sClassName, 'BxDol', 5)) {
  640. if (0 === strncmp($sClassName, 'BxDolStudio', 11))
  641. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  642. else
  643. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  644. return;
  645. }
  646. if (0 === strncmp($sClassName, 'BxBase', 6)) {
  647. if (0 === strncmp($sClassName, 'BxBaseMod', 9)) {
  648. $aMatches = array();
  649. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  650. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  651. return;
  652. }
  653. } if (0 === strncmp($sClassName, 'BxBaseStudio', 12)) {
  654. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  655. return;
  656. } else {
  657. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  658. return;
  659. }
  660. }
  661. if (0 === strncmp($sClassName, 'BxTempl', 7)) {
  662. if(0 === strncmp($sClassName, 'BxTemplStudio', 13)) {
  663. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  664. } else {
  665. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  666. }
  667. if (file_exists($sPath)) {
  668. require_once($sPath);
  669. return;
  670. }
  671. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  672. }
  673. }
  674. /**
  675. * used in spl_autoload_register() function, so no need to call bx_import for system classes
  676. */
  677. function bx_autoload($sClassName)
  678. {
  679. if (0 === strncmp($sClassName, 'BxDol', 5) || 0 === strncmp($sClassName, 'BxBase', 6) || 0 === strncmp($sClassName, 'BxTempl', 7))
  680. bx_import($sClassName);
  681. }
  682. /**
  683. * Gets an instance of class pathing necessary parameters if it's necessary.
  684. *
  685. * @param string $sClassName class name.
  686. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  687. * @param array $mixedModule an array with module description. Is used when the requested class is located in some module.
  688. * @return unknown
  689. */
  690. function bx_instance($sClassName, $aParams = array(), $mixedModule = array())
  691. {
  692. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  693. return $GLOBALS['bxDolClasses'][$sClassName];
  694. if ($mixedModule) {
  695. if (!is_array($mixedModule)) {
  696. $o = BxDolModule::getInstance($mixedModule);
  697. $mixedModule = $o->_aModule;
  698. }
  699. $sClassName = bx_ltrim_str($sClassName, $mixedModule['class_prefix']);
  700. bx_import($sClassName, $mixedModule);
  701. $sClassName = $mixedModule['class_prefix'] . $sClassName;
  702. }
  703. $oClass = new ReflectionClass($sClassName);
  704. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  705. return $GLOBALS['bxDolClasses'][$sClassName];
  706. }
  707. /**
  708. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  709. *
  710. * @param $mixedInput - string/array which should be filtered
  711. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  712. * @return converted string / array
  713. */
  714. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  715. {
  716. $aUnits = array(
  717. "\n" => "\\n",
  718. "\r" => "",
  719. );
  720. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  721. $aUnits["'"] = "\\'";
  722. $aUnits['<script'] = "<scr' + 'ipt";
  723. $aUnits['</script>'] = "</scr' + 'ipt>";
  724. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  725. $aUnits['"'] = '\\"';
  726. $aUnits['<script'] = '<scr" + "ipt';
  727. $aUnits['</script>'] = '</scr" + "ipt>';
  728. } else {
  729. $aUnits['"'] = '&quot;';
  730. $aUnits["'"] = '&apos;';
  731. $aUnits["<script>"] = '&lt;script&gt;';
  732. $aUnits["</script>"] = '&lt;/script&gt;';
  733. }
  734. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  735. }
  736. /**
  737. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  738. *
  739. * @param $mixedInput - string/array which should be filtered
  740. * @param $iQuoteType - string escaping BX_ESCAPE_STR_AUTO, BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  741. * @return converted string / array
  742. */
  743. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  744. {
  745. $aUnits = array ();
  746. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  747. $aUnits["'"] = "\\'";
  748. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  749. $aUnits['"'] = '&quot;';
  750. else
  751. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  752. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  753. }
  754. /**
  755. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  756. *
  757. * @param mixed $mixedInput - string/array which should be filtered
  758. * @return converted string / array
  759. */
  760. function bx_php_string_apos ($mixedInput)
  761. {
  762. return str_replace("'", "\\'", $mixedInput);
  763. }
  764. function bx_php_string_quot ($mixedInput)
  765. {
  766. return str_replace('"', '\\"', $mixedInput);
  767. }
  768. /**
  769. * Gets file contents by URL.
  770. *
  771. * @param string $sFileUrl - file URL to be read.
  772. * @param array $aParams - an array of parameters to be pathed with URL.
  773. * @param string $sMethod - post or get.
  774. * @param array $aHeaders - custom headers.
  775. * @param string $sHttpCode - HTTP code to return
  776. * @param array $aBasicAuth - array with 'user' and 'password' for Basic HTTP Auth
  777. * @return string the file's contents.
  778. */
  779. function bx_file_get_contents($sFileUrl, $aParams = array(), $sMethod = 'get', $aHeaders = array(), &$sHttpCode = null, $aBasicAuth = array(), $iTimeout = 0, $aCustomCurlParams = array())
  780. {
  781. if ('post' != $sMethod)
  782. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  783. $sResult = '';
  784. if(function_exists('curl_init')) {
  785. $rConnect = curl_init();
  786. curl_setopt($rConnect, CURLOPT_USERAGENT, 'UNA ' . BX_DOL_VERSION);
  787. curl_setopt($rConnect, CURLOPT_TIMEOUT, 10);
  788. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  789. curl_setopt($rConnect, CURLOPT_HEADER, NULL === $sHttpCode ? false : true);
  790. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  791. if (0 !== $iTimeout) {
  792. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, $iTimeout);
  793. curl_setopt($rConnect, CURLOPT_TIMEOUT, $iTimeout);
  794. }
  795. if (!ini_get('open_basedir'))
  796. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  797. if ($aHeaders)
  798. curl_setopt($rConnect, CURLOPT_HTTPHEADER, $aHeaders);
  799. if ($aBasicAuth)
  800. curl_setopt($rConnect, CURLOPT_USERPWD, $aBasicAuth['user'] . ':' . $aBasicAuth['password']);
  801. if ('post' == $sMethod) {
  802. curl_setopt($rConnect, CURLOPT_POST, true);
  803. curl_setopt($rConnect, CURLOPT_POSTFIELDS, http_build_query($aParams));
  804. }
  805. $sAllCookies = '';
  806. foreach($_COOKIE as $sKey=>$sValue){
  807. $sAllCookies .= $sKey . '=' . $sValue . ';';
  808. }
  809. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  810. if ($aCustomCurlParams)
  811. foreach ($aCustomCurlParams as $sName => $mixedValue)
  812. curl_setopt($rConnect, constant($sName), $mixedValue);
  813. $sResult = curl_exec($rConnect);
  814. if (curl_errno($rConnect) == 60) { // CURLE_SSL_CACERT
  815. curl_setopt($rConnect, CURLOPT_CAINFO, BX_DIRECTORY_PATH_PLUGINS . 'curl/cacert.pem');
  816. $sResult = curl_exec($rConnect);
  817. }
  818. if (NULL !== $sHttpCode)
  819. $sHttpCode = curl_getinfo($rConnect, CURLINFO_HTTP_CODE);
  820. curl_close($rConnect);
  821. }
  822. else {
  823. $iSaveTimeout = false;
  824. if (0 !== $iTimeout) {
  825. $iSaveTimeout = ini_get('default_socket_timeout');
  826. ini_set('default_socket_timeout', $iTimeout);
  827. }
  828. $sResult = @file_get_contents($sFileUrl);
  829. if (0 !== $iTimeout && false !== $iSaveTimeout) {
  830. ini_set('default_socket_timeout', $iSaveTimeout);
  831. }
  832. }
  833. return $sResult;
  834. }
  835. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  836. {
  837. $aResult = array();
  838. $sContent = bx_file_get_contents($sSourceUrl);
  839. if ($sContent) {
  840. $sCharset = '';
  841. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  842. if (isset($aMatch[1]))
  843. $sCharset = $aMatch[1];
  844. $sContent = preg_replace("/<script[^>]*>(.*?)<\/script>/i", '', $sContent);
  845. $sContent = preg_replace("/<style[^>]*>(.*?)<\/style>/i", '', $sContent);
  846. if (preg_match("/<title[^>]*>(.*?)<\/title>/i", $sContent, $aMatch))
  847. $aResult['title'] = strip_tags($aMatch[1]);
  848. else
  849. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  850. $aResult['description'] = bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset);
  851. $aResult['keywords'] = bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset);
  852. if ($aProcessAdditionalTags) {
  853. foreach ($aProcessAdditionalTags as $k => $a) {
  854. $aResult[$k] = bx_parse_html_tag(
  855. $sContent,
  856. isset($a['tag']) ? $a['tag'] : 'meta',
  857. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  858. isset($a['name']) ? $a['name'] : $k,
  859. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  860. $sCharset,
  861. isset($a['specialchars_decode']) ? $a['specialchars_decode'] : true);
  862. if ((isset($a['name']) && 'og:image' == $a['name']) || (isset($a['tag']) && 'link' == $a['tag'])) {
  863. $aResult[$k] = bx_get_site_info_fix_relative_url ($sSourceUrl, $aResult[$k]);
  864. }
  865. }
  866. }
  867. }
  868. return $aResult;
  869. }
  870. /**
  871. * Fix relative URL to make it absolute
  872. * @param $sSourceUrl main URL
  873. * @param $s URL to fix
  874. * @return absolute URL or URL wothout changes
  875. */
  876. function bx_get_site_info_fix_relative_url ($sSourceUrl, $s)
  877. {
  878. if (0 === stripos($s, 'http://') || 0 === stripos($s, 'https://') || 0 === stripos($s, 'ftp://') || !$s)
  879. return $s;
  880. if ('/' == $s[0]) {
  881. $a = parse_url($sSourceUrl);
  882. return $a['scheme'] . '://' . $a['host'] . (empty($a['port']) || 80 == $a['port'] || 443 == $a['port'] ? '' : ':' . $a['port']) . $s;
  883. }
  884. return $sSourceUrl . ('/' === substr($sSourceUrl, -1) ? $s : '/' . $s);
  885. }
  886. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false, $bSpecialCharsDecode = true)
  887. {
  888. if (!preg_match("/<{$sTag}\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"]\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"][^>]*>/i", $sContent, $aMatch) || !isset($aMatch[1]))
  889. preg_match("/<{$sTag}\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"]\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"][^>]*>/i", $sContent, $aMatch);
  890. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  891. if ($s && $sCharset)
  892. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  893. if ($bSpecialCharsDecode)
  894. $s = htmlspecialchars_decode($s);
  895. return $s;
  896. }
  897. // calculation ini_get('upload_max_filesize') in bytes as example
  898. function return_bytes($val)
  899. {
  900. $val = trim($val);
  901. $last = strtolower($val[strlen($val)-1]);
  902. $val = (int)$val;
  903. switch($last) {
  904. // The 'G' modifier is available since PHP 5.1.0
  905. case 'k':
  906. $val *= 1024;
  907. break;
  908. case 'm':
  909. $val *= 1024 * 1024;
  910. break;
  911. case 'g':
  912. $val *= 1024 * 1024 * 1024;
  913. break;
  914. }
  915. return $val;
  916. }
  917. // Generate Random Password
  918. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  919. {
  920. $sPassword = '';
  921. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  922. if($bSpecialCharacters === true)
  923. $sChars .= "!?=/&+,.";
  924. for($i = 0; $i < $iLength; $i++) {
  925. $x = mt_rand(0, strlen($sChars) -1);
  926. $sPassword .= $sChars[$x];
  927. }
  928. return $sPassword;
  929. }
  930. // Generate Random Salt for Password encryption
  931. function genRndSalt()
  932. {
  933. return genRndPwd(8, true);
  934. }
  935. /**
  936. * Encrypt user password.
  937. * When BX_PWD_ALGO is 'custom', then bx_custom_pwd_encrypt function with custom algorythm must be defined in inc/header.inc.php file.
  938. * @param $sPwd clear password
  939. * @param $sSalt salt
  940. * @return password hash
  941. */
  942. function encryptUserPwd($sPwd, $sSalt)
  943. {
  944. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  945. switch ($sAlgo) {
  946. case 'custom':
  947. return bx_custom_pwd_encrypt($sPwd, $sSalt);
  948. case 'crypt':
  949. return crypt($sPwd, BX_PWD_ALGO_SALT);
  950. case 'sha1_crypt_salt':
  951. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  952. case 'sha1_md5_salt':
  953. default:
  954. return sha1(md5($sPwd) . $sSalt);
  955. }
  956. }
  957. /**
  958. * Hash profile ID
  959. */
  960. function encryptUserId($sId)
  961. {
  962. if (!($oProfile = BxDolProfile::getInstance($sId)))
  963. return false;
  964. if (!($oAccount = $oProfile->getAccountObject()))
  965. return false;
  966. $aAccountInfo = $oAccount->getInfo();
  967. return sha1(md5($sId) . md5($aAccountInfo['salt']) . BX_DOL_SECRET);
  968. }
  969. function bx_get ($sName, $sMethod = false)
  970. {
  971. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  972. return $_GET[$sName];
  973. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  974. return $_POST[$sName];
  975. else
  976. return false;
  977. }
  978. function bx_set ($sName, $sValue, $sMethod = false)
  979. {
  980. if(!$sMethod)
  981. $sMethod = 'get';
  982. $bResult = true;
  983. switch($sMethod) {
  984. case 'get':
  985. $_GET[$sName] = $sValue;
  986. break;
  987. case 'post':
  988. $_POST[$sName] = $sValue;
  989. break;
  990. default:
  991. $bResult = false;
  992. }
  993. return $bResult;
  994. }
  995. function bx_get_with_prefix ($sPrefix, $sMethod = false)
  996. {
  997. $aSources = array('get' => &$_GET, 'post' => &$_POST);
  998. $aFiltered = array();
  999. foreach($aSources as $sName => $aSource)
  1000. if($sMethod == $sName || !$sMethod)
  1001. $aFiltered = array_merge($aFiltered, array_filter($aSource, function($sKey) use ($sPrefix) {
  1002. return strpos($sKey, $sPrefix) === 0;
  1003. }, ARRAY_FILTER_USE_KEY));
  1004. $aUpdated = array();
  1005. array_walk($aFiltered, function($sValue, $sKey) use ($sPrefix, &$aUpdated) {
  1006. $aUpdated[trim(str_replace($sPrefix, '', $sKey), '_-')] = $sValue;
  1007. });
  1008. return $aUpdated;
  1009. }
  1010. function bx_get_base_url_inline($aParams = array())
  1011. {
  1012. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  1013. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . $_SERVER['REQUEST_URI'];
  1014. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  1015. if(!empty($_SERVER['QUERY_STRING'])) {
  1016. $aPageParamsAdd = array();
  1017. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  1018. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  1019. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  1020. }
  1021. if(!empty($aParams) && is_array($aParams))
  1022. $aPageParams = array_merge($aPageParams, $aParams);
  1023. return array($sPageLink, $aPageParams);
  1024. }
  1025. function bx_get_base_url_popup($aParams = array())
  1026. {
  1027. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  1028. if(!empty($aParams) && is_array($aParams))
  1029. $aPageParams = array_merge($aPageParams, $aParams);
  1030. return array($sPageLink, $aPageParams);
  1031. }
  1032. function bx_get_base_url($sPageLink)
  1033. {
  1034. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  1035. $sPageParams = '';
  1036. if(strpos($sPageLink, '?') !== false)
  1037. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  1038. $aPageParams = array();
  1039. if(!empty($sPageParams))
  1040. parse_str($sPageParams, $aPageParams);
  1041. return array($sPageLink, $aPageParams);
  1042. }
  1043. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  1044. {
  1045. $fEquatorLatInKm = 111.321;
  1046. $aRv = array();
  1047. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  1048. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  1049. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  1050. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  1051. return $aRv;
  1052. }
  1053. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  1054. {
  1055. $s = '';
  1056. foreach ($a as $sKey => $sVal) {
  1057. if (in_array($sKey, $aExcludeKeys))
  1058. continue;
  1059. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  1060. continue;
  1061. if (is_array($sVal)) {
  1062. foreach ($sVal as $sSubVal) {
  1063. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1064. }
  1065. } else {
  1066. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1067. }
  1068. }
  1069. return $s;
  1070. }
  1071. function bx_append_url_params ($sUrl, $mixedParams)
  1072. {
  1073. if (!$mixedParams)
  1074. return $sUrl;
  1075. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  1076. if (is_array($mixedParams)) {
  1077. foreach($mixedParams as $sKey => $sValue) {
  1078. if (!is_array($sValue)) {
  1079. $sParams .= $sKey . '=' . $sValue . '&';
  1080. }
  1081. else {
  1082. foreach($sValue as $sSubValue)
  1083. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  1084. }
  1085. }
  1086. $sParams = substr($sParams, 0, -1);
  1087. } else {
  1088. $sParams .= $mixedParams;
  1089. }
  1090. return $sUrl . $sParams;
  1091. }
  1092. function bx_rrmdir($directory)
  1093. {
  1094. if (substr($directory,-1) == "/")
  1095. $directory = substr($directory,0,-1);
  1096. if (!file_exists($directory) || !is_dir($directory))
  1097. return false;
  1098. elseif (!is_readable($directory))
  1099. return false;
  1100. if (!($directoryHandle = opendir($directory)))
  1101. return false;
  1102. while ($contents = readdir($directoryHandle)) {
  1103. if ($contents != '.' && $contents != '..') {
  1104. $path = $directory . "/" . $contents;
  1105. if (is_dir($path))
  1106. bx_rrmdir($path);
  1107. else
  1108. unlink($path);
  1109. }
  1110. }
  1111. closedir($directoryHandle);
  1112. if (!rmdir($directory))
  1113. return false;
  1114. return true;
  1115. }
  1116. function bx_clear_folder ($sPath, $aExts = array ())
  1117. {
  1118. if (substr($$sPath,-1) == "/")
  1119. $sPath = substr($sPath,0,-1);
  1120. if (!file_exists($sPath) || !is_dir($sPath))
  1121. return false;
  1122. elseif (!is_readable($sPath))
  1123. return false;
  1124. if (!($h = opendir($sPath)))
  1125. return false;
  1126. while ($sFile = readdir($h)) {
  1127. if ('.' == $sFile || '..' == $sFile)
  1128. continue;
  1129. $sFullPath = $sPath . '/' . $sFile;
  1130. if (is_dir($sFullPath))
  1131. continue;
  1132. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1133. @unlink($sFullPath);
  1134. }
  1135. closedir($h);
  1136. return true;
  1137. }
  1138. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1139. {
  1140. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1141. return $sString;
  1142. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1143. return $sReplace . substr($sString, strlen($sPrefix));
  1144. return $sString;
  1145. }
  1146. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1147. {
  1148. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1149. return $sString;
  1150. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1151. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1152. return $sString;
  1153. }
  1154. /**
  1155. * Strip all lines with no information for example: <p></p>, <br /><br />
  1156. */
  1157. function bx_trim_nl_duplicates($s)
  1158. {
  1159. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1160. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1161. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1162. }));
  1163. }
  1164. /**
  1165. * Convert array to attributes string
  1166. *
  1167. * Example:
  1168. * @code
  1169. * $a = array('name' => 'test', 'value' => 5);
  1170. * $s = bx_convert_array2attrs($a);
  1171. * echo $s; // outputs: name="test" value="5"
  1172. * @endcode
  1173. *
  1174. * @param $a - array of attributes
  1175. * @param $sClasses - classes to merge with 'class' attribute
  1176. * @param $sStyles - styles to merge with 'style' attribute
  1177. * @return string
  1178. */
  1179. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1180. {
  1181. $sRet = '';
  1182. if (!$a || !is_array($a))
  1183. $a = array();
  1184. if ($sClasses) {
  1185. $sClasses = trim($sClasses);
  1186. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1187. }
  1188. if ($sStyles) {
  1189. $sStyles = trim($sStyles);
  1190. if (';' != $sStyles[strlen($sStyles)-1])
  1191. $sStyles .= ';';
  1192. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1193. }
  1194. foreach ($a as $sKey => $sValue) {
  1195. if(is_null($sValue)) // pass NULL values
  1196. continue;
  1197. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1198. $sRet .= " $sKey=\"$sValueC\"";
  1199. }
  1200. return $sRet;
  1201. }
  1202. function bx_unicode_urldecode($s)
  1203. {
  1204. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1205. foreach ($a[1] as $uniord) {
  1206. $dec = hexdec($uniord);
  1207. $utf = '';
  1208. if ($dec < 128) {
  1209. $utf = chr($dec);
  1210. } else if ($dec < 2048) {
  1211. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1212. $utf .= chr(128 + ($dec % 64));
  1213. } else {
  1214. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1215. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1216. $utf .= chr(128 + ($dec % 64));
  1217. }
  1218. $s = str_replace('%u'.$uniord, $utf, $s);
  1219. }
  1220. return urldecode($s);
  1221. }
  1222. /**
  1223. * Raise an audit event
  1224. * @param int $iContentId - content id
  1225. * @param string $sContentModule - module name
  1226. * @param string $sAction - system action key
  1227. * @param array $aParams - array of parameters
  1228. */
  1229. function bx_audit($iContentId, $sContentModule, $sAction, $aParams)
  1230. {
  1231. if (!getParam('sys_audit_enable') || getParam('sys_audit_acl_levels') == '')
  1232. return;
  1233. $iProfileId = bx_get_logged_profile_id();
  1234. if (!BxDolAcl::getInstance()->isMemberLevelInSet(explode(',', getParam('sys_audit_acl_levels')), $iProfileId))
  1235. return;
  1236. $sContentTitle = $sContentInfoObject = $sContextProfileTitle = $sData = $sActionParams = '';
  1237. $iContextProfileId = 0;
  1238. if (isset($aParams['profile_id']))
  1239. $iProfileId = (int)$aParams['profile_id'];
  1240. if (isset($aParams['content_title']))
  1241. $sContentTitle = $aParams['content_title'];
  1242. if (isset($aParams['context_profile_id']))
  1243. $iContextProfileId = (int)$aParams['context_profile_id'];
  1244. if (isset($aParams['context_profile_title']))
  1245. $sContextProfileTitle = $aParams['context_profile_title'];
  1246. if (isset($aParams['action_params']) && is_array($aParams['action_params']) && count($aParams['action_params']))
  1247. $sActionParams = serialize($aParams['action_params']);
  1248. if (isset($aParams['content_info_object']))
  1249. $sContentInfoObject = $aParams['content_info_object'];
  1250. if (isset($aParams['data']) && is_array($aParams['data']) && count($aParams['data']))
  1251. $sData = serialize($aParams['data']);
  1252. $sProfileTitle = BxDolProfile::getInstance($iProfileId)->getDisplayName();
  1253. $oDb = BxDolDb::getInstance();
  1254. $sSql = $oDb->prepare("INSERT INTO `sys_audit`(`added`, `profile_id`, `profile_title`, `content_id`, `content_title`, `content_module`, `context_profile_id`, `context_profile_title`, `action_lang_key`, `action_lang_key_params`, `content_info_object`, `extras`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  1255. ,time(), $iProfileId, $sProfileTitle, $iContentId, $sContentTitle, $sContentModule, $iContextProfileId, $sContextProfileTitle, $sAction, $sActionParams ,$sContentInfoObject, $sData);
  1256. return !$oDb->query($sSql);
  1257. }
  1258. /**
  1259. * Raise an alert
  1260. * @param string $sUnit - system type
  1261. * @param string $sAction - system action
  1262. * @param int $iObjectId - object id
  1263. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1264. * @param array $aExtras - extra parameters
  1265. */
  1266. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1267. {
  1268. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1269. $o->alert();
  1270. }
  1271. /**
  1272. * Perform serice call
  1273. * @param $mixed module name or module id
  1274. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1275. * @param $aParams params to pass to service method
  1276. * @param $sClass class to search for service method, by default it is main module class
  1277. * @return service call result
  1278. */
  1279. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1280. {
  1281. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache);
  1282. }
  1283. function bx_replace_markers($mixed, $aMarkers)
  1284. {
  1285. if (empty($aMarkers))
  1286. return $mixed;
  1287. if (is_array($mixed)) {
  1288. foreach ($mixed as $sKey => $sValue)
  1289. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1290. } else {
  1291. foreach ($aMarkers as $sKey => $sValue)
  1292. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  1293. }
  1294. return $mixed;
  1295. }
  1296. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1297. {
  1298. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1299. }
  1300. /**
  1301. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1302. * @param $s string where words are separated with underscore
  1303. * @param $aWordsDelimiter word delimeters
  1304. * @return string where every word begins with capital letter
  1305. */
  1306. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1307. {
  1308. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1309. }
  1310. /**
  1311. * Trigger user error
  1312. * @param $sMsg message to display
  1313. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1314. */
  1315. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1316. {
  1317. $a = debug_backtrace();
  1318. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1319. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1320. }
  1321. /**
  1322. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1323. */
  1324. function bx_get_ver ($bInvalidateCache = false)
  1325. {
  1326. $oDb = BxDolDb::getInstance();
  1327. if ($bInvalidateCache)
  1328. $oDb->cleanMemory('sys_version');
  1329. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1330. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1331. }
  1332. /**
  1333. * Check if site maintetance mode is enabled.
  1334. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1335. * please note that this is hidden file and some file managers don't show it.
  1336. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1337. * @return true if site is in maintenance mode, or false otherwise
  1338. */
  1339. function bx_check_maintenance_mode ($bShowHttpError = false)
  1340. {
  1341. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1342. if ($bMaintetance && $bShowHttpError)
  1343. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1344. return $bMaintetance;
  1345. }
  1346. /**
  1347. * Check for minimal requirements.
  1348. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1349. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1350. * @return false if requirements are met, or array of errors of requirements aren't met
  1351. */
  1352. function bx_check_minimal_requirements ($bShowHttpError = false)
  1353. {
  1354. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1355. return false;
  1356. $aErrors = array();
  1357. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1358. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1359. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1360. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1361. $aErrors[] = (ini_get('allow_url_include') == 0) ? '' : '<b>allow_url_include</b> is on (you need to disable it, or your site will be unsafe)';
  1362. $aErrors = array_diff($aErrors, array('')); // delete empty
  1363. $bFailedMinimalRequirements = !empty($aErrors);
  1364. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1365. $sErrors = implode(" <br /> ", $aErrors);
  1366. bx_show_service_unavailable_error_and_exit($sErrors);
  1367. }
  1368. return $bFailedMinimalRequirements ? $aErrors : false;
  1369. }
  1370. /**
  1371. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1372. * @param $bProcessRedirect process redirect and exit if needed
  1373. */
  1374. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1375. {
  1376. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1377. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1378. $bRedirectRequired = isset($_SERVER['HTTP_HOST']) && 0 !== strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host']) && 0 !== strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host'] . ':' . (!empty($aUrl['port']) ? $aUrl['port'] : $iPortDefault));
  1379. if ($bRedirectRequired && $bProcessRedirect) {
  1380. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1381. header("Location:{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}", true, 301);
  1382. exit;
  1383. }
  1384. return $bRedirectRequired;
  1385. }
  1386. /**
  1387. * Check if redirect to remove install folder.
  1388. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1389. * @param $bProcessRedirect process redirect and exit if needed
  1390. */
  1391. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1392. {
  1393. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1394. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1395. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1396. exit;
  1397. }
  1398. return $bRemoveInstallFolder;
  1399. }
  1400. /**
  1401. * Show HTTP 503 service unavailable error and exit
  1402. */
  1403. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1404. {
  1405. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1406. header('Retry-After: 600');
  1407. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1408. exit;
  1409. }
  1410. /**
  1411. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1412. * @param $sPath path to file to output to the browser
  1413. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1414. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1415. * @param $iCacheAge file cache age, by default 0
  1416. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1417. * @return true on success or false on error
  1418. */
  1419. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1420. {
  1421. if (!file_exists($sPath))
  1422. return false;
  1423. $fp = @fopen($sPath, 'rb');
  1424. $size = filesize($sPath);
  1425. $length = $size;
  1426. $start = 0;
  1427. $end = $size - 1;
  1428. header('Content-type: ' . $sMimeType);
  1429. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1430. header("Accept-Ranges: 0-$length");
  1431. if ($sFilename)
  1432. header('Content-Disposition: inline; filename="' . $sFilename . '"');
  1433. if (isset($_SERVER['HTTP_RANGE'])) {
  1434. $c_start = $start;
  1435. $c_end = $end;
  1436. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1437. if (strpos($range, ',') !== false) {
  1438. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1439. header("Content-Range: bytes $start-$end/$size");
  1440. return false;
  1441. }
  1442. if ($range == '-') {
  1443. $c_start = $size - substr($range, 1);
  1444. }else{
  1445. $range = explode('-', $range);
  1446. $c_start = $range[0];
  1447. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1448. }
  1449. $c_end = ($c_end > $end) ? $end : $c_end;
  1450. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1451. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1452. header("Content-Range: bytes $start-$end/$size");
  1453. return false;
  1454. }
  1455. $start = $c_start;
  1456. $end = $c_end;
  1457. $length = $end - $start + 1;
  1458. fseek($fp, $start);
  1459. header('HTTP/1.1 206 Partial Content');
  1460. }
  1461. header("Content-Range: bytes $start-$end/$size");
  1462. header("Content-Length: ".$length);
  1463. $buffer = 1024 * 8;
  1464. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1465. if ($p + $buffer > $end) {
  1466. $buffer = $end - $p + 1;
  1467. }
  1468. set_time_limit(0);
  1469. echo fread($fp, $buffer);
  1470. flush();
  1471. }
  1472. fclose($fp);
  1473. return true;
  1474. }
  1475. /**
  1476. * Wrap in A tag links in TEXT string
  1477. * @param $text - text string without tags
  1478. * @param $sAttrs - attributes string to add to the added A tag
  1479. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1480. * @return string where all links are wrapped in A tag
  1481. */
  1482. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1483. {
  1484. if ($bHtmlSpecialChars)
  1485. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1486. $re = "@\b((https?://)|(www\.))(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,16})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1487. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1488. $matches = $matches[0];
  1489. if ($i = count($matches))
  1490. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1491. while ($i--)
  1492. {
  1493. $sAttrsLocal = $sAttrs;
  1494. $url = $matches[$i][0];
  1495. if (!preg_match('@^https?://@', $url))
  1496. $url = 'http://'.$url;
  1497. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1498. $sAttrsLocal .= ' target="_blank" ';
  1499. if ($bAddNofollow)
  1500. $sAttrsLocal .= ' rel="nofollow" ';
  1501. }
  1502. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1503. }
  1504. // email pattern
  1505. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1506. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1507. return $text;
  1508. }
  1509. /**
  1510. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1511. * @param $sHtmlOrig - HTML string
  1512. * @param $sAttrs - attributes string to add to the added A tag
  1513. * @return modified HTML string, in case of errror original string is returned
  1514. */
  1515. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1516. {
  1517. if (!trim($sHtmlOrig))
  1518. return $sHtmlOrig;
  1519. $sId = 'bx-linkify-' . md5(microtime());
  1520. $dom = new DOMDocument();
  1521. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1522. $xpath = new DOMXpath($dom);
  1523. foreach ($xpath->query('//text()') as $text) {
  1524. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1525. continue;
  1526. $frag = $dom->createDocumentFragment();
  1527. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1528. $text->parentNode->replaceChild($frag, $text);
  1529. }
  1530. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1531. $s = $dom->saveHTML($dom->getElementById($sId));
  1532. else
  1533. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1534. if (false === $s) // in case of error return original string
  1535. return $sHtmlOrig;
  1536. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1537. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1538. return mb_substr($s, 54, -6); // strip added tags
  1539. }
  1540. /**
  1541. * Returns current site protocol http:// or https://
  1542. */
  1543. function bx_proto()
  1544. {
  1545. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1546. }
  1547. /**
  1548. * Checks protocol in the link
  1549. */
  1550. function bx_has_proto($sLink)
  1551. {
  1552. return preg_match('@^https?://@', $sLink);
  1553. }
  1554. function bx_is_empty_array ($a)
  1555. {
  1556. if (!is_array($a))
  1557. return true;
  1558. if (empty($a))
  1559. return true;
  1560. foreach ($a as $k => $v)
  1561. if ($v)
  1562. return false;
  1563. return true;
  1564. }
  1565. function bx_is_full_array ($a)
  1566. {
  1567. if (!is_array($a))
  1568. return false;
  1569. if (empty($a))
  1570. return false;
  1571. foreach ($a as $k => $v)
  1572. if (empty($v))
  1573. return false;
  1574. return true;
  1575. }
  1576. function bx_is_url_in_content ($sContent)
  1577. {
  1578. $a = array(
  1579. 'http://',
  1580. 'https://',
  1581. 'https/',
  1582. 'http/',
  1583. 'www.',
  1584. '.com'
  1585. );
  1586. foreach ($a as $s)
  1587. if (false !== strpos($sContent, $s))
  1588. return true;
  1589. return false;
  1590. }
  1591. function bx_is_dynamic_request ()
  1592. {
  1593. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  1594. }
  1595. /** @} */