分类列表页

@param string $cat 分类名称
@return string
@throws \yii\web\NotFoundHttpException
514424
public function actionIndex($cat = '')
    {
        yii::$app->setViewPath('@cms/frontend/views');
        if ($cat == '') {
            $cat = yii::$app->getRequest()->getPathInfo();
        }
        $where = ['type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED];
        if ($cat != '' && $cat != 'index') {
            if ($cat == yii::t('cms', 'uncategoried')) {
                $where['cid'] = 0;
            } else {
                if (! $category = Category::findOne(['alias' => $cat])) {
                    throw new NotFoundHttpException(yii::t('cms', 'None category named {name}', ['name' => $cat]));
                }
                $descendants = Category::getDescendants($category['id']);
                if( empty($descendants) ) {
                    $where['cid'] = $category['id'];
                }else{
                    $cids = ArrayHelper::getColumn($descendants, 'id');
                    $cids[] = $category['id'];
                    $where['cid'] = $cids;
                }
            }
        }
        $query = Article::find()->with('category')->where($where);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'sort' => SORT_ASC,
                    'created_at' => SORT_DESC,
                    'id' => SORT_DESC,
                ]
            ]
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'type' => ( !empty($cat) ? yii::t('cms', 'Category {cat} articles', ['cat'=>$cat]) : yii::t('cms', 'Latest Articles') ),
        ]);
    }
53997
public function getShareKey($platform)
    {
        if (Yii::$app->has('authClientCollection')) {
            /** @var \yii\authclient\ClientInterface[] $clients */
            $clients = Yii::$app->get('authClientCollection')->clients;
            if (isset($clients[$platform])) {
                switch ($platform) {
                    case 'facebook':
                    case 'google':
                    case 'linkedin':
                    case 'live':
                    case 'twitter':
                    case 'vkontakte':
                    case 'yandex':
                    case 'douban':
                    case 'qq':
                    case 'wechat':
                    case 'weibo':
                        $clientId = $clients[$platform]->clientId;
                        break;
                    default:
                        $clientId = false;
                }
                return $clientId;
            }
        }
        return false;
    }
390507
public function contentList()
    {
        $url = Config::get('url.content_list');
        // 下载网页
        $response = $this->request('get', [$url]);
        $body = $this->checkAndThrow($response);
        // 分析网页
        $crawler = new Crawler($body);
        $list = [];
        $crawler->filter('.datelist')->children()
            ->each(function (Crawler $node, $i) use (&$list) {
                $nodeTd = $node->children();
                if ($i > 0 && $nodeTd->count() == 4) {
                    $nodeTitle = $nodeTd->eq(0)->filter('a');
                    if (preg_match("/'([^']*)/", $nodeTitle->attr('onclick'), $matches)) {
                        $item['url'] = $matches[1];
                        $item['title'] = $nodeTitle->html();
                        $item['unit'] = $nodeTd->eq(1)->html();
                        $item['publish_time'] = $nodeTd->eq(2)->html();
                        $item['expire_time'] = $nodeTd->eq(3)->html();
                        $list[] = $item;
                    }
                }

            });

        return $list;
    }
1105815
public function actionView($name = '')
    {
        if ($name == '') {
            $name = yii::$app->getRequest()->getPathInfo();
        }
        $model = Article::findOne(['type' => Article::SINGLE_PAGE, 'sub_title' => $name]);
        if (empty($model)) {
            throw new NotFoundHttpException('None page named ' . $name);
        }
        return $this->render('view', [
            'model' => $model,
        ]);
    }
358097
public function getAgentList()
    {
        $result = $this->httpGet(self::WECHAT_AGENT_SET_PREFIX, [
            'access_token' => $this->getAccessToken()
        ]);
        return isset($result['errmsg']) && $result['errmsg'] == 'ok' ? $result['agentlist'] : $this->dump($result);
    }
444927
protected function filter(array $categories)
    {
        // 过滤空的子分类
        foreach ($categories as $i => $category) {
            if (!isset($category['navs']) || !$category['navs']) {
                unset($categories[$i]);
                continue;
            }
            foreach ($category['navs'] as $j => $subCategories) {
                if (!isset($subCategories['navs']) || !$subCategories['navs']) {
                    unset($categories[$i]['navs'][$j]);
                }
            }
        }

        // 过滤空的父分类
        foreach ($categories as $i => $category) {
            if (!isset($category['navs']) || !$category['navs']) {
                unset($categories[$i]);
            }
        }

        return $categories;
    }
753479
public function getCategoryProperty($cateId)
    {
        $result = $this->wechat->httpRaw(self::WECHAT_CATEGORY_PROPERTY_GET_PREFIX, [
            'cate_id' => $cateId
        ], [
            'access_token' => $this->wechat->getAccessToken()
        ]);
        return isset($result['errmsg']) && $result['errmsg'] == 'success' ? $result['properties'] : false;
    }
