Esempio n. 1
0
 public function actionInit()
 {
     $auth = Yii::$app->authManager;
     $auth->removeAll();
     $user = $auth->createRole(User::ROLE_USER);
     $auth->add($user);
     // own model rule
     $ownModelRule = new OwnModelRule();
     $auth->add($ownModelRule);
     $manager = $auth->createRole(User::ROLE_MANAGER);
     $auth->add($manager);
     $auth->addChild($manager, $user);
     $loginToBackend = $auth->createPermission('loginToBackend');
     $auth->add($loginToBackend);
     $auth->addChild($manager, $loginToBackend);
     $publisher = $auth->createRole(User::ROLE_PUBLISHER);
     $auth->add($publisher);
     $auth->addChild($publisher, $loginToBackend);
     $advertiser = $auth->createRole(User::ROLE_ADVERTISER);
     $auth->add($advertiser);
     $auth->addChild($advertiser, $loginToBackend);
     $admin = $auth->createRole(User::ROLE_ADMINISTRATOR);
     $auth->add($admin);
     $auth->addChild($admin, $manager);
     $auth->assign($admin, 1);
     $auth->assign($manager, 2);
     $auth->assign($user, 3);
     $auth->assign($publisher, 4);
     $auth->assign($advertiser, 5);
     Console::output('Success! RBAC roles has been added.');
 }
Esempio n. 2
0
 public function actionInit()
 {
     $auth = Yii::$app->authManager;
     $auth->removeAll();
     $user = $auth->createRole(User::ROLE_USER);
     $auth->add($user);
     // own model rule
     $ownModelRule = new OwnModelRule();
     $auth->add($ownModelRule);
     $submissionRule = new SubmissionRule();
     $auth->add($submissionRule);
     $updateOwnResearch = $auth->createPermission('updateOwnResearch');
     $updateOwnResearch->description = 'update research by status';
     $updateOwnResearch->ruleName = $submissionRule->name;
     $auth->add($updateOwnResearch);
     $auth->addChild($user, $updateOwnResearch);
     $manager = $auth->createRole(User::ROLE_MANAGER);
     $auth->add($manager);
     $auth->addChild($manager, $user);
     $loginToBackend = $auth->createPermission('loginToBackend');
     $auth->add($loginToBackend);
     $auth->addChild($manager, $loginToBackend);
     $admin = $auth->createRole(User::ROLE_ADMINISTRATOR);
     $auth->add($admin);
     $auth->addChild($admin, $manager);
     $auth->assign($admin, 1);
     $auth->assign($manager, 2);
     $auth->assign($user, 3);
     Console::output('Success! RBAC roles has been added.');
 }
Esempio n. 3
0
 protected function stderr($string)
 {
     if (Console::streamSupportsAnsiColors(\STDOUT)) {
         $string = Console::ansiFormat("    Error: " . $string, [Console::FG_RED]);
     }
     return fwrite(\STDERR, $string);
 }
 /**
  * Show errors
  * @param array $errors array of errors string
  * @throws yii\base\ExitException
  */
 protected function showErrors($errors)
 {
     foreach ((array) $errors as $err) {
         Console::error(Console::ansiFormat(Yii::t('activeuser_backend', "Error") . ": ", [Console::FG_RED]) . $err[0]);
     }
     yii::$app->end();
 }
 /**
  * 初始默认角色数据
  */
 public function initRbac()
 {
     Console::output('初始化RBAC数据 ....');
     $auth = Yii::$app->authManager;
     /* ================= 权限 ================= */
     $visitAdmin = $auth->createPermission('visitAdmin');
     $visitAdmin->description = '访问后台管理界面权限';
     $auth->add($visitAdmin);
     /* ================= 身份 ================= */
     $guest = $auth->createRole('guest');
     // 匿名用户
     $guest->description = '匿名用户';
     $auth->add($guest);
     $user = $auth->createRole('user');
     //普通用户
     $user->description = '普通用户';
     $auth->add($user, $guest);
     //普通用户 > 匿名用户
     $admin = $auth->createRole('admin');
     // 管理员
     $admin->description = '管理员';
     $auth->add($admin);
     $auth->addChild($admin, $user);
     // 管理员 > 普通用户
     $auth->addChild($admin, $visitAdmin);
     // 管理员可以访问后台
     $founder = $auth->createRole('founder');
     // 创始人
     $founder->description = '创始人';
     $auth->add($founder);
     $auth->addChild($founder, $admin);
     // 创始人 > 管理员
     Console::output('初始化RBAC数据完成 ....');
 }
 public function actionInit()
 {
     $auth = Yii::$app->authManager;
     $user = $auth->createRole(User::ROLE_USER);
     $auth->add($user);
     Console::output('Success! RBAC roles has been added.');
 }
