Пример #1
0
 /**
  * @inheritdoc
  */
 public function getDiff($file = null)
 {
     $previewFile = [];
     $ret = [];
     $appendFileDiff = function () use(&$previewFile, &$ret) {
         if (!empty($previewFile)) {
             $ret[] = new Diff($previewFile);
             $previewFile = [];
         }
     };
     $fullDiff = [];
     if (!is_null($file)) {
         $fullDiff = $this->repository->getDiff(Repository::DIFF_PATH, $file, $this->id);
     } else {
         $fullDiff = $this->repository->getDiff(Repository::DIFF_COMMIT, $this->id);
     }
     foreach ($fullDiff as $row) {
         if (StringHelper::startsWith($row, 'diff')) {
             // the new file diff, append to $ret
             $appendFileDiff();
         }
         $previewFile[] = $row;
     }
     // append last file diff to full array
     $appendFileDiff();
     return $ret;
 }
Пример #2
0
 public function actionIndex()
 {
     $actions = [];
     $rc = new \ReflectionClass($this);
     $publicMethods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC);
     $availableActions = [];
     foreach ($publicMethods as $publicMethod) {
         $methodName = $publicMethod->name;
         if ($methodName == 'actions') {
             continue;
         }
         if (StringHelper::startsWith($methodName, 'action')) {
             $availableActions[] = $methodName;
         }
     }
     if (count($this->actions()) > 0) {
         $availableActions = $availableActions + array_keys($this->actions());
     }
     $menus = [];
     foreach ($availableActions as $actionName) {
         $routeId = Inflector::camel2id(substr($actionName, strlen('action')));
         $menus[] = Html::a($actionName, [$routeId]);
     }
     echo implode('<br/>', $menus);
 }
Пример #3
0
 public function up()
 {
     $this->execute('ALTER TABLE galaxysss_1.gs_unions_office ADD category VARCHAR(100) NULL;');
     $path = Yii::getAlias('@app/app/assets/1.xml');
     $data = file_get_contents($path);
     $x = new \DOMDocument();
     $x->loadXML($data);
     $ret = [];
     /** @var \DOMElement $element */
     foreach ($x->documentElement->childNodes as $element) {
         if ($element instanceof \DOMElement) {
             $data = $element->getAttribute('data-jmapping');
             $pos = Str::pos('lat', $data);
             $pos1 = Str::pos('lng', $data);
             $lat = Str::sub($data, $pos + 5, $pos1 - $pos - 7);
             $pos = Str::pos('lng', $data);
             $pos1 = Str::pos('category', $data);
             $lng = Str::sub($data, $pos + 5, $pos1 - $pos - 8);
             $pos = Str::pos('category', $data);
             $category = Str::sub($data, $pos + 11);
             $category = Str::sub($category, 0, Str::length($category) - 2);
             $category = explode('|', $category);
             $list = $element->getElementsByTagName("p");
             if ($list->length == 1) {
                 /** @var \DOMElement $content */
                 $content = $list->item(0);
                 $content = $x->saveXML($content);
                 $content = Str::sub($content, 3);
                 $content = Str::sub($content, 0, Str::length($content) - 4);
                 $content = explode('<br/>', $content);
                 $ret2 = [];
                 foreach ($content as $item) {
                     if (StringHelper::startsWith($item, '<b>')) {
                         $item = Str::sub($item, 3);
                         $item = Str::sub($item, 0, Str::length($item) - 4);
                     }
                     $ret2[] = trim($item);
                 }
                 $name = $ret2[0];
                 array_shift($ret2);
                 if (StringHelper::startsWith($ret2[count($ret2) - 1], 'Открытие')) {
                     $ret2 = array_reverse($ret2);
                     array_shift($ret2);
                     $ret2 = array_reverse($ret2);
                 }
                 if (StringHelper::startsWith($ret2[count($ret2) - 1], '"ВкусВилл')) {
                     $ret2 = array_reverse($ret2);
                     array_shift($ret2);
                     $ret2 = array_reverse($ret2);
                 }
                 $address = $ret2[0];
                 array_shift($ret2);
                 $ret[] = [392, $address, $name, $lat, $lng, join('|', $category), Html::tag('p', join('<br/>', $ret2))];
             }
         }
     }
     $this->batchInsert('gs_unions_office', ['union_id', 'point_address', 'name', 'point_lat', 'point_lng', 'category', 'content'], $ret);
 }
