protected static function checkFileContent()
 {
     $fileContent = file_get_contents(static::$tmpFilepath);
     // check encoding and convert to utf-8 when necessary
     $detectedEncoding = mb_detect_encoding($fileContent, 'UTF-8, ISO-8859-1, WINDOWS-1252', true);
     if ($detectedEncoding) {
         if ($detectedEncoding !== 'UTF-8') {
             $fileContent = iconv($detectedEncoding, 'UTF-8', $fileContent);
         }
     } else {
         echo 'Zeichensatz der CSV-Date stimmt nicht. Der sollte UTF-8 oder ISO-8856-1 sein.';
         return false;
     }
     //prepare data array
     $tmpData = str_getcsv($fileContent, PHP_EOL);
     array_shift($tmpData);
     $preparedData = [];
     $data = array_map(function ($row) use(&$preparedData) {
         $tmpDataArray = str_getcsv($row, ';');
         $tmpKey = trim($tmpDataArray[0]);
         array_shift($tmpDataArray);
         $preparedData[$tmpKey] = $tmpDataArray;
     }, $tmpData);
     // generate json
     $jsonContent = json_encode($preparedData, JSON_HEX_TAG | JSON_HEX_AMP);
     self::$jsonContent = $jsonContent;
     return true;
 }
Example #2
2
 /**
  * @todo перенести в комманды
  * Контроллер для записи Категорий
  * @Secure(roles = "ROLE_ADMIN")
  * @Route("/testxmlcat", name = "testcategories")
  */
 public function reParceCategoriesAction()
 {
     $html = file_get_contents("http://www.medknigaservis.ru/ervr/medknigaservis.xml");
     $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
     $html = iconv("windows-1251", "utf-8", $html);
     $saw = new \nokogiri($html);
     $xml = $saw->get('category')->toArray();
     #echo '<pre>';
     #print_r($xml);
     #echo '</pre>';
     #echo '<hr />';
     for ($i = 0; true; $i++) {
         if (isset($xml[$i]['#text'][0])) {
             echo '<b>' . $xml[$i]['#text'][0] . '</b><br />';
             $cat = new MarketCategory();
             $cat->setName($xml[$i]['#text'][0]);
             $cat->setOfferId($xml[$i]['id']);
             $em = $this->getDoctrine()->getManager();
             $em->persist($cat);
             $em->flush();
         } else {
             break;
         }
     }
     return $this->render('EvrikaMainBundle:Shop:main.html.twig');
 }
