<?php
/**
* @version EC=CUBE4
* @copyright 株式会社 翔 kakeru.co.jp
* @author Kawai
* 2021年11月16日作成
* 2022年01月25日更新 都道府県、支払い方法等のマスタ情報取得用メソッドの追加 by worker_g
*
*
* ランドマークヘルパー
* twig
* {{% set hoge = Service('Customize\\Service\\LmHelper').hoge(Email) %}
*
* C= C= C= ┌(;・_・)┘トコトコ
******************************************************/
namespace Customize\Service;
use Eccube\Common\EccubeConfig;
use InvalidArgumentException;
use Lm\Engine\EC\Entity\OrderHeaderExtended;
use Lm\Entity\OrderHeader;
use Lm\Service\Db\SqlService;
use Lm\Service\Db\DbManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Customize\Service\MobileDetector as LmMobileDetector;
class LmHelper
{
const IS_NOT_NULLABLE = 1;
/**
* @var EccubeConfig
*/
protected $eccubeConfig;
/**
* @var PrefectureService
*/
protected $PrefectureService;
/**
* @var CartHelper
*/
protected $CartHelper;
/**
* @var Request|null
*/
protected $Request;
protected $session;
protected $mobileDetector;
/**
* @param ContainerInterface $Container
* @param EccubeConfig $eccubeConfig
* @param PrefectureService $prefectureService
*/
public function __construct(EccubeConfig $eccubeConfig,
PrefectureService $prefectureService,
CartHelper $CartHelper,
RequestStack $requestStack,
SessionInterface $session,
LmMobileDetector $mobileDetector
)
{
$this->eccubeConfig = $eccubeConfig;
$this->PrefectureService = $prefectureService;
$this->CartHelper = $CartHelper;
$this->Request = $requestStack->getCurrentRequest();
$this->session = $session;
$this->mobileDetector = $mobileDetector;
}
/**
* @param $text
* @return string
*/
public static function display_text($text)
{
return nl2br(str_replace(">", ">", str_replace("<", "<", stripslashes($text))));
}
/**
* @param $text
* @return string
*/
public static function display_form_text($text)
{
return htmlspecialchars($text, ENT_QUOTES);
}
/**
* ページングリンクの生成を行う。
* 第2引数に数値を渡した場合、総レコード数として解釈。
* 第2引数に配列(全レコード)を渡した場合、配列より総レコード数を算出。
* 総レコード数と第3引数(1ページあたりの表示件数)より総ページ数を算出。
*
* TODO: 共通テンプレート(*.twig)の作成
*
* @param int $page
* @param int|array $pages
* @param int $items_per_page
* @param int $max_paging_links
* @param array $params
* @return array
*/
public static function paging($page, $pages, $items_per_page = 10, $max_paging_links = 10, $params = [])
{
// 総レコード数の解釈
if (is_array($pages)) {
$total_count = count($pages);
} else if (is_numeric($pages)) {
$total_count = $pages;
} else {
throw new InvalidArgumentException();
}
// 総ページ数 = 総レコード数 / 1ページあたりの表示件数
$pages = ceil($total_count / $items_per_page);
// ページオフセット(当該ページの開始レコード位置)の算出
$page_offset = ($page - 1) * $items_per_page;
// 返り値の用意
$ret = array(
'page' => $page,
'page_offset' => $page_offset,
'pages' => $pages,
'page_list' => array(),
'total_count' => $total_count,
'prev' => null,
'next' => null,
'params_url' => null,
'start_no' => $page_offset + 1,
'end_no' => $items_per_page * $page,
);
//$max_paging_linksはページ番号の表示数
$next = $page + 1;
$prev = $page - 1;
//ページ番号リンク用
$start = ($page - floor($max_paging_links / 2) > 0) ? ($page - floor($max_paging_links / 2)) : 1;//始点
$end = ($start > 1) ? ($page + floor($max_paging_links / 2)) : $max_paging_links;//終点
$start = ($pages < $end) ? $start - ($end - $pages) : $start;//始点再計算
if ($page > 1) {
$ret['prev'] = self::display_text($prev);
}
//最初のページへのリンク
if ($start >= floor($max_paging_links / 2)) {
$ret['page_list'][] = self::display_text(1);
if ($start > floor($max_paging_links / 2)) $ret['page_list'][] = null; //ドットの表示
}
for ($i = $start; $i <= $end; $i++) {//ページリンク表示ループ
if ($i <= $pages && $i > 0)//1以上最大ページ数以下の場合
$ret['page_list'][] = self::display_text($i);//ページ番号リンク表示
}
//最後のページへのリンク
if ($pages > $end) {
if ($pages - 1 > $end) $ret['page_list'][] = null; //ドットの表示
$ret['page_list'][] = self::display_text($pages);
}
if ($page < $pages) {
$ret['next'] = self::display_text($next);
}
// TODO: $params_url -> 改善の余地あり?
$params_url = '';
if (!empty($params)) {
// if (isset($params['id']) && ctype_digit($params['id'])) {
// $params_url .= "id={$params['id']}&";
// }
// if (isset($params['category']) && ctype_digit($params['category'])) {
// $params_url .= "category={$params['category']}&";
// }
// if (isset($params['goods_id']) && ctype_digit($params['goods_id'])) {
// $params_url .= "goods_id={$params['goods_id']}&";
// }
$params_url = http_build_query($params);
$params_url = "?{$params_url}";
}
$ret['params_url'] = $params_url;
return $ret;
}
/**
* @param $goodsId
* @param $filename
* @return string
*/
public function getGoodsImageUrl($goodsId, $filename)
{
//
$url = $this->getConfig('CFIMG_GOODS_URL');
//
$folder = substr($goodsId, -1, 1);
$folder = "{$folder}/{$goodsId}";
//
$ret = "{$url}/{$folder}/{$filename}";
//
return $ret;
}
/**
* @return PrefectureService
*/
public function pref()
{
return $this->PrefectureService;
}
/**
* EC-CUBEコンフィグ項目の値を取得する
*
* @param array|string|int $key
* string|int ・・・ 指定されたキーのコンフィグ項目の値を取得する。
* array ・・・・・・ キーを階層構造で指定することで再帰的に走査し、任意の階層のコンフィグ項目を取得する。
* @param array|null $_config 指定不可。再帰処理用。
* @return mixed
*/
public function getConfig($key, $_config = null)
{
//
if ($_config === null) {
//
$_config = $this->eccubeConfig;
}
//
if (is_array($key)) {
//
if (count($key) !== 1) {
//
throw new \Exception('キーの階層構造が不正です');
}
//
$childKey = key($key);
//
return $this->getConfig($key[$childKey], $_config[$childKey]);
} else {
return $_config[$key] ?? null;
}
}
/**
* @return mixed
*/
public function getPaymentTypeList()
{
return $this->getConfig('PAYMENT_TYPE_LIST');
}
/**
* @return mixed
*/
public function getSiteTypeList()
{
return $this->getConfig('SITE_TYPE_LIST');
}
/**
* カートタイプを返す
* dtb_cart cart_typr
*
* @return int CrtType
*/
public function getCartType()
{
return $this->CartHelper->GetCartType();
}
/**
* 全ての文字をHTML用に変換
*
* @param string
* @return string
*/
public static function displayText($text)
{
return nl2br(str_replace(">", ">", str_replace("<", "<", stripslashes($text))));
}
/**
* TODO: キャッシュ使用可否判定
*
* @return bool
*/
public function useCache()
{
return false;
}
/**
* TODO: キャッシュロード
*
* @param string $dataCacheId
* @param Request $request
* @return array
*/
public function loadCache($dataCacheId, $request)
{
return null;
}
/**
* TODO: キャッシュにデータ保存
*
* @param string $dataCacheId
* @param array $data
* @return なし
*/
public function saveCache($dataCacheId, $data)
{
return null;
}
/**
* キーワード分解
*
* @param string $keyword
* @param bool $trim
* @return array
*/
public function getKeywords($keyword, $trim = true)
{
$searchtext = str_replace(' ', ' ', $keyword);
$tmpArray = preg_split('/[ ]+/', $searchtext);
$keywords = array();
$searchSimilarWordsService = new SearchSimilarWordsService();
foreach ($tmpArray as $keyword) {
// 曖昧検索(search_similar_words)処理の経由
array_push($keywords, $searchSimilarWordsService->getValidKeyword($keyword, $trim));
}
return $keywords;
}
/**
* 指定した日時がLM休日かどうか判定する
*
* @param int $time
* @return bool
*/
protected function getLmHoliday($time)
{
// 休日テーブルを照会
$sql = new SqlService();
$sql->Table('holiday_calendar_table');
$sql->Where(sprintf('holiday_year = 0 OR holiday_year = %d', intval(date("Y", $time))));
$sql->Where(sprintf('holiday_month = 0 OR holiday_month = %d', intval(date("m", $time))));
$sql->Where(sprintf('holiday_day = 0 OR holiday_day = %d', intval(date("d", $time))));
$sql->Where(sprintf('holiday_week = 0 OR holiday_week = %d', (date("w", $time) + 1)));
$sql->Where(sprintf('holiday_count = 0 OR holiday_count = %d', (intval((date("d", $time) - 1) / 7) + 1)));
$sql->Where('holiday_year = 0 AND holiday_month = 0 AND holiday_day = 0 AND holiday_count = 0 AND holiday_week = 0', "AND NOT");
/*
※元クエリ内容
$strSQL = "select * from holiday_calendar_table
where ( holiday_year = 0 or holiday_year = " . intval(date("Y", $today)) . " )
and ( holiday_month = 0 or holiday_month = " . intval(date("m", $today)) . " )
and ( holiday_day = 0 or holiday_day = " . intval(date("d", $today)) . " )
and ( holiday_week = 0 or holiday_week = " . (date("w", $today) + 1) . " )
and ( holiday_count = 0 or holiday_count = " . (intval((date("d", $today) - 1) / 7) + 1) . " )
and not ( holiday_year = 0 and holiday_month = 0 and holiday_day = 0 and holiday_count = 0 and holiday_week = 0 )"
*/
$result = $sql->Find();
return !empty($result);
}
/**
* 指定した日時が指定の仕入先の休日に該当するかどうか判定する
*
* @param int $time
* @param int array $shiiresakiList 仕入先コード(複数可能)
* @return bool
*/
protected function getShiiresakiHoliday($time, $shiiresakiList)
{
// 仕入先休日テーブルを照会
$sql = new SqlService();
$sql->Table('shiiresaki_yasumi_table');
if (count($shiiresakiList) === 1) {
$sql->Where(sprintf('shiiresaki_id = %d', $shiiresakiList[0]));
} else {
$sql->Where('shiiresaki_id IN (' . join(',', $shiiresakiList) . ')');
}
$sql->Where("holiday = '" . date('Y-m-d', $time) . "'");
/*
※元クエリ内容
$strSQL = "SELECT * FROM shiiresaki_yasumi_table
WHERE shiiresaki_id = $sid
AND holiday = '$searchDate'";
*/
$result = $sql->Find();
return !empty($result);
}
/**
* LM休日及び仕入先休日を元に、指定した日時から指定営業日経過後の「営業日」を算出する
*
* @param int $time 基準日時
* @param int $days 指定営業日
* @param int array $shiiresakiList 仕入先コード(複数可能)デフォルトは 16=長瀞
* @return string Ymd 見つからない場合は null
*/
public function getWorkingDate($time, $days, $shiiresakiList = [16])
{
$ret = null;
$cnt = 0;
$base = date("Y-m-d", $time);
// 最大30日間内で検索し、見つからない場合はエラーとする
$max_date = 30;
for ($i = 0; $i <= $days; $i++) {
$find = false;
for ($j = 0; $j < $max_date; $j++) {
$targetDate = strtotime($base . " " . $cnt . " day");
// LM休日判定
$isLmHoliday = $this->getLmHoliday($targetDate);
if (!$isLmHoliday) {
if ($shiiresakiList) {
// 仕入先休日判定
$isShiiresakiHoliday = $this->getShiiresakiHoliday($targetDate, $shiiresakiList);
if (!$isShiiresakiHoliday) {
$find = true;
break;
}
} else {
// 仕入先判定なし
$find = true;
break;
}
}
$cnt++;
}
// 見つかった場合は次の日に進める
$cnt = $find ? $cnt + 1 : $cnt;
}
return $find ? date('Ymd', $targetDate) : null;
}
/**
* 都道府県IDを元に離島かどうか判断し配送日を返す
*
* @param int $prefectureId
* @return int
*/
protected function getIslandByPrefecture($prefectureId)
{
$ret = 1;
if ($prefectureId == 1 or $prefectureId >= 36) {
$ret = 2;
}
return $ret;
}
/**
* 郵便番号を元に離島かどうか判断し配送日を返す
*
* @param string $postcode
* @param int $prefectureId
* @return int
*/
protected function getIslandByPostcode($postcode, $prefectureId)
{
$ret = 1;
// 郵便番号補正
if (!strstr($postcode, '-')) {
$postcode = preg_replace("/^(\d{3})(\d{4})$/", "$1-$2", $postcode);
}
// 離島郵便番号テーブルを照会
$sql = new SqlService();
$sql->Table('island_table');
$sql->Where("island_postcode = '" . $postcode . "' OR island_postcode = '" . substr($postcode, 0, 3) . "-0000'");
/*
※元クエリ内容
$strSQL = "SELECT * FROM island_table WHERE island_postcode = '" . $post_code . "'";
$strSQL = "SELECT * FROM island_table WHERE island_postcode = '" . substr(str_replace("-", "", $post_code), 0, 3) . "-0000'";
*/
$result = $sql->Find();
if (!empty($result)) {
$ret = 2;
} else {
$ret = $this->getIslandByPrefecture($prefectureId);
}
return $ret;
}
/**
* TODO: 商品IDを元に、仕入先毎のお届け予定日に関する情報を取得する
*
* @param int $goodsId
* @return array
*/
protected function getShiiresakiSendDateByGoodsId($goodsId)
{
$ret = [
'shiiresaki_id' => -1,
'shiiresaki_senddate' => 0,
'send_limit' => 0,
];
// 商品・仕入先テーブルを結合して情報取得
$sql = new SqlService();
$sql->Selects('shiiresaki_id');
$sql->Selects("DATE_FORMAT( T.shiiresaki_shimekiri_time, '%H%i' ) AS `sdate`");
$sql->Selects("shiiresaki_senddate");
$sql->Table('shiiresaki_table');
$sql->Join('goods_table', 'shiiresaki_id = goods_shiiresaki', 'INNER');
$sql->Where(sprintf('T1.goods_id = %d', (int)$goodsId));
/*
※元クエリ内容
$strSQL = "select shiiresaki_id, date_format( shiiresaki_shimekiri_time, '%H%i' ) as sdate, shiiresaki_senddate
from goods_table
inner join shiiresaki_table on goods_shiiresaki = shiiresaki_id
where goods_id = " . $data_id;
*/
$result = $sql->Find();
if (!empty($result)) {
// 発注締切時間の後
$send_limit = 0;
if (date("Hi") >= $result['sdate']) {
$send_limit = 1;
}
$ret = [
'shiiresaki_id' => $result['shiiresaki_id'],
'shiiresaki_senddate' => $result['shiiresaki_senddate'],
'send_limit' => $send_limit,
];
}
return $ret;
}
/**
* 商品IDを元に、指定した日時より直近の商品のお届け予定日を算出する
*
* @param int $time
* @param int $prefectureId
* @param string $postcode
* @param int $goodsId
* @return string Ymd 見つからない場合は null
*/
public function getSendSchedule($time, $prefectureId, $postcode = null, $goodsId = null)
{
// 起点日
$base = $time ? $time : time();
// 配送日数
$deliverDays = 0;
// 仕入先配送日数
$deliverDaysShiiresaki = 0;
// 休日判定対象の仕入先(デフォルトは物流業者=76)
$shiiresakiList = [76];
// 締切時間判定
$timeLimit = false;
// 発注締切時間(12:00)を判定
if ($time && date("Hi", $base) >= 1200) {
$timeLimit = true;
}
// 商品指定
if ($goodsId !== null) {
// 商品仕入先別の配送日を計算
$shiiresakiSendInfo = $this->getShiiresakiSendDateByGoodsId($goodsId);
if ($shiiresakiSendInfo['shiiresaki_id'] !== -1 && !$time) {
$shiiresakiList[] = $shiiresakiSendInfo['shiiresaki_id'];
}
// 発送締切時間
$timeLimit = ($shiiresakiSendInfo['send_limit'] > 0) ? true : false;
// 仕入先配送日数を加算
$deliverDaysShiiresaki = $shiiresakiSendInfo['shiiresaki_senddate'];
}
// 発送締切時間を超える場合は日数加算
$deliverDays = ($timeLimit) ? $deliverDays + 1 : $deliverDays;
// ここまででいったん休日判定計算する
$dt = $this->getWorkingDate($base, $deliverDays, $shiiresakiList);
$base = strtotime($dt);
// 曜日を判定
$week = date("w", mktime(0, 0, 0, date("m", $base), date("d", $base), date("Y", $base)));
if ($week == 5) {
// 計算した日付が金曜の場合は月曜まで進めて計算する
$deliverDays = ($deliverDaysShiiresaki > 0) ? $deliverDaysShiiresaki - 1 : 0;
$base = mktime(0, 0, 0, date("m", $base), date("d", $base) + 3 + $deliverDays, date("Y", $base));
$dt = $this->getWorkingDate($base, $deliverDays, $shiiresakiList);
} else {
$deliverDays = $deliverDaysShiiresaki;
$deliverDays = $deliverDays ? $deliverDays : $deliverDays + 1;
$dt = $this->getWorkingDate($base, $deliverDays, $shiiresakiList);
}
// 都道府県別に配送日数を計算(郵便番号指定があれば離島テーブルより計算)
if ($postcode !== null) {
$deliverDays = $this->getIslandByPostcode($postcode, $prefectureId);
} else {
$deliverDays = $this->getIslandByPrefecture($prefectureId);
}
// 配送日数を加算して返す(休日判定無し)
$base = strtotime($dt);
$base = mktime(0, 0, 0, date("m", $base), date("d", $base) + $deliverDays, date("Y", $base));
return date('Ymd', $base);
}
/**
* TODO: 曜日を取得
* @return mixed
*/
public function getDayOfWeek()
{
return $this->getConfig('DOW_LIST');
}
/**
* TODO: その他手数料を取得
* @return mixed
*/
public function getNewKakuninOtherAmounts()
{
return $this->getConfig('NEW_KAKUNIN_OTHER_AMOUNTS_LIST');
}
/**
* TODO: プリント種類を取得
* @return mixed
*/
public function getPrintName()
{
return $this->getConfig('PRINT_NAME');
}
/**
* シークレットプレビュー中か否か
*
* @return bool
*/
public static function isSecret()
{
return self::checkIsPermittedIpAddress();
}
/**
* アクセス元IPアドレスが、指定された権限において許可されたものか判定する
*
* TODO: $_SERVERの使用廃止
*
* @param array $permissionIdList
* @param $ipAddress
* @return bool
*/
public static function checkIsPermittedIpAddress(array $permissionIdList = [
0, // 0:CS
1, // 1:管理者
], $ipAddress = null)
{
$ipAddress = $ipAddress ?: $_SERVER['HTTP_X_FORWARDED_FOR'] ?: $_SERVER['REMOTE_ADDR'];
$ipAddress = explode(', ', $ipAddress);
$ipAddress = $ipAddress[0];
$ip_range_list = self::getIpRangeListByPermissionIdList($permissionIdList);
$client_ip = ip2long($ipAddress);
$is_admin = false;
foreach ($ip_range_list as $ip_range) {
list($ip_from, $ip_to) = explode(' ', $ip_range);
if ($client_ip < ip2long($ip_from) || $client_ip > ip2long($ip_to)) {
continue;
}
$is_admin = true;
break;
}
return $is_admin;
}
/**
* 指定された権限における許可IPリストを取得する
*
* @param $permissionIdList
* @return string[]
*/
public static function getIpRangeListByPermissionIdList($permissionIdList)
{
//
$result = (new SqlService())
->Select('T1.login_client_ip')
->Table('auth_admin_table')
->Join('login_table', 'aa_id = login_client_type', 'INNER')
->Set('aa_id', (array)$permissionIdList, 'IN')
->GroupBy('T1.login_client_ip')
->Order('aa_id', 'ASC')
->FindAll();
//
$result = array_unique(explode(',', implode(',', array_filter(array_map(function ($item) {
return $item['login_client_ip'];
}, $result), function ($item) {
return !empty($item);
}))));
//
sort($result);
//
return $result;
}
/**
* 一時ファイルを作成する
*
* @param $fp
* @param $filename
* @return bool
*/
public static function createTempfile(&$filename)
{
$fp = tmpfile();
$meta = stream_get_meta_data($fp);
$filename = $meta['uri'];
return $fp;
}
public function getPageType()
{
//
$result = [
'type' => '',
'value' => '',
];
//
$route = $this->Request->get('_route');
//
if ($route === 'item/detail') {
//
$result['type'] = 'item';
$result['value'] = $this->Request->get('goodsId');
} else if ($route === 'page/main-category') {
//
$result['type'] = 'main-category';
$result['value'] = $this->Request->get('mc');
} else if ($route === 'page/sub-category') {
//
$result['type'] = 'category';
$result['value'] = $this->Request->get('ct');
} else if ($route === 'homepage') {
//
$result['type'] = 'top';
$result['value'] = null;
} else {
//
$result['type'] = 'other';
$result['value'] = null;
}
//
return $result;
}
static function hoge_dump($array, $maxLevel = 1, $_level = 0)
{
foreach ($array as $key => $value) {
$type = gettype($value);
$type = ($type === 'object') ? get_class($value) : $type;
//
echo str_repeat(' ', $_level) . "{$key}({$type}): " . (($type === 'DateTime' ? $value->format('Y-m-d H:i:s') : (is_object($value) ? '(Object)' : (is_array($value) ? '(Array)' : $value)))), PHP_EOL;
if (($_level < $maxLevel)) {
//
if (preg_match('/(?:Entity|PersistentCollection)/', $type)) {
self::hoge_dump($value->toArray(), $maxLevel, $_level + 1);
} else if (preg_match('/(?:array)/i', $type)) {
self::hoge_dump($value, $maxLevel, $_level + 1);
} else {
self::hoge_dump((array)($value), $maxLevel, $_level + 1);
}
}
}
}
public function filterImagePathEnabled()
{
//
$config = $this->eccubeConfig['Filter']['ImagePath'];
//
$configEnabled = !empty($config['Enabled']);
//
return $configEnabled;
}
public function filterSliderEnabled()
{
//
$config = $this->eccubeConfig['Filter']['Slider'];
//
$configEnabled = !empty($config['Enabled']);
//
$requestDisabled = $this->Request->get('slider') === 'false';
//
return $configEnabled && !$requestDisabled;
}
public function filterRemoveCommentEnabled()
{
//
$config = $this->eccubeConfig['Filter']['RemoveComment'];
//
$configEnabled = !empty($config['Enabled']);
//
$requestDisabled = $this->Request->get('cb') === 'true';
//
return $configEnabled && !$requestDisabled;
}
public function filterAjaxPriceEnabled()
{
//
$config = $this->eccubeConfig['Filter']['AjaxPrice'];
//
$configEnabled = !empty($config['Enabled']);
//
$requestDisabled = $this->Request->get('cb') === 'true';
//
return $configEnabled && !$requestDisabled;
}
public function filterWebpEnabled()
{
//
$config = $this->eccubeConfig['Filter']['Webp'];
//
$configEnabled = !empty($config['Enabled']);
//
$requestDisabled = $this->Request->get('webp') === 'false';
//
return $configEnabled && !$requestDisabled;
}
/**
* {[EC-CUBE]商品規格1ID} を {[LM]商品カラーID} に変換する
*
* @param $src
* @return int
* @throws \Exception
*/
public function convClassCategory1IdToGclId($src)
{
//
$offset = (int)$this->getConfig([
'DbConvert' => [
'ProductClassCategory' => [
'offset' => '1'
]
]
]);
//
$dst = $src - $offset;
//
return $dst;
}
/**
* {[LM]商品カラーID} を {[EC-CUBE]商品規格1ID} に変換する
*
* @param $src
* @return int
* @throws \Exception
*/
public function convGclIdToClassCategory1Id($src)
{
//
$offset = (int)$this->getConfig([
'DbConvert' => [
'ProductClassCategory' => [
'offset' => '1'
]
]
]);
//
$dst = $src + $offset;
//
return $dst;
}
/**
* {[EC-CUBE]商品規格2ID} を {[LM]商品サイズID} に変換する
*
* @param $src
* @return int
* @throws \Exception
*/
public function convClassCategory2IdToGpId($src)
{
//
$offset = (int)$this->getConfig([
'DbConvert' => [
'ProductClassCategory' => [
'offset' => '2'
]
]
]);
//
$dst = $src - $offset;
//
return $dst;
}
public function convClassCategory2IdToGpIdRe($dst)
{
$offset = (int)$this->getConfig([
'DbConvert' => [
'ProductClassCategory' => [
'offset' => '2'
]
]
]);
$src = $dst - $offset;
return $src;
}
/**
* {[LM]商品サイズID} を {[EC-CUBE]商品規格2ID} に変換する
*
* @param $src
* @return int
* @throws \Exception
*/
public function convGpIdToClassCategory2Id($src)
{
//
$offset = (int)$this->getConfig([
'DbConvert' => [
'ProductClassCategory' => [
'offset' => '2'
]
]
]);
//
$dst = $src + $offset;
//
return $dst;
}
public function getIntegerArray($array)
{
foreach ($array as $key => $item) {
if (!ctype_digit($item)) {
unset($array[$key]);
}
}
return $array;
}
/**
* @param OrderHeaderExtended|OrderHeader|array|int $order
* @return string
* @throws \Exception
*/
public function convertOrderToOrderId($order)
{
/**
* @var OrderHeaderExtended $orderHeaderEx
*/
if ($orderHeaderEx = OrderHeaderExtended::factory($order)) {
//
return $orderHeaderEx->getOrderNo();
} else {
//
return $order;
}
}
/**
* @param string $url
* @return string|null
*/
public function getRedirectUrl($url)
{
//
$result = (new SqlService())
->Select('ru_uri_after')
->Table('redirect_url_table')
->Set('ru_type', '0')
->Set('ru_uri_before', $url)
->Limit(1)
->Find();
//
if (!empty($result)) {
//
return $result['ru_uri_after'];
}
//
return null;
}
public function getBackUrl()
{
$domain = $this->eccubeConfig['UT_URL'];
$referer = $this->session->remove('referer');
if ($referer && strpos($referer, $domain) !== false) {
return $referer;
}
return $domain;
}
public function isValidationPass($var, $length, $isNotNull, $type, $format)
{
$var = mb_convert_encoding($var, "EUC-JP", "UTF-8");
//タグチェック
if (stristr($var, ">") || stristr($var, "<")) {
return false;
}
//NULLチェック
if ($isNotNull == self::IS_NOT_NULLABLE && $var == "") {
return false;
} elseif ($isNotNull != self::IS_NOT_NULLABLE && $var == "") {
return true;
}
//型ごとのチェック処理
switch ($type) {
case 1: //英数字
for ($i = 0; $i < strlen($var); $i++) {
if (!(stristr("abcdefghijklmnopqrstuvwxyz_-@#1234567890./:?~:=&", substr($var, $i, 1)))) {
return false;
}
}
return $length >= strlen($var);
case 2: //数字
for ($i = 0; $i < strlen($var); $i++) {
if (!(stristr("0123456789", substr($var, $i, 1)))) {
return false;
}
}
return $length >= strlen($var);
case 3: //日付
switch ($format) {
case "YYYY/MM/DD HH:MM:SS":
if (substr($var, 10, 1) != " ") {
return false;
}
if (!(substr($var, 11, 2) >= "00" && substr($var, 11, 2) <= "23")) {
return false;
}
if (substr($var, 13, 1) != ":") {
return false;
}
if (!(substr($var, 14, 2) >= "00" && substr($var, 14, 2) <= "59")) {
return false;
}
if (substr($var, 16, 1) != ":") {
return false;
}
if (!(substr($var, 17, 2) >= "00" && substr($var, 17, 2) <= "59")) {
return false;
}
if (!strtotime(substr($var, 11, 8))) {
return false;
}
if (strlen($var) != 19) {
return false;
}
case "YYYY/MM/DD":
if (!(substr($var, 8, 2) >= "01" && substr($var, 8, 2) <= "31")) {
return false;
}
if (substr($var, 7, 1) != "/") {
return false;
}
if (strlen($var) != 10) {
return false;
}
case "YYYY/MM":
if (!(substr($var, 0, 4) >= 1 && substr($var, 0, 4) <= 9999)) {
return false;
}
if (!(substr($var, 5, 2) >= 1 && substr($var, 5, 2) <= 12)) {
return false;
}
if (substr($var, 4, 1) != "/") {
return false;
}
if (strlen($var) != 7) {
return false;
}
break;
default:
return false;
}
if ($format == "YYYY/MM") {
$checkDay = "$var/01";
} else {
$checkDay = $var;
}
//日付の妥当性を確認
return checkdate(substr($checkDay, 5, 2), substr($checkDay, 8, 2), substr($checkDay, 0, 4));
case 4: //電話、郵便番号
for ($i = 0; $i < strlen($var); $i++) {
if (!(stristr("1234567890-", substr($var, $i, 1)))) {
return false;
}
}
return $length >= strlen($var);
case 5: //分数
if (strlen($var) > $length) {
return false;
}
$check = explode("/", $var, 2);
for ($i = 0; $i < strlen($check[0]); $i++) {
if (!(stristr("0123456789", substr($check[0], $i, 1))) && $i == 0 && substr($check[0], $i, 1) != "-") {
return false;
}
}
//文字に/が含まれている場合は、分母もチェック
if (strstr($var, "/")) {
for ($i = 0; $i < strlen($check[1]); $i++) {
if (!(stristr("0123456789", substr($check[1], $i, 1)))) {
return false;
}
}
//分母が0でないかチェック
if ($check[1] < 1) {
return false;
}
}
break;
case 6: //半角文字
for ($i = 0; $i < strlen($var); $i++) {
if (!(stristr("abcdefghijklmnopqrstuvwxyz_-+*@1234567890./:?~:=ABCDEFGHIJKLMNOPQRSTUVWXYZ#&", substr($var, $i, 1)))) {
return false;
}
}
return $length >= strlen($var);
case 7: //メール
return preg_match("/^[^@]+@[^.]+\..+/", $var);
case 8: //数字(小数)
for ($i = 0; $i < strlen($var); $i++) {
if (!(stristr("0123456789.", substr($var, $i, 1)))) {
return false;
}
}
return (float)$var > (float)$length;
default:
return $length >= strlen($var);
}
return true;
}
/***
* @param $birthday
* @return int
*/
public function calculateAge($birthday): ?int
{
if (empty($birthday)) {
return null;
}
$today = new \DateTime();
$birthdate = new \DateTime($birthday);
$age = $today->diff($birthdate)->y;
return $age;
}
public function getCacheKey($masterCacheKey, $Datas)
{
$device = $this->mobileDetector->isMobile() ? 'sp' : 'pc';
$suffix = hash('sha256', base64_encode(serialize($Datas)));
return "{$masterCacheKey}__{$device}__{$suffix}";
}
public function hasSusoage($Carts = null)
{
//
return GoodsService::isSusoageExistInJanIdList(array_map(function ($ProductClass) {
//
return $ProductClass->getId();
}, $this->getEstimateProductClasses($Carts)));
}
public function hasKyouei($Carts = null)
{
//
return GoodsService::isKyoueiExistInJanIdList(array_map(function ($ProductClass) {
//
return $ProductClass->getId();
}, $this->getAllProductClasses($Carts)));
}
public function hasShishu($Carts = null)
{
if (!$Carts) {
$Carts = $this->CartHelper->getCarts();
}
$flag = true;
$hasProduct = false;
foreach ($Carts as $Cart) {
//
foreach ($Cart->getCartItems() as $CartItem) {
//
$options = $CartItem->getOptions();
if ($CartItem->isProduct() && !empty($options)) {
$flagItem = false;
$hasProduct = true;
//
$options = json_decode($options, true);
if (isset($options['print']) && is_array($options['print'])) {
$prints = $options['print'];
foreach ($prints as $print) {
if ($print['position'] == 3) {
$flagItem = true;
}
}
}
$flag = $flag && $flagItem;
}
}
}
//
return $flag && $hasProduct;
}
/**
* @return ProductClass[]
*/
public function getEstimateProductClasses($Carts = null)
{
/**
* @var ProductClass[] $ProductClasses
*/
$ProductClasses = [];
//
if (!$Carts) {
$Carts = $this->CartHelper->getCarts();
}
foreach ($Carts as $Cart) {
//
foreach ($Cart->getCartItems() as $CartItem) {
//
if ($CartItem->isProduct() && !empty($CartItem->getOptions())) {
//
$ProductClasses[] = $CartItem->getProductClass();
}
}
}
//
return $ProductClasses;
}
public function hasNotEstimate($Carts = null)
{
if (!$Carts) {
$Carts = $this->CartHelper->getCarts();
}
foreach ($Carts as $Cart) {
//
foreach ($Cart->getCartItems() as $CartItem) {
//
if ($CartItem->isProduct() && (!$CartItem->getEstimateId() || !$CartItem->getOptions())) {
//
return true;
}
}
}
return false;
}
/**
* @return ProductClass[]
*/
public function getAllProductClasses($Carts = null)
{
/**
* @var ProductClass[] $ProductClasses
*/
$ProductClasses = [];
if (!$Carts) {
$Carts = $this->CartHelper->getCarts();
}
//
foreach ($Carts as $Cart) {
//
foreach ($Cart->getCartItems() as $CartItem) {
//
if ($CartItem->isProduct()) {
//
$ProductClasses[] = $CartItem->getProductClass();
}
}
}
//
return $ProductClasses;
}
}