Пример #4
0
 public function __get($name)
 {
     if (\yii\helpers\StringHelper::startsWith($name, 'id')) {
         $id = (int) substr($name, 2);
         if (is_null($this->id)) {
             return null;
         }
         return \yii\helpers\ArrayHelper($this->id, $id, null);
     }
 }
Пример #5
0
 /**
  * @hass-todo
  */
 public function actionIndex()
 {
     $namespaces = \HassClassLoader::getHassCoreFile();
     $result = [];
     foreach ($namespaces as $namespace => $dir) {
         $controllerDir = $dir . DIRECTORY_SEPARATOR . "controllers";
         if (!is_dir($controllerDir)) {
             continue;
         }
         $files = FileHelper::findFiles($controllerDir);
         $moduleId = trim(substr($namespace, strrpos(rtrim($namespace, "\\"), "\\")), "\\");
         $result[$moduleId]["module"] = $moduleId;
         $result[$moduleId]["permissions"] = [];
         foreach ($files as $file) {
             $childDir = rtrim(pathinfo(substr($file, strpos($file, "controllers") + 12), PATHINFO_DIRNAME), ".");
             if ($childDir) {
                 $class = $namespace . "controllers\\" . str_replace("/", "\\", $childDir) . "\\" . rtrim(basename($file), ".php");
             } else {
                 $class = $namespace . "controllers\\" . rtrim(basename($file), ".php");
             }
             $controllerId = Inflector::camel2id(str_replace("Controller", "", pathinfo($file, PATHINFO_FILENAME)));
             $reflect = new \ReflectionClass($class);
             $methods = $reflect->getMethods(\ReflectionMethod::IS_PUBLIC);
             /** @var \ReflectionMethod $method */
             foreach ($methods as $method) {
                 if (!StringHelper::startsWith($method->name, "action")) {
                     continue;
                 }
                 if ($method->name == "actions") {
                     $object = \Yii::createObject(["class" => $class], [$controllerId, $moduleId]);
                     $actions = $method->invoke($object);
                     foreach ($actions as $actionId => $config) {
                         $route = $moduleId . "/" . $controllerId . "/" . $actionId;
                         if ($childDir) {
                             $route = $moduleId . "/" . $childDir . "/" . $controllerId . "/" . $actionId;
                         }
                         $result[$moduleId]["permissions"][$route] = ["type" => Item::TYPE_PERMISSION, "description" => $controllerId . "-" . Inflector::camel2words($actionId)];
                     }
                     continue;
                 }
                 $actionId = Inflector::camel2id(substr($method->name, 6));
                 $route = $moduleId . "/" . $controllerId . "/" . $actionId;
                 if ($childDir) {
                     $route = $moduleId . "/" . $childDir . "/" . $controllerId . "/" . $actionId;
                 }
                 $result[$moduleId]["permissions"][$route] = ["type" => Item::TYPE_PERMISSION, "description" => $controllerId . "-" . Inflector::camel2words(substr($method->name, 6))];
             }
         }
     }
     $result["super"] = ['module' => 'SUPER_PERMISSION', 'permissions' => array(\hass\rbac\Module::SUPER_PERMISSION => array('type' => Item::TYPE_PERMISSION, 'description' => 'SUPER_PERMISSION'))];
     $result = "<?php \n return " . var_export($result, true) . ";";
     file_put_contents(dirname(__DIR__) . "/permissions.php", $result);
     return $this->render("index");
 }