Esempio n. 7
0
 /**
  * @inheritdoc
  */
 protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
 {
     $dirNameBase = $dirName;
     foreach ($messages as $category => $msgs) {
         /**
          * Fix Directory
          */
         $module = $this->getModuleByCategory($category);
         if ($module !== null) {
             // Use Module Directory
             $dirName = str_replace(Yii::getAlias("@humhub/messages"), $module->getBasePath() . '/messages', $dirNameBase);
             preg_match('/.*?Module\\.(.*)/', $category, $result);
             $category = $result[1];
         } else {
             // Use Standard HumHub Directory
             $dirName = $dirNameBase;
         }
         $file = str_replace("\\", '/', "{$dirName}/{$category}.php");
         $path = dirname($file);
         FileHelper::createDirectory($path);
         $msgs = array_values(array_unique($msgs));
         $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
         $this->stdout("Saving messages to {$coloredFileName}...\n");
         $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
     }
 }
Esempio n. 8
0
 /**
  * Снимаем онлайн у тех, у кого за последнее время активность == 0
  */
 public function actionRefreshOnline()
 {
     $oldTime = time() - \Yii::$app->params['onlineLength'];
     $userUpdated = User::updateAll(['<=', 'updated', $oldTime]);
     $this->stdout(Console::wrapText("- {$userUpdated} отправлено в оффлайн", 10), Console::BOLD);
     $this->stdout("\n");
 }
Esempio n. 9
0
 /**
  * Processes update e-mails for all users
  */
 public static function processCron($controller)
 {
     // Detect the mailing interval we're in
     $interval = 0;
     if (Yii::$app->controller->action->id == 'hourly') {
         $interval = self::INTERVAL_HOURY;
     } elseif (Yii::$app->controller->action->id == 'daily') {
         $interval = self::INTERVAL_DAILY;
     } else {
         throw new \yii\console\Exception('Invalid mail update interval!');
     }
     // Get users
     $users = User::find()->distinct()->joinWith(['httpSessions', 'profile'])->where(['user.status' => User::STATUS_ENABLED]);
     $totalUsers = $users->count();
     $processed = 0;
     Console::startProgress($processed, $totalUsers, 'Sending update e-mails to users... ', false);
     $mailsSent = 0;
     foreach ($users->each() as $user) {
         $mailSender = new self();
         $mailSender->user = $user;
         $mailSender->interval = $interval;
         if ($mailSender->send()) {
             $mailsSent++;
         }
         Console::updateProgress(++$processed, $totalUsers);
     }
     Console::endProgress(true);
     $controller->stdout('done - ' . $mailsSent . ' email(s) sent.' . PHP_EOL, Console::FG_GREEN);
     // Switch back to system language
     self::switchLanguage();
 }
