MOON
Server: Apache
System: Linux u18017238.onlinehome-server.com 3.10.0-1127.19.1.el7.x86_64 #1 SMP Tue Aug 25 17:23:54 UTC 2020 x86_64
User: emblazeone (1003)
PHP: 7.3.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: /home/emblazeone/public_html/lyyt/common/models/WbpActiveRecord.php
<?php

namespace common\models;

use vendor\wbp\helpers\UrlStr;
use wbp\file\File;
use wbp\helpers\UploadifyHelper;
use wbp\images\models\Image;
use wbp\video\Video;
use Yii;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

class WbpActiveRecord extends \yii\db\ActiveRecord
{
    const STATUS_DISABLED = 0;
    const STATUS_ACTIVE = 1;

    const ADMIN_ADD_SCENARIO = 'admin-add';
    const ADMIN_EDIT_SCENARIO = 'admin-update';


    protected $arrayPars = [];
    public static $imageTypes = [];
    public static $videoTypes = [];
    public static $fileTypes = [];



    public static $floatValues = [];

    public static $imageSizesRequired = [];

    public static $seoKey = '';

    private $IDplaceholder = "-{|ID|}";

    public $relationFields=[];

    public function __get($name)
    {
        foreach ($this->relationFields as $relationName=>$values){
            if(in_array($name,$values)){
                $object=call_user_func([$this,'get'.ucfirst($relationName)]);
                return $object->{$name};
            }
        }

        return parent::__get($name); // TODO: Change the autogenerated stub
    }

    public function __set($name, $value)
    {
        foreach ($this->relationFields as $relationName=>$values){
            if(in_array($name,$values)){
                $object=call_user_func([$this,'get'.ucfirst($relationName)]);

                return $object->{$name}=$value;
            }
        }

        return parent::__set($name, $value); // TODO: Change the autogenerated stub
    }

    public function behaviors()
    {
        $behaviours = parent::behaviors();
        $additional = [
            'image' => [
                'class' => \wbp\images\behaviors\ImageBehave::className(),
            ],
            'video' => [
                'class' => \wbp\video\behaviors\VideoBehave::className(),
            ],
            'file' => [
                'class' => \wbp\file\behaviors\FileBehave::className(),
            ]
        ];

        if (in_array('created_at', $this->attributes()) && in_array('updated_at', $this->attributes())) {
            $additional = ArrayHelper::merge($additional, [
                'time' => [
                    'class' => TimestampBehavior::className(),
                    'value' => new Expression('NOW()'),
                ]
            ]);
        }

        return ArrayHelper::merge($behaviours, $additional);
    }

    public function prepareFloat($value){
        if($value===null || $value===false) return 0;
        $value=preg_replace('#[^0-9\.,\-]#', '', $value);

        if(strstr($value, '.')!=false){
            $value=str_replace(',','', $value);
        }else{
            $value=str_replace(',','.', $value);
        }

        if(strstr($value, '.')===0){
            $value="0".$value;
        }

        $tmp=explode('.',$value);
        if(count($tmp)>2){
            $tmp[count($tmp)-1]='.'.$tmp[count($tmp)-1];
            $value=implode('', $tmp);
        }

        if(!$value) return 0;

        return $value;
    }