Пример #6
0
 /**
  * Constructor
  *
  * @param string $pathName
  * @param BaseRepository $repository
  * @param string|null $status file status in revision
  *
  * @throws CommonException
  */
 public function __construct($pathName, BaseRepository $repository, $status = null)
 {
     $this->name = basename($pathName);
     $this->path = FileHelper::normalizePath($pathName);
     // first character for status
     $this->status = !is_null($status) ? substr($status, 0, 1) : $status;
     $this->repository = $repository;
     if (!StringHelper::startsWith($this->path, $repository->getProjectPath())) {
         throw new CommonException("Path {$this->path} outband of repository");
     }
     $this->relativePath = substr($this->path, strlen($repository->getProjectPath()));
     parent::__construct([]);
 }
 public function actionIndex()
 {
     if (count(Yii::$app->request->post()) > 0) {
         $formValues = Yii::$app->request->post((new Investigator())->formName());
         $add = [];
         $skip = [];
         foreach ($formValues as $name => $value) {
             if (StringHelper::startsWith($name, 'id')) {
                 $id = substr($name, 2);
                 foreach (Yii::$app->session->get('items') as $sessionItem) {
                     if ($sessionItem['id'] == $id) {
                         switch ($value) {
                             // пропустить
                             case 1:
                                 $skip[] = $sessionItem['id'];
                                 break;
                                 // добавить
                             // добавить
                             case 2:
                                 $add[] = $sessionItem['id'];
                                 break;
                         }
                     }
                 }
             }
         }
         if (count($skip) > 0) {
             (new Query())->createCommand()->update(Inv::TABLE, ['status' => Inv::STATUS_SKIP], ['in', 'id', $skip])->execute();
         }
         foreach ($add as $item) {
             $i = Inv::find($item);
             $class = $i->getField('class_name');
             // послание
             /** @var \app\services\investigator\InvestigatorInterface $class */
             $class = new $class();
             $extractor = $class->getItem($i->getField('url'));
             // добавляю
             Chenneling::insertExtractorInterface($extractor);
         }
         if (count($add) > 0) {
             (new Query())->createCommand()->update(Inv::TABLE, ['status' => Inv::STATUS_ADD], ['in', 'id', $add])->execute();
         }
         Yii::$app->session->remove('items');
         Yii::$app->session->setFlash('contactFlash');
         return $this->render([]);
     } else {
         $items = \app\models\Investigator::query(['status' => \app\models\Investigator::STATUS_NEW])->select(['class_name as class', 'id', 'url', 'date_insert', 'status', 'name'])->all();
         Yii::$app->session->set('items', $items);
         return $this->render(['items' => $items]);
     }
 }
Пример #8
0
 /**
  * @inheritdoc
  */
 protected function initialize($rows)
 {
     $diffId = null;
     $this->previousFilePath = self::NULL_PATH;
     $this->newFilePath = self::NULL_PATH;
     foreach ($rows as $n => $row) {
         if ($n >= 0 && $n <= 2) {
             // first 3 lines are description
             if (trim($this->description)) {
                 $this->description .= PHP_EOL . $row;
             } else {
                 $this->description = $row;
             }
             if (StringHelper::startsWith($row, 'Binary files')) {
                 // stop parsing if diff is binary
                 $this->isBinary = true;
                 break;
             }
             // old or new file path
             $matches = [];
             if (preg_match('#^\\-\\-\\-[\\s]a(.*)$#i', $row, $matches)) {
                 $this->previousFilePath = $matches[1];
             } else {
                 if (preg_match('#^\\+\\+\\+[\\s]b(.*)$#i', $row, $matches)) {
                     $this->newFilePath = $matches[1];
                 }
             }
         } else {
             if ($n == 3 && StringHelper::startsWith($row, 'GIT binary patch')) {
                 // stop parsing if diff is binary
                 $this->isBinary = true;
                 break;
             } else {
                 if (StringHelper::startsWith($row, '@@')) {
                     // new diff line
                     $diffId = $row;
                     $matches = [];
                     $pattern = '#^@@[\\s]\\-([\\d]+),?([\\d]+)?[\\s]\\+([\\d]+),?([\\d]+)?[\\s]@@#i';
                     preg_match($pattern, $row, $matches);
                     $this->lines[$diffId] = ['beginA' => isset($matches[1]) ? (int) $matches[1] : 1, 'beginB' => isset($matches[3]) ? (int) $matches[3] : 1, 'cntA' => isset($matches[2]) ? (int) $matches[2] : 0, 'cntB' => isset($matches[4]) ? (int) $matches[4] : 0, 'lines' => []];
                 } else {
                     if ($diffId && isset($this->lines[$diffId])) {
                         // changed row
                         $this->lines[$diffId]['lines'][] = $row;
                     }
                 }
             }
         }
     }
 }
 public function beforeAction($action)
 {
     if (!parent::beforeAction($action)) {
         return false;
     }
     $get = Yii::$app->request->get();
     $filterParams = array_filter($get, function ($val, $key) {
         return StringHelper::startsWith($key, self::FILTER_GET_TAG);
     }, ARRAY_FILTER_USE_BOTH);
     //        $filterNames = array_map(function($val){
     //            return substr($val, strlen(self::FILTER_GET_TAG));
     //        }, $filterParams);
     foreach ($filterParams as $key => $value) {
         $this->addFilter($key, $value);
     }
     return true;
 }