183130
private function resolveTypeIndex()
    {
        // 构建文件分类
        $archives = [];
        $files = $this->files;
        foreach ($files as $key => $file) {
            // 单页文件不做索引
            if (in_array($file['page_uuid'], $this->single_pages)) {
                continue;
            }
            // 文件类型处理
            $len = count($file['type']);
            $str = '';
            for ($i=0; $i < $len; $i++) {
                $str.= '__' . $file['type'][$i];
                $str = trim($str, '__');
                $archives[] = $str;
            }
        }
        unset($file);

        $archives = array_unique($archives);
        $keys = $archives;
        foreach ($archives as $k1 => $v1) {
            foreach ($keys as $v2) {
                if (strpos($v2, $v1) !== false && ($v1 !== $v2)) {
                    unset($archives[$k1]);
                    break;
                }
            }
        }
        unset($v1,$k1,$v2);

        $type_index = [];
        foreach ($archives as $key => $t) {
            $type = explode('__', $t);
            $length = count($type);
            $url = '/category';
            $type_index = $this->my_merge($type_index, $this->getArray(0, $length, $type, $url));
        }
        // dd($type_index);
        $this->type_index = $type_index;
    }
434882
public function goGet($url = '', $query = null, $timeout = 30000, $headers = [])
    {
        if (!($this->client instanceof \swoole_http_client)) {
            throw new Exception('You must complete the DNS query first, Such as $client->goDnsLookup()');
        }

        if (empty($this->urlData)) {
            $this->urlData = self::parseUrl($url);
        } else {
            if (!empty($url)) {
                $this->urlData['path'] = $url;
            }
        }
        $this->setHeaders($headers);

        //支持直接在url之后带参数形式的GET请求
        $q = '';
        if (!empty($this->urlData['query'])) {
            $q = ltrim($this->urlData['query'], '?');
        }

        if (!empty($query)) {
            $q .= (empty($q) ? '' : '&') . http_build_query($query) ;
        }

        $sendGetReq  = $this->getObject(Http::class, [$this, 'GET', $this->urlData['path'], $q, $timeout]);

        return $sendGetReq;
    }
1222556
public static function getHeader(string $header):  ? string
    {
        self::init();
        if (function_exists('\getallheaders')) {
            $headers = array_change_key_case(getallheaders(), CASE_UPPER);
            $header  = str_replace('_', '-', $header);
            return $headers[strtoupper($header)] ?? null;
        }

        //通过$_SERVER寻找
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                $key    = substr($key, 5); //HTTP开头认为是header头
                $header = str_replace('-', '_', $header); //不区分-和_
                if (strcasecmp($key, $header) == 0) {
                    return $value;
                }
            }
        }
        return null;
    }
935840
public function getScriptUrl()
    {
        if (!$this->scriptUrl) {
            $scriptName = 'index.php';
            if(false != $scriptUrl = $this->getServer('PHP_SELF')) {
                $scriptName = $this->getServer('SCRIPT_FILENAME');
                // 去掉 index.php之后的字符
                if (false !== ($pos = stripos($scriptUrl, basename($scriptName)))) {
                    $scriptUrl = substr($scriptUrl, 0, $pos + strlen(basename($scriptName)));
                }
                
                if($scriptName && $scriptName == $scriptUrl) {
                    $docRoot = $this->getServer('DOCUMENT_ROOT');
                    if($docRoot && strpos($scriptName, $docRoot) === 0) {
                        $scriptUrl = str_replace('\\','/', str_replace($docRoot, '', $scriptName));
                    } else {
                        $scriptUrl = '/'.basename($scriptName);
                    }
                } elseif ($scriptName && strlen($scriptName) < strlen($scriptUrl)) {
                    $scriptUrl = '/'.basename($scriptName);
                } else {
                    //$scriptUrl = $scriptUrl;
                }
            } else {
                $scriptUrl = '/'.basename($scriptName);
            }
            
            $this->scriptUrl = htmlentities($scriptUrl);
        }
        
        return $this->scriptUrl;
    }