Example #3
0
function addm($char, $mes, $priv)
{
    setlocale(LC_ALL, "ru_RU.CP1251");
    if (!isset($char['sex']) || $char['sex'] == "male") {
        $mes = preg_replace("/\\{([\\d\\w\\s]*?)\\|([\\d\\w\\s]*?)\\}/i", "\\1", $mes);
    } else {
        $mes = preg_replace("/\\{([\\d\\w\\s]*?)\\|([\\d\\w\\s]*?)\\}/i", "\\2", $mes);
    }
    $mes = '<span style="color:#FF2828;font-size:12px;">' . iconv("Windows-1251", "UTF-8//IGNORE", $mes) . '</style>';
    $message = $mes;
    $message = mysql_real_escape_string($message);
    $sel = myquery("SELECT `count` FROM `game_bot_chat_resp` WHERE `id` = '" . $char['name'] . "';");
    $n = mysql_fetch_array($sel);
    if ($n['count'] <= 4) {
        myquery("INSERT INTO `game_bot_chat_resp` (`id`,`count`) VALUES ('" . $char['name'] . "','1') ON DUPLICATE KEY UPDATE `count` = `count` + 1;");
        $update_chat = myquery("insert into game_log (town,fromm,too,message,date,ptype) values (0,'-1','" . $char['user_id'] . "','" . $message . "','" . time() . "'," . $priv . ")");
    } else {
        $sel = myquery("SELECT `text` FROM `game_bot_chat_annoy` ORDER BY RAND() ASC LIMIT 1");
        $mes = mysql_fetch_array($sel);
        if (!isset($char['sex']) || $char['sex'] == "male") {
            $mes = preg_replace("/\\{([\\d\\w\\s]*?)\\|([\\d\\w\\s]*?)\\}/i", "\\1", $mes);
        } else {
            $mes = preg_replace("/\\{([\\d\\w\\s]*?)\\|([\\d\\w\\s]*?)\\}/i", "\\2", $mes);
        }
        $message = mysql_real_escape_string('<span style="color:#FF2828;font-size:12px;">' . iconv("Windows-1251", "UTF-8//IGNORE", $mes['text']) . '</style>');
        $update_chat = myquery("insert into game_log (town,fromm,too,message,date,ptype) values (0,'-1','" . $char['user_id'] . "','" . $message . "','" . time() . "'," . $priv . ")");
    }
}
Example #4
0
 private function profileDefault($mode = 'run', $priceType = null)
 {
     if ($mode == 'info') {
         return ['name' => 'Базовый', 'description' => 'Профиль по умолчанию'];
     }
     if ($mode == 'run') {
         $offers = \app\models\Offers::find()->all();
         $arCsv = ['Название;Поставщик;Исходная цена;Посчитанная цена;Количество'];
         $providers = \app\models\Providers::find()->all();
         $arProviders = [];
         foreach ($providers as $value) {
             $arProviders[$value->id] = $value->name;
         }
         foreach ($offers as $offer) {
             $name = \app\components\Goods::getName($offer->goods_id);
             $provider = $arProviders[$offer->providers_id];
             $price = $offer->price;
             $quantity = $offer->quantity;
             //                print $name;
             $calcPrice = $price * \app\components\CalculationDiscount::calc($offer->goods_id, $offer->providers_id, $priceType);
             //                $calcPrice =  \app\components\CalculationDiscount::calc($offer);
             $arCsv[] = "{$name};{$provider};{$price};{$calcPrice};{$quantity}";
         }
         $csv = implode(chr(10), $arCsv);
         $this->_unloadStr('prise.csv', iconv('utf-8', 'windows-1251', $csv));
     }
 }
 public static function sanitize($text)
 {
     $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
     $text = trim($text, '-');
     $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
     return preg_replace('~[^-\w]+~', '', $text);
 }
Example #6
0
 /**
  * @brief 编码转换
  * @param string &$str 被转换编码的字符串
  * @param string $outCode 输出的编码
  * @return string 被编码后的字符串
  */
 public static function setCode($str, $outCode = 'UTF-8')
 {
     if (self::isUTF8($str) == false) {
         return iconv('GBK', $outCode, $str);
     }
     return $str;
 }
Example #7
0
 /**
  * handle request and build XML
  * @access protected
  *
  */
 protected function buildXml()
 {
     if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_DELETE)) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
     }
     if (!isset($_GET["FileName"])) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
     }
     $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_GET["FileName"]);
     $_resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();
     if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName) || $_resourceTypeInfo->checkIsHiddenFile($fileName)) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
     }
     if (!$_resourceTypeInfo->checkExtension($fileName, false)) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
     }
     $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $fileName);
     $bDeleted = false;
     if (!file_exists($filePath)) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
     }
     if (!@unlink($filePath)) {
         $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
     } else {
         $bDeleted = true;
     }
     if ($bDeleted) {
         $thumbPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getThumbsServerPath(), $fileName);
         @unlink($thumbPath);
         $oDeleteFileNode = new Ckfinder_Connector_Utils_XmlNode("DeletedFile");
         $this->_connectorNode->addChild($oDeleteFileNode);
         $oDeleteFileNode->addAttribute("name", iconv('gbk', 'utf-8', $fileName));
         //$oDeleteFileNode->addAttribute("name", $fileName);
     }
 }