Пример #10
0
 /**
  * Возвращает массив чистых строк без тегов
  *
  * @return array
  */
 public function getContentAsArray()
 {
     $html = $this->getObjArticle();
     $ret = [];
     foreach ($html->find('div.td-post-text-content/p') as $p) {
         if ($p instanceof \simple_html_dom_node) {
             if ($p->children[0]->tag != 'noindex') {
                 $string = trim($p->plaintext);
                 if (StringHelper::startsWith($string, '&nbsp;')) {
                     $string = Str::sub($string, 6);
                 }
                 $ret[] = $string;
             }
         }
     }
     return $ret;
 }
Пример #11
0
 public function update2($id)
 {
     $item = parent::update();
     $item['id'] = $id;
     $class = new \app\models\SubscribeHistory($item);
     $content = $class->getField('content');
     require_once Yii::getAlias('@csRoot/services/simplehtmldom_1_5/simple_html_dom.php');
     $content = str_get_html($content);
     foreach ($content->find('img') as $element) {
         $src = $element->attr['src'];
         if (StringHelper::startsWith($src, 'http') == false) {
             $element->attr['src'] = Url::to($src, true);
         }
     }
     $content = $content->root->outertext();
     $class->setContent($content);
     return $item;
 }
Пример #12
0
 /**
  * View project path tree or raw project file
  *
  * @param string|null $path Relative project path (null if root)
  */
 public function actionRaw($path = null)
 {
     $absolutePath = FileHelper::normalizePath($this->repository->getProjectPath() . DIRECTORY_SEPARATOR . $path);
     if (!StringHelper::startsWith($absolutePath, $this->repository->getProjectPath()) || !file_exists($absolutePath)) {
         throw new NotFoundHttpException();
     }
     $breadcrumbs = $this->generateBreadcrumbs($path);
     if (is_dir($absolutePath)) {
         // render path tree
         $filesList = $this->repository->getFilesList($path);
         return $this->render('tree', ['project' => $this->project, 'repository' => $this->repository, 'filesList' => $filesList, 'breadcrumbs' => $breadcrumbs]);
     } else {
         if (is_file($absolutePath)) {
             // render raw file
             $fileContents = file_get_contents($absolutePath);
             return $this->render('raw', ['repository' => $this->repository, 'project' => $this->project, 'breadcrumbs' => $breadcrumbs, 'fileContents' => $fileContents]);
         }
     }
     // if else - 404
     throw new NotFoundHttpException();
 }
Пример #13
0
 /**
  * Format the given amount into a displayable currency.
  *
  * @param int $amount
  *
  * @return string
  */
 public static function formatAmount($amount)
 {
     if (static::$formatCurrencyUsing) {
         return call_user_func(static::$formatCurrencyUsing, $amount);
     }
     $amount = number_format($amount / 100, 2);
     if (StringHelper::startsWith($amount, '-')) {
         return '-' . static::usesCurrencySymbol() . ltrim($amount, '-');
     }
     return static::usesCurrencySymbol() . $amount;
 }
Пример #14
0
 /**
  * Убирает теги
  * script,
  * meta,
  * iframe и
  * аттрибуты событий начинающиеся на on и
  * аттрибут href для ссылки a если он начинается на javascript
  *
  * @param \simple_html_dom | string $content
  *
  * @return \simple_html_dom
  */
 public static function filter($content)
 {
     if (!$content instanceof \simple_html_dom) {
         require_once Yii::getAlias('@csRoot/services/simplehtmldom_1_5/simple_html_dom.php');
         $content = str_get_html($content);
     }
     foreach ($content->find('*') as $element) {
         foreach ($element->attr as $k => $v) {
             if (StringHelper::startsWith($k, 'on')) {
                 unset($element->attr[$k]);
             }
         }
     }
     // script
     foreach ($content->find('script') as $element) {
         foreach ($element->nodes as $node) {
             $node->_ = [];
         }
     }
     // a href="javascript: ... "
     // удаляю аттрибут
     foreach ($content->find('a') as $element) {
         foreach ($element->nodes as $node) {
             if (isset($element->attr['href'])) {
                 $href = $element->attr['href'];
                 if (StringHelper::startsWith($href, 'javascript')) {
                     unset($element->attr['href']);
                 }
             }
         }
     }
     // meta
     // удаляю все атрибуты и подноды
     foreach ($content->find('meta') as $element) {
         $element->attr = [];
         foreach ($element->nodes as $node) {
             $node->_ = [];
         }
     }
     return $content;
 }