729786
public function toArray()
    {
        $item    = [];
        $visible = [];
        $hidden  = [];

        // 合并关联数据
        $data = array_merge($this->data, $this->relation);

        // 过滤属性
        if (!empty($this->visible)) {
            $array = $this->parseAttr($this->visible, $visible);
            $data  = array_intersect_key($data, array_flip($array));
        } elseif (!empty($this->hidden)) {
            $array = $this->parseAttr($this->hidden, $hidden, false);
            $data  = array_diff_key($data, array_flip($array));
        }

        foreach ($data as $key => $val) {
            if ($val instanceof Model || $val instanceof ModelCollection) {
                // 关联模型对象
                if (isset($visible[$key])) {
                    $val->visible($visible[$key]);
                } elseif (isset($hidden[$key])) {
                    $val->hidden($hidden[$key]);
                }
                // 关联模型对象
                $item[$key] = $val->toArray();
            } else {
                // 模型属性
                $item[$key] = $this->getAttr($key);
            }
        }

        // 追加属性（必须定义获取器）
        if (!empty($this->append)) {
            foreach ($this->append as $key => $name) {
                if (is_array($name)) {
                    // 追加关联对象属性
                    $relation = $this->getRelation($key);

                    if (!$relation) {
                        $relation = $this->getAttr($key);
                        $relation->visible($name);
                    }

                    $item[$key] = $relation->append($name)->toArray();

                } elseif (strpos($name, '.')) {
                    list($key, $attr) = explode('.', $name);
                    // 追加关联对象属性
                    $relation = $this->getRelation($key);

                    if (!$relation) {
                        $relation = $this->getAttr($key);
                        $relation->visible([$attr]);
                    }

                    $item[$key] = $relation->append([$attr])->toArray();

                } else {
                    $value = $this->getAttr($name, $item);
                    if (false !== $value) {
                        $item[$name] = $value;
                    }
                }
            }
        }

        return $item;
    }
968784
public function toString(array $parts = array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment'))
	{
		// Make sure the query is created
		$query = $this->getQuery();

		$uri = '';
		$uri .= in_array('scheme', $parts) ? (!empty($this->scheme) ? $this->scheme . '://' : '') : '';
		$uri .= in_array('user', $parts) ? $this->user : '';
		$uri .= in_array('pass', $parts) ? (!empty($this->pass) ? ':' : '') . $this->pass . (!empty($this->user) ? '@' : '') : '';
		$uri .= in_array('host', $parts) ? $this->host : '';
		$uri .= in_array('port', $parts) ? (!empty($this->port) ? ':' : '') . $this->port : '';
		$uri .= in_array('path', $parts) ? $this->path : '';
		$uri .= in_array('query', $parts) ? (!empty($query) ? '?' . $query : '') : '';
		$uri .= in_array('fragment', $parts) ? (!empty($this->fragment) ? '#' . $this->fragment : '') : '';

		return $uri;
	}
38858
protected function _getCatPath($oCat)
    {
        $sCatPathString = '';
        $sSep = '';
        while ($oCat) {
            // prepare oCat title part
            $sCatPathString = $oCat->oxcategories__oxtitle->value . $sSep . $sCatPathString;
            $sSep = '/';
            // load parent
            $oCat = $oCat->getParentCategory();
        }

        return $sCatPathString;
    }
1006149
public function getCategorySubCategories($cateId)
    {
        $result = $this->wechat->httpRaw(self::WECHAT_CATEGORY_SUB_CATEGROIES_GET_PREFIX, [
            'cate_id' => $cateId
        ], [
            'access_token' => $this->wechat->getAccessToken()
        ]);
        return isset($result['errmsg']) && $result['errmsg'] == 'success' ? $result['cate_list'] : false;
    }
574665
public function drawChar()
    {
        $x = ($this->width - 10) / $this->charNum;
        $captchaStr = '';//保存产生的字符串

        for ($i = 0; $i < $this->charNum; $i++) {
            $char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
            $captchaStr .= $char;
            $fontColor = imagecolorallocate($this->img, random_int(80, 200), random_int(80, 200), random_int(80, 200));
            imagefttext(
                $this->img, $this->fontSize, random_int(-30, 30), $i * $x + random_int(6, 10),
                random_int($this->height / 1.3, $this->height - 5), $fontColor,
                $this->font, $char
            );
        }

        $this->captcha = strtolower($captchaStr);

        //把纯的验证码字符串放置到SESSION中进行保存，便于后面进行验证对比
        $_SESSION[static::$sessionKey] = md5($this->captcha);

        //设置cookie到前端浏览器，可用于前端验证
        setcookie(static::$sessionKey, md5($this->captcha));
    }
884834
public function parse() {
        $result = [];
        foreach ($this->routingTable as $key => $route) {
            $this->params = [];
            $route['regx'] = preg_replace_callback(
                "/%([^%]+)%/",
                [$this, 'match'],
                preg_quote(str_replace(['[', ']', ':'], ['%', '%', ' '], $route['url']))//$route['url']
            );

            /** 处理斜线 */
            $route['regx'] = rtrim($route['regx'], '/');
            $route['regx'] = '|^' . $route['regx'] . '[/]?$|';

            $route['format'] = preg_replace("/\[([^\]]+)\]/", "%s", $route['url']);//$route['url']
            $route['params'] = $this->params;

            $result[$key] = $route;
        }

        return $result;
    }