Source of file ImageWithStyle.php
Size: 15,336 Bytes - Last Modified: 2021-12-23T10:42:00+00:00
/var/www/docs.ssmods.com/process/src/code/model/ImageWithStyle.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 | <?php class ImageWithStyle extends DataObject { ####################### ### Names Section ####################### private static $singular_name = 'Image With Style'; public function i18n_singular_name() { return _t('ImageWithStyle.SINGULAR_NAME', 'Image With Style'); } private static $plural_name = 'Images With Style'; public function i18n_plural_name() { return _t('ImageWithStyle.PLURAL_NAME', 'Images With Style'); } ####################### ### Model Section ####################### private static $db = [ 'Title' => 'Varchar(100)', 'Description' => 'Text', 'AlternativeImageURL' => 'Varchar(255)', //e.g. https://via.placeholder.com/468x60?text=hellooooooooooooooo 'VideoLink' => 'Varchar(255)', 'Var1' => 'Varchar', 'Var2' => 'Varchar', 'Var3' => 'Varchar', 'Var4' => 'Varchar', 'Var5' => 'Varchar', ]; private static $has_one = [ 'Image' => 'Image', 'Style' => 'ImageStyle', 'LinksTo' => 'SiteTree', ]; private static $belongs_many_many = [ 'Selections' => 'ImagesWithStyleSelection' ]; ####################### ### Further DB Field Details ####################### private static $indexes = [ 'Created' => true ]; private static $default_sort = [ 'Created' => 'DESC' ]; private static $required_fields = [ 'Title', 'StyleID' ]; private static $searchable_fields = [ 'Title' => 'PartialMatchFilter' ]; ####################### ### Field Names and Presentation Section ####################### private static $field_labels = [ 'Style' => 'Display Style', 'Title' => 'Image Title', 'Selections' => 'Lists' ]; private static $field_labels_right = [ 'Pages' => 'On what pages is this image visible' ]; private static $summary_fields = [ 'Title' => 'Title', 'Style.Title' => 'Style', 'Image.CMSThumbnail' => 'Image' ]; private static $casting = [ 'ImageElement' => 'HTMLText' ]; private static $unique_vars = ['Var1', 'Var2', 'Var3', 'Var4', 'Var5']; ####################### ### Casting Section ####################### ####################### ### can Section ####################### public function canDelete($member = null) { return false; } ####################### ### write Section ####################### public function validate() { $result = parent::validate(); $fieldLabels = $this->FieldLabels(); $indexes = $this->Config()->get('indexes'); $requiredFields = $this->Config()->get('required_fields'); if($this->exists() && $this->hasRealStyle()) { if($this->VideoLink) { $requiredFields[] = 'VideoLink'; } elseif($this->AlternativeImageURL) { $requiredFields[] = 'AlternativeImageURL'; } else { $requiredFields[] = 'ImageID'; } } if (is_array($requiredFields)) { foreach ($requiredFields as $field) { $value = $this->$field; if (! $value) { $fieldWithoutID = $field; if (substr($fieldWithoutID, -2) === 'ID') { $fieldWithoutID = substr($fieldWithoutID, 0, -2); } $myName = isset($fieldLabels[$fieldWithoutID]) ? $fieldLabels[$fieldWithoutID] : $fieldWithoutID; $result->error( _t( 'ImageWithStyle.'.$field.'_REQUIRED', $myName.' is required' ), 'REQUIRED_ImageWithStyle_'.$field ); } if (isset($indexes[$field]) && isset($indexes[$field]['type']) && $indexes[$field]['type'] === 'unique') { $id = (empty($this->ID) ? 0 : $this->ID); $count = ImageWithStyle::get() ->filter(array($field => $value)) ->exclude(array('ID' => $id)) ->count(); if ($count > 0) { $myName = $fieldLabels['$field']; $result->error( _t( 'ImageWithStyle.'.$field.'_UNIQUE', $myName.' needs to be unique' ), 'UNIQUE_ImageWithStyle_'.$field ); } } } } return $result; } public function onBeforeWrite() { parent::onBeforeWrite(); //... if (!$this->StyleID) { $this->StyleID = $defaultStyle->ID; } } public function onAfterWrite() { parent::onAfterWrite(); //... $image = $this->Image(); if ($image && $image->exists()) { $image->Title = $this->Title; $image->write(); } } public function requireDefaultRecords() { parent::requireDefaultRecords(); //... } ####################### ### Import / Export Section ####################### public function getExportFields() { //.. return parent::getExportFields(); } ####################### ### CMS Edit Section ####################### public function CMSEditLink() { $controller = singleton("tba"); return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/".$this->ID."/edit"; } public function CMSAddLink() { $controller = singleton("tba"); return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/new"; } public function getCMSFields() { $fields = parent::getCMSFields(); //do first?? $rightFieldDescriptions = $this->Config()->get('field_labels_right'); foreach ($rightFieldDescriptions as $field => $desc) { $formField = $fields->DataFieldByName($field); if (! $formField) { $formField = $fields->DataFieldByName($field.'ID'); } if ($formField) { $formField->setDescription($desc); } } //... if ($this->hasRealStyle()) { $style = $this->Style(); $varsArray = $this->Config()->get('unique_vars'); //var_dump($this->Style()); foreach ($varsArray as $varName) { if ($this->Style()->hasStyleVariable($varName)) { $name = $varName . 'Name'; $type = $varName . 'Type'; $descriptionField = $varName . 'Description'; switch ($this->Style()->$type) { case 'Pixels': case 'Percentage': $newField = NumericField::create($varName, $style->$name) ->setRightTitle($this->Style()->$descriptionField.' ('.$style->$type.'). Negative number are allowed in some instances.'); break; case 'Options': $newField = OptionSetField::create($varName, $style->$name, $this->Style()->OptionsAsArray($varName)) ->setRightTitle($this->Style()->$descriptionField); break; } $fields->replaceField( $varName, $newField ); } else { $fields->removeByName($varName); } } if ($style->ClassNameForCSS) { $fields->replaceField( 'Image', $uploadField = PerfectCMSImagesUploadField::create('Image', 'Image', null, $style->ClassNameForCSS) ); $uploadField->setFolderName($this->BestFolder()); } } else { $varsArray = $this->Config()->get('unique_vars'); foreach ($varsArray as $var) { $fields->removeByName($var); } $fields->replaceField( 'Image', $uploadField = LiteralField::create('ImageReminder', '<h2>Image Upload</h2><p>Please select a style first (see below) and save this record. After that you can upload an image</p>') ); } $fields->replaceField( 'Selections', CheckboxSetField::create( 'Selections', 'Included in ...', ImagesWithStyleSelection::get()->map() ) ); $fields->replaceField( 'LinksToID', TreeDropdownField::create( 'LinksToID', 'LinksTo', 'SiteTree' ) ); $fields->replaceField( 'VideoLink', TextField::create( 'VideoLink', 'Link to Video' )->setDescription('For youtube, your link should look something like: https://www.youtube.com/watch?v=igiiMi2ZIMo.') ); return $fields; } /** * @return string (HTML) */ public function ImageElement() { return $this->getImageElement(); } /** * @return string (HTML) */ public function getImageElement() { $html = ''; if ($this->hasRealStyle()) { if ($this->hasVideoOrImage()) { return $this->renderWith('ImageWithStyle'); } } return $html; } public function getImageObject() { return $this->Image(); } public function getCaption() : string { return (string) $this->Description; } public function getClassNameForCSS() : string { $style = $this->Style(); if($style && $style->exists()) { return (string) $style->ClassNameForCSS; } return ''; } public function getImageTag() { if($this->AlternativeImageURL) { return '<img src="'.$this->AlternativeImageURL.'" alt="'.Convert::raw2att($this->Title).'" />'; } else { return $this->Image()->PerfectCMSImageTag($this->Style()->ClassNameForCSS); } } public function getIsVideo() : bool { return $this->getVideoCode() ? true : false; } public function getVideoCode() : string { $type = $this->getVideoType(); switch ($type) { case 'YOUTUBE': // this regular expression could be quite fragile IDK // YouTube video URL IDs are NOT guaranteed to always be 11 characters long... $youTubeVideoIDRegex = preg_match('/v=\w{11}/', $this->VideoLink, $matches); if (count($matches) === 0) { throw new Exception('Could not find the Youtube ID from the VideoLink'); } // remove the "v=" from the front of the result return substr($matches[0], 2); case 'VIMEO': $vimeoIDRegex = preg_match('/vimeo.com\/([0-9]+$)/', $this->VideoLink, $matches); if (count($matches) === 0) { throw new Exception('Could not find the Vimeo ID from the VideoLink'); } return substr($matches[0], strlen('vimeo.com/')); default: return ''; } } protected function getVideoType() : string { if($this->VideoLink) { if (stripos($this->VideoLink, 'youtube') !== false) { return "YOUTUBE"; } elseif (stripos($this->VideoLink, 'vimeo') !== false) { return 'VIMEO'; } } return ''; } public function getVideoThumbnailSrc() : string { $type = $this->getVideoType(); switch ($type) { case 'YOUTUBE': return 'https://img.youtube.com/vi/'.$this->getVideoCode().'/maxresdefault.jpg'; case 'VIMEO': $videoMetaData = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $this->getVideoCode() . '.php')); return $videoMetaData[0]['thumbnail_large']; default: return ''; } } public function getCalculatedLinkTo() : string { if($this->VideoLink) { return $this->VideoLink; } elseif($this->LinksToID && $page = $this->LinksTo()) { return $page->Link(); } return ''; } public function hasVideoOrImage() : bool { if($this->getIsVideo()) { return true; } if($this->AlternativeImageURL) { return true; } else { return $this->Image() && $this->Image()->exists(); } } public function getMyStyles() { return $this->buildStyles(); } /** * @return string (HTML) */ protected function buildStyles() { $styles = ''; if ($this->hasRealStyle()) { $style = $this->Style(); $stylesArray = []; $varsArray = $this->Config()->get('unique_vars'); ; //var_dump($this->Style()); foreach ($varsArray as $var) { if ($this->$var) { $name = $var . 'Name'; $type = $var . 'Type'; $styleString = $style->$name . ': ' . $this->$var . $this->convertVarTypeToCSS($style->$type) . ';'; array_push($stylesArray, $styleString); } } if (! empty($stylesArray)) { $styles = ' style="'.implode(" ", $stylesArray).'"'; } } return $styles; } protected function hasRealStyle() : bool { $style = $this->Style(); return $style && $style->exists(); } /** * @param string * @return string */ protected function convertVarTypeToCSS($type) { $str = ''; switch ($type) { case 'Pixels': $str = 'px'; break; case 'Percentage': $str = '%'; break; case 'Options': break; } return $str; } public function BestFolder() { if ($this->Selections()->count()) { foreach ($this->Selections() as $selection) { if ($folder = $selection->PlaceToStoreImages()) { if ($folder->FileName) { return trim( str_replace(ASSETS_DIR, '', $folder->Filename), '/' ); } } } } } } |