Esempio n. 10
0
 /**
  * Create a new frontend/admin module.
  *
  * @return number
  */
 public function actionCreate()
 {
     Console::clearScreenBeforeCursor();
     $moduleName = $this->prompt("Enter the name of the module you like to generate:");
     $newName = preg_replace("/[^a-z]/", "", strtolower($moduleName));
     if ($newName !== $moduleName) {
         if (!$this->confirm("We have changed the name to '{$newName}'. Do you want to proceed with this name?")) {
             return $this->outputError('Abort by user.');
         } else {
             $moduleName = $newName;
         }
     }
     $appModulesFolder = Yii::$app->basePath . DIRECTORY_SEPARATOR . 'modules';
     $moduleFolder = $appModulesFolder . DIRECTORY_SEPARATOR . $moduleName;
     if (file_exists($moduleFolder)) {
         return $this->outputError("The folder " . $moduleFolder . " exists already.");
     }
     $folders = ['basePath' => $moduleFolder, 'adminPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'admin', 'adminPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'aws', 'frontendPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'blocks', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'controllers', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'views', 'modelsPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'models'];
     $ns = 'app\\modules\\' . $moduleName;
     foreach ($folders as $folder) {
         FileHelper::createDirectory($folder);
     }
     $contents = [$moduleFolder . DIRECTORY_SEPARATOR . 'README.md' => $this->renderReadme($folders, $moduleName, $ns), $moduleFolder . DIRECTORY_SEPARATOR . 'admin/Module.php' => $this->renderAdmin($folders, $moduleName, $ns), $moduleFolder . DIRECTORY_SEPARATOR . 'frontend/Module.php' => $this->renderFrontend($folders, $moduleName, $ns)];
     foreach ($contents as $fileName => $content) {
         FileHelper::writeFile($fileName, $content);
     }
     return $this->outputSuccess("Module files has been created successfull. Check the README file to understand how to added the module to your config.");
 }
Esempio n. 11
0
 public function actionIndex()
 {
     $this->stdout('Description goes here.' . PHP_EOL);
     $helpCommand = Console::ansiFormat("yii help dota2api/economy", [Console::FG_CYAN]);
     $this->stdout("Use {$helpCommand} to get usage info." . PHP_EOL);
     return self::EXIT_CODE_NORMAL;
 }
Esempio n. 12
0
 public function actionInit()
 {
     $auth = Yii::$app->authManager;
     $auth->removeAll();
     Console::output('Removing All! RBAC.....');
     $manageUser = $auth->createRole('ManageUser');
     $manageUser->description = 'สำหรับจัดการข้อมูลผู้ใช้งาน';
     $auth->add($manageUser);
     $author = $auth->createRole('Author');
     $author->description = 'สำหรับการเขียนบทความ';
     $auth->add($author);
     $management = $auth->createRole('Management');
     $management->description = 'สำหรับจัดการข้อมูลผู้ใช้งานและบทความ';
     $auth->add($management);
     $admin = $auth->createRole('Admin');
     $admin->description = 'สำหรับการดูแลระบบ';
     $auth->add($admin);
     $auth->addChild($management, $manageUser);
     $auth->addChild($management, $author);
     $auth->addChild($admin, $management);
     $auth->assign($admin, 1);
     $auth->assign($management, 2);
     $auth->assign($author, 3);
     Console::output('Success! RBAC roles has been added.');
 }
Esempio n. 13
0
 public function startHead($controller, $headType, $headId, $restarting)
 {
     if (!$restarting) {
         // Console::output(Console::ansiFormat('Starting ' . $headId, [Console::FG_CYAN]));
     } else {
         // Console::output(Console::ansiFormat('Restarting ' . $headId, [Console::FG_CYAN]));
     }
     $_this = $this;
     $process = new \React\ChildProcess\Process($this->getSubCommand($controller, [$headType, $headId]));
     $process->on('exit', function ($exitCode, $termSignal) use(&$_this, &$controller, $headType, $headId) {
         if ($exitCode !== 0) {
             Console::stderr(Console::ansiFormat("Broadcast head {$headType}:{$headId} exited with error code {$exitCode}", [Console::FG_RED]));
             sleep(10);
         }
         if (static::isPaused()) {
             Yii::$app->end(0);
         }
         $_this->_heads[$headId] = $_this->startHead($controller, $headType, $headId, true);
     });
     $this->loop->addTimer(0.0001, function ($timer) use($process, &$_this) {
         $process->start($timer->getLoop());
         $process->stdout->on('data', function ($output) use($_this) {
             $stdout = fopen('php://stdout', 'w+');
             fwrite($stdout, $output);
         });
         $process->stderr->on('data', function ($output) use($_this) {
             $stderr = fopen('php://stderr', 'w+');
             fwrite($stderr, $output);
         });
     });
     sleep(5);
     return $process;
 }