Пример #15
0
 /**
  * @param array             $field
  * @param \cs\base\BaseForm $model
  *
  * @return array поля для обновления в БД
  */
 public static function onUpdate($field, $model)
 {
     $fieldName = $field[BaseForm::POS_DB_NAME];
     $files = $model->{$fieldName};
     $tableName = $model->getTableName();
     $fieldDb = ModelFields::insertOne(['table_name' => $tableName, 'field_name' => $fieldName]);
     ModelFiles::deleteByCondition(['row_id' => $fieldDb->getId()]);
     $folder = \cs\services\UploadFolderDispatcher::createFolder('FileUploadMany', $fieldDb->getId(), $model->id);
     $allFiles = [];
     foreach ($files as $file) {
         $allFiles[] = $file[0];
     }
     $currentFiles = (new Query())->select('w.file_path, w.id')->from('widget_uploader_many w')->innerJoin('widget_uploader_many_fields wf', 'w.field_id = wf.id')->where(['w.row_id' => $model->id, 'wf.table_name' => $model->getTableName(), 'wf.field_name' => $fieldName])->all();
     foreach ($currentFiles as $currentFile) {
         if (!in_array($currentFile['file_path'], $allFiles)) {
             (new SitePath($currentFile['file_path']))->deleteFile();
             $id = (int) $currentFile['id'];
             ModelFiles::deleteByCondition(['id' => $id]);
         }
     }
     foreach ($files as $file) {
         if (StringHelper::startsWith($file[0], '/')) {
             continue;
         }
         $sourcePathFull = Yii::getAlias(self::$uploadDirectory . '/' . $file[0]);
         $destinationFile = $folder->cloneObject($file[0]);
         copy($sourcePathFull, $destinationFile->getPathFull());
         ModelFiles::insert(['file_path' => $destinationFile->getPath(), 'file_name' => $file[1], 'row_id' => $model->id, 'field_id' => $fieldDb->getId(), 'datetime' => gmdate('YmdHis')]);
     }
     return [$fieldName => count($files)];
 }
Пример #16
0
 /**
  * Validate and filter repository path
  *
  * @param string $attribute validation attribute
  * @param array $params validation params
  * @return void
  */
 public function validateRepoPath($attribute, $params)
 {
     if (!$this->hasErrors($attribute)) {
         // path
         $path = FileHelper::normalizePath($this->{$attribute});
         // windows flag
         $isWindows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN';
         if ($isWindows && !preg_match('#^[A-Za-z]{1}\\:#i', $path) || !$isWindows && !StringHelper::startsWith($path, DIRECTORY_SEPARATOR)) {
             // path must be absolute
             $this->addError($attribute, Yii::t('project', 'Please type absolute path to repository'));
             return;
         }
         if (!file_exists($path)) {
             $this->addError($attribute, Yii::t('project', 'Directory not found here'));
             return;
         }
         if (!is_dir($path)) {
             $this->addError($attribute, Yii::t('project', 'This not a directory'));
             return;
         }
         if (!is_readable($path) || !is_writeable($path)) {
             $this->addError($attribute, Yii::t('project', 'Current system user can\'t read at specified path.'));
             return;
         }
         $this->repo_path = $path;
     }
 }
Пример #17
0
 public function testStartsWithCaseInsensitive()
 {
     $this->assertTrue(StringHelper::startsWith('sTrInG', 'StRiNg', false));
     $this->assertTrue(StringHelper::startsWith('CaSe', 'cAs', false));
     $this->assertTrue(StringHelper::startsWith('HTTP://BÜrger.DE/', 'http://bürger.de', false));
     $this->assertTrue(StringHelper::startsWith('üЯйΨB', 'ÜяЙΨ', false));
 }