    public function beforeSave($insert)
    {
        foreach (static::$floatValues as $attribute){
            $this->{$attribute} = $this->prepareFloat($this->{$attribute});
        }


        $attributes = $this->attributes();
        if (in_array('href', $attributes) && in_array('title', $attributes) && $this->href == '') {
            $this->href = UrlStr::urlstr($this->title);
            //check for already exist
            $check = self::findOne(['href'=>$this->href]);
            if($check){
                $this->href .= $this->IDplaceholder;
            }
            //end check
        }

        foreach ($this->arrayPars as $par) {
            $newArray=[];
            if(is_array($this->{$par})){
                $newArray=[];
                foreach ($this->{$par} as $num => $value){
                    if($value){
                        $newArray[]=$this->{$par}[$num];
                    }
                }
            }
            $this->{$par}=$newArray;
            if (!$this->{$par} || !is_array($this->{$par}) || count($this->{$par}) == 0) {
                $this->{$par} = '';
            } elseif(is_array($this->{$par}) && count($this->{$par})) {
                $this->{$par} = '0|' . implode('|', $this->{$par}) . '|0';
            }
        }

        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        foreach ($this->arrayPars as $par) {
            $this->{$par} = explode('|', $this->{$par});
            $newArray=[];
            foreach ($this->{$par} as $num => $id) {
                if ($id) $newArray[]=$id;
            }
            $this->{$par} = $newArray;
        }

        $this->saveUploadedImages();
        $this->saveUploadedVideos();
        $this->saveUploadedFiles();

        if (isset($this->href)) {
            if (stristr($this->href, $this->IDplaceholder)) {
                $this->href = str_replace($this->IDplaceholder, "-" . $this->id, $this->href);
                $this->save();
            }
        }

        foreach ($this->relationFields as $relationName=>$values){
            $object=call_user_func([$this,'get'.ucfirst($relationName)]);
//            var_dump($object); exit();
            $object->save();
        }


        return parent::afterSave($insert, $changedAttributes);
    }

    public function afterFind()
    {
        foreach ($this->arrayPars as $par) {
            $this->{$par} = explode('|', $this->{$par});
            $newArray=[];
            foreach ($this->{$par} as $num => $id) {
                if ($id) $newArray[]=$id;
            }
            $this->{$par} = $newArray;
        }
        return parent::afterFind();
    }

    public function duplicate($save=true)
    {
        $class = get_called_class();
        $clone = new $class;
        foreach ($this->attributes as $name=>$value){
            if($name=='id') continue;
            $clone->{$name}=$value;
        }
        $clone->attributes = $this->attributes;
        if($save) $clone->save();
        return $clone;
    }

    public function getMultiLang($name, $languagePrefix=false)
    {
        if($languagePrefix!==false) $langPrefix=$languagePrefix;
        else $langPrefix = Yii::$app->lang->getLanguagePrefix();

        $value=$this->{$name . $langPrefix};

        if(!$value && $this->{$name}) return $this->{$name};

        return $value;
    }

    public function getShortParam($param, $multilang = true, $seperator = '%main-content%')
    {
        if ($multilang) return $this->StripUnclosedTags(explode($seperator, $this->getMultiLang($param))[0]);
        else return $this->StripUnclosedTags(explode($seperator, $this->{$param})[0]);
    }

    public function getFullParam($param, $multilang = true, $seperator = '%main-content%')
    {
        if ($multilang) return $this->StripUnclosedTags(str_replace($seperator, '', $this->getMultiLang($param)));
        else return $this->StripUnclosedTags(str_replace($seperator, '', $this->{$param}));
    }

    public static function getList($key = 'id', $value = 'title', $sort = 'sort,id desc', $where = false,$andWhere = false)
    {
        $class = get_called_class();
        $result = [];
        $items = $class::find();
        if ($where) $items = $items->where($where);
        if ($andWhere) $items = $items->andWhere($andWhere);
        $items = $items->orderBy($sort)->all();
        foreach ($items as $item) {
            $result[$item->{$key}] = $item->{$value};//.'&nbsp;';
        }
        return $result;
    }

    public static function getListFromArray($models, $key = 'id', $value = 'title')
    {
        $result = [];
        foreach ($models as $item) {
            $result[$item[$key]] = $item[$value];
        }
        return $result;
    }

    static function sort($elements, $pars = [])
    {
        $class = get_called_class();
        $items = $class::find()->orderBy('sort, id desc');
        $i = 0;
        foreach ($items->each() as $item) {
            $item->sort = $i;
            $item->save();
            $i++;
        }

        $sort = $class::find()->min('sort');
        foreach ($elements as $element) {
            if (!(int)$element) continue;
            $item = $class::findOne(['id' => $element]);
            if (!$item) continue;
            $item->sort = $sort;
            $item->save();
            $sort++;
        }

    }