Esempio n. 14
0
 /**
  * Prints a string to STDERR.
  *
  * @param string $string the string to print
  * @return int|boolean Number of bytes printed or false on error
  */
 public static function stderr($string)
 {
     $args = func_get_args();
     array_shift($args);
     $string = parent::ansiFormat($string, $args) . "\n";
     return parent::stderr($string);
 }
Esempio n. 15
0
 /**
  * @inheritDoc
  */
 public function render($files, $targetDir)
 {
     //        $types = array_merge($this->apiContext->classes, $this->apiContext->interfaces, $this->apiContext->traits);
     //
     //        $extTypes = [];
     //        foreach ($this->extensions as $k => $ext) {
     //            $extType = $this->filterTypes($types, $ext);
     //            if (empty($extType)) {
     //                unset($this->extensions[$k]);
     //                continue;
     //            }
     //            $extTypes[$ext] = $extType;
     //        }
     $fileCount = count($files) + 1;
     if ($this->controller !== null) {
         Console::startProgress(0, $fileCount, 'Rendering markdown files: ', false);
     }
     $done = 0;
     $fileData = [];
     $chapters = $this->loadGuideStructure($files);
     foreach ($files as $file) {
         $fileData[basename($file)] = file_get_contents($file);
         //            if (preg_match("/^(.*)\n=+/", $fileData[$file], $matches)) {
         //                $headlines[$file] = $matches[1];
         //            } else {
         //                $headlines[$file] = basename($file);
         //            }
     }
     $md = new ApiMarkdownLaTeX();
     $output = '';
     foreach ($chapters as $chapter) {
         if (isset($chapter['headline'])) {
             $output .= '\\chapter{' . $chapter['headline'] . "}\n";
         }
         foreach ($chapter['content'] as $content) {
             if (isset($fileData[$content['file']])) {
                 $md->labelPrefix = $content['file'] . '#';
                 $output .= '\\label{' . $content['file'] . '}';
                 $output .= $md->parse($fileData[$content['file']]) . "\n\n";
             } else {
                 $output .= '\\newpage';
                 $output .= '\\label{' . $content['file'] . '}';
                 $output .= '\\textbf{Error: not existing file: ' . $content['file'] . '}\\newpage' . "\n";
             }
             if ($this->controller !== null) {
                 Console::updateProgress(++$done, $fileCount);
             }
         }
     }
     file_put_contents($targetDir . '/guide.tex', $output);
     copy(__DIR__ . '/main.tex', $targetDir . '/main.tex');
     copy(__DIR__ . '/title.tex', $targetDir . '/title.tex');
     copy(__DIR__ . '/Makefile', $targetDir . '/Makefile');
     if ($this->controller !== null) {
         Console::updateProgress(++$done, $fileCount);
         Console::endProgress(true);
         $this->controller->stdout('done.' . PHP_EOL, Console::FG_GREEN);
     }
     echo "\nnow run `make` in {$targetDir} (you need pdflatex to compile pdf file)\n\n";
 }