function HandleAddItem()
{
    define("CMD_ADD_OURITEM", <<<SQL
\t\tINSERT INTO our_items (name, our_category_id, art, mdate)
\t\t\tVALUES (?, ?, ?, NOW())
SQL
);
    define("CMD_SEL_OURITEM_NEWID", <<<SQL
\t\tSELECT id FROM our_items 
\t\t\tWHERE name = ? AND our_category_id = ? AND art = ?
SQL
);
    global $db;
    $newItem = iconv("UTF-8", "windows-1251", urldecode($_REQUEST["itemName"]));
    $art = "art" . $_REQUEST["parentNodeId"] . "_" . time();
    $res =& $db->query(CMD_ADD_OURITEM, array($newItem, $_REQUEST["parentNodeId"], $art));
    if (PEAR::isError($res)) {
        printError($res);
        exit;
    }
    $newId =& $db->getOne(CMD_SEL_OURITEM_NEWID, array($newItem, $_REQUEST["parentNodeId"], $art));
    if (PEAR::isError($newId)) {
        printError($newId);
        exit;
    }
    // ¬озвратить номер добавленой категории
    print trim($newId);
}
Example #9
0
 public static function translate($string)
 {
     $pinyin_table = self::$pinyin_table;
     $flow = array();
     $string = iconv('UTF-8', 'GB2312', $string);
     $length = strlen($string);
     for ($i = 0; $i < $length; $i++) {
         $h = ord($string[$i]);
         if ($h >= 0x81 and $h <= 0xfe) {
             if (isset($string[$i + 1])) {
                 $i++;
                 $l = ord($string[$i]);
                 if (isset($pinyin_table[$h][$l])) {
                     array_push($flow, $pinyin_table[$h][$l]);
                 } else {
                     array_push($flow, $h);
                     array_push($flow, $l);
                 }
             } else {
                 array_push($flow, ord($string[$i]));
             }
         } else {
             array_push($flow, ord($string[$i]));
         }
     }
     $pinyin = array();
     $size = sizeof($flow);
     for ($i = 0; $i < $size; $i++) {
         if (is_array($flow[$i])) {
             array_push($pinyin, $flow[$i][0]);
         }
     }
     return $pinyin;
 }
Example #10
0
 /**
  * @depends testLoadDOMDocument
  */
 function testLoadDOMDocumentUTF16()
 {
     $xml = '<?xml version="1.0" encoding="UTF-16"?><root xmlns="DAV:">blabla</root>';
     $xml = iconv('UTF-8', 'UTF-16LE', $xml);
     $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml);
     $this->assertEquals('blabla', $dom->firstChild->nodeValue);
 }
Example #11
0
 function utf_conv($iso, $charset, $what)
 {
     if (function_exists('iconv')) {
         $what = iconv($iso, $charset, $what);
     }
     return $what;
 }
Example #12
0
 public static function prepare()
 {
     if ($_SERVER['CONTENT_TYPE'] && preg_match('/charset=([^;]*)/', $_SERVER['CONTENT_TYPE'], $matches)) {
         $encoding = strtoupper($matches[1]);
     } else {
         $encoding = ENCODING;
     }
     $urlencoded = strpos($_SERVER['CONTENT_TYPE'], 'urlencoded');
     foreach ($_REQUEST as $var => $val) {
         $value = $val;
         if ($urlencoded) {
             if (!is_array($value)) {
                 $value = urldecode($value);
             } else {
                 foreach ($value as $i => $v) {
                     $value[$i] = urldecode($v);
                 }
             }
         }
         if ($encoding and $encoding != ENCODING) {
             $value = iconv($encoding, ENCODING, $value);
         }
         $_REQUEST[$var] = $value;
     }
 }