Пример #18
0
 /**
  * Render file view.
  * If has CommonException - it's may by only not found commit, or not found file in project path.
  *
  * @return array
  * @throws NotFoundHttpException
  */
 public function run()
 {
     /* @var $commit BaseCommit */
     $commit = null;
     /* @var $fileDiff BaseDiff[] */
     $fileDiff = [];
     /* @var $fileContents string */
     $fileContents = '';
     $isBinary = false;
     try {
         // get commit model by commit identifier
         $commit = $this->repository->getCommit($this->commitId);
         $fileDiff = $commit->getDiff($this->filePath);
         $isBinary = isset($fileDiff[0]) && $fileDiff[0]->getIsBinary();
         if ($this->mode === self::MODE_RAW_BINARY && $isBinary) {
             // returns raw binary file
             $images = ['png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif'];
             $pathinfo = pathinfo($this->filePath);
             $mimeType = isset($images[strtolower($pathinfo['extension'])]) ? $images[strtolower($pathinfo['extension'])] : 'application/octet-stream';
             if (!StringHelper::startsWith($mimeType, 'image/')) {
                 header('Content-Description: File Transfer');
                 header('Content-Disposition: attachment; filename=' . basename($this->filePath));
             }
             header('Content-Type: ' . $mimeType);
             header('Content-Transfer-Encoding: binary');
             header('Expires: 0');
             header('Cache-Control: must-revalidate');
             header('Pragma: public');
             $commit->getRawBinaryFile($this->filePath, function ($data) {
                 print $data;
                 flush();
             });
             exit;
         } elseif ($this->mode === self::MODE_RAW && $commit->getFileStatus($this->filePath) != File::STATUS_DELETION) {
             // modified file
             $fileContents = $isBinary ? '' : $commit->getRawFile($this->filePath);
         } elseif ($this->mode === self::MODE_RAW) {
             // moved file
             $fileContents = $isBinary ? '' : $commit->getPreviousRawFile($this->filePath);
         }
     } catch (CommonException $ex) {
         throw new ServerErrorHttpException(Yii::t('app', 'System error: {message}', ['message' => $ex->getMessage()]), $ex->getCode(), $ex);
     }
     $viewFile = null;
     switch ($this->mode) {
         case self::MODE_DIFF:
             $viewFile = $isBinary ? 'file_raw' : 'file_diff';
             break;
         case self::MODE_COMPARE:
             $viewFile = $isBinary ? 'file_raw' : 'file_compare';
             break;
         case self::MODE_RAW:
             $viewFile = 'file_raw';
             break;
         default:
             throw new NotFoundHttpException();
     }
     return ['diff' => Yii::t('project', 'Revision') . ': ' . $commit->getId(), 'html' => $this->controller->renderAjax('commit/' . $viewFile, ['project' => $this->project, 'commit' => $commit, 'diffs' => $fileDiff, 'fileContents' => $fileContents, 'path' => $this->filePath, 'isBinary' => $isBinary])];
 }
Пример #19
0
 /**
  * Save basic model and extra field values
  * @param bool|true $runValidation
  * @return bool
  */
 public function save($runValidation = true)
 {
     if ($this->primaryModel->isNewRecord) {
         $ok = $this->primaryModel->insert($runValidation) !== false;
         if (!$ok) {
             return false;
         }
         $this->id = $this->primaryModel->id;
         foreach ($this as $key => $value) {
             if (!StringHelper::startsWith($key, $this->extra_field_prefix)) {
                 continue;
             }
             $field_id = substr($key, strlen($this->extra_field_prefix));
             $fieldValue = new TourFieldValue();
             $fieldValue->field_id = $field_id;
             $fieldValue->booking_id = $this->primaryModel->id;
             $fieldValue->value = $value;
             $fieldValue->insert($runValidation);
         }
     } else {
         $ok = $this->primaryModel->update($runValidation) !== false;
         if (!$ok) {
             return false;
         }
         foreach ($this->primaryModel->fieldValues as $fieldValue) {
             $ok = $fieldValue->update($runValidation) !== false;
             if (!$ok) {
                 return false;
             }
         }
     }
     return true;
 }
Пример #20
0
 protected function insertGetValue($value, $field)
 {
     $name = $field[self::POS_DB_NAME];
     if (isset($field[self::POS_RULE])) {
         if ($field[self::POS_RULE] != '') {
             if ($field[self::POS_RULE] == 'file') {
                 return FileUpload::onInsert($value, $field, $this);
             }
         }
     }
     if (isset($field[self::POS_RULE])) {
         if ($field[self::POS_RULE] != '') {
             if ($field[self::POS_RULE] == 'date') {
                 $format = ArrayHelper::getValue($field, BaseForm::POS_PARAMS . '.format', '');
                 if ($format != '') {
                     if (StringHelper::startsWith($format, 'php:')) {
                         $format = substr($format, 4);
                         if (!is_null($this->{$name})) {
                             if ($this->{$name} != '') {
                                 $date = \DateTime::createFromFormat($format, $this->{$name}, new \DateTimeZone('UTC'));
                                 return $date->format('Y-m-d');
                             }
                         }
                     }
                 }
                 return '';
             }
         }
     }
     return $this->{$name};
 }
Пример #21
0
 public function getThumbs()
 {
     $pattern = 'thumb_' . $this->primaryKey . '_';
     $directory = $this->getStorageDirectory() . DIRECTORY_SEPARATOR . $this->getPartitionDirectory();
     $allFiles = \Yii::$app->get("fileStorage")->listFolderContents($directory);
     $collection = [];
     foreach ($allFiles as $file) {
         if (StringHelper::startsWith($file["basename"], $pattern)) {
             $collection[] = $file["path"];
         }
     }
     return $collection;
 }
