/** * Tests UTF-8 fixing. */ public function testFixUtf() { $this->assertEquals('žluťoučký kůň pěl ďábelské ódy', Charset::fixUtf('žluťoučký kůň pěl ďábelské ódy')); $this->assertEquals('Государственный гимн Российской Федерации', Charset::fixUtf('Государственный гимн Российской Федерации')); $this->assertEquals('', Charset::fixUtf(file_get_contents(DIR_FILES . '/charset/cp1250.txt'))); $this->assertEquals('', Charset::fixUtf(file_get_contents(DIR_FILES . '/charset/iso-8859-2.txt'))); }
/** * Tests UTF-8 fixing. */ public function testFixUtf() { $this->assertEquals('žluťoučký kůň pěl ďábelské ódy', Charset::fixUtf('žluťoučký kůň pěl ďábelské ódy')); $this->assertEquals('Государственный гимн Российской Федерации', Charset::fixUtf('Государственный гимн Российской Федерации')); $expected = 'glibc' === ICONV_IMPL ? '' : 'luouk k pern pl belsk '; $this->assertEquals($expected, Charset::fixUtf(file_get_contents(DIR_FILES . '/charset/cp1250.txt'))); $this->assertEquals($expected, Charset::fixUtf(file_get_contents(DIR_FILES . '/charset/iso-8859-2.txt'))); }
function set($param, $value) { // json_encode & co supportano solo UTF-8 // questo controllo aiuta a prevenire errori nell'invio // di stringhe. Nota che un array di stringhe non verra' if (is_string($value)) { Charset::AssureUtf8($value); } $this->values[$param] = $value; }
public static function Decod_Header($variable, $charset_conv = "utf-8") { $decod = imap_mime_header_decode($variable); if (array_key_exists(0, $decod)) { if ($decod[0]->charset == "default") { $subject = $variable; } else { if ($decod[0]->text != "") { $subject = Charset::CambiaCharset($decod[0]->text, $decod[0]->charset, $charset_conv); } } } else { $subject = $variable; } return $subject; }
function onContentPrepare($context, &$article, &$params, $page = 0) { $input = JFactory::getApplication()->input; $view = $input->get('view'); if (strstr(@$_SERVER["HTTP_REFERER"], "view=form") && strstr(@$_SERVER["HTTP_REFERER"], "layout=edit")) { return false; } $cosa_mostrare = $this->params->get("cosa_mostrare"); if (!is_array($cosa_mostrare)) { $cosa_mostrare = array($cosa_mostrare); } $cats = $this->params->get("category"); if (!is_array($cats)) { $cats = array($cats); } $counter = $this->params->get("counter", "0"); $position = $this->params->get("position", "top"); $css = $this->params->get("css", "color:#000; font-family:Arial; font-size:14px; line-height:19px; padding:20px;"); $memory_limit = $this->params->get("memory_limit", "25"); $visual_pdf = $this->params->get("visual_pdf", "0"); $show_in_blog = $this->params->get("show_in_blog", "0"); $icon_position = $this->params->get("icon_position", "left"); if ($show_in_blog == 0 && ($view == "featured" || $view == "category")) { return false; } if ($icon_position == "right") { $document = JFactory::getDocument(); $style = '.stButton { float: right !important; }'; $document->addStyleDeclaration($style); } if ($visual_pdf == 1) { $visual_pdf = 0; } else { $visual_pdf = 1; } //se l'articolo non è della giusta categoria esce subito $categoria_presente = 0; foreach ($cats as $cat) { if (@$article->catid == $cat) { $categoria_presente = 1; } } if ($categoria_presente == 0) { return false; } else { echo '<link rel="stylesheet" href="' . JURI::base() . 'plugins/content/articletool/style/style.css" type="text/css" />'; if (JRequest::getVar('print', 0, 'get') != 1 && JRequest::getVar('download', 0, 'get') != 1) { //inserisce gli script per far funzionare sharethis foreach ($cosa_mostrare as $ico) { if ($ico != "stampa" && $ico != "scarica") { $http = ""; if ($_SERVER["REQUEST_SCHEME"] == "https") { $http = "s"; } $article->text .= '<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http' . $http . '://w' . $http . '.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher: "cf4e376e-1d9c-43b1-8df7-617e403ae918", doNotHash: false, doNotCopy: false, hashAddressBar: false});</script>'; break; } } $icone = ""; $uri = JFactory::getURI(); //mostro le icone dei social, invia per mail, stampa e scarica foreach ($cosa_mostrare as $ico) { if ($ico == "stampa") { $uri->setVar('print', 1); $uri->setVar('download', 0); $uri->setVar('id', $article->id); if ($counter == 0) { $icone .= "\n\t\t\t\t\t\t\t<span class='stButton stButton_print'>\n\t\t\t\t\t\t\t<a id='article_tool_print' href='" . $uri->toString() . "' target='_blank'>\n\t\t\t\t\t\t\t\t<img src='" . JURI::base() . "plugins/content/articletool/images/print.png' />\n\t\t\t\t\t\t\t</a></span>"; } else { $icone .= "<a id='article_tool_print' href='" . $uri->toString() . "' target='_blank'>\n\t\t\t\t\t\t\t<span class='stButton'><span class='stButton_gradient'>\n\t\t\t\t\t\t\t\t<img src='" . JURI::base() . "plugins/content/articletool/images/print.png' />\n\t\t\t\t\t\t\t<span class='chicklets chicklets_article_tool_print'>Print</span></span></span></a>"; } } else { if ($ico == "scarica") { $uri->setVar('print', 0); $uri->setVar('download', 1); $uri->setVar('id', $article->id); if ($counter == 0) { $icone .= "\n\t\t\t\t\t\t\t<span class='stButton stButton_pdf'>\n\t\t\t\t\t\t\t<a id='article_tool_pdf' href='" . $uri->toString() . "' target='_blank'>\n\t\t\t\t\t\t\t\t<img src='" . JURI::base() . "plugins/content/articletool/images/pdf.png' />\n\t\t\t\t\t\t\t</a></span>"; } else { $icone .= "<a id='article_tool_pdf' href='" . $uri->toString() . "' target='_blank'>\n\t\t\t\t\t\t\t<span class='stButton'><span class='stButton_gradient'>\n\t\t\t\t\t\t\t\t<img src='" . JURI::base() . "plugins/content/articletool/images/pdf.png' />\n\t\t\t\t\t\t\t<span class='chicklets chicklets_article_tool_pdf'>Download</span></span></span></a>"; } } else { $url_corrente = substr(JURI::base(), 0, -1) . JRoute::_(ContentHelperRoute::getArticleRoute($article->slug, $article->catid)); if ($counter == 0) { $type = "large"; } else { $type = "hcount"; } $icone .= '<span class="st_' . $ico . '_' . $type . '" st_url="' . $url_corrente . '" displayText="' . $ico . '"></span>'; } } } if ($position == "top") { $article->text = "<div class='article_tool_container'>" . $icone . "</div><div class='article_tool_separator'></div>" . $article->text; } if ($position == "bottom") { $article->text .= "<div class='article_tool_container'>" . $icone . "</div><div class='article_tool_separator'></div>"; } } if (!function_exists('relative_to_absolute')) { function relative_to_absolute($article, $home) { preg_match_all('/src="(.+?)"/', $article->text, $src); preg_match_all('/href="(.+?)"/', $article->text, $href); $urls = array_merge($src[1], $href[1]); foreach ($urls as $url) { if (!strstr($url, "http://") && !strstr($url, "https://")) { $sepsl = "/"; if (substr($home, -1, 1) == "/") { $sepsl = ""; } $article->text = str_replace('"' . $url . '"', $home . $sepsl . $url, $article->text); } } return $article->text; } } $article->text = relative_to_absolute($article, JURI::base()); if (!function_exists('get_article_by_get')) { function get_article_by_get() { $db = JFactory::getDBO(); $sql = "SELECT * FROM #__content WHERE id = " . JRequest::getVar('id', 0, 'get'); $db->setQuery($sql); $fullArticle = $db->loadAssocList(); return $fullArticle[0]["introtext"] . $fullArticle[0]["fulltext"]; } } $charset = new Charset(); if (JRequest::getVar('print', 0, 'get') == 1) { $article->text = get_article_by_get(); $article->text = relative_to_absolute($article, JURI::base()); $article->text .= ' <script type="text/javascript"> window.print(); window.close(); </script> '; echo "<meta http-equiv='content-type' content='text/html; charset=" . $charset->get() . "' /><div style='" . $css . "'>" . $article->text . "</div>"; JFactory::getApplication()->close(); die(""); } if (JRequest::getVar('download', 0, 'get') == 1) { $article->text = get_article_by_get(); $article->text = relative_to_absolute($article, JURI::base()); //$txt_to_rend=file_get_contents(JURI::current()); $txt_to_rend = "<meta http-equiv='content-type' content='text/html; charset=" . $charset->get() . "' /><div style='" . $css . "'>" . $article->text . "</div>"; require_once "plugins/content/articletool/dompdf/dompdf_config.inc.php"; if (get_magic_quotes_gpc()) { $txt_to_rend = stripslashes($txt_to_rend); } $old_limit = ini_set("memory_limit", $memory_limit . "M"); $dompdf = new DOMPDF(); $dompdf->load_html($txt_to_rend); $dompdf->set_paper("portrait", "letter"); $dompdf->render(); /*i pdf possono essere messi in cache, vedere se nella jed ci sono componenti article to pdf*/ $dompdf->stream($article->title . ".pdf", array("Attachment" => $visual_pdf)); JFactory::getApplication()->close(); die(""); } return true; } }
/** * Mime header value decoder. Usually unicode characters are encoded * according to RFC-2047. This function will decode RFC-2047 encoded * header values as well as detect headers which are not encoded. * * Caveats: * If headers contain non-ascii characters the result of this function * is completely undefined. If osTicket is corrupting your email * headers, your mail software is not encoding the header text * correctly. * * Returns: * Header value, transocded to UTF-8 */ function mime_decode($text, $encoding = 'utf-8') { // Handle poorly or completely un-encoded header values ( if (function_exists('mb_detect_encoding')) { if (($src_enc = mb_detect_encoding($text)) && strcasecmp($src_enc, 'ASCII') !== 0) { return Charset::transcode($text, $src_enc, $encoding); } } // Handle ASCII text and RFC-2047 encoding $str = ''; $parts = imap_mime_header_decode($text); foreach ($parts as $part) { $str .= $this->mime_encode($part->text, $part->charset, $encoding); } return $str ? $str : imap_utf8($text); }
public static function Inserta_Actualiza_Registros($conexion, $tabla, $registros, $parametros, $seleccion, $codif_fte = 'CP850', $codif_dest = 'UTF-8') { foreach ($registros as $r) { $linea_sel = array(); $linea_ins = array(); $linea_upd = array(); foreach ($parametros as $k => $p) { $linea_upd[$k] = strcmp(substr($p, 0, 1), ':') ? Charset::CambiaCharset($r[$p], $codif_fte, $codif_dest) : substr($p, 1, strlen($p) - 1); } foreach ($seleccion as $k => $p) { $linea_sel[$k] = strcmp(substr($p, 0, 1), ':') ? Charset::CambiaCharset($r[$p], $codif_fte, $codif_dest) : substr($p, 1, strlen($p) - 1); } $linea_ins = array_merge($linea_sel, $linea_upd); try { Conexion::Inserta_Registro($conexion, $tabla, $linea_ins); } catch (Exception $e) { Conexion::Actualiza_Registro($conexion, $tabla, $linea_upd, $linea_sel); } } }
/** * Parse RFC 2397 formatted data strings. Format according to the RFC * should look something like: * * data:[type/subtype][;charset=utf-8][;base64],data * * Parameters: * $data - (string) RFC2397 formatted data string * $output_encoding - (string:optional) Character set the input data * should be encoded to. * $always_convert - (bool|default:true) If the input data string does * not specify an input encding, assume iso-8859-1. If this flag is * set, the output will always be transcoded to the declared * output_encoding, if set. * * Returs: * array (data=>parsed and transcoded data string, type=>MIME type * declared in the data string or text/plain otherwise) * * References: * http://www.ietf.org/rfc/rfc2397.txt */ function parseRfc2397($data, $output_encoding = false, $always_convert = true) { if (substr($data, 0, 5) != "data:") { return array('data' => $data, 'type' => 'text/plain'); } $data = substr($data, 5); list($meta, $contents) = explode(",", $data, 2); if ($meta) { list($type, $extra) = explode(";", $meta, 2); } else { $extra = ''; } if (!isset($type) || !$type) { $type = 'text/plain'; } $parameters = explode(";", $extra); # Handle 'charset' hint in $extra, such as # data:text/plain;charset=iso-8859-1,Blah # Convert to utf-8 since it's the encoding scheme for the database. $charset = $always_convert ? 'iso-8859-1' : false; foreach ($parameters as $p) { list($param, $value) = explode('=', $extra); if ($param == 'charset') { $charset = $value; } elseif ($param == 'base64') { $contents = base64_decode($contents); } } if ($output_encoding && $charset) { $contents = Charset::transcode($contents, $charset, $output_encoding); } return array('data' => $contents, 'type' => $type); }
/** * @dataProvider providerForInvalidCharset * @expectedException Respect\Validation\Exceptions\CharsetException */ public function testInvalidCharsetShouldFailAndThrowCharsetException($charset, $input) { $validator = new Charset($charset); $this->assertFalse($validator->__invoke($input)); $this->assertFalse($validator->assert($input)); }
<?php define('in_flow', true); @(include_once '../inc/global.inc.php'); include 'lib/charset.php'; init_adodb(); init_smarty(); global $smarty, $cfg, $db; if (!isset($_POST['postflag'])) { $pic = rand(1, 17); $smarty->assign("picid", $pic); $smarty->display("login.html"); } else { $_POST['username'] = Charset::convert($_POST['username'], "utf8", "gbk"); if (login($_POST['username'], MD5($_POST['password'])) == true) { echo "success"; exit; } else { echo "fail"; exit; } }
/** * 转换编码 * @param int $origen 原始字符串 * @param String $from_charset 原始编码 Big5, GBK, Utf-8, ISO-8851-1 ... * @param String $to_charset 目标编码 */ function convert($origen, $from_charset, $to_charset) { return Charset::instance($from_charset, $to_charset)->Convert($origen); }
static function buildHashFile($mofile, $outfile = false, $return = false) { if (!$outfile) { $stream = fopen('php://stdout', 'w'); } elseif (is_string($outfile)) { $stream = fopen($outfile, 'w'); } elseif (is_resource($outfile)) { $stream = $outfile; } if (!$stream) { throw new InvalidArgumentException('Expected a filename or valid resource'); } if (!$mofile instanceof FileReader) { $mofile = new FileReader($mofile); } $reader = new parent($mofile, true); if ($reader->short_circuit || $reader->error) { throw new Exception('Unable to initialize MO input file'); } $reader->load_tables(); // Get basic table if (!($table = $reader->cache_translations)) { throw new Exception('Unable to read translations from file'); } // Transcode the table to UTF-8 $header = $table[""]; $info = array(); preg_match('/^content-type: (.*)$/im', $header, $info); $charset = false; if ($content_type = $info[1]) { // Find the charset property $settings = explode(';', $content_type); foreach ($settings as $v) { @(list($prop, $value) = explode('=', trim($v), 2)); if (strtolower($prop) == 'charset') { $charset = trim($value); break; } } } if ($charset && strcasecmp($charset, 'utf-8') !== 0) { foreach ($table as $orig => $trans) { $table[Charset::utf8($orig, $charset)] = Charset::utf8($trans, $charset); unset($table[$orig]); } } // Add in some meta-data $table[self::META_HEADER] = array('Revision' => $reader->revision, 'Total-Strings' => $reader->total, 'Table-Size' => count($table), 'Build-Timestamp' => gmdate(DATE_RFC822), 'Format-Version' => 'A', 'Encoding' => 'UTF-8'); // Serialize the PHP array and write to output $contents = sprintf('<?php return %s;', var_export($table, true)); if ($return) { return $contents; } else { fwrite($stream, $contents); } }
/** * json_encode * * @param mixvar $var 多类型变量 * @param string $charset 默认'utf-8'源变量中字符编码 'utf-8' or 'gb2312' or 'big5' * @return string */ public static function jsonencode($var, $charset = NULL) { if (is_null($charset)) { $charset = self::$source_lang; } else { self::$source_lang = $charset; } if (!$charset) { $charset = 'utf-8'; } switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (double) $var; case 'string': $var = strtr($var, array("\r" => '\\r', "\n" => '\\n', "\t" => '\\t', "\\b" => '\\b', "\f" => '\\f', '\\' => '\\\\', '"' => '\\"', "" => '\\b', "\f" => '\\f')); $var = self::escape($var, $charset); return '"' . $var . '"'; case 'array': return self::encodearray($var); case 'object': $var = get_object_vars($var); return self::encodearray($var); default: return 'null'; } }
/** * Sends a trace. * * @param string $message Message text * @param string $file File name * @param integer $line File line * @param array $trace Trace * @return boolean */ public static function trace(string $message, string $file, int $line, array $trace) : bool { $output = [['Type' => self::TRACE, 'Label' => null], ['Message' => Charset::fixUtf($message), 'File' => $file, 'Line' => $line, 'Trace' => self::replaceVariable($trace)]]; return self::send($output); }
$NewFileOutput = $NewEncoding->Convert($NewFileOutput, $encFrom, $encTo, $Entities); } writeFile(LANG_ABS_PATH . "/utf8/lang-{$lang}.php", $NewFileOutput); } // ---------------------------------- // Now do the countries files // ---------------------------------- $FileName = LANG_ABS_PATH . "/source/countries-{$lang}.php"; $File = file($FileName); $FileText = implode("", $File); writeFile(LANG_ABS_PATH . "/iso/countries-{$lang}.php", $FileText); if (!$convert_to_utf_mannually) { $FileText = str_replace("charset={$encFrom}", "charset=utf-8", $FileText); if ($lang == 'chinese') { require_once dirname(__FILE__) . "/lib/ConvertCharset/chinese/charset.class.php"; $FileText = Charset::convert($FileText, 'gb2312', 'utf-8'); } else { $FileText = str_replace("charset={$encFrom}", "charset=utf-8", $FileText); $FileText = $NewEncoding->Convert($FileText, $encFrom, $encTo, $Entities); } writeFile(LANG_ABS_PATH . "/utf8/countries-{$lang}.php", $FileText); } echo "<strong>Converted {$lang}</strong><hr><BR>"; //break; } } // end if admin_op echo "<ul>"; echo "<li><a href='" . getLeonardoLink(array('op' => 'admin_languages', 'admin_op' => 'update')) . "'>Process ALL language files and create/update files in 'utf8'/'iso' dirs</a></li>"; foreach ($availableLanguages as $lang) { echo "<li><a href='" . getLeonardoLink(array('op' => 'admin_languages', 'admin_op' => 'update', 'update_lang' => $lang)) . "'>Process only " . strtoupper($lang) . " language files</a></li>";
<?php define('in_flow', true); @(include_once '../inc/global.inc.php'); include 'lib/charset.php'; init_adodb(); init_smarty(); global $smarty, $cfg, $db; $tbl_article = $cfg['tbl_article']; if (!isset($_POST['postflag'])) { $sql = "select id,heading,score,editor from {$tbl_article} where id = " . intval($_GET['article_id']); $arr = $db->GetRow($sql); $arr['heading'] = Charset::convert($arr['heading'], "gbk", "utf8"); $arr['editor'] = Charset::convert($arr['editor'], "gbk", "utf8"); $smarty->assign("article", $arr); $smarty->display("givescore.html"); } else { $privileges_check = "givescore"; $sql = "select catalog from {$tbl_article} where id = " . intval($_POST['article_id']); $catalog_id = $db->GetOne($sql); if (!checkpower($catalog_id, GetUid(), 3)) { echo intval($_POST['fscore']); exit; } else { $sql = "update {$tbl_article} set score = " . intval($_POST['score']) . " where id = " . intval($_POST['article_id']) . " limit 1"; if ($db->Execute($sql)) { echo intval($_POST['score']); } else { echo intval($_POST['fscore']); } }
params: topic_id: id del topic (base) su cui aggiungere una risposta message: messaggio returns: success: false => errore, true => OK post_html: html contenente il post appena inserito */ require_once "__inc__.php"; $response = new RestfulResponse("json"); $av = new AutoValidator("frm-forum-reply", $_POST); if ($av->validate()) { if ($currentUser->isLogged()) { // Valida i campi di input validate_num($_POST['topic_id']); $topic = new Topic($_POST['topic_id']); $message = db_escape(Charset::Utf8ToDB($_POST['message'])); if (!Forum::IsUserFlooding($currentUser)) { if (!$topic['locked']) { // Trova il forum_id $values = DB::FindOne("SELECT argument FROM forum_posts WHERE id = {$_POST['topic_id']}"); $forum_id = $values['argument']; exequery(sprintf("INSERT INTO forum_posts (user_id, root_topic, argument, message, type, post_date, last_post_date, ip) \n VALUES(%d, %d, %d, '%s', %d, %d, %d, '%s')", $currentUser['id'], $_POST['topic_id'], $forum_id, $message, Forum::TYPE_POST, time(), time(), get_ip())); $id = DB::LastId(); $post = new ForumPost($id); Forum::UpdateTopicAfterReply($_POST['topic_id']); Forum::IncPostCountForUser($currentUser); Forum::AddReplyNotifications($post['id']); $response->set("post_html", $post->render("forum/post.html")); $response->setSuccess(true); } else { $response->setError("Il topic e' stato chiuso dal moderatore.");
function transliterate($str, $enc) { // see this for hebraic-chinisee // http://www.derickrethans.nl/translit.php global $CONF_use_utf; if ($enc == 'gb2312') { // echo "#### $str $enc ##"; if (!$CONF_use_utf) { require_once dirname(__FILE__) . "/lib/ConvertCharset/convert_gb2312.php"; return gb2312_to_latin($str); } else { if (substr(phpversion(), 0, 1) >= 5) { require_once dirname(__FILE__) . "/lib/ConvertCharset/chinese/charset.class.php"; $gb2312_str = Charset::convert($str, 'utf-8', 'gb2312'); $str2 = Charset::PinYin($gb2312_str, 'gb2312'); // echo "^gb2312_str : $gb2312_str ^ "; // echo "^str2: $str2 ^ "; return $str2; } else { return $str; } } } require_once dirname(__FILE__) . "/lib/ConvertCharset/ConvertCharset.class.php"; require_once dirname(__FILE__) . "/lib/utf8_to_ascii/utf8_to_ascii.php"; // if $CONF_use_utf it means the $str is already in utf // so translitarate it directly if ($CONF_use_utf) { return utf8_to_ascii($str); } $NewEncoding = new ConvertCharset(); $str_utf8 = $NewEncoding->Convert($str, $enc, "utf-8", $Entities); return utf8_to_ascii($str_utf8); }
protected static function BIG2GB() { $ret = ''; while (self::$string) { if (ord(self::$string[0]) > 0x80) { $index = hexdec(bin2hex(self::$string[0] . self::$string[1])); $value = self::$table[$index]; $ret .= self::hex2bin(dechex($value)); self::$string = substr(self::$string, 2); } else { $ret .= self::$string[0]; self::$string = substr(self::$string, 1); } } return $ret; }
/** * Tests checking text on containing cyrillic symbols * @covers \Copycat\System\Charset::isCyrillic() */ public function testIsCyrillic() { $this->assertTrue(Charset::isCyrillic('тест')); $this->assertFalse(Charset::isCyrillic('test')); }
function mime_encode($text, $charset = null, $encoding = 'utf-8') { return Charset::transcode($text, $charset, $encoding); }
/** * Perform simple operations to make data consistent between JSON and * XML data types */ function fixup($current) { global $cfg; if ($current['ticket']) { $current = $current['ticket']; } if (!is_array($current)) { return $current; } foreach ($current as $key => &$value) { if ($key == "phone" && is_array($value)) { $value = $value[":text"]; } else { if ($key == "alert") { $value = (bool) (strtolower($value) === 'false' ? false : $value); } else { if ($key == "autorespond") { $value = (bool) (strtolower($value) === 'false' ? false : $value); } else { if ($key == "message") { if (!is_array($value)) { $value = array("body" => $value, "type" => "text/plain"); } else { $value["body"] = $value[":text"]; unset($value[":text"]); } if (isset($value['encoding'])) { $value['body'] = Charset::utf8($value['body'], $value['encoding']); } if (!strcasecmp($value['type'], 'text/html')) { $value = new HtmlThreadBody($value['body']); } else { $value = new TextThreadBody($value['body']); } } else { if ($key == "attachments") { if (!isset($value['file'][':text'])) { $value = $value['file']; } if ($value && is_array($value)) { foreach ($value as &$info) { $info["data"] = $info[":text"]; unset($info[":text"]); } unset($info); } } else { if (is_array($value)) { $value = $this->fixup($value); } } } } } } } unset($value); return $current; }
method: POST params: to : nome dell'utente a cui inviare i messaggi subject : oggetto del messaggio message : testo del messaggio important : flag se il messaggio è importante o no multiple : flag se il messaggio è multiplo o no returns: success: false => errore, true => OK */ require_once "__inc__.php"; $response = new RestfulResponse(); //Salvo i parametri $to = Charset::Utf8ToDB($_POST['to']); $subject = Charset::Utf8ToDB($_POST['subject']); $message = Charset::Utf8ToDB($_POST['message']); $important = isset($_POST['important']) ? $_POST['important'] : false; //boolean $multiple = isset($_POST['multiple']) ? $_POST['multiple'] : false; //boolean $av = new AutoValidator("message-write", $_POST); if ($av->validate()) { //Controllo solo multiple, to e important (gli altri due vengono controllati in MessageService) $important = $currentUser->isAdmin() && $important ? 1 : 0; $multiple = $multiple == "true"; if ($multiple != 1) { $to = db_escape($to); $to = DB::FindOne("SELECT id FROM users WHERE user='******' LIMIT 1"); $to = (int) $to['id']; } $ms = new MessageService($currentUser['id']);
*/ require_once "__inc__.php"; $response = new RestfulResponse("json"); $av = new AutoValidator("frm-forum-post", $_POST); if ($av->validate()) { if ($currentUser->isLogged()) { // Valida i campi di input validate_num($_POST['forum_id']); $subject = db_escape(Charset::Utf8ToDB($_POST['subject'])); $message = db_escape(Charset::Utf8ToDB($_POST['message'])); $is_poll = isset($_POST['poll']); // Le domande del sondaggio vengono memorizzate nel campo // "poll" come array serializzato. Se "poll" e' null, allora // vuol dire che il topic non e' un sondaggio if ($is_poll) { $poll_questions = explode("\n", trim(purify(Charset::Utf8ToDB($_POST['poll'])))); if (count($poll_questions) >= 2) { $poll_data = db_escape(serialize($poll_questions)); } else { // Numero di domande nel sondaggio non valido (< 2) $poll_data = null; } } if (!Forum::IsUserFlooding($currentUser)) { exequery(sprintf("INSERT INTO forum_posts (user_id, argument, subject, message, type, post_date, last_post_date, ip, poll, replies) \n VALUES(%d, %d, '%s', '%s', %d, %d, %d, '%s', \"%s\", 0)", $currentUser['id'], $_POST['forum_id'], $subject, $message, Forum::TYPE_TOPIC, time(), time(), get_ip(), $poll_data)); $id = DB::LastId(); $topic = new Topic($id); Forum::IncPostCountForUser($currentUser); $response->set("topic_url", $topic->getUrl()); $response->setSuccess(true); } else {
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** Permette di cercare il nome di un utente da una parte del nome method: POST params: name : parte del nome da cercare num_records : numero massimo di nomi che deve ritornare (limite di 50 per evitare di dare troppe informazioni) returns: results : array con nomi degli utenti */ require_once "__inc__.php"; $response = new RestfulResponse("json"); if (isset($_POST['term'])) { $term = Charset::Utf8ToDB($_POST['term']); $num_records = @$_POST['num_records']; // Validazione if (!isset($num_records)) { $num_records = 20; } if ($num_records > 50) { $num_records = 50; } $results = UserSearch::Find($term, $num_records); $response->set('results', $results); $response->setSuccess(true); } else { $response->setError("Missing term param"); } $response->send();
public function testConvertInteger() { $this->assertEquals('✖', Charset::convertInteger(Charset::UNICODE_CROSS_CHAR)); $this->assertEquals('✔', Charset::convertInteger(Charset::UNICODE_CHECKMARK_CHAR)); }
method: POST params: hash: username e password oscurati (vedi /js/site.js Login.encrypt) returns: success: false => errore, true => OK error: messaggio di errore se success e' false */ require_once "__inc__.php"; $response = new RestfulResponse("json"); $av = new AutoValidator("frm-register", $_POST); if ($av->validate()) { if (isset($_POST['question']) && $_POST['question'] == "10") { $email = db_escape(purify(trim(Charset::Utf8ToDB($_POST['email'])))); $creds = LoginUtils::HashToCredentials(db_escape($_POST['hash'])); $username = db_escape(purify(trim(Charset::Utf8ToDB($creds['username'])))); $password = db_escape(purify(trim(Charset::Utf8ToDB($creds['password'])))); // Username libero? if (!DB::FindOne("SELECT 1 FROM users WHERE user = \"{$username}\"")) { // Legacy: Un timestamp sarebbe stato meglio, ma non dobbiamo fare nulla con questo dato, quindi va bene cosi' $data = date("d/m/Y G:i"); $description = "Normal User"; $md5 = LoginUtils::Md5FromCredentials($username, $password); // Tutto a posto exequery(sprintf('INSERT INTO users (user, mail, ip, os_browser, date, description, permission, verified, md5, last_login_timestamp, last_login_ip, newsletter) VALUES ("%s", "%s", "%s", "%s", "%s", "%s", %s, %s, "%s", %s, "%s", %s)', $username, $email, get_ip(), db_escape(purify($_SERVER["HTTP_USER_AGENT"])), $data, $description, User::PERMISSION_USER, 1, $md5, time(), get_ip(), 1)); // Logga l'utente $currentUser = UserFactory::CreateFromCredentials($username, $password); if ($currentUser->isLogged()) { $response->setSuccess(true); // Logga Log::Info(sprintf("%s si e' registrato", $currentUser['username']));
function getBody($type = 'text/html', $encoding = false) { // First select the body switch ($type) { case 'text/html': $body = $this->BodyHtml; break; default: return false; } // Figure out the source encoding (§5.1.2) $charset = false; if (@$this->OemCodepage) { $charset = 'cp' . $this->OemCodepage; } elseif (@$this->InternetCodepage) { $charset = 'cp' . $this->InternetCodepage; } // Transcode it if ($encoding && $charset) { $body = Charset::transcode($body, $charset, $encoding); } return $body; }
/** * Sends a trace. * * @param string $message Message text * @param string $file File name * @param integer $line File line * @param array $trace Trace * @return boolean */ public static function trace($message, $file, $line, array $trace) { $output = array(array('Type' => self::TRACE, 'Label' => null), array('Message' => Charset::fixUtf($message), 'File' => $file, 'Line' => $line, 'Trace' => self::replaceVariable($trace))); return self::send($output); }
<?php /** Si occupa di recuperare la password dell'utente method: POST params: hash: obscured username and password (see /js/site.js Login.encrypt) usecookie: "0" => do not set cookie, "1" => set cookie returns: success: "0" => error happened, "1" => OK banned_message (optional): a ban message if the user is currently banned */ require_once "__inc__.php"; $response = new RestfulResponse("json"); $username = db_escape(Charset::Utf8ToDB($_POST['user'])); $userObj = new User("user = \"{$username}\""); if ($userObj->isValid()) { $ip = get_ip(); $url = $site_url . "/p/login/resetPassword.php?token={$userObj['md5']}&uid={$userObj['id']}"; $message = $userObj['username'] . ",<br/>\nè stata inoltrata una richiesta da [{$ip}] per resettare la tua password su <a href=\"{$site_url}\">www.pierotofy.it</a>.<br/>\n<br/>\nPer continuare la procedura visita il link qui sotto riportato:<br/><br/>\n\n<a href=\"{$url}\">{$url}</a>\n"; try { if (Mailer::SendEmail("*****@*****.**", "*****@*****.**", "Recupero password", $message)) { $response->setSuccess(true); } else { $response->setError("E' successo un errore durante l'invio dell'e-mail."); } } catch (Exception $e) { $response->setError("Eccezione: " . $e->getMessage()); } } else { $response->setError("L'utente non e' valido.");