Example #13
0
 public function do_iCMS($a = null)
 {
     if ($_GET['name']) {
         $name = $_GET['name'];
         $encode = mb_detect_encoding($name, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"));
         if (strtoupper($encode) != 'UTF-8') {
             if (function_exists('iconv')) {
                 $name = iconv($encode, 'UTF-8//IGNORE', $name);
             } elseif (function_exists('mb_convert_encoding')) {
                 $name = mb_convert_encoding($name, 'UTF-8//IGNORE', $encode);
             }
         }
         $val = iS::escapeStr($name);
         $field = 'name';
     } elseif ($_GET['tkey']) {
         $field = 'tkey';
         $val = iS::escapeStr($_GET['tkey']);
     } elseif ($_GET['id']) {
         $field = 'id';
         $val = (int) $_GET['id'];
     } else {
         iPHP::throw404('标签请求出错', 30001);
     }
     return $this->tag($val, $field);
 }
Example #14
0
 public function PackMsg($arr)
 {
     $bind = unserialize($arr['MessegeContent']);
     $packstr = $bind['PackFormat'];
     $res = pack($packstr, $bind['Length'], $bind['Length2'], $bind['uType'], $bind['MsgLevel'], $bind['Line'], $bind['CountDown'], iconv("utf-8", "GB2312", $bind['MessegeContent'] . ""));
     return $res;
 }
/**
 * Wrapper around IBM AIX iconv(), whose character set naming differs
 * from the GNU version of iconv().
 *
 * @param   string   input character set
 * @param   string   output character set
 * @param   string   the string to convert
 *
 * @return  mixed    converted string or FALSE on failure
 *
 * @access  public
 *
 * @author  bwiberg  Björn Wiberg <*****@*****.**>
 */
function PMA_aix_iconv_wrapper($in_charset, $out_charset, $str)
{
    global $gnu_iconv_to_aix_iconv_codepage_map;
    // Check for transliteration argument at the end of output character set name
    $translit_search = strpos(strtolower($out_charset), '//translit');
    $using_translit = !($translit_search === FALSE);
    // Extract "plain" output character set name (without any transliteration argument)
    $out_charset_plain = $using_translit ? substr($out_charset, 0, $translit_search) : $out_charset;
    // Transform name of input character set (if found)
    if (array_key_exists(strtolower($in_charset), $gnu_iconv_to_aix_iconv_codepage_map)) {
        $in_charset = $gnu_iconv_to_aix_iconv_codepage_map[strtolower($in_charset)];
    }
    // Transform name of "plain" output character set (if found)
    if (array_key_exists(strtolower($out_charset_plain), $gnu_iconv_to_aix_iconv_codepage_map)) {
        $out_charset_plain = $gnu_iconv_to_aix_iconv_codepage_map[strtolower($out_charset_plain)];
    }
    // Add transliteration argument again (exactly as specified by user) if used
    // Build the output character set name that we will use
    $out_charset = $using_translit ? $out_charset_plain . substr($out_charset, $translit_search) : $out_charset_plain;
    // NOTE: Transliteration not supported; we will use the "plain" output character set name
    $out_charset = $out_charset_plain;
    // Call iconv() with the possibly modified parameters
    $result = iconv($in_charset, $out_charset, $str);
    return $result;
}
Example #16
0
 /**
  * 用户登录认证
  * @param  string  $username 用户名
  * @param  string  $password 用户密码
  * @param  integer $type     用户名类型 (1-用户名,2-邮箱,3-手机,4-UID)
  * @return integer           登录成功-用户ID,登录失败-错误编号
  */
 public function login($username, $password, $type = 1)
 {
     if (file_exists('./api/uc_login.lock')) {
         include_once './api/uc_client/client.php';
         if (strtolower(UC_CHARSET) == 'gbk') {
             $username = iconv('UTF-8', 'GBK', $username);
         }
         $uc_user = uc_user_login($username, $password, 0);
         if ($uc_user[0] == -2) {
             return '密码错误';
         } elseif ($uc_user[0] == -1) {
             return '用户不存在,或者被删除';
         } elseif ($uc_user[0] > 0) {
             if (strtolower(UC_CHARSET) == 'gbk') {
                 $uc_user[1] = iconv('GBK', 'UTF-8', $uc_user[1]);
             }
             D('member')->where(array('uid' => $uc_user[0]))->setField('nickname', $uc_user[1]);
             D('ucenter_member')->where(array('id' => $uc_user[0]))->setField('username', $uc_user[1]);
             return $uc_user[0];
         }
     } else {
         if (UC_SYNC && $username != get_username(1)) {
             return $this->ucLogin($username, $password);
         }
         return $this->model->login($username, $password, $type);
     }
 }
Example #17
0
/**
 * 获取地区父级路径路径
 * @param $parentid 父级ID
 * @param $keyid 菜单keyid
 * @param $callback json生成callback变量
 * @param $result 递归返回结果数组
 * @param $infos
 */
function ajax_getpath($parentid, $keyid, $callback, $result = array(), $infos = array())
{
    $keyid = intval($keyid);
    $parentid = intval($parentid);
    if (!$infos) {
        $datas = getcache($keyid, 'linkage');
        $infos = $datas['data'];
    }
    if (array_key_exists($parentid, $infos)) {
        $result[] = iconv(CHARSET, 'utf-8', $infos[$parentid]['name']);
        return ajax_getpath($infos[$parentid]['parentid'], $keyid, $callback, $result, $infos);
    } else {
        if (count($result) > 0) {
            krsort($result);
            $jsonstr = json_encode($result);
            echo trim_script($callback) . '(', $jsonstr, ')';
            exit;
        } else {
            $result[] = iconv(CHARSET, 'utf-8', $datas['title']);
            $jsonstr = json_encode($result);
            echo trim_script($callback) . '(', $jsonstr, ')';
            exit;
        }
    }
}
Example #18
0
 /**
  * Create new DataObject.
  *
  * @param StdClass $object
  * @param array $default Default values
  * @access public
  */
 public function __construct(array $data = null, $defaults = array())
 {
     if (array_key_exists('dbconfig', $defaults) && $defaults['dbconfig'] instanceof Flux_Config) {
         $this->_dbConfig = $defaults['dbconfig'];
         unset($defaults['dbconfig']);
     } else {
         $tmpArr = array();
         $this->_dbConfig = new Flux_Config($tmpArr);
     }
     $this->_encFrom = $this->_dbConfig->getEncoding();
     $this->_encTo = $this->_encFrom ? $this->_dbConfig->get('Convert') : false;
     if (!is_null($data)) {
         $this->_data = $data;
     }
     foreach ($defaults as $prop => $value) {
         if (!isset($this->_data[$prop])) {
             $this->_data[$prop] = $value;
         }
     }
     if ($this->_encTo) {
         foreach ($this->_data as $prop => $value) {
             $this->_data[$prop] = iconv($this->_encFrom, $this->_encTo, $value);
         }
     }
 }
Example #19
0
 public function testHTMLCleaningWithNonASCIIChars()
 {
     // this file is UTF-8 but odd comments are sent up looking like Windows-1252 so we need the
     // input text to be encoded thus otherwise the output is different
     $text = iconv('UTF-8', 'Windows-1252', "This is a curly  ’ apostrophe. Is 2 &lt; 3 ø ø €  ’ « ö à");
     $this->assertEquals("This is a curly  &rsquo; apostrophe. Is 2 &lt; 3 &oslash; &oslash; &euro;  &rsquo; &laquo; &ouml; &agrave;", prepare_comment_for_display($text));
 }
Example #20
0
 function change($data, $input, $output)
 {
     $input = strtoupper(trim($input));
     $output = strtoupper(trim($output));
     if ($input == $output) {
         return $data;
     }
     if ($input == 'UTF-8' && $output == 'ISO-8859-1') {
         $data = str_replace(array('€', '„', '“'), array('EUR', '"', '"'), $data);
     }
     if (function_exists('iconv')) {
         set_error_handler('acymailing_error_handler_encoding');
         $encodedData = iconv($input, $output . "//IGNORE", $data);
         restore_error_handler();
         if (!empty($encodedData) && !acymailing_error_handler_encoding('result')) {
             return $encodedData;
         }
     }
     if (function_exists('mb_convert_encoding')) {
         return mb_convert_encoding($data, $output, $input);
     }
     if ($input == 'UTF-8' && $output == 'ISO-8859-1') {
         return utf8_decode($data);
     }
     if ($input == 'ISO-8859-1' && $output == 'UTF-8') {
         return utf8_encode($data);
     }
     return $data;
 }
Example #21
0
 /**
  * Generate a partial report for a single processed file.
  *
  * Function should return TRUE if it printed or stored data about the file
  * and FALSE if it ignored the file. Returning TRUE indicates that the file and
  * its data should be counted in the grand totals.
  *
  * @param array   $report      Prepared report data.
  * @param boolean $showSources Show sources?
  * @param int     $width       Maximum allowed line width.
  *
  * @return boolean
  */
 public function generateFileReport($report, $showSources = false, $width = 80)
 {
     $out = new XMLWriter();
     $out->openMemory();
     $out->setIndent(true);
     if ($report['errors'] === 0 && $report['warnings'] === 0) {
         // Nothing to print.
         return false;
     }
     $out->startElement('file');
     $out->writeAttribute('name', $report['filename']);
     foreach ($report['messages'] as $line => $lineErrors) {
         foreach ($lineErrors as $column => $colErrors) {
             foreach ($colErrors as $error) {
                 $error['type'] = strtolower($error['type']);
                 if (PHP_CODESNIFFER_ENCODING !== 'utf-8') {
                     $error['message'] = iconv(PHP_CODESNIFFER_ENCODING, 'utf-8', $error['message']);
                 }
                 $out->startElement('error');
                 $out->writeAttribute('line', $line);
                 $out->writeAttribute('column', $column);
                 $out->writeAttribute('severity', $error['type']);
                 $out->writeAttribute('message', $error['message']);
                 $out->writeAttribute('source', $error['source']);
                 $out->endElement();
             }
         }
     }
     //end foreach
     $out->endElement();
     echo $out->flush();
     return true;
 }
 public function export_csv($page = 1)
 {
     set_time_limit(0);
     $limit = ($page - 1) * intval(app_conf("BATCH_PAGE_SIZE")) . "," . intval(app_conf("BATCH_PAGE_SIZE"));
     $map['ecv_type_id'] = intval($_REQUEST['ecv_type_id']);
     $list = M(MODULE_NAME)->where($map)->limit($limit)->findAll();
     if ($list) {
         register_shutdown_function(array(&$this, 'export_csv'), $page + 1);
         $ecv_value = array('sn' => '""', 'password' => '""', 'money' => '""', 'use_limit' => '""', 'begin_time' => '""', 'end_time' => '""');
         if ($page == 1) {
             $content = iconv("utf-8", "gbk", "序列号,密码,面额,使用数量,生效时间,过期时间");
             $content = $content . "\n";
         }
         foreach ($list as $k => $v) {
             $ecv_value['sn'] = '"' . iconv('utf-8', 'gbk', $v['sn']) . '"';
             $ecv_value['password'] = '******' . iconv('utf-8', 'gbk', $v['password']) . '"';
             $ecv_value['money'] = '"' . iconv('utf-8', 'gbk', format_price($v['money'])) . '"';
             $ecv_value['use_limit'] = '"' . iconv('utf-8', 'gbk', $v['use_limit']) . '"';
             $ecv_value['begin_time'] = '"' . iconv('utf-8', 'gbk', to_date($v['begin_time'])) . '"';
             $ecv_value['end_time'] = '"' . iconv('utf-8', 'gbk', to_date($v['end_time'])) . '"';
             $content .= implode(",", $ecv_value) . "\n";
         }
         header("Content-Disposition: attachment; filename=voucher_list.csv");
         echo $content;
     } else {
         if ($page == 1) {
             $this->error(L("NO_RESULT"));
         }
     }
 }
Example #23
0
 function streamData($data, $name, $time = 0, $level = -1)
 {
     $time = $this->dosTime($time);
     $crc = crc32($data);
     $dlen = strlen($data);
     $level < 0 && ($level = (int) $this->level);
     $level < 0 && ($level = self::LEVEL);
     $data = gzdeflate($data, $level);
     $zlen = strlen($data);
     $name = strtr($name, '\\', '/');
     $n = @iconv('UTF-8', 'CP850', $name);
     // If CP850 can not represent the filename, use unicode
     if ($name !== @iconv('CP850', 'UTF-8', $n)) {
         $n = $name;
         $h = "";
     } else {
         $h = "";
     }
     $nlen = strlen($n);
     $h = "" . $h . "" . pack('V', $time) . pack('V', $crc) . pack('V', $zlen) . pack('V', $dlen) . pack('v', $nlen) . pack('v', 0);
     // extra field length
     echo "PK", $h, $n, $data;
     $dlen = $this->dataLen;
     $this->dataLen += 4 + strlen($h) + $nlen + $zlen;
     $this->cdr[] = "PK" . "" . $h . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V', $dlen) . $n;
 }
 protected function downFile($path, $file_name)
 {
     header("Content-type:text/html;charset=utf-8");
     // echo $path,$file_name;
     //中文兼容
     $file_name = iconv("utf-8", "gb2312", $file_name);
     //获取网站根目录,这里可以换成你的下载目录
     $file_sub_path = $path;
     $file_path = $file_sub_path . $file_name;
     //判断文件是否存在
     if (!file_exists($file_path)) {
         echo '文件不存在';
         return;
     }
     $fp = fopen($file_path, "r");
     $file_size = filesize($file_path);
     //下载文件所需的header申明
     Header("Content-type: application/octet-stream");
     Header("Accept-Ranges: bytes");
     Header("Accept-Length:" . $file_size);
     Header("Content-Disposition: attachment; filename=" . $file_name);
     $buffer = 1024;
     $file_count = 0;
     //返回数据到浏览器
     while (!feof($fp) && $file_count < $file_size) {
         $file_con = fread($fp, $buffer);
         $file_count += $buffer;
         echo $file_con;
     }
     fclose($fp);
 }
Example #25
0
 /**
  * 漢字轉拼音函數
  *
  * @param string $s
  * @return string
  */
 function str2py($s, $spac = '')
 {
     $s = preg_replace("/\\s/is", "_", $s);
     $s = preg_replace("/(|\\~|\\`|\\!|\\@|\\#|\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\+|\\=|\\{|\\}|\\[|\\]|\\||\\|\\:|\\;|\"|\\'|\\<|\\,|\\>|\\.|\\?|\\/)/is", "", $s);
     $py = "";
     $i = 0;
     //加入這一句,自動識別UTF-8
     if (strlen("拼音") > 4) {
         $s = iconv('UTF-8', 'GBK', $s);
     }
     for ($i = 0; $i < strlen($s); $i++) {
         if (ord($s[$i]) > 128) {
             $char = $this->asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256);
             if ($this->all) {
                 $py .= $char . $spac;
             } else {
                 $py .= $char[0] . $spac;
             }
             //取拼音的第一個字符
             $i++;
         } else {
             $py .= $s[$i] . $spac;
         }
         if (strlen($py) >= 20) {
             return $py;
         }
     }
     return strtolower($py);
     //轉換為小寫
 }
