<?php
require_once dirname(dirname(__FILE__)) . '/init.php';

$categoryMap = array(
    '系统管理'=>array(1,1),
    '网络通讯'=>array(2,1),
    '日常实用'=>array(3,1),
    '社区资讯'=>array(4,1),
    '影音拍照'=>array(5,1),
    '地图导航'=>array(6,1),
    '主题美化'=>array(7,1),
    '学习娱乐'=>array(8,1),
    '医疗保健'=>array(9,1),
    '电子书籍'=>array(10,1),
    '体育竞速'=>array(11,2),
    '经营策略'=>array(12,2),
    '动作冒险'=>array(13,2),
    '棋牌益智'=>array(14,2),
    '动作冒险'=>array(15,2),
    '飞行射击'=>array(16,2),
    '趣味休闲'=>array(17,2),
    '模拟器'=>array(18,2)
);

$cateUrl = 'http://nduoa.com/apk/list/49?order=release_time';
$cContent = getFile($cateUrl);
preg_match_all('/<a\s*target=\"_blank\"\s*class=\"icon\"\s*href=\"(.*?)\">/is', $cContent, $matches);
if (empty($matches[1]))
{
    die("获取不到软件地址\n");
}

foreach ($matches[1] as $mmmm)
{
    $url = 'http://nduoa.com'.$mmmm;
    $check = $db->getValue('SELECT COUNT(*) FROM '.SoftCollectLogs::table().' WHERE url = '.S::sqlEscape($url));
    if ($check)
    {
        continue;
    }
    
    $content = getFile($url);
    preg_match('/<title>(.*?)\|/is', $content, $t);
    $title = trim($t[1]);
    echo $title . '...';

    preg_match('/<li\s*class=\"item\">\<strong>(.*?)\<\/strong>\<\/li>/is', $content, $st);
    $shortTitle = trim($st[1]);

    preg_match('/<div\s*class=\"dsp\">(.*?)\<\/div>/is', $content, $c);
    //$desc = preg_replace('/<h3>(.*?)\<\/h3>/is', '', $c[1], 1);
    $desc = str_replace(array('<h3>', '</h3>'), array('[b]', '[/b]'), $c[1]);
    $desc = strip_tags($desc);
    $desc = str_replace(array('[b]', '[/b]'), array('<b>', '</b>'), $desc);
    $desc = analyzeText($desc);
    $desc = str_replace('&nbsp;', ' ', $desc);

    preg_match('/<div\s*class=\"app_version\">软件版本：(.*?)\<\/div>/is', $content, $v);
    $version = trim($v[1]);

    preg_match_all('/<a\s*href=\"\/category\/\d+\">(.*?)\<\/a>\<\/li>/is', $content, $cate);
    $cName = $cate[1][1];
    $cArray = $categoryMap[$cName];
    if (empty($cArray))
    {
        $cArray = array(1,1);
    }

    $softContent = array(
        'name' => $title,
        'short_name' => $shortTitle,
        'cid' => $cArray[0],
        'type' => $cArray[1],
        'pid' => 1,
        'createdate' => CDATETIME,
        'date' => CDATE,
        'info' => mysql_real_escape_string($desc),
        'source' => 2,
        'version' => $version,
    );
    $db->insert(SoftContents::table())->value($softContent)->q();
    $id = $db->getInsertId();

    /**/
    preg_match('/<ul\s*class=\"tab_body\">(.*?)\<\/ul>/is', $content, $m);
    preg_match_all('/<img\s*src=\"(.*?)\"/is', $m[1], $p);
    $images = 0;
    $firstImage = '';
    if (!empty($p[1]))
    {
        foreach ($p[1] as $pUrl)
        {
            $pCcontent = getFile($pUrl);
            $fileName = guid() . '.' . fileext($pUrl);
            $pFile = getSoftBaseSavePath(CDATE, 'image') . $fileName;
            file_put_contents($pFile, $pCcontent);
            $pData = array(
                'cid' => $id,
                'name' => $fileName,
                'date' => CDATE,
                'createdate' => CDATETIME,
            );
            $db->insert(SoftCpics::table())->value($pData)->q();
            if (!$firstImage)
            {
                $firstImage = $fileName;
            }
        }
        $images = count($p[1]);
    }

    if ($images)
    {
        $path = empty($_SYS['cfg_path']) ? '/' : '/' . $_SYS['cfg_path'];
        $newContent = '<img src="'.$path.'data/soft/image/'.CDATE.'/'.$firstImage.'" alt="图" /><br/>'.$desc;
        $db->update(SoftContents::table())->value(array('images' => $images, 'info' => mysql_real_escape_string($newContent)))->where(array('id'=>$id))->q();
    }

    /**/
    preg_match('/data-uri=\"(.*?)\"/is', $content, $d);
    $dC = file_get_contents($d[1]);
    $basePath = getSoftBaseSavePath(CDATE);
    $cFileName =guid() . '.apk';
    $saveFile = $basePath . $cFileName;
    file_put_contents($saveFile, $dC);
    $size = filesize($saveFile);
    $db->insert(SoftPcontents::table())->value(array('cid'=>$id,'pid'=>1,'filename'=>$cFileName,'name'=>$title.'.apk','createdate'=>CDATETIME,'size'=>$size,'date'=>CDATE,'filetype'=>'application/vnd.android.package-archive'))->q();

    $db->insert(SoftCollectLogs::table())->value(array('url'=>$url, 'date' => CDATE, 'createdate' => CDATETIME))->q();
    unset($dC);
    echo "done\n";
}
function guid()
{
    mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
    $charid = strtoupper(md5(uniqid(rand(), true)));
    $hyphen = chr(45);// "-"
    $uuid = substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12);

    return $uuid;
}

function getSoftBaseSavePath($date, $dir = 'attachments')
{
    $basePath = ROOT_PATH . 'data' . DS . 'soft' . DS . $dir . DS;
    if (!is_writeable($basePath))
    {
        return false;
    }
    $path = $basePath . $date . DS;
    if (!is_dir($path))
    {
        @mkdir($path, 0777, true);
    }

    return $path;
}