Permalink
Browse files

Fix image resizing

  • Loading branch information...
Thoulah committed Feb 11, 2019
1 parent 374d6a2 commit 90ae18e749829c0f61869d877853a983b5d96206
@@ -27,14 +27,13 @@ public function actionIndex() {
*/
public function actionAlbumImage() {
$x = 0;
$count = self::getCountAlbums($artists = Lyrics1Artists::albumsList());
$count = self::getAlbumsCount($artists = Lyrics1Artists::albumsList());
Console::startProgress(0, $count);
foreach ($artists as $artist) :
foreach ($artist->albums as $album) :
Console::updateProgress(++$x, $count);
list($width, $height) = getimagesizefromstring($album->image);
$exif = exif_read_data("data://image/jpeg;base64,".base64_encode($album->image));
if ($width === self::ALBUM_IMAGE_DIMENSIONS && $height === self::ALBUM_IMAGE_DIMENSIONS && empty($exif['SectionsFound']) && $exif['MimeType'] === 'image/jpeg' && !is_null($album->image_color))
list($width, $height, $type) = getimagesizefromstring($album->image);
if ($width === self::ALBUM_IMAGE_DIMENSIONS && $height === self::ALBUM_IMAGE_DIMENSIONS && $type === IMAGETYPE_JPEG && !is_null($album->image_color))
continue;
Console::write($artist->name, [Console::FG_PURPLE], 3);
@@ -49,7 +48,7 @@ public function actionAlbumImage() {
Console::write("{$width}x{$height}", [$width === self::ALBUM_IMAGE_DIMENSIONS ? Console::FG_GREEN : Console::FG_RED], 2);
if (($width > self::ALBUM_IMAGE_DIMENSIONS && $height > self::ALBUM_IMAGE_DIMENSIONS) || !empty($exif['SectionsFound']) || $exif['MimeType'] !== 'image/jpeg') :
if (($width > self::ALBUM_IMAGE_DIMENSIONS && $height > self::ALBUM_IMAGE_DIMENSIONS) || $type !== IMAGETYPE_JPEG) :
if ($width >= self::ALBUM_IMAGE_DIMENSIONS && $height >= self::ALBUM_IMAGE_DIMENSIONS) :
$album->image = Image::resize($album->image, self::ALBUM_IMAGE_DIMENSIONS);
$album->image_color = self::getAverageImageColor($album->image);
@@ -80,7 +79,7 @@ public function actionAlbumImage() {
*/
public function actionAlbumPdf() {
$x = 0;
$count = self::getCountAlbums($artists = Lyrics1Artists::albumsList());
$count = self::getAlbumsCount($artists = Lyrics1Artists::albumsList());
Console::startProgress(0, $count);
foreach ($artists as $artist) :
foreach ($artist->albums as $album) :
@@ -218,12 +217,11 @@ private static function getAverageImageColor(string $image): string {
return sprintf('#%02X%02X%02X', $rTotal / $total, $gTotal / $total, $bTotal / $total);
}
private static function getCountAlbums($list): int {
private static function getAlbumsCount($list): int {
$count = 0;
foreach ($list as $artist) :
foreach ($artist->albums as $album) :
foreach ($artist->albums as $album)
$count++;
endforeach;
endforeach;
return $count;
}
@@ -6,7 +6,7 @@
use yii\web\{NotFoundHttpException, Response};
class LyricsController extends \yii\web\Controller {
public $page;
public $view;
public $data;
public $artist;
public $year;
@@ -15,24 +15,23 @@ class LyricsController extends \yii\web\Controller {
public $lastModified;
public function init(): void {
parent::init();
$this->artist = Yii::$app->request->get('artist');
$this->year = Yii::$app->request->get('year');
$this->album = Yii::$app->request->get('album');
$this->size = Yii::$app->request->get('size');
if ($this->artist && $this->year && $this->album) :
list($this->page, $this->data) = $this->getAlbum();
list($this->view, $this->data) = $this->getAlbum();
$this->lastModified = Lyrics3Tracks::getLastModified($this->artist, $this->year, $this->album);
elseif ($this->artist) :
list($this->page, $this->data) = $this->getArtist();
list($this->view, $this->data) = $this->getArtist();
$this->lastModified = Lyrics2Albums::getLastModified($this->artist);
else :
$this->page = '1_index';
$this->view = '1_index';
$this->data = Lyrics1Artists::artistsList();
$this->lastModified = Lyrics1Artists::getLastModified();
endif;
parent::init();
}
public function behaviors(): array {
@@ -49,14 +48,14 @@ public function behaviors(): array {
public function actionIndex(): string {
Yii::$app->view->registerMetaTag(['name' => 'google', 'content' => 'notranslate']);
return $this->render($this->page, [
return $this->render($this->view, [
'data' => $this->data,
]);
}
public function actionAlbumpdf(): Response {
$fileName = Lyrics2Albums::buildPdf($this->data[0]->album, $this->renderPartial('albumPdf', ['tracks' => $this->data]));
return Yii::$app->response->sendFile($fileName, implode(' - ', [$this->data[0]->artist->url, $this->data[0]->album->year, $this->data[0]->album->url]).'.pdf');
$pdf = Lyrics2Albums::buildPdf($this->data[0]->album, $this->renderPartial('albumPdf', ['tracks' => $this->data]));
return Yii::$app->response->sendFile($pdf, implode(' - ', [$this->data[0]->artist->url, $this->data[0]->album->year, $this->data[0]->album->url]).'.pdf');
}
public function actionAlbumcover(): Response {
@@ -82,7 +81,7 @@ private function getArtist(): array {
private function getAlbum(): array {
$tracks = Lyrics3Tracks::tracksList($this->artist, $this->year, $this->album);
if (!ArrayHelper::keyExists(0, $tracks) || (php_sapi_name() !== 'cli' && (!Yii::$app->user->isGuest && !Yii::$app->user->identity->isAdmin) && !$tracks[0]->album->active))
if (!ArrayHelper::keyExists(0, $tracks))
throw new NotFoundHttpException('Album not found.');
if ($tracks[0]->artist->url !== $this->artist || $tracks[0]->album->url !== $this->album)
@@ -4,8 +4,8 @@
$isGuest = php_sapi_name() === 'cli' || Yii::$app->controller->action->id === 'sitemap' ? true : Yii::$app->user->isGuest;
$isAdmin = !$isGuest && Yii::$app->user->identity->isAdmin;
$unread = $isAdmin ? Comments::find()->where(['active' => Comments::STATUS_INACTIVE])->count() : 0;
$unreadBadge = $unread > 0 ? Html::tag('span', $unread, ['class' => 'badge badge-info ml-1']) : '';
$unread = $isAdmin ? Comments::find()->where(['not', ['active' => true]])->count() : 0;
$unreadBadge = $unread > 0 ? Html::tag('sup', $unread, ['class' => 'badge badge-info ml-1']) : '';
return [
['label' => Yii::$app->icon->show('newspaper', ['class' => 'mr-1']).Html::tag('span', Yii::t('mr42', 'Articles')), 'url' => ['/articles/index'], 'visible' => true],
@@ -38,7 +38,7 @@
['label' => Yii::t('mr42', 'Collection'), 'url' => ['/music/collection']],
],
],
['label' => Yii::$app->icon->show('dungeon', ['class' => 'mr-1']).Html::tag('span', Yii::$app->name), 'url' => null,
['label' => Yii::$app->icon->show('share-alt', ['class' => 'mr-1']).Html::tag('span', Yii::$app->name), 'url' => null,
'items' => [
['label' => Yii::t('mr42', 'Contact'), 'url' => ['/site/contact']],
['label' => Yii::t('mr42', 'My Pi'), 'url' => ['/site/pi']],
@@ -6,9 +6,8 @@ class Console extends \yii\helpers\Console {
public static function write(string $msg, array $format, int $tabs = 1) {
$output = self::ansiFormat($msg, $format);
self::stdout($output);
for ($x = 0; $x < ($tabs - intdiv(self::ansiStrlen($output), 8)); $x++) :
for ($x = 0; $x < ($tabs - intdiv(self::ansiStrlen($output), 8)); $x++)
self::stdout("\t");
endfor;
}
public static function writeError(string $msg, array $format) {
@@ -12,17 +12,15 @@ public function cleanInput(string $data, string $markdown = 'original', bool $al
'/(vimeo):(()?[[:digit:]]+):(21by9|16by9|4by3|1by1)/U' => [$this, 'getVideo'],
'/(youtube):((PL)?[[:ascii:]]{11,32}):(21by9|16by9|4by3|1by1)/U' => [$this, 'getVideo'],
], $data);
if ($markdown) :
if ($markdown)
$data = Markdown::process($data, $markdown);
endif;
$data = $this->addImageResponsiveClass($data);
return trim($data);
}
public function jspack(string $file): string {
if (!file_exists($fileName = Yii::getAlias("@app/assets/js/{$file}"))) :
if (!file_exists($fileName = Yii::getAlias("@app/assets/js/{$file}")))
return "{$file} does not exist.";
endif;
$cacheFile = Yii::getAlias("@runtime/assets/js/{$file}");
if (!file_exists($cacheFile) || filemtime($cacheFile) < filemtime($fileName)) :
@@ -35,7 +33,7 @@ public function jspack(string $file): string {
return file_get_contents($cacheFile);
}
private function addImageResponsiveClass($html) {
private function addImageResponsiveClass(string $html): string {
$html = preg_match('/<img.*? class="/', $html)
? preg_replace("/<img (.*?) class=\"(.*?)\"(.*?)>/i", '<img $1 class="$2 img-fluid"$3>', $html)
: preg_replace('/(<img.*?)(\>)/', '$1 class="img-fluid"$2', $html);
@@ -9,9 +9,8 @@ class Icon {
public function show(string $name, array $options = []): string {
$classPrefix = ArrayHelper::remove($options, 'prefix', 'fas fa-');
$style = $this->getStyle((explode(' ', $classPrefix))[0]);
if (!file_exists(Yii::getAlias("@bower/fontawesome/svgs/{$style}/{$name}.svg"))) :
if (!file_exists(Yii::getAlias("@bower/fontawesome/svgs/{$style}/{$name}.svg")))
return $this->show('question-circle', $options);
endif;
$doc = new DOMDocument();
$doc->load(Yii::getAlias("@bower/fontawesome/svgs/{$style}/{$name}.svg"));
@@ -22,13 +21,11 @@ public function show(string $name, array $options = []): string {
$svg->setAttribute('data-icon', $name);
$svg->setAttribute('data-prefix', (explode(' ', $classPrefix))[0]);
$svg->setAttribute('role', 'img');
foreach ($options as $key => $value) :
foreach ($options as $key => $value)
$svg->setAttribute($key, $value);
endforeach;
endforeach;
foreach ($doc->getElementsByTagName('path') as $path) :
foreach ($doc->getElementsByTagName('path') as $path)
$path->setAttribute('fill', 'currentColor');
endforeach;
return $doc->saveXML($doc->documentElement);
}
@@ -39,12 +36,9 @@ public function fieldAddon(string $name, array $options = []): string {
private function getStyle(string $prefix): string {
switch ($prefix) :
case 'fab':
return 'brands';
case 'far':
return 'regular';
default:
return 'solid';
case 'fab': return 'brands';
case 'far': return 'regular';
default: return 'solid';
endswitch;
}
}
@@ -27,17 +27,14 @@ public static function getItemList(): array {
public static function getUrlList($items = null): array {
foreach ($items ?? self::getItemList() as $item) :
if (!is_array($item) || ArrayHelper::keyExists('visible', $item)) :
if (!is_array($item) || ArrayHelper::keyExists('visible', $item))
continue;
endif;
if (isset($item['url'])) :
if (isset($item['url']))
$pages[] = ArrayHelper::getValue($item, 'url.0');
endif;
if (isset($item['items'])) :
if (isset($item['items']))
$pages[] = self::getUrlList($item['items']);
endif;
endforeach;
array_walk_recursive($pages, function($val) use (&$return) { $return[] = $val; });
return $return;
@@ -45,9 +45,8 @@ private function replaceLine(string $filename, string $search, string $replace)
while (!feof($reading)) :
$line = fgets($reading);
if (stristr($line, $search)) :
if (stristr($line, $search))
$line = $search.' '.$replace.PHP_EOL;
endif;
fputs($writing, $line);
endwhile;
fclose($reading); fclose($writing);
@@ -7,9 +7,8 @@ class Articles extends BaseArticles {
public function afterFind() {
parent::afterFind();
$this->url = $this->url ?? $this->title;
if (!empty($this->content)) :
if (!empty($this->content))
$this->content = Yii::$app->formatter->cleanInput($this->content, 'gfm', true);
endif;
if ($this->source) :
$this->content .= Html::tag('div',
@@ -9,9 +9,6 @@
use yii\web\AccessDeniedHttpException;
class BaseArticles extends \yii\db\ActiveRecord {
const STATUS_INACTIVE = false;
const STATUS_ACTIVE = true;
public static function tableName(): string {
return '{{%articles}}';
}
@@ -50,7 +47,7 @@ public function behaviors(): array{
public function addComment(Comments $comment) {
$comment->parent = $this->id;
$comment->user = Yii::$app->user->isGuest ? null : Yii::$app->user->id;
$comment->active = Yii::$app->user->isGuest ? Self::STATUS_INACTIVE : Self::STATUS_ACTIVE;
$comment->active = Yii::$app->user->isGuest ? false : true;
return $comment->save();
}
@@ -59,13 +56,11 @@ public function beforeDelete(): bool {
}
public function beforeSave($insert): bool {
if (Yii::$app->user->isGuest) :
if (Yii::$app->user->isGuest)
throw new AccessDeniedHttpException('Please login.');
endif;
if (!parent::beforeSave($insert)) :
if (!parent::beforeSave($insert))
return false;
endif;
$this->url = !empty($this->url) ? $this->url : null;
$this->source = !empty($this->source) ? $this->source : null;
@@ -114,12 +109,7 @@ public function getComments() {
return $this->hasMany(Comments::class, ['parent' => 'id']);
}
public static function find() {
return parent::find()
->onCondition(
php_sapi_name() === 'cli' || (!Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin)
? ['or', ['active' => [Self::STATUS_INACTIVE, Self::STATUS_ACTIVE]]]
: ['active' => Self::STATUS_ACTIVE]
);
public static function find(): Query {
return new Query(get_called_class());
}
}
@@ -11,9 +11,6 @@ class Comments extends ActiveRecord {
public $email;
public $captcha;
const STATUS_INACTIVE = false;
const STATUS_ACTIVE = true;
public static function tableName(): string {
return '{{%articles_comments}}';
}
@@ -59,19 +56,17 @@ public function behaviors(): array {
];
}
public function afterFind() {
public function afterFind(): void {
parent::afterFind();
$this->content = Yii::$app->formatter->cleanInput($this->content, 'gfm-comment');
}
public function beforeSave($insert): bool {
if (!parent::beforeSave($insert)) :
if (!parent::beforeSave($insert))
return false;
endif;
if (!$insert && Yii::$app->user->isGuest) :
if (!$insert && Yii::$app->user->isGuest)
throw new AccessDeniedHttpException('Please login.');
endif;
$this->content = Yii::$app->formatter->cleanInput($this->content, false);
$this->name = $this->nameField ?? null;
@@ -88,7 +83,7 @@ public function showApprovalButton(): string {
);
}
public function sendCommentMail($model, $comment) {
public function sendCommentMail($model, $comment): void {
Yii::$app->mailer->compose(
['text' => 'commentToAuthor'],
['model' => $model, 'comment' => $comment]
@@ -114,12 +109,7 @@ public function getArticle() {
return $this->hasOne(Articles::class, ['id' => 'parent']);
}
public static function find() {
return parent::find()
->onCondition(
php_sapi_name() === 'cli' || (!Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin)
? ['or', ['active' => [Self::STATUS_INACTIVE, Self::STATUS_ACTIVE]]]
: ['active' => Self::STATUS_ACTIVE]
);
public static function find(): Query {
return new Query(get_called_class());
}
}
@@ -4,9 +4,9 @@
class Tags extends BaseArticles {
public static function findTagWeights(): array {
if (empty($tags = self::getTags())) :
if (empty($tags = self::getTags()))
return [];
endif;
foreach ($tags as $key => $value) :
$list[$key]['count'] = $value;
$list[$key]['weight'] = 8 + (int) (16 * $value / (array_sum($tags) + 10));
@@ -26,9 +26,8 @@ public static function lastUpdate(string $tag): int {
private static function getTags(): array {
$list = [];
foreach (parent::find()->select('tags')->all() as $tag) :
foreach (StringHelper::explode($tag->tags) as $item) :
foreach (StringHelper::explode($tag->tags) as $item)
isset($list[$item]) ? $list[$item]++ : $list[$item] = 1;
endforeach;
endforeach;
return $list;
}
Oops, something went wrong.

0 comments on commit 90ae18e

Please sign in to comment.