Esempio n. 16
0
 public function actionInit()
 {
     $auth = Yii::$app->authManager;
     $auth->removeAll();
     $user = $auth->createRole(User::ROLE_USER);
     $user->description = 'User';
     $auth->add($user);
     // own model rule
     $ownModelRule = new OwnModelRule();
     $auth->add($ownModelRule);
     $manager = $auth->createRole(User::ROLE_MANAGER);
     $manager->description = 'Manager';
     $auth->add($manager);
     $auth->addChild($manager, $user);
     $loginToBackend = $auth->createPermission('loginToBackend');
     $loginToBackend->description = 'Login to backend';
     $auth->add($loginToBackend);
     $auth->addChild($manager, $loginToBackend);
     $admin = $auth->createRole(User::ROLE_ADMINISTRATOR);
     $admin->description = 'Administrator';
     $auth->add($admin);
     $auth->addChild($admin, $manager);
     $auth->assign($admin, 1);
     Console::output('Success! RBAC roles has been added.');
 }
Esempio n. 17
0
 public function setExecutable($paths)
 {
     foreach ($paths as $executable) {
         $executable = Yii::getAlias($executable);
         Console::output("Setting executable: {$executable}");
         @chmod($executable, 0755);
     }
 }
Esempio n. 18
0
 public function dropTableIfExist($table)
 {
     if ($this->tableExist($table)) {
         return $this->dropTable($table);
     } else {
         Console::output('Table "' . $table . '" not found');
     }
 }
 protected function getStdIn($message)
 {
     do {
         $this->stdout($message, Console::FG_YELLOW);
         $data = Console::stdin();
     } while (!$data);
     return $data;
 }
Esempio n. 20
0
 public function testStripAnsiFormat()
 {
     ob_start();
     ob_implicit_flush(false);
     echo 'a';
     Console::moveCursorForward(1);
     echo 'a';
     Console::moveCursorDown(1);
     echo 'a';
     Console::moveCursorUp(1);
     echo 'a';
     Console::moveCursorBackward(1);
     echo 'a';
     Console::moveCursorNextLine(1);
     echo 'a';
     Console::moveCursorPrevLine(1);
     echo 'a';
     Console::moveCursorTo(1);
     echo 'a';
     Console::moveCursorTo(1, 2);
     echo 'a';
     Console::clearLine();
     echo 'a';
     Console::clearLineAfterCursor();
     echo 'a';
     Console::clearLineBeforeCursor();
     echo 'a';
     Console::clearScreen();
     echo 'a';
     Console::clearScreenAfterCursor();
     echo 'a';
     Console::clearScreenBeforeCursor();
     echo 'a';
     Console::scrollDown();
     echo 'a';
     Console::scrollUp();
     echo 'a';
     Console::hideCursor();
     echo 'a';
     Console::showCursor();
     echo 'a';
     Console::saveCursorPosition();
     echo 'a';
     Console::restoreCursorPosition();
     echo 'a';
     Console::beginAnsiFormat([Console::FG_GREEN, Console::BG_BLUE, Console::UNDERLINE]);
     echo 'a';
     Console::endAnsiFormat();
     echo 'a';
     Console::beginAnsiFormat([Console::xtermBgColor(128), Console::xtermFgColor(55)]);
     echo 'a';
     Console::endAnsiFormat();
     echo 'a';
     $ouput = Console::stripAnsiFormat(ob_get_clean());
     ob_implicit_flush(true);
     // $output = str_replace("\033", 'X003', $ouput );// uncomment for debugging
     $this->assertEquals(str_repeat('a', 25), $ouput);
 }
 public function stdout($string)
 {
     if (Console::streamSupportsAnsiColors(STDOUT)) {
         $args = func_get_args();
         array_shift($args);
         $string = Console::ansiFormat($string, $args);
     }
     return Console::stdout($string);
 }
 public function actionCron()
 {
     $time = new \DateTime('now');
     foreach ($this->getScheduler()->all() as $task) {
         if ($this->getScheduler()->handle($task, $time)) {
             Console::output("Executed " . $task->getKey());
         }
     }
 }
