/** * Convert display date for saving to model * * @return string JSON encoded HTML output */ public function actionConvert() { $output = ''; Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $post = Yii::$app->request->post(); if (isset($post['displayDate'])) { $saveFormat = ArrayHelper::getValue($post, 'saveFormat'); $dispFormat = ArrayHelper::getValue($post, 'dispFormat'); $dispTimezone = ArrayHelper::getValue($post, 'dispTimezone'); $saveTimezone = ArrayHelper::getValue($post, 'saveTimezone'); $settings = ArrayHelper::getValue($post, 'settings', []); // Russian dates ends with \r. - i dont know why if (StringHelper::endsWith($dispFormat, '.')) { $dispFormat = substr($dispFormat, 0, strlen($dispFormat) - 4); $post['displayDate'] = substr($post['displayDate'], 0, strlen($post['displayDate']) - 4); } if (ArrayHelper::getValue($post, 'type') != DateControl::FORMAT_DATETIME) { $dispTimezone = null; $saveTimezone = null; } $date = DateControl::getTimestamp($post['displayDate'], $dispFormat, $dispTimezone, $settings); if (empty($date) || !$date) { $value = ''; } elseif ($saveTimezone != null) { $value = $date->setTimezone(new DateTimeZone($saveTimezone))->format($saveFormat); } else { $value = $date->format($saveFormat); } return ['status' => 'success', 'output' => $value]; } else { return ['status' => 'error', 'output' => 'No display date found']; } }
/** * @param $path * @param array $dbInfo * @param array $restoreOptions * @return string */ public function makeRestoreCommand($path, array $dbInfo, array $restoreOptions) { $arguments = []; if (StringHelper::endsWith($path, '.gz', false)) { $arguments[] = 'gunzip -c'; $arguments[] = $path; $arguments[] = '|'; } if ($this->isWindows()) { $arguments[] = 'set PGPASSWORD='******'password']; $arguments[] = '&'; } else { $arguments[] = 'PGPASSWORD='******'password']; } // default port if (empty($dbInfo['port'])) { $dbInfo['port'] = '5432'; } $arguments = array_merge($arguments, ['psql', '--host=' . $dbInfo['host'], '--port=' . $dbInfo['port'], '--username='******'username'], '--no-password']); if ($restoreOptions['preset']) { $arguments[] = trim($restoreOptions['presetData']); } $arguments[] = $dbInfo['dbName']; if (!StringHelper::endsWith($path, '.gz', false)) { $arguments[] = '<'; $arguments[] = $path; } return implode(' ', $arguments); }
/** * Generates a class name with camelcase style and specific suffix, if not already provided * * @param string $string The name of the class, e.g.: hello_word would * @param string $suffix The suffix to append on the class name if not eixsts, e.g.: MySuffix * @return string The class name e.g. HelloWorldMySuffix * @since 1.0.0-beta4 */ public function createClassName($string, $suffix = false) { $name = Inflector::camelize($string); if ($suffix && StringHelper::endsWith($name, $suffix, false)) { $name = substr($name, 0, -strlen($suffix)); } return $name . $suffix; }
public function getContent() { if (is_null($this->content)) { $arr = $this->getContentAsArray(); $ret = []; $ret[] = Html::tag('p', Html::img($this->getImage(), ['width' => '100%', 'class' => 'thumbnail'])); foreach ($arr as $item) { if (StringHelper::endsWith($item, "\n")) { $item = Str::sub($item, 0, Str::length($item) - 1); } if (StringHelper::endsWith($item, "\r")) { $item = Str::sub($item, 0, Str::length($item) - 1); } $ret[] = Html::tag('p', $item); } $this->content = join("\r\n", $ret); } return $this->content; }
/** * 根据运行时命令解析绝对路径 */ private function parseFullName() { if ($this->fullName === null) { $bin = realpath($_SERVER['_']); $argv = $_SERVER['argv']; if (StringHelper::endsWith($bin, 'bin/php')) { //run like: /usr/bin/php php-script [arguments|options] $script = realpath($argv[0]); $argv[0] = $script; array_unshift($argv, $bin); $this->fullName = $argv; } else { //run like: php-script [arguments|options] $argv = array_slice($argv, 1); array_unshift($argv, $bin); $this->fullName = $argv; } } }
public function actionGenerate() { $webUrl = Yii::getAlias('@frontendUrl'); // проверка наличия слеша в конце ссылки if (!StringHelper::endsWith($webUrl, '/', false)) { $webUrl .= '/'; } $webPath = Yii::getAlias('@frontend/web/'); // create sitemap $sitemap = new Sitemap($webPath . 'sitemap.xml'); // add some URLs foreach (Article::find()->published()->all() as $item) { $sitemap->addItem($webUrl . 'article/' . $item->slug, time(), Sitemap::DAILY); } // write it $sitemap->write(); // get URLs of sitemaps written $sitemapFileUrls = $sitemap->getSitemapUrls($webUrl); // create sitemap for static files $staticSitemap = new Sitemap($webPath . 'sitemap_static.xml'); // add some URLs $staticSitemap->addItem($webUrl . 'article/index'); $staticSitemap->addItem($webUrl . 'site/contact'); // write it $staticSitemap->write(); // get URLs of sitemaps written $staticSitemapUrls = $staticSitemap->getSitemapUrls($webUrl); // create sitemap index file $index = new Index($webPath . 'sitemap_index.xml'); // add URLs foreach ($sitemapFileUrls as $sitemapUrl) { $index->addSitemap($sitemapUrl); } // add more URLs foreach ($staticSitemapUrls as $sitemapUrl) { $index->addSitemap($sitemapUrl); } // write it $index->write(); Console::output('The sitemap generated successfully.'); }
/** * @return array * [[ * 'name' * 'url' * ],...] */ public function getItems() { $doc = $this->getDocument($this->url); $ret = []; $c = 1; foreach ($doc->find('.wall_item') as $div) { if ($c > 1) { $url = 'https://vk.com' . $div->find('.wi_date')[0]->attr['href']; $html = $div->find('.pi_text')[0]; $header = explode('..............................', $html->plaintext); $header = trim($header[0]); if (StringHelper::endsWith($header, '.')) { $header = Str::sub($header, 0, Str::length($header) - 1); } $header = Str::toLower($header); $first = Str::toUpper(Str::sub($header, 0, 1)); $header = $first . Str::sub($header, 1); $ret[] = ['name' => $header, 'url' => $url]; } $c++; } return $ret; }
/** * @param $path * @param array $dbInfo * @param array $restoreOptions * @return mixed */ public function makeRestoreCommand($path, array $dbInfo, array $restoreOptions) { $arguments = []; if (StringHelper::endsWith($path, '.gz', false)) { $arguments[] = 'gunzip -c'; $arguments[] = $path; $arguments[] = '|'; } // default port if (empty($dbInfo['port'])) { $dbInfo['port'] = '3306'; } $arguments = array_merge($arguments, ['mysql', '--host=' . $dbInfo['host'], '--port=' . $dbInfo['port'], '--user='******'username'], '--password='******'password']]); if ($restoreOptions['preset']) { $arguments[] = trim($restoreOptions['presetData']); } $arguments[] = $dbInfo['dbName']; if (!StringHelper::endsWith($path, '.gz', false)) { $arguments[] = '<'; $arguments[] = $path; } return implode(' ', $arguments); }
/** * Get the folder name where the views for this ActiveWindow should be stored. * * @return string */ public function getViewFolderName() { if ($this->_viewFolderName === null) { $name = $this->getName(); if (StringHelper::endsWith($name, $this->suffix, false)) { $name = substr($name, 0, -strlen($this->suffix)); } $this->_viewFolderName = strtolower($name); } return $this->_viewFolderName; }
/** * {@inheritdoc} */ public function getDetail() { $apiUrl = null; $timings = $this->calculateTimings(); ArrayHelper::multisort($timings, 3, SORT_DESC); $rows = []; $i = 0; // Try to get API URL try { $restClient = \Yii::$app->get('restclient'); $apiUrl = StringHelper::endsWith($restClient->config['base_uri'], '/') ? $restClient->config['base_uri'] : $restClient->config['base_uri'] . '/'; } catch (InvalidConfigException $e) { // Pass } foreach ($timings as $logId => $timing) { $time = $duration = '-'; if (is_double($timing[2])) { $time = date('H:i:s.', $timing[2]) . sprintf('%03d', (int) (($timing[2] - (int) $timing[2]) * 1000)); $duration = sprintf('%.1f ms', $timing[3] * 1000); } $message = $timing[1]; $traces = $timing[4]; if (($pos = mb_strpos($message, '#')) !== false) { $url = mb_substr($message, 0, $pos); $body = mb_substr($message, $pos + 1); } else { $url = $message; $body = null; } if (($pos = mb_strpos($message, ' ')) !== false) { $method = mb_substr($message, 0, $pos); } else { $method = null; } $traceString = ''; if (!empty($traces)) { $traceString .= Html::ul($traces, ['class' => 'trace', 'item' => function ($trace) { return "<li>{$trace['class']}{$trace['type']}{$trace['function']}({$trace['line']})</li>"; }]); } $runLink = $newTabLink = ''; if ($method == 'GET') { $runLink = Html::a('run query', Url::to(['rest-query', 'logId' => $logId, 'tag' => $this->tag]), ['class' => 'restclient-link', 'data' => ['id' => $i]]); $newTabLink = Html::a('to new tab', $apiUrl . preg_replace('/^[A-Z]+\\s+/', '', $url) . $body, ['target' => '_blank']); } $url_encoded = Html::encode(isset($apiUrl) ? str_replace(' ', ' ' . $apiUrl, $url) : $url); $body_encoded = Html::encode($body); $rows[] = <<<HTML <tr> <td style="width: 10%;">{$time}</td> <td style="width: 10%;">{$duration}</td> <td style="width: 75%;"><div><b>{$url_encoded}</b><br/><p>{$body_encoded}</p>{$traceString}</div></td> <td style="width: 15%;">{$runLink}<br/>{$newTabLink}</td> </tr> <tr style="display: none;" class="restclient-wrapper" data-id="{$i}"> <td class="time"></td> <td class="duration"></td> <td colspan="2" class="result"></td> </tr> HTML; ++$i; } $rows = implode("\n", $rows); \Yii::$app->view->registerCss(<<<CSS .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; } CSS ); \Yii::$app->view->registerJs(<<<JS function syntaxHighlight(json) { json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) { var cls = 'number'; if (/^"/.test(match)) { if (/:\$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; }); } \$('.restclient-link').on('click', function (event) { event.preventDefault(); var id = \$(this).data('id'); var result = \$('.restclient-wrapper[data-id=' + id +']'); result.find('.result').html('Sending request...'); result.show(); \$.ajax({ type: 'POST', url: \$(this).attr('href'), success: function (data) { var is_json = true; try { var json = JSON.parse(data.result); } catch(e) { is_json = false; } result.find('.time').html(data.time); result.find('.duration').html(data.duration); if (is_json) { result.find('.result').html( syntaxHighlight( JSON.stringify( JSON.parse(data.result), undefined, 10) ) ); } else if (data.result instanceof Object) { console.log(typeof(data.result)); var html = ''; for (var key in data.result) { html += key+':'+data.result[key]+'<br/>'; } result.find('.result').html( html ); } else { result.find('.result').html( data.result ); } }, error: function (jqXHR, textStatus, errorThrown) { result.find('.time').html(''); result.find('.result').html('<span style="color: #c00;">Error: ' + errorThrown + ' - ' + textStatus + '</span><br />' + jqXHR.responseText); }, dataType: 'json' }); return false; }); JS , View::POS_READY); return <<<HTML <h1>Rest Client Queries</h1> <table class="table table-condensed table-bordered table-striped table-hover" style="table-layout: fixed;"> <thead> <tr> <th style="width: 10%;">Time</th> <th style="width: 10%;">Duration</th> <th style="width: 75%;">Url / Query</th> <th style="width: 15%;">Run Query on node</th> </tr> </thead> <tbody> {$rows} </tbody> </table> HTML; }
/** * Validates file name. * @param string $filename the filename that must be validated. * @param boolean $validateEncoded whether method must validate encoded in local file system charset file name. * This param internally is used by this method. * @param boolean $validateEncoded whether method must validate encoded in local file system charset file name. * This param internally is used by this method. * @return boolean whether this filename can be used for saving new file. */ protected function isValidFileName($filename, $validateEncoded = true) { if (!is_string($filename) || in_array($filename, ['', '.', '..'], true)) { return false; } if ($this->containsSpecialChar($filename)) { return false; } $charset = Yii::$app->charset; foreach ($this->disallowedExtensions as $disallowedExt) { if (StringHelper::endsWith($filename, ".{$disallowedExt}", false)) { return false; } elseif (mb_strripos($filename, ".{$disallowedExt}.", 0, $charset) !== false) { return false; } } if ($validateEncoded) { $encodedFilename = FileSystemHelper::encodeFilename($filename); return $this->isValidFileName($encodedFilename, false); } return true; }
public function testEndsWithCaseInsensitive() { $this->assertTrue(StringHelper::endsWith('sTrInG', 'StRiNg', false)); $this->assertTrue(StringHelper::endsWith('string', 'nG', false)); $this->assertTrue(StringHelper::endsWith('BüЯйΨ', 'ÜяЙΨ', false)); }
/** * @throws InvalidConfigException * @throws \yii\base\InvalidConfigException */ public function init() { parent::init(); if (!empty($this->dbList)) { if (!ArrayHelper::isIndexed($this->dbList)) { throw new InvalidConfigException('Property dbList must be as indexed array'); } foreach ($this->dbList as $dbAlias) { /** * @var Connection $db */ $db = Instance::ensure($dbAlias, Connection::className()); $this->dbInfo[$dbAlias]['driverName'] = $db->driverName; $this->dbInfo[$dbAlias]['dsn'] = $db->dsn; $this->dbInfo[$dbAlias]['host'] = $this->getDsnAttribute('host', $db->dsn); $this->dbInfo[$dbAlias]['port'] = $this->getDsnAttribute('port', $db->dsn); $this->dbInfo[$dbAlias]['dbName'] = $this->getDsnAttribute('dbname', $db->dsn); $this->dbInfo[$dbAlias]['username'] = $db->username; $this->dbInfo[$dbAlias]['password'] = $db->password; $this->dbInfo[$dbAlias]['prefix'] = $db->tablePrefix; } } $this->path = Yii::getAlias($this->path); if (!StringHelper::endsWith($this->path, '/', false)) { $this->path .= '/'; } if (!is_dir($this->path)) { throw new InvalidConfigException('Path is not directory'); } if (!is_writable($this->path)) { throw new InvalidConfigException('Path is not writable! Check chmod!'); } $this->fileList = FileHelper::findFiles($this->path, ['only' => ['*.sql', '*.gz']]); }
/** * Возвращает название статьи * * @return string */ public function getHeader() { $html = $this->getObjArticle(); $header = explode('..............................', $html->plaintext); $header = trim($header[0]); if (StringHelper::endsWith($header, '.')) { $header = Str::sub($header, 0, Str::length($header) - 1); } $header = Str::toLower($header); $first = Str::toUpper(Str::sub($header, 0, 1)); $header = $first . Str::sub($header, 1); return $header; }
/** * Вызов возможен как render($view, $params) * или как render($params) * тогда $view = название функции action * например если вызов произошел из метода actionOrders то $view = 'orders' * * @param string|array $view шаблон или параметры шаблона * @param array $params параметры шаблона если $view = шаблон, иначе не должен указываться * * @return string = \yii\base\Controller::render() */ public function render($view = '', $params = []) { if (is_array($view)) { $params = $view; $view = strtolower(str_replace('action', '', debug_backtrace(2)[1]['function'])); } else { if ($view == '') { $params = []; $view = strtolower(str_replace('action', '', debug_backtrace(2)[1]['function'])); } else { if ($view == '.tpl') { $view = strtolower(str_replace('action', '', debug_backtrace(2)[1]['function'])) . '.tpl'; } } } if (StringHelper::endsWith(strtolower($view), '.tpl')) { $this->layout .= '.tpl'; } if (self::getParam('_view', '') != '') { \cs\services\VarDumper::dump($params, 10); return ''; } return parent::render($view, $params); }
/** * Gets the value of an environment variable. Supports boolean, empty and null. * * @param string $key * @param mixed $default * @return mixed */ function env($key, $default = null) { $value = getenv($key); if ($value === false) { return value($default); } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return; } if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { return substr($value, 1, -1); } return $value; }