Example #26
0
 public function index()
 {
     $this->load->library('functions');
     $post['url'] = 'http://activity.app.bama555.com/gs/climb/index/%2BxiSxiM8zzlgsjO9%2FxjDvRs1COzza5F92QBGVw%2Fex5iSJMoZ6vkDqWEGidW8DjzF%2Fi0vSyUcl0p3NcMMwgrD1Q%3D%3D';
     $post['agent'] = 'MicroMessenger';
     $post['referer'] = 'http://activity.app.bama555.com/gs/climb/mountain/%2BxiSxiM8zzlgsjO9%2FxjDvRs1COzza5F92QBGVw%2Fex5iSJMoZ6vkDqWEGidW8DjzF%2Fi0vSyUcl0p3NcMMwgrD1Q%3D%3D';
     $name = iconv('gbk', 'utf-8', 'ÖúÁ¦Ö£Çï·ÒµÇɽ');
     $pname = iconv('gbk', 'utf-8', '·½½Ü·å');
     $post['post'] = array('name' => $pname, 'tel' => '15158193804', 'sex' => 1, 'submit' => $name);
     print_r($post);
     echo $this->functions->curlHtml($post);
     echo "<pre>";
     echo $html;
     echo "<pre>";
     exit;
     preg_match('/location\\.href=\'(.*?)\'/is', $html, $u);
     $newp['url'] = $u[1];
     $newp['agent'] = 'MicroMessenger';
     $html = $this->functions->curlHtml($newp);
     preg_match('/location\\.href=\'(.*?)\'/is', $html, $u);
     echo $html;
     $newp['url'] = $u[1];
     $newp['agent'] = 'MicroMessenger';
     $html = $this->functions->curlHtml($newp);
     echo $html;
 }
 public function getGradeDetails()
 {
     $studentData;
     $url = 'http://202.197.224.134:8083/jwgl/cj/cj1_cjLiebiao.jsp?xq=0&xkjc=&type=null&xkdl2=&xh=' . $this->sid . '&bh=null';
     $snoopy = new Snoopy();
     $snoopy->rawheaders['Cookie'] = $this->cookies;
     $snoopy->fetch($url);
     if ($snoopy->status != 200) {
         return $this->setMsg(3);
     }
     $data = iconv('gbk', 'utf-8', $snoopy->results);
     $data = str_replace('   style="color:red"', '', $data);
     $data = str_replace('&nbsp;', '', $data);
     preg_match_all('/\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>\\s+\\<td\\>\\s+(.*?)\\s+\\<\\/td\\>/', $data, $matches);
     $num = count($matches[1]);
     for ($i = 1; $i < $num; $i++) {
         $studentData[$i - 1]['course'] = urlencode($matches[1][$i]);
         $studentData[$i - 1]['type'] = urlencode($matches[2][$i]);
         $studentData[$i - 1]['credit'] = urlencode($matches[3][$i]);
         $studentData[$i - 1]['daily_grade'] = urlencode($matches[4][$i]);
         $studentData[$i - 1]['exam_grade'] = urlencode($matches[5][$i]);
         $studentData[$i - 1]['comp_grade'] = urlencode($matches[6][$i]);
         $studentData[$i - 1]['term'] = urlencode($matches[7][$i]);
     }
     $this->studentData = $studentData;
 }
 /**
  * 搜索
  * @param string $q			关键词	    	类似sql like'%$q%'
  * @param array $siteids	站点id数组
  * @param array $typeids	类型ids  		类似sql IN('')
  * @param array $adddate	时间范围数组 		类似sql between start AND end		 格式:array('start','end');
  * @param int $offset 		偏移量
  * @param int $limit  		匹配项数目限制	类似sql limit $offset, $limit
  * @param string $orderby	排序字段		类似sql order by $orderby {id:文章id,weight:权重}
  */
 public function search($q, $siteids = array(1), $typeids = '', $adddate = '', $offset = 0, $limit = 20, $orderby = '@id desc')
 {
     if (CHARSET != 'utf-8') {
         $utf8_q = iconv(CHARSET, 'utf-8', $q);
     }
     if ($orderby) {
         //按一种类似SQL的方式将列组合起来,升序或降序排列。
         $this->cl->SetSortMode(SPH_SORT_EXTENDED, $orderby);
     }
     if ($limit) {
         $this->cl->SetLimits($offset, $limit, $limit > 1000 ? $limit : 1000);
     }
     //过滤类型
     if ($typeids) {
         $this->cl->SetFilter('typeid', $typeids);
     }
     //过滤站点
     if ($siteids) {
         $this->cl->SetFilter('siteid', $siteids);
     }
     //过滤时间
     if ($adddate) {
         $this->cl->SetFilterRange('adddate', $adddate[0], $adddate[1], false);
     }
     $res = $this->cl->Query($utf8_q, 'main, delta');
     return $res;
 }
 /**
  * 导出csv数据报表
  * @author yugang@ymt360.com
  * @since 2015-01-30
  */
 public function export_csv($title_arr, $data, $file_path = 'default.csv')
 {
     array_unshift($data, $title_arr);
     // 在公共的方法中使用导出时间不限制
     // 以防止数据表太大造成csv文件过大,造成超时
     set_time_limit(0);
     $temp_file_path = BASEPATH . '../application/temp/' . uniqid() . '.csv';
     $file = fopen($temp_file_path, 'w');
     $keys = array_keys($title_arr);
     foreach ($data as $item) {
         // 对数组中的内容按照标题的顺序排序,去除不需要的内容
         $info = array();
         foreach ($keys as $v) {
             $info[$v] = isset($item[$v]) ? $item[$v] : '';
         }
         fputcsv($file, $info);
     }
     fclose($file);
     //在win下看utf8的csv会有点问题
     $str = file_get_contents($temp_file_path);
     $str = iconv('UTF-8', 'GBK', $str);
     unlink($temp_file_path);
     // 下载文件
     $this->load->helper('download');
     force_download($file_path, $str);
 }
 /**
  * Обработать файл
  */
 public function processFile()
 {
     $file = file_get_contents($this->getAddress());
     $coding = mb_detect_encoding($file, mb_detect_order(), true);
     if (!$coding) {
         $file = iconv("WINDOWS-1251", "UTF-8", $file);
         file_put_contents($this->getAddress(), $file);
     }
     $file = fopen($this->getAddress(), 'r');
     $isFirst = true;
     $accidents = [];
     while (($data = fgetcsv($file, null, ';')) !== FALSE) {
         if ($isFirst) {
             $isFirst = false;
             continue;
         }
         $item = ['description' => $data[1], 'lng' => str_replace(',', '.', $data[2]), 'lat' => str_replace(',', '.', $data[3]), 'date' => \DateTime::createFromFormat('d.m.Y H:m', $data[0])->format('Y-m-d H:m:s')];
         if ($item['description'] == 'ДТП БЕЗ ПОТЕРПIЛИХ') {
             $item['status'] = Enum::ACCIDENT_STATUS_VICTIMS;
         } elseif ($item['description'] == 'ДТП З ПОТЕРПIЛИМИ') {
             $item['status'] = Enum::ACCIDENT_STATUS_DEATHS;
         } else {
             continue;
         }
         $accidents[] = $item;
     }
     return Accident::find()->insetBatchAccidents($accidents);
 }