Esempio n. 23
0
 /**
  * Prints a string to STDERR.
  *
  * @param string $string the string to print
  * @return int|boolean Number of bytes printed or false on error
  */
 public function stderr($string)
 {
     if ($this->isColorEnabled(\STDERR)) {
         $args = func_get_args();
         array_shift($args);
         $string = Console::ansiFormat($string, $args) . "\n";
     }
     return Console::stderr($string);
 }
Esempio n. 24
0
 /**
  * Colorizes a message for console output.
  * @param string $message the message to colorize.
  * @param array $format the message format.
  * @return string the colorized message.
  * @see Console::ansiFormat() for details on how to specify the message format.
  */
 protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
 {
     $stream = PHP_SAPI === 'cli' ? \STDERR : \STDOUT;
     // try controller first to allow check for --color switch
     if (Yii::$app->controller instanceof \yii\console\Controller && Yii::$app->controller->isColorEnabled($stream) || Yii::$app instanceof \yii\console\Application && Console::streamSupportsAnsiColors($stream)) {
         $message = Console::ansiFormat($message, $format);
     }
     return $message;
 }
 /**
  * message
  *
  * @param string $string
  * @access private
  * @return integer|null
  */
 private function message($string)
 {
     if (!empty($string) && !$this->quiet) {
         $args = func_get_args();
         array_shift($args);
         $string = Console::ansiFormat($string, $args);
         return Console::stdout($string);
     }
 }
Esempio n. 26
0
 /**
  * Helper method for writting console application output, include before and after wrappers.
  *
  * @param string $message The message which is displayed
  * @param string $color   A color from \yii\helpers\Console::FG_GREEN;
  * @param return void
  */
 protected function output($message, $color = null)
 {
     $format = [];
     if (!$this->isMuted()) {
         if ($color !== null) {
             $format[] = $color;
         }
         echo Console::ansiFormat("\r" . $message . "\n", $format);
     }
 }
Esempio n. 27
0
 /**
  * Initializing $_languageElements array.
  * @param array $languageSourceIds
  */
 private function _initLanguageElements($languageSourceIds)
 {
     $languageSources = LanguageSource::findAll(['id' => $languageSourceIds]);
     foreach ($languageSources as $languageSource) {
         $this->_languageElements[$languageSource->category][$languageSource->message] = $languageSource->id;
         $category = Console::ansiFormat($languageSource->category, [Console::FG_RED]);
         $message = Console::ansiFormat($languageSource->message, [Console::FG_RED]);
         $this->_scanner->stdout('category: ' . $category . ', message: ' . $message);
     }
 }
 /**
  * @param string $command serialized command object
  * @return string
  */
 public function actionHandle($command)
 {
     try {
         $command = unserialize(base64_decode($command));
         $command->setRunningInBackground(true);
         $this->commandBus->handle($command);
     } catch (\Exception $e) {
         Console::error($e->getMessage());
     }
 }
 /**
  * Drop all tables in existing DB
  * Use it before Migration
  * @access public
  */
 public function actionDropAllTables()
 {
     if ($this->interactive) {
         if (!Console::confirm('Sure that all tables will be dropped?', false)) {
             $this->stdout("# Canceled. Nothing happened\n", Console::FG_YELLOW);
             return 1;
         }
     }
     $this->_dropTables();
 }
 public function actionList()
 {
     Console::output("Currently waiting exports:");
     /** @var ActiveQuery $exportRequests */
     $requestsQuery = ExportRequest::find()->where(['is_exported' => 0])->orderBy(['created_at' => SORT_ASC]);
     foreach ($requestsQuery->each() as $exportRequest) {
         /** @var ExportRequest $exportRequest */
         Console::output("[#" . $exportRequest->id . ": " . $exportRequest->created_at . "] - " . $exportRequest->data_raw);
     }
 }