sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function daysInMonth($year, $month) { if ($year < 1) { throw new InvalidArgumentException('Year ' . $year . ' is invalid for this calendar'); } elseif ($month < 1 || $month > 13) { throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar'); } elseif ($month == 2) { return $this->daysInMonthHeshvan($year); } elseif ($month == 3) { return $this->daysInMonthKislev($year); } elseif ($month == 6) { return $this->daysInMonthAdarI($year); } else { return self::$FIXED_MONTH_LENGTHS[$month]; } }
Determine the number of days in a specified month, allowing for leap years, etc. @param int $year @param int $month @return int
entailment
protected function jdToY($julian_day) { // Estimate the year, and underestimate it, it will be refined after $year = max((int) ((($julian_day - 347998) * 98496) / 35975351) - 1, 1); // Adjust by adding years; while ($julian_day >= $this->yToJd($year + 1)) { $year++; } return $year; }
Convert a Julian day number into a year. @param int $julian_day @return int
entailment
public function jdToYmd($julian_day) { // Find the year, by adding one month at a time to use up the remaining days. $year = $this->jdToY($julian_day); $month = 1; $day = $julian_day - $this->yToJd($year) + 1; while ($day > $this->daysInMonth($year, $month)) { $day -= $this->daysInMonth($year, $month); $month++; } // PHP 5.4 and earlier converted non leap-year Adar into month 6, instead of month 7. $month -= ($month === 7 && $this->options[self::EMULATE_BUG_54254] && !$this->isLeapYear($year)) ? 1 : 0; return array($year, $month, $day); }
Convert a Julian day number into a year/month/day. @param int $julian_day @return int[]
entailment
protected function yToJd($year) { $div19 = (int) (($year - 1) / 19); $mod19 = ($year - 1) % 19; $months = 235 * $div19 + 12 * $mod19 + (int) ((7 * $mod19 + 1) / 19); $parts = 204 + 793 * ($months % 1080); $hours = 5 + 12 * $months + 793 * (int) ($months / 1080) + (int) ($parts / 1080); $conjunction = 1080 * ($hours % 24) + ($parts % 1080); $julian_day = 1 + 29 * $months + (int) ($hours / 24); if ($conjunction >= 19440 || $julian_day % 7 === 2 && $conjunction >= 9924 && !$this->isLeapYear($year) || $julian_day % 7 === 1 && $conjunction >= 16789 && $this->isLeapYear($year - 1) ) { $julian_day++; } // The actual year start depends on the day of the week return $julian_day + self::$ROSH_HASHANAH[$julian_day % 7]; }
Calculate the Julian Day number of the first day in a year. @param int $year @return int
entailment
public function ymdToJd($year, $month, $day) { return $this->yToJd($year) + self::$CUMULATIVE_DAYS[$this->isLeapYear($year)][$this->yearType($year)][$month] + $day - 1; }
Convert a year/month/day to a Julian day number. @param int $year @param int $month @param int $day @return int
entailment
private function yearType($year) { $year_length = $this->yToJd($year + 1) - $this->yToJd($year); if ($year_length === 353 || $year_length === 383) { return self::DEFECTIVE_YEAR; } elseif ($year_length === 355 || $year_length === 385) { return self::COMPLETE_YEAR; } else { return self::REGULAR_YEAR; } }
Determine whether a year is normal, defective or complete. @param int $year @return int defective (-1), normal (0) or complete (1)
entailment
protected function hebrewMonthNames($year) { $leap_year = $this->isLeapYear($year); return array( 1 => "\xfa\xf9\xf8\xe9", // Tishri - תשרי "\xe7\xf9\xe5\xef", // Heshvan - חשון "\xeb\xf1\xec\xe5", // Kislev - כסלו "\xe8\xe1\xfa", // Tevet - טבת "\xf9\xe1\xe8", // Shevat - שבט $leap_year ? ($this->options[self::EMULATE_BUG_54254] ? "\xe0\xe3\xf8" : "\xe0\xe3\xf8 \xe0'") : "\xe0\xe3\xf8", // Adar I - אדר - אדר א׳ - אדר $leap_year ? ($this->options[self::EMULATE_BUG_54254] ? "'\xe0\xe3\xf8 \xe1" : "\xe0\xe3\xf8 \xe1'") : "\xe0\xe3\xf8", // Adar II - 'אדר ב - אדר ב׳ - אדר "\xf0\xe9\xf1\xef", // Nisan - ניסן "\xe0\xe9\xe9\xf8", // Iyar - אייר "\xf1\xe9\xe5\xef", // Sivan - סיון "\xfa\xee\xe5\xe6", // Tammuz - תמוז "\xe0\xe1", // Av - אב "\xe0\xec\xe5\xec", // Elul - אלול ); }
Hebrew month names. @link https://bugs.php.net/bug.php?id=54254 @param int $year @return string[]
entailment
protected function addGereshayim($hebrew) { switch (strlen($hebrew)) { case 0: // Zero, e.g. the zeros from the year 5,000 return $hebrew; case 1: // Single digit - append a geresh return $hebrew . self::GERESH_ISO8859; default: // Multiple digits - insert a gershayim return substr_replace($hebrew, self::GERSHAYIM_ISO8859, -1, 0); } }
Add geresh (׳) and gershayim (״) punctuation to numeric values. Gereshayim is a contraction of “geresh” and “gershayim”. @param string $hebrew @return string
entailment
private function numberToNumerals($number, array $numerals) { $string = ''; while ($number > 0) { foreach ($numerals as $n => $t) { if ($number >= $n) { $string .= $t; $number -= $n; break; } } } return $string; }
Convert a number into a string, in the style of roman numerals @param int $number @param string[] $numerals @return string
entailment
public function numberToHebrewNumerals($number, $show_thousands) { // Years (e.g. "5782") may be written without the thousands (e.g. just "782"), // but since there is no zero, the number 5000 must be written as "5 thousand" if ($show_thousands || $number % 1000 === 0) { $thousands = (int)($number / 1000); } else { $thousands = 0; } $number = $number % 1000; $hebrew = $this->numberToNumerals($number, self::$HEBREW_NUMERALS_UTF8); // Two bytes per UTF8 character if (strlen($hebrew) === 2) { // Append a geresh after single-digit $hebrew .= self::GERESH; } elseif (strlen($hebrew) > 2) { // Some letters have a "final" form, when used at the end of a word. $hebrew = substr($hebrew, 0, -2) . strtr(substr($hebrew, -2), self::$FINAL_FORMS_UTF8); // Insert a gershayim before the final letter $hebrew = substr_replace($hebrew, self::GERSHAYIM, -2, 0); } if ($thousands) { if ($hebrew) { $hebrew = $this->numberToHebrewNumerals($thousands, $show_thousands) . $hebrew; } else { $hebrew = $this->numberToHebrewNumerals($thousands, $show_thousands) . ' ' . self::ALAFIM; } } return $hebrew; }
Convert a number into Hebrew numerals using UTF8. @param int $number @param bool $show_thousands @return string
entailment
protected function numberToHebrewNumeralsIso8859($number, $gereshayim) { $hebrew = $this->numberToNumerals($number, self::$HEBREW_NUMERALS_ISO8859_8); // Hebrew numerals are letters. Add punctuation to prevent confusion with actual words. if ($gereshayim) { return $this->addGereshayim($hebrew); } else { return $hebrew; } }
Convert a number into Hebrew numerals using ISO8859-8. @param int $number @param bool $gereshayim Add punctuation to numeric values @return string
entailment
protected function yearToHebrewNumerals($year, $alafim_geresh, $alafim, $gereshayim) { if ($year < 1000) { return $this->numberToHebrewNumeralsIso8859($year, $gereshayim); } else { $thousands = $this->numberToHebrewNumeralsIso8859((int) ($year / 1000), false); if ($alafim_geresh) { $thousands .= self::GERESH_ISO8859; } if ($alafim) { $thousands .= ' ' . self::ALAFIM_ISO8859 . ' '; } return $thousands . $this->numberToHebrewNumeralsIso8859($year % 1000, $gereshayim); } }
Format a year using Hebrew numerals. @param int $year @param bool $alafim_geresh Add a geresh (׳) after thousands @param bool $alafim Add the word for thousands after the thousands @param bool $gereshayim Add geresh (׳) and gershayim (״) punctuation to numeric values @return string
entailment
public function jdToHebrew($julian_day, $alafim_garesh, $alafim, $gereshayim) { list($year, $month, $day) = $this->jdToYmd($julian_day); return $this->numberToHebrewNumeralsIso8859($day, $gereshayim) . ' ' . $this->hebrewMonthName($year, $month) . ' ' . $this->yearToHebrewNumerals($year, $alafim_garesh, $alafim, $gereshayim); }
Convert a Julian Day number into a Hebrew date. @param int $julian_day @param bool $alafim_garesh @param bool $alafim @param bool $gereshayim @return string
entailment
public function daysInMonth($year, $month) { if ($year === 0) { throw new InvalidArgumentException('Year ' . $year . ' is invalid for this calendar'); } elseif ($month < 1 || $month > 12) { throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar'); } elseif ($month === 1 || $month === 3 || $month === 5 || $month === 7 || $month === 8 || $month === 10 || $month === 12) { return 31; } elseif ($month === 4 || $month === 6 || $month === 9 || $month === 11) { return 30; } elseif ($this->isLeapYear($year)) { return 29; } else { return 28; } }
Determine the number of days in a specified month, allowing for leap years, etc. @param int $year @param int $month @return int
entailment
public function jdToYmd($julian_day) { $c = $julian_day + 32082; $d = (int) ((4 * $c + 3) / 1461); $e = $c - (int) (1461 * $d / 4); $m = (int) ((5 * $e + 2) / 153); $day = $e - (int) ((153 * $m + 2) / 5) + 1; $month = $m + 3 - 12 * (int) ($m / 10); $year = $d - 4800 + (int) ($m / 10); if ($year < 1) { // 0 is 1 BCE, -1 is 2 BCE, etc. $year--; } return array($year, $month, $day); }
Convert a Julian day number into a year/month/day. @param int $julian_day @return int[]
entailment
public function easterDays($year) { // The “golden” number $golden = 1 + $year % 19; // The “dominical” number (finding a Sunday) $dom = ($year + (int) ($year / 4) + 5) % 7; if ($dom < 0) { $dom += 7; } // The uncorrected “Paschal full moon” date $pfm = (3 - 11 * $golden - 7) % 30; if ($pfm < 0) { $pfm += 30; } // The corrected “Paschal full moon” date if ($pfm === 29 || $pfm === 28 && $golden > 11) { $pfm--; } $tmp = (4 - $pfm - $dom) % 7; if ($tmp < 0) { $tmp += 7; } return $pfm + $tmp + 1; }
Get the number of days after March 21 that easter falls, for a given year. Uses the algorithm found in PHP’s ext/calendar/easter.c @param int $year @return int
entailment
public function init() { /** @var Language $oLang */ $oLang = oxNew(Language::class); header('Content-Type: application/javascript'); $oUtils = Registry::getUtils(); $sJson = $oUtils->encodeJson($oLang->getLanguageStrings()); $oUtils->showMessageAndExit(";( function(g){ g.i18n = " . $sJson . "; })(window);"); }
Init function
entailment
public function generateTokenSignature($data, PrivateKey $privateKey) { if (!$privateKey instanceof VirgilPrivateKey) { throw new VirgilCryptoException("instance of VirgilPrivateKey expected"); } return $this->virgilCrypto->generateSignature($data, $privateKey); }
@param string $data @param PrivateKey $privateKey @return string @throws VirgilCryptoException
entailment
public function verifyTokenSignature($signature, $data, PublicKey $publicKey) { if (!$publicKey instanceof VirgilPublicKey) { throw new VirgilCryptoException("instance of VirgilPublicKey expected"); } return $this->virgilCrypto->verifySignature($data, $signature, $publicKey); }
@param string $signature @param string $data @param PublicKey $publicKey @return bool @throws VirgilCryptoException
entailment
public function renderRichTextEditor($width, $height, $objectValue, $fieldName) { if (strpos($width, '%') === false) { $width .= 'px'; } if (strpos($height, '%') === false) { $height .= 'px'; } $oConfig = $this->getConfig(); $oLang = Registry::getLang(); $oUtilsView = Registry::get('oxUtilsView'); $oSmarty = $oUtilsView->getSmarty(true); $oSmarty->assign('oView', $this->getView()); $oSmarty->assign('oViewConf', $this->getViewConfig()); $oSmarty->assign('sEditorField', $fieldName); $oSmarty->assign('sEditorValue', $objectValue); $oSmarty->assign('iEditorHeight', $height); $oSmarty->assign('iEditorWidth', $width); $oSmarty->assign('blTextEditorDisabled', $this->isTextEditorDisabled()); $iDynInterfaceLanguage = $oConfig->getConfigParam('iDynInterfaceLanguage'); $sLangAbbr = $oLang->getLanguageAbbr((isset($iDynInterfaceLanguage) ? $iDynInterfaceLanguage : $oLang->getTplLanguage())); $oSmarty->assign('langabbr', $sLangAbbr); return $oSmarty->fetch('ddoewysiwyg.tpl'); }
Render text editor. @param int $width The editor width @param int $height The editor height @param object $objectValue The object value passed to editor @param string $fieldName The name of object field which content is passed to editor @return string The Editor output
entailment
public function getVideoByUrl(string $videoUrl): Video { $url = new Nette\Http\Url($videoUrl); if (stripos($url->host, 'youtu.be') !== false) { return $this->getVideo(trim($url->getPath(), '/')); } $videoId = $url->getQueryParameter('v'); if (stripos($url->host, 'youtube.com') === false || $videoId === null) { throw new Nette\InvalidArgumentException('videoUrl must be valid youtube url.'); } return $this->getVideo($videoId); }
Fetches video data by youtube url
entailment
public function getVideo(string $videoId): Video { return $this->parseData($this->getData($videoId), $videoId); }
Fetches video data
entailment
protected function getModelValue($name) { $array = preg_split('/[\[\]]+/', $name, -1, PREG_SPLIT_NO_EMPTY); if (count($array) == 2 and in_array($array[0], Config::get('translatable.locales'))) { list($lang, $name) = $array; $value = isset($this->model->translate($lang)->{$name}) ? $this->model->translate($lang)->{$name} : ''; return $this->escape($value); } return $this->escape($this->model->{$name}); }
Getting value from Model or ModelTranslation to populate form. @param string $name key @return string value
entailment
public function encodeJson($mMsg = null) { if (is_string($mMsg)) { if (!$this->isUtfString($mMsg)) { $mMsg = utf8_encode($mMsg); } } else { // Typecast for Objects if (is_object($mMsg)) { $mMsg = ( array ) $mMsg; } $mMsg = $this->_encodeUtf8Array($mMsg); } return json_encode($mMsg); }
@param null|mixed $mMsg @return string
entailment
public function isUtfString($sString = '') { if (is_string($sString) && (function_exists('mb_detect_encoding') && mb_detect_encoding($sString, 'UTF-8', true) !== false)) { return true; } return false; }
@param string $sString @return bool
entailment
protected function _encodeUtf8Array($aArray) { $aRet = array(); foreach ($aArray as $sKey => $mValue) { if (!$this->isUtfString($mValue)) { $sKey = utf8_encode($sKey); } if (is_string($mValue)) { if (!$this->isUtfString($mValue)) { $mValue = utf8_encode($mValue); } } elseif (is_array($mValue)) { $mValue = $this->_encodeUtf8Array($mValue); } $aRet[$sKey] = $mValue; } return $aRet; }
@param array $aArray @return array
entailment
public function addKeyRecipient($recipientId, $publicKey) { try { $this->cipher->addKeyRecipient($recipientId, $publicKey); return $this; } catch (Exception $e) { throw new CipherException($e->getMessage(), $e->getCode()); } }
@inheritdoc @throws CipherException
entailment
public function isValid(NumberInterface $number): bool { if ($number->getCheckDigit() === null) { throw new \InvalidArgumentException("Check digit is null."); } $checksum = $this->calcChecksum($number) + $number->getCheckDigit(); return ($checksum % 10) === 0; }
{@inheritDoc}
entailment
public function calcCheckDigit(NumberInterface $number): int { $checksum = $this->calcChecksum($number); // Get the last digit of the checksum. $checkDigit = $checksum % 10; return $checkDigit === 0 ? $checkDigit : 10 - $checkDigit; }
{@inheritDoc}
entailment
public function calcChecksum(NumberInterface $number): int { $nDigits = strlen($number->getNumber()); // Need to account for check digit $parity = ($nDigits + 1) % 2; $checksum = 0; for ($i = 0; $i < $nDigits; $i++) { $digit = (int) $number->getNumber()[$i]; // Every other digit, starting from the rightmost, // shall be doubled. if (($i % 2) === $parity) { $digit *= 2; if ($digit > 9) { $digit -= 9; } } $checksum += $digit; } return $checksum; }
{@inheritDoc}
entailment
public function encrypt(InputOutputInterface $cipherInputOutput, $embedContentInfo = true) { try { return $this->cipher->encrypt($cipherInputOutput->getInput(), $embedContentInfo); } catch (Exception $exception) { throw new CipherException($exception->getMessage(), $exception->getCode()); } }
@inheritdoc @throws CipherException
entailment
public function decryptWithKey(InputOutputInterface $cipherInputOutput, $recipientId, $privateKey) { try { return $this->cipher->decryptWithKey($cipherInputOutput->getInput(), $recipientId, $privateKey); } catch (Exception $exception) { throw new CipherException($exception->getMessage(), $exception->getCode()); } }
@inheritdoc @throws CipherException
entailment
function isGood() { $meta = stream_get_meta_data($this->stream); $mode = $meta['mode']; return false === strpos($mode, 'r') || true === strpos($mode, 'r+'); }
Checks if sink stream is good for write. @return bool
entailment
public function generateKeys($keyPairType = null) { try { if ($keyPairType == null) { $keyPairType = $this->keyPairType; } $keyPair = $this->cryptoService->generateKeyPair($keyPairType); $publicKeyDerEncoded = $this->cryptoService->publicKeyToDer($keyPair[0]); $privateKeyDerEncoded = $this->cryptoService->privateKeyToDer($keyPair[1]); $receiverID = $this->calculateFingerprint($publicKeyDerEncoded); $virgilPublicKey = new VirgilPublicKey($receiverID, $publicKeyDerEncoded); $virgilPrivateKey = new VirgilPrivateKey($receiverID, $privateKeyDerEncoded); return new VirgilKeyPair($virgilPublicKey, $virgilPrivateKey); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param integer $keyPairType @return VirgilKeyPair @throws VirgilCryptoException
entailment
public function decryptThenVerify( $encryptedAndSignedContent, VirgilPrivateKey $recipientPrivateKey, array $signerPublicKeys ) { try { $cipher = $this->cryptoService->createCipher(); $cipherInputOutput = $cipher->createInputOutput($encryptedAndSignedContent); $decryptedContent = $cipher->decryptWithKey( $cipherInputOutput, $recipientPrivateKey->getReceiverID(), $recipientPrivateKey->getValue() ); $signature = $cipher->getCustomParam(self::CUSTOM_PARAM_KEY_SIGNATURE); $isSignatureValid = false; foreach ($signerPublicKeys as $signerPublicKey) { if ($this->verifySignature($decryptedContent, $signature, $signerPublicKey)) { $isSignatureValid = true; } } if (!$isSignatureValid) { throw new SignatureIsNotValidException('signature is not valid'); } return $decryptedContent; } catch (SignatureIsNotValidException $exception) { throw new SignatureIsNotValidException($exception->getMessage()); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $encryptedAndSignedContent @param VirgilPrivateKey $recipientPrivateKey @param VirgilPublicKey[] $signerPublicKeys @return string @throws VirgilCryptoException @throws SignatureIsNotValidException
entailment
public function signThenEncrypt($content, VirgilPrivateKey $signerPrivateKey, array $recipientsPublicKeys) { try { $cipher = $this->cryptoService->createCipher(); $cipherInputOutput = $cipher->createInputOutput($content); $signature = $this->generateSignature($content, $signerPrivateKey); $cipher->setCustomParam(self::CUSTOM_PARAM_KEY_SIGNATURE, $signature); foreach ($recipientsPublicKeys as $recipientPublicKey) { $cipher->addKeyRecipient( $recipientPublicKey->getReceiverID(), $recipientPublicKey->getValue() ); } return $cipher->encrypt($cipherInputOutput); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $content @param VirgilPrivateKey $signerPrivateKey @param VirgilPublicKey[] $recipientsPublicKeys @return string @throws VirgilCryptoException
entailment
public function verifySignature($content, $signature, VirgilPublicKey $signerPublicKey) { try { return $this->cryptoService->verify( $content, $signature, $signerPublicKey->getValue() ); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $content @param string $signature @param VirgilPublicKey $signerPublicKey @return bool @throws VirgilCryptoException
entailment
public function verifyStreamSignature($source, $signature, VirgilPublicKey $signerPublicKey) { try { return $this->cryptoService->verifyStream($source, $signature, $signerPublicKey->getValue()); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param resource $source @param string $signature @param VirgilPublicKey $signerPublicKey @return bool @throws VirgilCryptoException
entailment
public function generateSignature($content, VirgilPrivateKey $signerPrivateKey) { try { return $this->cryptoService->sign($content, $signerPrivateKey->getValue()); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $content @param VirgilPrivateKey $signerPrivateKey @return string @throws VirgilCryptoException
entailment
public function generateStreamSignature($source, VirgilPrivateKey $signerPrivateKey) { try { return $this->cryptoService->signStream($source, $signerPrivateKey->getValue()); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param resource $source @param VirgilPrivateKey $signerPrivateKey @return string @throws VirgilCryptoException
entailment
public function decrypt($encryptedContent, VirgilPrivateKey $recipientPrivateKey) { try { $cipher = $this->cryptoService->createCipher(); $cipherInputOutput = $cipher->createInputOutput($encryptedContent); return $cipher->decryptWithKey( $cipherInputOutput, $recipientPrivateKey->getReceiverID(), $recipientPrivateKey->getValue() ); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $encryptedContent @param VirgilPrivateKey $recipientPrivateKey @return string @throws VirgilCryptoException
entailment
public function decryptStream($source, $sin, VirgilPrivateKey $recipientPrivateKey) { try { $cipher = $this->cryptoService->createStreamCipher(); $cipherInputOutput = $cipher->createInputOutput($source, $sin); $cipher->decryptWithKey( $cipherInputOutput, $recipientPrivateKey->getReceiverID(), $recipientPrivateKey->getValue() ); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param resource $source @param resource $sin @param VirgilPrivateKey $recipientPrivateKey @throws VirgilCryptoException
entailment
public function encrypt($content, array $recipientsPublicKeys) { try { $cipher = $this->cryptoService->createCipher(); $cipherInputOutput = $cipher->createInputOutput($content); foreach ($recipientsPublicKeys as $recipientPublicKey) { $cipher->addKeyRecipient( $recipientPublicKey->getReceiverID(), $recipientPublicKey->getValue() ); } return $cipher->encrypt($cipherInputOutput); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $content @param VirgilPublicKey[] $recipientsPublicKeys @return string @throws VirgilCryptoException
entailment
public function encryptStream($source, $sin, array $recipientsPublicKeys) { try { $cipher = $this->cryptoService->createStreamCipher(); $cipherInputOutput = $cipher->createInputOutput($source, $sin); foreach ($recipientsPublicKeys as $recipientPublicKey) { $cipher->addKeyRecipient( $recipientPublicKey->getReceiverID(), $recipientPublicKey->getValue() ); } $cipher->encrypt($cipherInputOutput); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param resource $source @param resource $sin @param VirgilPublicKey[] $recipientsPublicKeys @throws VirgilCryptoException
entailment
public function generateHash($content, $algorithm) { try { return $this->cryptoService->computeHash($content, $algorithm); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $content @param string $algorithm @return string @throws VirgilCryptoException
entailment
public function importPublicKey($exportedPublicKey) { try { $publicKeyDerEncoded = $this->cryptoService->publicKeyToDer($exportedPublicKey); $receiverID = $this->calculateFingerprint($publicKeyDerEncoded); return new VirgilPublicKey($receiverID, $publicKeyDerEncoded); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $exportedPublicKey @return VirgilPublicKey @throws VirgilCryptoException
entailment
public function importPrivateKey($exportedPrivateKey, $password = '') { try { $privateKeyDerEncoded = $this->cryptoService->decryptPrivateKey($exportedPrivateKey, $password); $receiverID = $this->calculateFingerprint( $this->cryptoService->extractPublicKey($privateKeyDerEncoded, '') ); return new VirgilPrivateKey($receiverID, $privateKeyDerEncoded); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param string $exportedPrivateKey @param string $password @return VirgilPrivateKey @throws VirgilCryptoException
entailment
public function exportPublicKey(VirgilPublicKey $publicKey) { try { return $this->cryptoService->publicKeyToDer($publicKey->getValue()); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param VirgilPublicKey $publicKey @return string @throws VirgilCryptoException
entailment
public function exportPrivateKey(VirgilPrivateKey $privateKey, $password = '') { try { return $this->cryptoService->privateKeyToDer($privateKey->getValue(), $password); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param VirgilPrivateKey $privateKey @param string $password @return string @throws VirgilCryptoException
entailment
public function extractPublicKey(VirgilPrivateKey $privateKey, $password = '') { try { $publicKeyData = $this->cryptoService->extractPublicKey($privateKey->getValue(), $password); return $this->importPublicKey($publicKeyData); } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param VirgilPrivateKey $privateKey @param string $password @return VirgilPublicKey @throws VirgilCryptoException
entailment
protected function calculateFingerprint($content) { try { if ($this->userSHA256Fingerprints) { $hash = $this->cryptoService->computeHash($content, HashAlgorithms::SHA256); } else { $hash = $this->cryptoService->computeHash($content, HashAlgorithms::SHA512); $hash = substr($hash, 0, 8); } return $hash; } catch (Exception $exception) { throw new VirgilCryptoException($exception->getMessage()); } }
@param $content @return string @throws VirgilCryptoException
entailment
public function exportPublicKey(PublicKey $publicKey) { if (!$publicKey instanceof VirgilPublicKey) { throw new VirgilCryptoException("instance of VirgilPublicKey expected"); } return $this->virgilCrypto->exportPublicKey($publicKey); }
@param PublicKey $publicKey @return string @throws VirgilCryptoException
entailment
public function generateKeyPair($keyPairType) { try { $keyPair = CryptoVirgilKeyPair::generate($keyPairType); return [$keyPair->publicKey(), $keyPair->privateKey()]; } catch (Exception $exception) { throw new KeyPairGenerationException($exception->getMessage(), $exception->getCode()); } }
Generate public/private key pair. @param integer $keyPairType @return array @throws KeyPairGenerationException
entailment
public function privateKeyToDer($privateKey, $privateKyePassword = '') { try { if (strlen($privateKyePassword) === 0) { return CryptoVirgilKeyPair::privateKeyToDER($privateKey); } return CryptoVirgilKeyPair::privateKeyToDER( $this->encryptPrivateKey($privateKey, $privateKyePassword), $privateKyePassword ); } catch (Exception $exception) { throw new PrivateKeyToDerConvertingException($exception->getMessage(), $exception->getCode()); } }
Converts private key to DER format. @param string $privateKey @param string $privateKyePassword @return string @throws PrivateKeyToDerConvertingException
entailment
public function publicKeyToDer($publicKey) { try { return CryptoVirgilKeyPair::publicKeyToDER($publicKey); } catch (Exception $exception) { throw new PublicKeyToDerConvertingException($exception->getMessage(), $exception->getCode()); } }
Converts public key to DER format. @param string $publicKey @return string @throws PublicKeyToDerConvertingException
entailment
public function isKeyPair($publicKey, $privateKey) { try { return CryptoVirgilKeyPair::isKeyPairMatch($publicKey, $privateKey); } catch (Exception $exception) { throw new InvalidKeyPairException($exception->getMessage(), $exception->getCode()); } }
Checks if given keys are parts of the same key pair. @param string $publicKey @param string $privateKey @return bool @throws InvalidKeyPairException
entailment
public function computeHash($publicKeyDER, $hashAlgorithm) { try { return (new CryptoVirgilHash($hashAlgorithm))->hash($publicKeyDER); } catch (Exception $exception) { throw new PublicKeyHashComputationException($exception->getMessage(), $exception->getCode()); } }
Calculates key hash by the hash algorithm. @param string $publicKeyDER DER public key value @param integer $hashAlgorithm Hash algorithm @return string @throws PublicKeyHashComputationException
entailment
public function extractPublicKey($privateKey, $privateKeyPassword) { try { return CryptoVirgilKeyPair::extractPublicKey($privateKey, $privateKeyPassword); } catch (Exception $exception) { throw new PublicKeyExtractionException($exception->getMessage(), $exception->getCode()); } }
Extracts public key from a private key. @param string $privateKey @param string $privateKeyPassword @return string @throws PublicKeyExtractionException
entailment
public function encryptPrivateKey($privateKey, $password) { try { return CryptoVirgilKeyPair::encryptPrivateKey($privateKey, $password); } catch (Exception $exception) { throw new PrivateKeyEncryptionException($exception->getMessage(), $exception->getCode()); } }
Encrypts private key with a password. @param string $privateKey @param string $password @return string @throws PrivateKeyEncryptionException
entailment
public function decryptPrivateKey($privateKey, $privateKeyPassword) { try { return CryptoVirgilKeyPair::decryptPrivateKey($privateKey, $privateKeyPassword); } catch (Exception $exception) { throw new PrivateKeyDecryptionException($exception->getMessage(), $exception->getCode()); } }
Decrypts private key with a password. @param string $privateKey @param string $privateKeyPassword @return string @throws PrivateKeyDecryptionException
entailment
public function sign($content, $privateKey) { try { return (new CryptoVirgilSigner($this->hashAlgorithm))->sign($content, $privateKey); } catch (Exception $exception) { throw new ContentSigningException($exception->getMessage(), $exception->getCode()); } }
Sign content with a private key. @param string $content @param string $privateKey @return string @throws ContentSigningException
entailment
public function verify($content, $signature, $publicKey) { try { return (new CryptoVirgilSigner($this->hashAlgorithm))->verify($content, $signature, $publicKey); } catch (Exception $exception) { throw new ContentVerificationException($exception->getMessage(), $exception->getCode()); } }
Verify content with a public key and signature. @param string $content @param string $signature @param string $publicKey @return bool @throws ContentVerificationException
entailment
public function signStream($stream, $privateKey) { try { $virgilSourceStream = new VirgilStreamDataSource($stream); $virgilSourceStream->reset(); return (new CryptoVirgilStreamSigner($this->hashAlgorithm))->sign( $virgilSourceStream, $privateKey ); } catch (Exception $exception) { throw new ContentSigningException($exception->getMessage(), $exception->getCode()); } }
Sign stream with a private key @param resource $stream @param string $privateKey @return string @throws ContentSigningException
entailment
public function verifyStream($stream, $signature, $publicKey) { try { $virgilSourceStream = new VirgilStreamDataSource($stream); return (new CryptoVirgilStreamSigner($this->hashAlgorithm))->verify( $virgilSourceStream, $signature, $publicKey ); } catch (Exception $exception) { throw new ContentVerificationException($exception->getMessage(), $exception->getCode()); } }
Verify stream with a public key and signature. @param resource $stream @param string $signature @param string $publicKey @return bool @throws ContentVerificationException
entailment
public function getOption($option, $default = null, $namespace = 'options') { $options = $this->getOptions($namespace); $optionArr = explode('.', $option); $option = $this->getOptionFromArray($options, $optionArr, $default, $option); return $option; }
Returns module option value. Dot character is used to separate sub arrays. Example: array( 'option1' => 'this is my option 1' 'option2' => array( 'key1' => 'sub key1', 'key2' => 'sub key2', ) ) $module->getOption('option1'); Returns: (string) "This is my option 1" $module->getOption('option2'); Returns: array( 'key1' => 'sub key1', 'key2' => 'sub key2', ) $module->getOption('option2.key1'); Returns: (string) "sub key1" @param string $option @param mixed $default @return mixed
entailment
public static function fromString(string $input): self { $input = preg_replace('/[^\d]/', '', $input); if (!is_numeric($input)) { throw new \InvalidArgumentException("Expects \$input to be a number, \"{$input}\" given."); } // Get the last digit. $checkDigit = (int) $input[strlen($input) - 1]; // Remove the last digit. $number = substr($input, 0, strlen($input) - 1); return new self($number, $checkDigit); }
Create a new number from an input that contains the check digit already. @param string $input The input that contains the check digit already. @return self
entailment
public function exportPrivateKey(PrivateKey $privateKey) { if (!$privateKey instanceof VirgilPrivateKey) { throw new VirgilCryptoException("instance of VirgilPrivateKey expected"); } return base64_encode($this->virgilCrypto->exportPrivateKey($privateKey, $this->password)); }
@param PrivateKey $privateKey @return string @throws VirgilCryptoException
entailment
public function getEventManager() { if (!$this->events instanceof EventManagerInterface) { $identifiers = array(__CLASS__, get_called_class()); if (isset($this->eventIdentifier)) { if ((is_string($this->eventIdentifier)) || (is_array($this->eventIdentifier)) || ($this->eventIdentifier instanceof Traversable) ) { $identifiers = array_unique($identifiers + (array) $this->eventIdentifier); } elseif (is_object($this->eventIdentifier)) { $identifiers[] = $this->eventIdentifier; } // silently ignore invalid eventIdentifier types } $this->setEventManager(new EventManager($identifiers)); } return $this->events; }
Retrieve the event manager Lazy-loads an EventManager instance if none registered. @return EventManagerInterface
entailment
public function init() { parent::init(); if ( $this->_oMedia === null ) { if ( class_exists( '\\OxidEsales\\VisualCmsModule\\Application\\Model\\Media' ) ) { $this->_oMedia = oxNew( \OxidEsales\VisualCmsModule\Application\Model\Media::class ); } else { $this->_oMedia = oxNew( Media::class ); } } $this->_sUploadDir = $this->_oMedia->getMediaPath(); $this->_sThumbDir = $this->_oMedia->getMediaPath(); $this->_iDefaultThumbnailSize = $this->_oMedia->getDefaultThumbSize(); }
Overrides oxAdminDetails::init()
entailment
public function render() { $oConfig = $this->getConfig(); $iShopId = $oConfig->getConfigParam('blMediaLibraryMultiShopCapability') ? $oConfig->getActiveShop()->getShopId() : null; $this->_aViewData['aFiles'] = $this->_getFiles(0, $iShopId); $this->_aViewData['iFileCount'] = $this->_getFileCount($iShopId); $this->_aViewData['sResourceUrl'] = $this->_oMedia->getMediaUrl(); $this->_aViewData['sThumbsUrl'] = $this->_oMedia->getThumbnailUrl(); return parent::render(); }
Overrides oxAdminDetails::render @return string
entailment
protected function _getFiles($iStart = 0, $iShopId = null) { $sSelect = "SELECT * FROM `ddmedia` WHERE 1 " . ($iShopId != null ? "AND `OXSHOPID` = '" . $iShopId . "' " : "") . "ORDER BY `OXTIMESTAMP` DESC LIMIT " . $iStart . ", 18 "; return DatabaseProvider::getDb(DatabaseProvider::FETCH_MODE_ASSOC)->getAll($sSelect); }
@param int $iStart @param null $iShopId @return array
entailment
protected function _getFileCount($iShopId = null) { $sSelect = "SELECT COUNT(*) AS 'count' FROM `ddmedia` WHERE 1 " . ($iShopId != null ? "AND `OXSHOPID` = '" . $iShopId . "' " : ""); return DatabaseProvider::getDb(DatabaseProvider::FETCH_MODE_ASSOC)->getOne($sSelect); }
@param null $iShopId @return false|string
entailment
public function upload() { $oConfig = $this->getConfig(); $sId = null; if ($_FILES) { $this->_oMedia->createDirs(); $sFileSize = $_FILES['file']['size']; $sFileType = $_FILES['file']['type']; $sSourcePath = $_FILES['file']['tmp_name']; $sDestPath = $this->_sUploadDir . $_FILES['file']['name']; $aFile = $this->_oMedia->uploadeMedia($sSourcePath, $sDestPath, true); $sId = md5( $aFile[ 'filename' ] ); $sThumbName = $aFile[ 'thumbnail' ]; $sFileName = $aFile[ 'filename' ]; $aImageSize = null; $sImageSize = ''; if (is_readable($sDestPath) && preg_match("/image\//", $sFileType)) { $aImageSize = getimagesize($sDestPath); $sImageSize = ($aImageSize ? $aImageSize[0] . 'x' . $aImageSize[1] : ''); } $iShopId = $oConfig->getActiveShop()->getShopId(); $sInsert = "REPLACE INTO `ddmedia` ( `OXID`, `OXSHOPID`, `DDFILENAME`, `DDFILESIZE`, `DDFILETYPE`, `DDTHUMB`, `DDIMAGESIZE` ) VALUES ( '" . $sId . "', '" . $iShopId . "', '" . $sFileName . "', " . $sFileSize . ", '" . $sFileType . "', '" . $sThumbName . "', '" . $sImageSize . "' );"; DatabaseProvider::getDb()->execute($sInsert); } if ($oConfig->getRequestParameter('src') == 'fallback') { $this->fallback(true); } else { header('Content-Type: application/json'); die(json_encode(array('success' => true, 'id' => $sId, 'file' => $sFileName, 'filepath' => $sDestPath, 'filetype' => $sFileType, 'filesize' => $sFileSize, 'imagesize' => $sImageSize))); } }
Upload files
entailment
public function remove() { $oConfig = $this->getConfig(); if ($aIDs = $oConfig->getRequestParameter('id')) { $oDb = DatabaseProvider::getDb(DatabaseProvider::FETCH_MODE_ASSOC); $sSelect = "SELECT `OXID`, `DDFILENAME`, `DDTHUMB` FROM `ddmedia` WHERE `OXID` IN('" . implode("','", $aIDs) . "'); "; $aData = $oDb->getAll($sSelect); foreach ($aData as $aRow) { @unlink($this->_sUploadDir . $aRow['DDFILENAME']); if ($aRow['DDTHUMB']) { foreach (glob($this->_sThumbDir . str_replace('thumb_' . $this->_iDefaultThumbnailSize . '.jpg', '*', $aRow['DDTHUMB'])) as $sThumb) { @unlink($sThumb); } } $sDelete = "DELETE FROM `ddmedia` WHERE `OXID` = '" . $aRow['OXID'] . "'; "; $oDb->execute($sDelete); } } exit(); }
Remove file
entailment
public function moreFiles() { $oConfig = $this->getConfig(); $iStart = $oConfig->getRequestParameter('start') ? $oConfig->getRequestParameter('start') : 0; //$iShopId = $oConfig->getRequestParameter( 'oxshopid' ) ? $oConfig->getRequestParameter( 'oxshopid' ) : null; $iShopId = $oConfig->getConfigParam('blMediaLibraryMultiShopCapability') ? $oConfig->getActiveShop()->getShopId() : null; $aFiles = $this->_getFiles($iStart, $iShopId); $blLoadMore = ($iStart + 18 < $this->_getFileCount($iShopId)); header('Content-Type: application/json'); die(json_encode(array('files' => $aFiles, 'more' => $blLoadMore))); }
Load more files
entailment
public function getLanguageStrings($iLang = null, $blAdminMode = null) { $aLang = array(); foreach ($this->_getLangTranslationArray($iLang, $blAdminMode) as $sLangKey => $sLangValue) { $aLang[$sLangKey] = $sLangValue; } foreach ($this->_getLanguageMap($iLang, $blAdminMode) as $sLangKey => $sLangValue) { $aLang[$sLangKey] = $sLangValue; } if (count($this->_aAdditionalLangFiles)) { foreach ($this->_getLangTranslationArray($iLang, $blAdminMode, $this->_aAdditionalLangFiles) as $sLangKey => $sLangValue) { $aLang[$sLangKey] = $sLangValue; } } return $aLang; }
@param null|integer $iLang @param null|bool $blAdminMode @return array
entailment
public static function onActivate() { self::setupModule(); self::updateModule(); self::activateModule(); self::regenerateViews(); self::clearCache(); }
Execute action on activate event
entailment
private static function setupModule() { // Check if ddmedia table was already created, if not create it. if (!self::tableExists('ddmedia')) { self::executeSQL(self::$_sCreateDdMediaSql); } // Check if ddmedia table has all needed fields, if not add them to the table. foreach (self::$_aSetupDdMediaSQLs as $sField => $sSql) { if (!self::fieldExists($sField, 'ddmedia')) { self::executeSQL($sSql); } } /** @var \OxidEsales\Eshop\Core\Config $oConfig */ $oConfig = Registry::getConfig(); $oConfig->saveShopConfVar('bool', 'blModuleWasEnabled', 'true', $oConfig->getShopId(), 'module:ddoewysiwyg'); }
Execute the sql at the first time of the module installation.
entailment
protected static function fieldExists($sFieldName, $sTableName) { $oDbMetaDataHandler = oxNew(DbMetaDataHandler::class ); return $oDbMetaDataHandler->fieldExists($sFieldName, $sTableName); }
Check if field exists in table @param string $sFieldName field name @param string $sTableName table name @return bool
entailment
private static function updateModule() { /** @var \OxidEsales\Eshop\Core\Config $oConfig */ $oConfig = Registry::getConfig(); /** @var Module $oModule */ $oModule = oxNew(Module::class); $oModule->load('ddoewysiwyg'); $sCurrentVersion = $oModule->getInfo('version'); $sInstalledVersion = $oConfig->getShopConfVar('iInstallledVersion', $oConfig->getShopId(), 'module:ddoewysiwyg'); if (!$sInstalledVersion || version_compare($sInstalledVersion, $sCurrentVersion, '<')) { if (self::$__aUpdateSQLs) { foreach (self::$__aUpdateSQLs as $sUpdateVersion => $aSQLs) { if (!$sInstalledVersion || version_compare($sUpdateVersion, $sInstalledVersion, '>')) { self::executeSQLs($aSQLs); } } } $oConfig->saveShopConfVar('str', 'iInstallledVersion', $sCurrentVersion, $oConfig->getShopId(), 'module:ddoewysiwyg'); } }
Updates module if it was already installed.
entailment
private static function executeSQLs($aSQLs) { if (count($aSQLs) > 0) { foreach ($aSQLs as $sSQL) { self::executeSQL($sSQL); } } }
Executes given sql statements. @param array $aSQLs
entailment
private static function clearCache() { /** @var \OxidEsales\Eshop\Core\UtilsView $oUtilsView */ $oUtilsView = Registry::get('oxUtilsView'); $sSmartyDir = $oUtilsView->getSmartyDir(); if ($sSmartyDir && is_readable($sSmartyDir)) { foreach (glob($sSmartyDir . '*') as $sFile) { if (!is_dir($sFile)) { @unlink($sFile); } } } // Initialise Smarty $oUtilsView->getSmarty(true); }
Empty cache
entailment
public function getThumbnailUrl($sFile = '', $iThumbSize = null) { if ($sFile) { if (!$iThumbSize) { $iThumbSize = $this->_iDefaultThumbnailSize; } $sThumbName = $this->getThumbName($sFile, $iThumbSize); if ($sThumbName) { return $this->getMediaUrl('thumbs/' . $sThumbName); } } else { return $this->getMediaUrl('thumbs/'); } return false; }
@param string $sFile @param null|integer $iThumbSize @return bool|string
entailment
public function getThumbName($sFile, $iThumbSize = null) { if (!$iThumbSize) { $iThumbSize = $this->_iDefaultThumbnailSize; } return str_replace('.', '_', md5(basename($sFile))) . '_thumb_' . $iThumbSize . '.jpg'; }
@param string $sFile @param null|integer $iThumbSize @return string
entailment
public function getMediaUrl($sFile = '') { $oConfig = $this->getConfig(); $sFilePath = $this->getMediaPath($sFile); if (!is_readable($sFilePath)) { return false; } if ($oConfig->isSsl()) { $sUrl = $oConfig->getSslShopUrl(false); } else { $sUrl = $oConfig->getShopUrl(false); } $sUrl = rtrim($sUrl, '/') . $this->_sMediaPath; if ($sFile) { return $sUrl . $sFile; } return $sUrl; }
@param string $sFile @return bool|string
entailment
public function getMediaPath($sFile = '') { $sPath = rtrim(getShopBasePath(), '/') . $this->_sMediaPath; if ($sFile) { return $sPath . $sFile; } return $sPath; }
@param string $sFile @return string
entailment
public function uploadeMedia($sSourcePath, $sDestPath, $blCreateThumbs = false) { $this->createDirs(); $sThumbName = ''; $sFileName = basename($sDestPath); $iFileCount = 0; while (file_exists($sDestPath)) { $aFileParts = explode('.', $sFileName); $aFileParts = array_reverse($aFileParts); $sFileExt = $aFileParts[0]; unset($aFileParts[0]); $sBaseName = implode('.', array_reverse($aFileParts)); $aBaseParts = explode('_', $sBaseName); $aBaseParts = array_reverse($aBaseParts); if (strlen($aBaseParts[0]) == 1 && is_numeric($aBaseParts[0])) { $iFileCount = (int) $aBaseParts[0]; unset($aBaseParts[0]); } $sBaseName = implode('_', array_reverse($aBaseParts)); $sFileName = $sBaseName . '_' . (++$iFileCount) . '.' . $sFileExt; $sDestPath = dirname( $sDestPath ) . '/' . $sFileName; } move_uploaded_file($sSourcePath, $sDestPath); if ($blCreateThumbs) { try { $sThumbName = $this->createThumbnail($sFileName); $this->createMoreThumbnails($sFileName); } catch ( \Exception $e) { $sThumbName = ''; } } return array( 'filepath' => $sDestPath, 'filename' => $sFileName, 'thumbnail' => $sThumbName ); }
@param string $sSourcePath @param string $sDestPath @param bool $blCreateThumbs @return array
entailment
public function createDirs() { if (!is_dir($this->getMediaPath())) { mkdir($this->getMediaPath()); } if (!is_dir($this->getThumbnailPath())) { mkdir($this->getThumbnailPath()); } }
Create directories
entailment
public function createThumbnail($sFileName, $iThumbSize = null, $blCrop = true) { $sFilePath = $this->getMediaPath($sFileName); if (is_readable($sFilePath)) { if (!$iThumbSize) { $iThumbSize = $this->_iDefaultThumbnailSize; } list($iImageWidth, $iImageHeight, $iImageType) = getimagesize($sFilePath); switch ($iImageType) { case 1: $rImg = imagecreatefromgif($sFilePath); break; case 2: $rImg = imagecreatefromjpeg($sFilePath); break; case 3: $rImg = imagecreatefrompng($sFilePath); break; default: throw new \Exception('Invalid filetype'); break; } $iThumbWidth = $iImageWidth; $iThumbHeight = $iImageHeight; $iThumbX = 0; $iThumbY = 0; if ($blCrop) { if ($iImageWidth < $iImageHeight) { $iThumbWidth = $iThumbSize; $iThumbHeight = $iImageHeight / ($iImageWidth / $iThumbWidth); $iThumbY = (($iThumbSize - $iThumbHeight) / 2); } elseif ($iImageHeight < $iImageWidth) { $iThumbHeight = $iThumbSize; $iThumbWidth = $iImageWidth / ($iImageHeight / $iThumbHeight); $iThumbX = (($iThumbSize - $iThumbWidth) / 2); } } else { if ($iImageWidth < $iImageHeight) { if ($iImageHeight > $iThumbSize) { $iThumbWidth *= ($iThumbSize / $iImageHeight); $iThumbHeight *= ($iThumbSize / $iImageHeight); } } elseif ($iImageHeight < $iImageWidth) { if ($iImageHeight > $iThumbSize) { $iThumbWidth *= ($iThumbSize / $iImageWidth); $iThumbHeight *= ($iThumbSize / $iImageWidth); } } } $rTmpImg = imagecreatetruecolor($iThumbWidth, $iThumbHeight); imagecopyresampled($rTmpImg, $rImg, $iThumbX, $iThumbY, 0, 0, $iThumbWidth, $iThumbHeight, $iImageWidth, $iImageHeight); if ($blCrop) { $rThumbImg = imagecreatetruecolor($iThumbSize, $iThumbSize); imagefill($rThumbImg, 0, 0, imagecolorallocate($rThumbImg, 0, 0, 0)); imagecopymerge($rThumbImg, $rTmpImg, 0, 0, 0, 0, $iThumbSize, $iThumbSize, 100); } else { $rThumbImg = $rTmpImg; } $sThumbName = $this->getThumbName($sFileName, $iThumbSize); imagejpeg($rThumbImg, $this->getThumbnailPath($sThumbName)); return $sThumbName; } return false; }
@param string $sFileName @param null|integer $iThumbSize @param bool $blCrop @return bool|string @throws \Exception
entailment
protected function entityToArray($entity, HydratorInterface $hydrator = null) { if (is_array($entity)) { return $entity; // cut down on duplicate code } elseif (is_object($entity)) { if (!$hydrator) { $hydrator = $this->getHydrator(); } return $hydrator->extract($entity); } throw new Exception\InvalidArgumentException('Entity passed to db mapper should be an array or object.'); }
Uses the hydrator to convert the entity to an array. Use this method to ensure that you're working with an array. @param object $entity @param HydratorInterface|null $hydrator @return array
entailment
public function filter($collection) { $duplicateKeys = array(); $clonedCollection = array(); foreach ($collection as $key => $value) { $clonedCollection[$key] = $value; } foreach ($clonedCollection as $key => $action) { if ($action instanceof TimelineInterface) { $action = $action->getAction(); } if ($action->hasDuplicateKey()) { $currentKey = $action->getDuplicateKey(); $currentPriority = $action->getDuplicatePriority(); if (array_key_exists($currentKey, $duplicateKeys)) { //actual entry has bigger priority if ($currentPriority > $duplicateKeys[$currentKey]['priority']) { $keyToDelete = $duplicateKeys[$currentKey]['key']; $duplicateKeys[$currentKey]['key'] = $key; $duplicateKeys[$currentKey]['priority'] = $currentPriority; } else { $keyToDelete = $key; } $duplicateKeys[$currentKey]['duplicated'] = true; unset($collection[$keyToDelete]); } else { $duplicateKeys[$currentKey] = array( 'key' => $key, 'priority' => $currentPriority, 'duplicated' => false, ); } } } foreach ($duplicateKeys as $key => $values) { if ($values['duplicated']) { $action = $collection[$values['key']]; if ($action instanceof TimelineInterface) { $action->getAction()->setIsDuplicated(true); } else { $action->setIsDuplicated(true); } } } return $collection; }
{@inheritdoc}
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sonata_dashboard'); // Keep compatibility with symfony/config < 4.2 if (!method_exists($treeBuilder, 'getRootNode')) { $node = $treeBuilder->root('sonata_dashboard')->children(); } else { $node = $treeBuilder->getRootNode()->children(); } $node ->arrayNode('class') ->addDefaultsIfNotSet() ->children() ->scalarNode('dashboard')->defaultValue('Application\\Sonata\\DashboardBundle\\Entity\\Dashboard')->end() ->scalarNode('block')->defaultValue('Application\\Sonata\\DashboardBundle\\Entity\\Block')->end() ->end() ->end() ->scalarNode('default_container') ->defaultValue('sonata.dashboard.block.container') ->cannotBeEmpty() ->end() ->arrayNode('templates') ->addDefaultsIfNotSet() ->children() ->scalarNode('compose') ->defaultValue('@SonataDashboard/DashboardAdmin/compose.html.twig') ->info('This value sets the composer template.') ->end() ->scalarNode('compose_container_show') ->defaultValue('@SonataDashboard/DashboardAdmin/compose_container_show.html.twig') ->info('This value sets the container composer template.') ->end() ->scalarNode('render') ->defaultValue('@SonataDashboard/DashboardAdmin/render.html.twig') ->info('This value sets the render template.') ->end() ->end() ->end() ; return $treeBuilder; }
Generates the configuration tree. @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
entailment
public function notify(ActionInterface $action, EntryCollection $entryCollection) { $i = 0; foreach ($entryCollection as $context => $entries) { foreach ($entries as $entry) { $i++; $this->timelineManager->createAndPersist($action, $entry->getSubject(), $context, 'notification'); } } if ($i > 0) { $this->timelineManager->flush(); } }
{@inheritdoc}
entailment
public function getUnreadNotifications(ComponentInterface $subject, $context = "GLOBAL", array $options = array()) { $options['context'] = $context; $options['type'] = 'notification'; return $this->timelineManager->getTimeline($subject, $options); }
@param ComponentInterface $subject The subject @param string $context The context @param array $options An array of options (offset, limit), see your timelineManager @return array
entailment
public function countKeys(ComponentInterface $subject, $context = "GLOBAL") { $options = array( 'context' => $context, 'type' => 'notification', ); return $this->timelineManager->countKeys($subject, $options); }
count how many timeline had not be read @param ComponentInterface $subject The subject @param string $context The context @return integer
entailment
public function markAsReadActions(array $actions) { $options = array( 'type' => 'notification', ); foreach ($actions as $action) { list($context, $subject, $actionId) = $action; $options['context'] = $context; $this->timelineManager->remove($subject, $actionId, $options); } $this->timelineManager->flush(); }
Give an array like this array( array( *CONTEXT*, *SUBJECT*, *KEY* ) array( *CONTEXT*, *SUBJECT*, *KEY* ) .... ) @param array $actions
entailment
public function markAllAsRead(ComponentInterface $subject, $context = "GLOBAL") { $options = array( 'context' => $context, 'type' => 'notification', ); $this->timelineManager->removeAll($subject, $options); $this->timelineManager->flush(); }
markAllAsRead @param ComponentInterface $subject subject @param string $context The context
entailment
public function parse($contents, $includeDefaults = false) { $old_libxml_error = libxml_use_internal_errors(true); $dom = new DOMDocument; if(@$dom->loadHTML($contents) === false) { throw new RuntimeException("Contents is empty"); } libxml_use_internal_errors($old_libxml_error); foreach($dom->getElementsByTagName('meta') as $tag) { if($includeDefaults && $tag->hasAttribute('name') && $tag->hasAttribute('content') && $tag->getAttribute('name') == 'description') { $this->addMeta('non-og-description', $tag->getAttribute('content'), self::APPEND); } else if($tag->hasAttribute('property') && $tag->hasAttribute('content')) { $this->addMeta($tag->getAttribute('property'), $tag->getAttribute('content'), self::APPEND); } } if($includeDefaults) { $titles = $dom->getElementsByTagName('title'); if ($titles->length > 0) { $this->addMeta('non-og-title', $titles->item(0)->textContent, self::APPEND); } } unset($dom); return $this; }
parse html tags @param $contents @param bool $includeDefaults @return $this
entailment
private function loadBlocks(DashboardInterface $dashboard): void { $blocks = $this->blockInteractor->loadDashboardBlocks($dashboard); // save a local cache foreach ($blocks as $block) { $this->blocks[$block->getId()] = $block; } }
load all the related nested blocks linked to one dashboard.
entailment
protected function _connect($dsn, array $config) { $connection = new Oci8( $dsn, $config['username'], $config['password'], $config['flags'] ); $this->connection($connection); return true; }
Establishes a connection to the database server @param string $dsn A Driver-specific PDO-DSN @param array $config configuration to be used for creating connection @return bool true on success
entailment