Пример #22
0
 /**
  * 判断指定ID的元素是否为自身的子元素 
  */
 public function isDescendant($id)
 {
     $record = self::find()->where(['id' => $id])->andWhere(['<>', 'id', $this->id])->one();
     if (!$record) {
         return false;
     }
     return \yii\helpers\StringHelper::startsWith($record->code, $this->code);
 }
Пример #23
0
        ?>
            <?php 
        $aNum = (int) $group['beginA'];
        $bNum = (int) $group['beginB'];
        ?>
            <tr>
                <td colspan="4" class="cell-description"><?php 
        echo Html::encode($description);
        ?>
</td>
            </tr>
            <?php 
        foreach ($group['lines'] as $n => $line) {
            ?>
                <?php 
            $type = StringHelper::startsWith($line, '-') ? 'del' : (StringHelper::startsWith($line, '+') ? 'new' : 'old');
            $line = Html::encode(substr($line, 1));
            $line = str_replace([" ", "\t"], ['&nbsp;', '&thinsp;'], $line);
            $a = $type === 'del' || $type === 'old' ? $aNum : null;
            $b = $type === 'new' || $type === 'old' ? $bNum : null;
            ?>
                <tr class="row-<?php 
            echo $type;
            if ($n === count($group['lines']) - 1) {
                ?>
 last-line<?php 
            }
            ?>
">
                    <td width="10" class="cell-a-num"><?php 
            echo $a ? $a : '+';
Пример #24
0
 /**
  * Sets given attributes unsafe in given scenario name
  * @param array $scenarios model scenarios
  * @param string $name targeted scenario name
  * @param array $attrs attrs to be set unsafe
  */
 public static function setAttributesUnsafe(&$scenarios, $name, array $attrs = [])
 {
     if (isset($scenarios[$name])) {
         foreach ($attrs as $attr) {
             $key = array_search($attr, $scenarios[$name]);
             if (false !== $key) {
                 $value = $scenarios[$name][$key];
                 if (!StringHelper::startsWith($value, '!')) {
                     $scenarios[$name][$key] = sprintf('!%s', $value);
                 }
             }
         }
     }
 }
Пример #25
0
 /**
  * @inheritdoc
  */
 protected function renderHeaderCellContent()
 {
     if (!$this->routeFilterReset) {
         $route = \Yii::$app->controller->getRoute();
         if (!\yii\helpers\StringHelper::startsWith($route, '/')) {
             $route = '/' . $route;
         }
         $this->routeFilterReset = [$route];
     }
     return Html::a('<span class="' . $this->resetButtonIcon . '"></span>', $this->routeFilterReset, ['title' => \Yii::t('yii', 'Reset filter'), 'data-pjax' => '0']);
 }
Пример #26
0
 /**
  * The method internally called in [[self::parseInputValue()]] and parse only string typed value.
  * @see [[self::parseInputValue()]]
  * @param string $value
  * @return string|null
  */
 protected function parseInputStringValue($value)
 {
     if ($value === '') {
         return null;
     }
     if (StringHelper::startsWith($value, $this->postParamUploadPrefix)) {
         $charset = Yii::$app->charset;
         $storagePrefixPos = mb_strpos($value, $this->postParamStoragePrefix, 0, $charset);
         $uploadPrefixLength = mb_strlen($this->postParamUploadPrefix, $charset);
         $valueLength = mb_strlen($value, $charset);
         $length = $storagePrefixPos === false ? $valueLength - $uploadPrefixLength : $storagePrefixPos - $uploadPrefixLength;
         $formName = mb_substr($value, $uploadPrefixLength, $length, $charset);
         if ($result = UploadedFile::getInstanceByName($formName)) {
             return $result;
         }
         if ($storagePrefixPos !== false) {
             $storagePrefixLength = mb_strlen($this->postParamStoragePrefix, $charset);
             $pos = $storagePrefixPos + $storagePrefixLength;
             $storageFileData = mb_substr($value, $pos, $valueLength - $pos, $charset);
         }
     }
     if (!isset($storageFileData) && StringHelper::startsWith($value, $this->postParamStoragePrefix)) {
         $storageFileData = StringHelper::byteSubstr($value, StringHelper::byteLength($this->postParamStoragePrefix));
     }
     if (isset($storageFileData) && $this->getStorage()->fileExists($storageFileData)) {
         return $storageFileData;
     }
     return null;
 }
Пример #27
0
 /**
  * @param array $classes
  * @param string|null $currentClass
  * @param string $startEventName
  * @return array
  */
 protected function events(array $classes, $currentClass, $startEventName)
 {
     $events = [];
     foreach ($classes as $class) {
         $reflection = new ReflectionClass($class);
         foreach ($reflection->getConstants() as $constant => $value) {
             if (StringHelper::startsWith($constant, $startEventName) && $this->checkExecuteEvents($class, $constant)) {
                 $events[$constant] = ($currentClass == null ? '' : $currentClass . $this->classNameKeySeparator) . $value;
             }
         }
     }
     $events = array_flip($events);
     asort($events);
     return $events;
 }
Пример #28
0
 /**
  * @inheritdoc
  */
 public function getSourceUrl($type, $line = null)
 {
     if (is_string($type)) {
         $type = $this->apiContext->getType($type);
     }
     foreach ($this->sourceLinks as $vendor => $source) {
         if (StringHelper::startsWith($type->name, $vendor)) {
             return $this->printUrl($source . str_replace('\\', '/', substr($type->name, strlen($vendor))) . '.php', $line);
         }
     }
     switch ($this->getTypeCategory($type)) {
         case 'yii':
             $baseUrl = 'https://github.com/yiisoft/yii2/blob/master';
             if ($type->name == 'Yii') {
                 $url = "{$baseUrl}/framework/Yii.php";
             } else {
                 $url = "{$baseUrl}/framework/" . str_replace('\\', '/', substr($type->name, 4)) . '.php';
             }
             break;
         case 'app':
             return null;
         default:
             $parts = explode('\\', substr($type->name, 4));
             $ext = $parts[0];
             unset($parts[0]);
             $url = "https://github.com/yiisoft/yii2-{$ext}/blob/master/" . implode('/', $parts) . '.php';
             break;
     }
     if ($line === null) {
         return $url;
     } else {
         return $url . '#L' . $line;
     }
 }
Пример #29
0
<?php

use yii\helpers\Url;
use backend\widgets\Nav;
use yii\helpers\StringHelper;
?>
<!-- nav -->
<nav class="nav-primary hidden-xs">
    <div class="text-muted text-sm hidden-nav-xs padder m-t-sm m-b-sm">目录</div>
    <?php 
echo Nav::widget(['items' => [['label' => '统计分析', 'url' => ['dashboard/index'], 'icon' => 'i i-statistics icon', 'rightIcon' => 'i i-circle-sm', 'font' => 'font-bold'], ['label' => '产品管理', 'active' => StringHelper::startsWith($this->context->route, 'product') && !StringHelper::startsWith($this->context->route, 'product-order'), 'icon' => 'i i-statistics icon', 'rightIcon' => 'i i-circle-sm', 'font' => 'font-bold', 'items' => [['label' => '产品列表', 'icon' => 'i i-dot icon', 'url' => ['product/index']], ['label' => '添加产品', 'icon' => 'i i-dot icon', 'url' => ['product/create']], ['label' => '分类列表', 'icon' => 'i i-dot icon', 'url' => ['product-category/index']], ['label' => '添加分类', 'icon' => 'i i-dot icon', 'url' => ['product-category/create']], ['label' => '属性分类', 'icon' => 'i i-dot icon', 'url' => ['product-attribute-category/index']], ['label' => '属性列表', 'icon' => 'i i-dot icon', 'url' => ['product-attribute/index']], ['label' => '添加属性', 'icon' => 'i i-dot icon', 'url' => ['product-attribute/create']]]], ['label' => '订单管理', 'active' => StringHelper::startsWith($this->context->route, 'product-order'), 'icon' => 'i i-meter icon', 'rightIcon' => 'i i-circle-sm', 'font' => 'font-bold', 'items' => [['label' => '订单列表', 'icon' => 'i i-dot icon', 'url' => ['product-order/index']]]]]]);
?>
    
    <div class="line dk hidden-nav-xs"></div>
    <div class="text-muted text-xs hidden-nav-xs padder m-t-sm m-b-sm">快捷访问</div>
    <ul class="nav">
        <li>
            <a href="<?php 
echo Url::to(['product/index']);
?>
">
            <i class="i i-circle-sm text-info-dk"></i>
            <span>产品列表</span>
            </a>
        </li>
        <li>
            <a href="<?php 
echo Url::to(['product-order/index']);
?>
">
            <i class="i i-circle-sm text-success-dk"></i>
Пример #30
-4
 /**
  * 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;
 }