    static function sortWhere($elements, $where = [])
    {
        $class = get_called_class();
        $items = $class::find()->orderBy('sort, id desc');
        if($where) $items = $items->where($where);
        $i = 0;
        foreach ($items->each() as $item) {
            $item->sort = $i;
            $item->save();
            $i++;
        }

        $sort = $class::find()->min('sort');
        foreach ($elements as $element) {
            if (!(int)$element) continue;
            $item = $class::findOne(['id' => $element]);
            if (!$item) continue;
            $item->sort = $sort;
            $item->save();
            $sort++;
        }

    }

    public function saveUploadedImages($item_id = '', $limit = false)
    {
        // Save uploaded images
        if (!$item_id) $item_id = $this->id;
        $types = [];
        $imagesUniques = Yii::$app->request->post('image');
        if (is_array($imagesUniques)) {
            foreach ($imagesUniques as $unique_id) {
                $images = Image::find()->where(['unique_id' => $unique_id]);
                foreach ($images->each() as $img) {
                    $name = $this::className();
                    if (!in_array($img->type, $name::$imageTypes)) continue;
                    if (!in_array($img->type, $types)) $types[] = $img->type;
                    $img->item_id = $item_id;
                    $img->save();
                }
            }
        }
        if ($limit) {
            foreach ($types as $type) {
                $images = Image::find()->where(['item_id' => $item_id, 'type' => $type])->orderBy('sort, id desc');
                $currentLimit = 0;
                foreach ($images->each() as $image) {
                    if ($currentLimit >= $limit) $image->delete();
                    $currentLimit++;
                }
            }
        }

    }

    public function saveUploadedVideos($item_id = '', $limit = false)
    {
        // Save uploaded images
        if (!$item_id) $item_id = $this->id;
        $types = [];
        $videosUniques = Yii::$app->request->post('video');
        if (is_array($videosUniques)) {
            foreach ($videosUniques as $unique_id) {
                $videos = Video::find()->where(['unique_id' => $unique_id]);
                foreach ($videos->each() as $vid) {
                    $name = $this::className();
                    if (!in_array($vid->type, $name::$videoTypes)) continue;
                    if (!in_array($vid->type, $types)) $types[] = $vid->type;
                    $vid->item_id = $item_id;
                    $vid->save();
                }
            }
        }
        if ($limit) {
            foreach ($types as $type) {
                $videos = Video::find()->where(['item_id' => $item_id, 'type' => $type])->orderBy('sort, id desc');
                $currentLimit = 0;
                foreach ($videos->each() as $video) {
                    if ($currentLimit >= $limit) $video->delete();
                    $currentLimit++;
                }
            }
        }

    }

    public function saveUploadedFiles($item_id = '', $limit = false)
    {
        if (!$item_id) $item_id = $this->id;
        UploadifyHelper::saveUploadedFiles(static::$fileTypes,$item_id,$limit);
    }

    function StripUnclosedTags($input)
    {
        // Close <br> tags
        $buffer = str_replace("<br>", "<br/>", $input);
        // Find all matching open/close HTML tags (using recursion)
        $pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/ixsm";
        preg_match_all($pattern, $buffer, $matches, PREG_OFFSET_CAPTURE);
        // Mask matching open/close tag sequences in the buffer
        foreach ($matches[0] as $match) {
            $ofs = $match[1];
            for ($i = 0; $i < strlen($match[0]); $i++, $ofs++)
                $buffer[$ofs] = "#";
        }
        // Remove unclosed tags
        $buffer = preg_replace("/<.*$/", "", $buffer);
        // Put back content of matching open/close tag sequences to the buffer
        foreach ($matches[0] as $match) {
            $ofs = $match[1];
            for ($i = 0; $i < strlen($match[0]) && $ofs < strlen($buffer); $i++, $ofs++)
                $buffer[$ofs] = $match[0][$i];
        }
        return $buffer;
    }
}