/** * @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"; }
/** * 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(); }
private function generatePosts() { $count = mt_rand(300, 500); Console::startProgress(0, $count, 'Generating posts: '); $sectionIds = (new Query())->select('id')->from('{{%section}}')->where('section_id IS NOT NULL')->column($this->getDb()); $authorIds = (new Query())->select('id')->from('{{%user}}')->column($this->getDb()); for ($i = 1; $i <= $count; ++$i) { $title = rtrim($this->getFaker()->sentence(mt_rand(3, 10)), '.'); $this->getDb()->createCommand()->insert('{{%post}}', ['title' => $title, 'slug' => Inflector::slug($title), 'section_id' => $sectionIds[array_rand($sectionIds)], 'author_id' => $authorIds[array_rand($authorIds)], 'text' => implode("\n\n", $this->getFaker()->paragraphs(mt_rand(1, 5))), 'created_at' => time(), 'updated_at' => time()])->execute(); Console::updateProgress($i, $count); } Console::endProgress(); }
/** * Returns progress closure. * * @param string $action * @return callable */ private function getProgress($action) { $progress = false; return function ($processed, $total, $message = null) use($progress, $action) { if (!$progress) { Console::startProgress(0, $total, $action); } if ($message) { Console::endProgress($message . PHP_EOL, false); } else { Console::updateProgress($processed, $total); } }; }
private function clearAliases($assets) { $len = count($assets); $message = ''; Console::startProgress(0, $len, 'Doing Updates: ', false); foreach ($assets as $key => $asset) { $uri = Yii::getAlias($asset); FileHelper::removeDirectory($uri); FileHelper::createDirectory($uri); Console::updateProgress($key + 1, $len); $message .= 'cleared: ' . $this->ansiFormat($uri, Console::FG_GREEN) . PHP_EOL; } Console::endProgress("done." . PHP_EOL); echo $message; }
public function onSubscribe($redis, $chan, $msg) { if ($msg === 'ready') { $this->post = ['s_bidnmKor' => '', 's_openDtm1' => date('Y/m/d', strtotime('-7 day')), 's_openDtm2' => date('Y/m/d'), 's_cstrtnJobGbCd' => '', 's_bidNum' => '', 'pageSpec' => 'default', 'targetRow' => 1, 'devonOrderBy' => '', 'selectednum' => '']; $this->pub->publish($this->channel . '-client', ['url' => self::URL, 'post' => http_build_query($this->post)]); return; } $html = iconv('euckr', 'utf-8//IGNORE', $msg); $html = strip_tags($html, '<tr><td><option>'); $html = preg_replace('/<td[^>]*>/i', '<td>', $html); if (strpos($html, '한국정보인증(주)의 보안S/W를 설치중입니다') > 0) { return; } $p = '#<tr onclick="fn_dds_open\\(\'\\d{7}\', \'(?<subno>\\d{2})\',[^>]*>' . ' <td>(?<notinum>\\d{7})</td>' . ' <td>(?<bidtype>[^<]*)</td>' . ' <td>(?<bidcls>[^<]*)</td>' . ' <td>(?<constnm>[^<]*)</td>' . ' <td>(?<constdt>\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2})</td>' . ' <td>(?<status>[^<]*)</td>' . ' </tr>#i'; if (preg_match_all(str_replace(' ', '\\s*', $p), $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $row = ['notinum' => trim($m['notinum']), 'subno' => trim($m['subno']), 'bidtype' => trim($m['bidtype']), 'bidcls' => trim($m['bidcls']), 'constnm' => trim($m['constnm']), 'constdt' => trim($m['constdt']), 'status' => trim($m['status'])]; $event = new WatchEvent(); $event->row = $row; $this->trigger(WatchEvent::EVENT_ROW, $event); } } if (preg_match('#/ (?<total_page>\\d+) 페이지\\)#', $html, $m)) { $total_page = intval($m['total_page']); } if (!$total_page) { $this->sub->close(); throw new \Exception('total_page is null'); } $page = ceil($this->post['targetRow'] / 10); if ($page === 1) { Console::startProgress(0, $total_page); Console::updateProgress(1, $total_page); } else { Console::updateProgress($page, $total_page); } if ($page == $total_page) { $this->pub->publish($this->channel . '-client', ['url' => 'close', 'post' => '']); $this->sub->close(); Console::endProgress(); return; } else { $this->post['targetRow'] += 10; } sleep(mt_rand($this->module->delay_min, $this->module->delay_max)); $this->pub->publish($this->channel . '-client', ['url' => self::URL, 'post' => http_build_query($this->post)]); }
public function generateFakeData($num) { Console::startProgress(0, 100); $topic = new Topic(); $comment = new PostComment(); $node = new PostMeta(); $faker = Faker\Factory::create('zh_CN'); $nodeData = [['name' => '分享', 'alias' => '', 'parent' => 0], ['name' => '招聘', 'alias' => 'jobs', 'parent' => 1], ['name' => '瞎扯淡', 'alias' => 'booshit', 'parent' => 1], ['name' => '健康', 'alias' => 'health', 'parent' => 1], ['name' => '创业', 'alias' => 'startup', 'parent' => 1]]; $transaction = Yii::$app->db->beginTransaction(); try { for ($j = 0; $j < count($nodeData); $j++) { $_node = clone $node; $_node->setAttributes($nodeData[$j] + ['type' => 'topic_category']); $_node->save(); } $this->execute("INSERT INTO {{%merit_template}} (`id`, `type`, `title`, `unique_id`, `method`, `event`, `action_type`, `rule_key`, `rule_value`, `increment`, `status`, `created_at`, `updated_at`) VALUES\n(1, 1, '登录', 'site/login', 2, 0, 2, 1, 1, 2, 1, 1458657160, 1458823425),\n(2, 1, '发帖', 'topic/default/create', 2, 0, 2, 0, NULL, 6, 1, 1458657218, 1458657218),\n(3, 1, '回复', 'topic/comment/create', 2, 0, 2, 0, NULL, 4, 1, 1458657251, 1458657251),\n(4, 1, '发动弹', 'tweet/default/create', 2, 0, 2, 0, NULL, 4, 1, 1458657296, 1468647701);\n"); /** @var User $user */ $user = User::find()->where(['role' => User::ROLE_SUPER_ADMIN])->one(); Yii::$app->user->setIdentity($user); for ($i = 1; $i <= $num; $i++) { $_topic = clone $topic; $_topic->setAttributes(['type' => Topic::TYPE, 'title' => $faker->text(rand(10, 50)), 'post_meta_id' => rand(2, 4), 'status' => rand(1, 2), 'content' => $faker->text(rand(100, 2000)), 'user_id' => 1]); if (!$_topic->save()) { throw new Exception(array_values($_topic->getFirstErrors())[0]); } for ($_i = 1; $_i <= rand(1, 20); $_i++) { $_comment = clone $comment; $_comment->setAttributes(['comment' => $faker->text(rand(100, 2000)), 'post_id' => $_topic->id, 'ip' => '127.0.0.1', 'user_id' => 1]); if (!$_comment->save()) { throw new Exception(array_values($_comment->getFirstErrors())[0]); } // 更新回复时间 $_topic->lastCommentToUpdate($user['username']); // 评论计数器 Topic::updateAllCounters(['comment_count' => 1], ['id' => $_topic->id]); // 更新个人总统计 UserInfo::updateAllCounters(['comment_count' => 1], ['user_id' => $_topic->user_id]); } Console::updateProgress($i / $num * 100, 100); } $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); throw $e; } Console::endProgress(); }
/** * Generate fake data and */ public function actionGenerate() { $input = $this->parseArguments(func_get_args()); $container = new Container(); $container->set(GeneratorInterface::class, array_merge(['class' => $this->generator_fqn], $input['generator'])); $container->set(DbProviderInterface::class, array_merge(['class' => $this->dbprovider_fqn], $input['dbprovider'])); $this->generator_obj = $container->get(GeneratorInterface::class); if (!$this->force && !$this->confirmGeneration()) { return; } $this->dbprovider_obj = $container->get(DbProviderInterface::class); Console::startProgress(0, $this->count); foreach ($this->dbprovider_obj->export($this->count) as $count) { Console::updateProgress($this->count - $count, $this->count); } Console::endProgress(true); }
/** * Импортировать товары */ public function actionRun() { $products = $this->_getProducts(); $total = count($products); $this->stdout("Import products from yupe: {$total}\n", Console::BOLD); Console::startProgress(0, $total); $counter = 0; foreach ($products as $product) { //print_R($product);die; $counter++; Console::updateProgress($counter, $total); $name = ArrayHelper::getValue($product, 'name'); $v3toysId = ArrayHelper::getValue($product, 'external_id'); $this->_addProduct($product); //sleep(1); } Console::endProgress(); }
/** * @inheritDoc */ public function render($context, $targetDir) { $types = array_merge($context->classes, $context->traits, $context->interfaces); $typeCount = count($types) + 1; if ($this->controller !== null) { Console::startProgress(0, $typeCount, 'Rendering files: ', false); } $done = 0; foreach ($types as $type) { $fileContent = $this->getView()->render('type', ['type' => $type, 'apiContext' => $context, 'types' => $types], $this); file_put_contents($targetDir . '/' . $this->generateFileName($type->name), $fileContent); if ($this->controller !== null) { Console::updateProgress(++$done, $typeCount); } } if ($this->controller !== null) { Console::updateProgress(++$done, $typeCount); Console::endProgress(true); $this->controller->stdout('done.' . PHP_EOL, Console::FG_GREEN); } }
public function generateFakeData($num) { Console::startProgress(0, 100); $queston = new Question(); $answer = new Answer(); $faker = Faker\Factory::create('zh_CN'); for ($i = 1; $i <= $num; $i++) { $_question = clone $queston; $_question->setAttributes(['subject' => $faker->text(rand(10, 100)), 'content' => $faker->text(rand(100, 2000)), 'author_id' => 1]); if ($_question->save()) { $_question->setActive(); for ($_i = 1; $_i <= rand(1, 20); $_i++) { $_answer = clone $answer; $_answer->setAttributes(['content' => $faker->text(rand(100, 2000)), 'author_id' => 1]); if ($_question->addAnswer($_answer)) { $_answer->setActive(); } } } Console::updateProgress($i / $num * 100, 100); } Console::endProgress(); }
public function generateFakeData($num) { Console::startProgress(0, 100); $topic = new Topic(); $comment = new PostComment(); $node = new PostMeta(); $faker = Faker\Factory::create('zh_CN'); $nodeData = [['name' => '分享', 'alias' => '', 'parent' => 0], ['name' => '招聘', 'alias' => 'recruit', 'parent' => 1], ['name' => '瞎扯淡', 'alias' => 'booshit', 'parent' => 1], ['name' => '健康', 'alias' => 'health', 'parent' => 1], ['name' => '创业', 'alias' => 'startup', 'parent' => 1]]; for ($j = 0; $j < count($nodeData); $j++) { $_node = clone $node; $_node->setAttributes($nodeData[$j] + ['type' => 'topic_category']); $_node->save(); } $user = User::find()->where(['role' => User::ROLE_SUPER_ADMIN])->one(); for ($i = 1; $i <= $num; $i++) { $_topic = clone $topic; $_topic->setAttributes(['type' => Topic::TYPE, 'title' => $faker->text(rand(10, 50)), 'post_meta_id' => rand(2, 4), 'status' => rand(1, 2), 'content' => $faker->text(rand(100, 2000)), 'user_id' => 1]); if (!$_topic->save()) { throw new Exception(array_values($_topic->getFirstErrors())[0]); } for ($_i = 1; $_i <= rand(1, 20); $_i++) { $_comment = clone $comment; $_comment->setAttributes(['comment' => $faker->text(rand(100, 2000)), 'post_id' => $_topic->id, 'ip' => '127.0.0.1', 'user_id' => 1]); if (!$_comment->save()) { throw new Exception(array_values($_comment->getFirstErrors())[0]); } // 更新回复时间 $_topic->lastCommentToUpdate($user['username']); // 评论计数器 Topic::updateAllCounters(['comment_count' => 1], ['id' => $_topic->id]); // 更新个人总统计 UserInfo::updateAllCounters(['comment_count' => 1], ['user_id' => $_topic->user_id]); } Console::updateProgress($i / $num * 100, 100); } Console::endProgress(); }
public function run($workload, $className) { try { $notinum_ex = $workload['bidno']; if (isset($workload['bidproc']) and ArrayHelper::isIn($workload['bidproc'], ['유찰', '재공고'])) { $query = BidKey::find()->where(['whereis' => '08', 'notinum' => $data['notinum']]); if ($notinum_ex == 1) { $query->andWhere("notinum_ex='' or notinum_ex='1'"); } else { $query->andWhere(['notinum_ex' => $notinum_ex]); } $bidkey = $query->orderBy('bidid desc')->limit(1)->one(); if ($bidkey !== null and $bidkey->bidproc !== 'F') { $this->gman_client->doBackground('i2_auto_suc_test', Json::encode(['bidid' => $bidkey->bidid, 'bidproc' => 'F'])); $this->stdout2(" >>> {$bidkey->bidid} ({$bidkey->bidproc}) %y유찰%n\n"); } return; } $worker = new $className(['notino' => $workload['notino'], 'bidno' => $workload['bidno'], 'bidseq' => $workload['bidseq'], 'state' => $workload['state']]); $worker->on('total_page', function ($event) { Console::startProgress(0, $event->sender->succom_total_page); }); $worker->on('page', function ($event) { if ($event->sender->succom_total_page == $event->sender->succom_page) { Console::updateProgress($event->sender->succom_page, $event->sender->succom_total_page); Console::endProgress(); } else { Console::updateProgress($event->sender->succom_page, $event->sender->succom_total_page); } }); $data = $worker->run(); $query = BidKey::find()->where(['whereis' => '08', 'notinum' => $data['notinum']]); if ($notinum_ex == 1) { $query->andWhere("notinum_ex='' or notinum_ex='1'"); } else { $query->andWhere(['notinum_ex' => $notinum_ex]); } $bidkey = $query->orderBy('bidid desc')->limit(1)->one(); if ($bidkey === null) { return; } $bidvalue = $bidkey->bidValue; $data['multispare'] = $bidvalue->multispare; if (is_array($data['selms'])) { $selms = []; $multispares = explode('|', $data['multispare']); foreach ($multispares as $i => $v) { if (ArrayHelper::isIn($v, $data['selms'])) { $selms[] = $i + 1; } } $data['selms'] = join('|', $selms); } $data['bidid'] = $bidkey->bidid; $data['bidproc'] = 'S'; $this->gman_client->doBackground('i2_auto_suc_test', Json::encode($data)); $this->stdout2(" >>> {$bidkey->bidid} ({$bidkey->bidproc}) 예가:{$data['yega']} 참여수:{$data['innum']} %g개찰%n\n"); } catch (\Exception $e) { $this->stdout("{$e}\n", Console::FG_RED); \Yii::error($e, 'ebidex'); } }
/** * Renders API documentation files * @param array $sourceDirs * @param string $targetDir * @return int */ public function actionIndex(array $sourceDirs, $targetDir) { $renderer = $this->findRenderer($this->template); $targetDir = $this->normalizeTargetDir($targetDir); if ($targetDir === false || $renderer === false) { return 1; } $renderer->apiUrl = './'; $renderer->guidePrefix = $this->guidePrefix; if ($this->pageTitle !== null) { $renderer->pageTitle = $this->pageTitle; } // setup reference to guide if ($this->guide !== null) { $renderer->guideUrl = $guideUrl = $this->guide; } else { $guideUrl = './'; $renderer->guideUrl = $targetDir; if (file_exists($renderer->generateGuideUrl('README.md'))) { $renderer->guideUrl = $guideUrl; } else { $renderer->guideUrl = null; } } // search for files to process if (($files = $this->searchFiles($sourceDirs)) === false) { return 1; } // load context from cache $context = $this->loadContext($targetDir); $this->stdout('Checking for updated files... '); foreach ($context->files as $file => $sha) { if (!file_exists($file)) { $this->stdout('At least one file has been removed. Rebuilding the context...'); $context = new Context(); if (($files = $this->searchFiles($sourceDirs)) === false) { return 1; } break; } if (sha1_file($file) === $sha) { unset($files[$file]); } } $this->stdout('done.' . PHP_EOL, Console::FG_GREEN); // process files $fileCount = count($files); $this->stdout($fileCount . ' file' . ($fileCount == 1 ? '' : 's') . ' to update.' . PHP_EOL); Console::startProgress(0, $fileCount, 'Processing files... ', false); $done = 0; foreach ($files as $file) { $context->addFile($file); Console::updateProgress(++$done, $fileCount); } Console::endProgress(true); $this->stdout('done.' . PHP_EOL, Console::FG_GREEN); // save processed data to cache $this->storeContext($context, $targetDir); $this->updateContext($context); // render models $renderer->controller = $this; $renderer->render($context, $targetDir); if (!empty($context->errors)) { ArrayHelper::multisort($context->errors, 'file'); file_put_contents($targetDir . '/errors.txt', print_r($context->errors, true)); $this->stdout(count($context->errors) . " errors have been logged to {$targetDir}/errors.txt\n", Console::FG_RED, Console::BOLD); } }
public static function onCronRun($event) { $controller = $event->sender; $interval = ""; if (Yii::$app->controller->action->id == 'hourly') { $interval = CronController::EVENT_ON_HOURLY_RUN; } elseif (Yii::$app->controller->action->id == 'daily') { $interval = CronController::EVENT_ON_DAILY_RUN; } else { return; } $users = User::find()->distinct()->joinWith(['httpSessions', 'profile'])->where(['status' => User::STATUS_ENABLED]); $totalUsers = $users->count(); $done = 0; $mailsSent = 0; $defaultLanguage = Yii::$app->language; Console::startProgress($done, $totalUsers, 'Sending update e-mails to users... ', false); foreach ($users->each() as $user) { if ($user->email === "") { continue; } // Check user should receive an email Yii::$app->user->switchIdentity($user); if ($user->language != "") { Yii::$app->language = $user->language; } else { Yii::$app->language = $defaultLanguage; } $notifications = Yii::$app->getModule('notification')->getMailUpdate($user, $interval); $activities = Yii::$app->getModule('activity')->getMailUpdate($user, $interval); if ($notifications != "" || $activities != "") { try { $mail = Yii::$app->mailer->compose(['html' => '@humhub/modules/content/views/mails/Update'], ['activities' => $activities, 'notifications' => $notifications]); $mail->setFrom([Setting::Get('systemEmailAddress', 'mailing') => Setting::Get('systemEmailName', 'mailing')]); $mail->setTo($user->email); if ($interval == CronController::EVENT_ON_HOURLY_RUN) { $mail->setSubject(Yii::t('base', "Latest news")); } else { $mail->setSubject(Yii::t('base', "Your daily summary")); } $mail->send(); $mailsSent++; } catch (\Swift_SwiftException $ex) { Yii::error('Could not send mail to: ' . $user->email . ' - Error: ' . $ex->getMessage()); } catch (Exception $ex) { Yii::error('Could not send mail to: ' . $user->email . ' - Error: ' . $ex->getMessage()); } } Console::updateProgress(++$done, $totalUsers); } Console::endProgress(true); $controller->stdout('done - ' . $mailsSent . ' email(s) sent.' . PHP_EOL, \yii\helpers\Console::FG_GREEN); }
/** * @param Query $query * @param string $name * @param bool $force * @return void * @throws \Exception */ protected function generate(Query $query, $name, $force) { $use = implode(', ', $query->getProviders()); if (!$force && count($query) > 0) { $this->stdout("use exist {$name} table.\n", Console::FG_YELLOW); } else { $this->stdout("generate {$name} table with {$use}:\n", Console::FG_GREEN); if (empty($this->controller->noProgress)) { $query->init(function ($code, $n) { static $total = 0; switch ($code) { case 0: Console::startProgress(0, $n); $total = $n; break; case 1: Console::updateProgress($n, $total); break; case 2: Console::updateProgress($total, $total); Console::endProgress(); break; } }); } else { $query->init(); } $this->stdout(" completed!\n", Console::FG_GREEN); } }
public function actionMigrateQty() { $command = Yii::$app->db->createCommand(); $sampleDir = __DIR__ . '/data'; $command->delete('{{%product_stock}}')->execute(); // $queryCheck = (new \yii\db\Query()) // ->select(['qty']) // ->from('{{%product_stock}}') // ->where('warehouse_id=:wid and product_id=:pid'); $rows = (require $sampleDir . '/qty_awal.php'); $total = count($rows); echo "\ninsert table {{%product_stock}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { // if ($queryCheck->params([':wid' => $row[0], ':pid' => $row[1]])->one()) { // $command->update('{{%product_stock}}', ['qty' => $row[2]], [ // 'warehouse_id' => $row[0], // 'product_id' => $row[1], // ])->execute(); // } else { $command->insert('{{%product_stock}}', $this->toAssoc($row, ['warehouse_id', 'product_id', 'qty']))->execute(); // } Console::updateProgress($i + 1, $total); } Console::endProgress(); }
public function i2conv_run($job) { $workload = $job->workload(); $workload = Json::decode($workload); try { $this->module->i2db->close(); $this->module->infodb->close(); $bidKey = BidKey::findOne($workload['bidid']); if ($bidKey === null) { return; } $bidvalue = $bidKey->bidValue; if ($bidvalue === null) { return; } if (!ArrayHelper::isIn($bidKey->state, ['Y', 'N', 'D'])) { return; } if ($bidKey->bidproc === 'J') { return; } if (empty($bidKey->location)) { return; } switch ($bidKey->bidtype) { case 'con': echo Console::renderColoredString('%y[공사]%n'); break; case 'ser': echo Console::renderColoredString('%g[용역]%n'); break; case 'pur': echo Console::renderColoredString('%b[구매]%n'); break; default: return; } echo $bidKey->constnm; echo '[' . $bidKey->notinum . ']'; echo '(' . $bidKey->state . ',' . $bidKey->bidproc . ')'; //------------------------------------------------------ // v3_bid_key //------------------------------------------------------ $v3bidkey = V3BidKey::findNew($bidKey->bidid); $this->stdout($v3bidkey->isNewRecord ? "[NEW]\n" : "\n", Console::FG_RED); $v3bidkey->attributes = ['whereis' => $bidKey->whereis, 'bidtype' => $bidKey->bidtype, 'con' => strpos($bidKey->bidview, 'con') === false ? 'N' : 'Y', 'ser' => strpos($bidKey->bidview, 'ser') === false ? 'N' : 'Y', 'pur' => strpos($bidKey->bidview, 'pur') === false ? 'N' : 'Y', 'notinum' => $bidKey->notinum, 'orgcode' => $bidKey->orgcode_i, 'constnm' => $bidKey->constnm, 'org' => $bidKey->org_i, 'bidproc' => $bidKey->bidproc, 'contract' => $bidKey->contract, 'bidcls' => $bidKey->bidcls, 'succls' => $bidKey->succls, 'conlevel' => $bidKey->toV3BidKey_conlevel(), 'ulevel' => $bidKey->opt, 'concode' => $bidKey->toV3BidKey_concode(), 'sercode' => $bidKey->toV3BidKey_sercode(), 'purcode' => $bidKey->toV3BidKey_purcode(), 'location' => $bidKey->location ? $bidKey->location : 0, 'convention' => $bidKey->convention == '3' ? '2' : $bidKey->convention, 'presum' => $bidKey->presum ? $bidKey->presum : 0, 'basic' => $bidKey->basic ? $bidKey->basic : 0, 'pct' => $bidKey->pct ? $bidKey->pct : '', 'registdate' => strtotime($bidKey->registdt) > 0 ? date('Y-m-d', strtotime($bidKey->registdt)) : '', 'explaindate' => strtotime($bidKey->explaindt) > 0 ? date('Y-m-d', strtotime($bidKey->explaindt)) : '', 'agreedate' => strtotime($bidKey->agreedt) > 0 ? date('Y-m-d', strtotime($bidKey->agreedt)) : '', 'opendate' => strtotime($bidKey->opendt) > 0 ? date('Y-m-d', strtotime($bidKey->opendt)) : '', 'closedate' => strtotime($bidKey->closedt) > 0 ? date('Y-m-d', strtotime($bidKey->closedt)) : '', 'constdate' => strtotime($bidKey->constdt) > 0 ? date('Y-m-d', strtotime($bidKey->constdt)) : '', 'writedate' => strtotime($bidKey->writedt) > 0 ? date('Y-m-d', strtotime($bidKey->writedt)) : '', 'reswdate' => strtotime($bidKey->resdt) > 0 ? date('Y-m-d', strtotime($bidKey->resdt)) : '', 'state' => $bidKey->state, 'in_id' => 91]; //------------------------------------------------------ // v3_bid_value //------------------------------------------------------ $v3BidValue = V3BidValue::findNew($v3bidkey->bidid); $v3BidValue->attributes = ['scrcls' => $bidvalue->scrcls, 'scrid' => $bidvalue->scrid, 'constno' => $bidvalue->constno, 'refno' => $bidvalue->refno, 'realorg' => $bidvalue->realorg, 'yegatype' => $bidvalue->yegatype, 'yegarng' => str_replace('|', '/', $bidvalue->yegarng), 'prevamt' => $bidvalue->prevamt, 'parbasic' => $bidvalue->parbasic, 'lvcnt' => $bidvalue->lvcnt, 'charger' => str_replace('|', '/', $bidvalue->charger), 'multispare' => str_replace('|', '/', str_replace(',', '', $bidvalue->multispare)), 'contper' => $bidvalue->contper, 'noticedt' => strtotime($bidKey->noticedt) > 0 ? strtotime($bidKey->noticedt) : 0, 'registdt' => strtotime($bidKey->registdt) > 0 ? strtotime($bidKey->registdt) : 0, 'explaindt' => strtotime($bidKey->explaindt) > 0 ? strtotime($bidKey->explaindt) : 0, 'agreedt' => strtotime($bidKey->agreedt) > 0 ? strtotime($bidKey->agreedt) : 0, 'opendt' => strtotime($bidKey->opendt) > 0 ? strtotime($bidKey->opendt) : 0, 'closedt' => strtotime($bidKey->closedt) > 0 ? strtotime($bidKey->closedt) : 0, 'constdt' => strtotime($bidKey->constdt) > 0 ? strtotime($bidKey->constdt) : 0, 'writedt' => strtotime($bidKey->writedt) > 0 ? strtotime($bidKey->writedt) : 0, 'editdt' => strtotime($bidKey->editdt) > 0 ? strtotime($bidKey->editdt) : 0]; //공동도급지역코드 (사용하나??) $arr = explode('|', $bidvalue->contloc); foreach ($arr as $val) { if (empty($val)) { continue; } $m = BidLocal::findOne(['bidid' => $v3bidkey->bidid, 'name' => iconv('utf-8', 'euckr', $val)]); if ($m !== null) { $v3BidValue->contloc = $m->code; break; //v3_bid_key.contloc char(4) 때문 1개 지역만 처리... } } //------------------------------------------------------ // v3_bid_itemcode //------------------------------------------------------ V3BidItemcode::deleteAll(['bidid' => $v3bidkey->bidid]); $bidItemcodes = $bidKey->toV3BidItemcodes_attributes(); foreach ($bidItemcodes as $row) { $v3BidItemcode = V3BidItemcode::findNew($v3bidkey->bidid, $row['bidtype'], $row['code']); $v3BidItemcode->name = $row['name']; $v3BidItemcode->save(); } //------------------------------------------------------ // v3_bid_local //------------------------------------------------------ V3BidLocal::deleteAll(['bidid' => $v3bidkey->bidid]); $bidlocals = $bidKey->bidLocals; foreach ($bidlocals as $bidlocal) { $v3BidLocal = new V3BidLocal(['bidid' => $v3bidkey->bidid, 'code' => $bidLocal->code, 'name' => $bidLocal->name]); $v3BidLocal->save(); } //------------------------------------------------------ // v3_bid_subcode //------------------------------------------------------ V3BidSubcode::deleteAll(['bidid' => $v3bidkey->bidid]); $subcodes = $bidKey->bidSubcodes; foreach ($subcodes as $subcode) { $v3BidSubcode = new V3BidSubcode(['bidid' => $v3bidkey->bidid, 'g2b_code' => $subcode->g2b_code, 'g2b_code_nm' => $subcode->g2b_code_nm, 'i2_code' => $subcode->i2_code, 'itemcode' => $subcode->itemcode, 'pri_cont' => $subcode->pri_cont, 'share' => $subcode->share]); $v3BidSubcode->save(); } //------------------------------------------------------- // v3_bid_content //------------------------------------------------------- $bidcontent = $bidKey->bidContent; if ($bidcontent !== null) { $v3content = V3BidContent::findNew($v3bidkey->bidid); $v3content->attributes = ['content_bid' => $bidcontent->bid_html, 'important_suc' => $bidcontent->nbidcomment, 'content_suc' => $bidcontent->nbid_html, 'upfile_bid' => $bidcontent->bid_file, 'upfile_suc' => $bidcontent->nbid_file, 'important_bid' => !empty($bidcontent->bidcomment_mod) ? $bidcontent->bidcomment_mod . '\\n<hr/>\\n' . $bidcontent->bidcomment : $bidcontent->bidcomment]; $v3content->save(); $v3BidValue->origin_lnk = $bidcontent->orign_lnk; $v3BidValue->attchd_lnk = $bidcontent->attchd_lnk; } //----------------------------------------------------- // v3_bid_goods //----------------------------------------------------- $bidGoods = $bidKey->bidGoods; V3BidGoods::deleteAll(['bidid' => $v3bidkey->bidid]); foreach ($bidGoods as $g) { $v3BidGood = new V3BidGoods(); $v3BidGood->attributes = $g->attributes; $v3BidGood->save(); } //------------------------------------------------------- // v3_bid_res,v3_bid_succom //------------------------------------------------------- $bidRes = $bidKey->bidRes; if (ArrayHelper::isIn($bidKey->bidproc, ['S', 'F']) && $bidRes !== null) { $v3BidResult = V3BidResult::findNew($v3bidkey->bidid); $v3BidResult->attributes = ['yega' => $bidRes->yega, 'innum' => $bidRes->innum, 'officenm1' => $bidRes->officenm1, 'prenm1' => $bidRes->prenm1, 'officeno1' => $bidRes->officeno1, 'success1' => $bidRes->success1, 'resdt' => strtotime($bidKey->resdt) > 0 ? strtotime($bidKey->resdt) : 0, 'reswdt' => strtotime($bidRes->reswdt) > 0 ? strtotime($bidRes->reswdt) : 0]; $arr = explode('|', $bidRes->selms); $selms = []; foreach ($arr as $v) { if ($v == '') { continue; } $selms[] = intval($v) - 1; } $v3BidResult->selms = implode('-', $selms); $v3BidResult->save(); if ($bidKey->whereis != '08' && $bidKey->bidproc != 'F') { $v3BidValue->multispare = str_replace('|', '/', str_replace(',', '', $bidRes->multispare)); } $v3BidValue->save(); if ($bidRes->innum > 0) { $succoms = $bidKey->succoms; if (count($succoms) == $bidRes->innum) { V3BidSuccom::deleteAll(['constdate' => $v3bidkey->constdate, 'bidid' => $v3bidkey->bidid]); Console::startProgress(0, $bidRes->innum); $n = 1; foreach ($succoms as $s) { $v3succom = V3BidSuccom::findNew($v3bidkey->constdate, $v3bidkey->bidid, $s->seq); $v3succom = new V3BidSuccom(['constdate' => $v3bidkey->constdate, 'bidid' => $v3bidkey->bidid, 'seq' => $s->seq, 'regdt' => strtotime($s->regdt) > 0 ? strtotime($s->regdt) : 0, 'pct' => $s->pct, 'prenm' => $s->prenm == null ? '' : $s->prenm, 'officenm' => $s->officenm, 'officeno' => $s->officeno, 'success' => $s->success, 'etc' => $s->etc, 'rank' => $s->rank]); $v3succom->save(); Console::updateProgress($n, $bidRes->innum); $n++; } Console::endProgress(); } } } $v3BidValue->save(); $v3bidkey->save(); $gman_client = new GearmanClient(); $gman_client->addServers($this->module->gman_server); $gman_client->doBackground('i2conv_legacy', Json::encode($workload)); } catch (\Exception $e) { echo Console::ansiFormat($e, [Console::FG_RED]), PHP_EOL; Yii::error($e, 'i2conv'); $gman_client = new GearmanClient(); $gman_client->addServers('192.168.1.242'); $gman_client->doBackground('send_chat_message_from_admin', Json::encode(['recv_id' => 149, 'message' => iconv('cp949', 'utf-8', $e) . "\n[i2conv]"])); } $this->stdout(sprintf("[%s] Peak memory usage: %s MB\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024), Console::FG_GREY); }
<?php use yii\helpers\Console; /* @var $this app\commands\SampleDataController */ /* @var $command yii\db\Command */ /* @var $faker Faker\Generator */ $rows = [[1, "Celana Panjang"], [2, "Celana Pendek"], [3, "Jaket"], [4, "Sweater"], [5, "Kaos"], [6, "Kemeja"], [7, "Sandal"], [8, "Tas"], [9, "Aksesoris"], [10, "Sepatu"], [11, "Parfum"]]; echo "Insert data product category\n"; $total = count($rows); Console::startProgress(0, $total); $command->delete('{{%category}}')->execute(); foreach ($rows as $i => $row) { $command->insert('{{%category}}', ['id' => $row[0], 'code' => sprintf('%04d', $row[0]), 'name' => $row[1], 'created_at' => $now, 'updated_at' => $now])->execute(); Console::updateProgress($i + 1, $total); } Console::endProgress();
/** * Create sample data */ public function actionCreate() { if (!Console::confirm('Are you sure you want to create sample data. Old data will be lose')) { return self::EXIT_CODE_NORMAL; } $command = Yii::$app->db->createCommand(); $sampleDir = __DIR__ . '/samples/zomb'; // TRUNCATE TABLE $command->delete('{{%product_stock}}')->execute(); $command->delete('{{%gl_detail}}')->execute(); $command->delete('{{%gl_header}}')->execute(); $command->delete('{{%goods_movement_dtl}}')->execute(); $command->delete('{{%goods_movement}}')->execute(); $command->delete('{{%sales_dtl}}')->execute(); $command->delete('{{%sales}}')->execute(); $command->delete('{{%transfer_dtl}}')->execute(); $command->delete('{{%transfer}}')->execute(); $command->delete('{{%invoice_dtl}}')->execute(); $command->delete('{{%invoice}}')->execute(); $command->delete('{{%payment_dtl}}')->execute(); $command->delete('{{%payment}}')->execute(); $command->delete('{{%warehouse}}')->execute(); $command->delete('{{%branch}}')->execute(); $command->delete('{{%orgn}}')->execute(); $command->delete('{{%vendor}}')->execute(); $command->delete('{{%product_uom}}')->execute(); $command->delete('{{%cogs}}')->execute(); $command->delete('{{%price}}')->execute(); $command->delete('{{%price_category}}')->execute(); $command->delete('{{%product_child}}')->execute(); $command->delete('{{%product}}')->execute(); $command->delete('{{%product_group}}')->execute(); $command->delete('{{%category}}')->execute(); $command->delete('{{%uom}}')->execute(); $command->delete('{{%entri_sheet}}')->execute(); $command->delete('{{%coa}}')->execute(); $command->delete('{{%payment_method}}')->execute(); // orgn $rows = (require $sampleDir . '/orgn.php'); $total = count($rows); echo "\ninsert table {{%orgn}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%orgn}}', $this->toAssoc($row, ['id', 'code', 'name']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%orgn}}')->execute(); Console::endProgress(); // branch $rows = (require $sampleDir . '/branch.php'); $total = count($rows); echo "\ninsert table {{%branch}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%branch}}', $this->toAssoc($row, ['id', 'orgn_id', 'code', 'name', 'addr']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%branch}}')->execute(); Console::endProgress(); // warehouse $rows = (require $sampleDir . '/warehouse.php'); $total = count($rows); echo "\ninsert table {{%warehouse}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%warehouse}}', $this->toAssoc($row, ['id', 'code', 'name']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%warehouse}}')->execute(); Console::endProgress(); // customer $rows = (require $sampleDir . '/vendor.php'); $total = count($rows); echo "\ninsert table {{%vendor}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%vendor}}', $this->toAssoc($row, ['id', 'type', 'code', 'name', 'contact_name', 'contact_number', 'status']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%vendor}}')->execute(); Console::endProgress(); // product category $rows = (require $sampleDir . '/category.php'); $total = count($rows); echo "\ninsert table {{%category}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%category}}', $this->toAssoc($row, ['id', 'code', 'name']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%category}}')->execute(); Console::endProgress(); // product group $rows = (require $sampleDir . '/product_group.php'); $total = count($rows); echo "\ninsert table {{%product_group}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%product_group}}', $this->toAssoc($row, ['id', 'code', 'name']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%product_group}}')->execute(); Console::endProgress(); // price category $rows = (require $sampleDir . '/price_category.php'); $total = count($rows); echo "\ninsert table {{%price_category}}\n"; Console::startProgress(0, $total); $pc_ids = []; foreach ($rows as $i => $row) { $pc_ids[] = $row[0]; $command->insert('{{%price_category}}', $this->toAssoc($row, ['id', 'name']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%price_category}}')->execute(); Console::endProgress(); // product $rows = (require $sampleDir . '/product.php'); $total = count($rows); echo "\ninsert table {{%product}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $row = $this->toAssoc($row, ['id', 'group_id', 'category_id', 'code', 'name', 'status', 'stockable']); $command->insert('{{%product}}', $row)->execute(); // barcode /* * Skip for test $batch = []; for ($j = 0; $j < 3; $j++) { $rand = mt_rand(1000000, 9999999) . mt_rand(100000, 999999); $batch[] = [$rand, $row['id']]; } try { $command->batchInsert('{{%product_child}}', ['barcode', 'product_id'], $batch)->execute(); } catch (Exception $exc) { echo 'Error: ' . $exc->getMessage() . "\n"; } * */ // price /* * Skip for test $batch = []; $price = mt_rand(95, 150) * 1000; foreach ($pc_ids as $pc_id) { $batch[] = [$row['id'], $pc_id, $price - $pc_id * 3000]; } $command->batchInsert('{{%price}}', ['product_id', 'price_category_id', 'price'], $batch)->execute(); */ // cogs /* * Skip for test $command->insert('{{%cogs}}', [ 'product_id' => $row['id'], 'cogs' => $price * 0.65, 'last_purchase_price' => $price - 20000, 'created_at' => time(), 'created_by' => 1, ])->execute(); * */ Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%product}}')->execute(); Console::endProgress(); // price $rows = (require $sampleDir . '/price.php'); $total = count($rows); echo "\ninsert table {{%price}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $pc_ids[] = $row[0]; $command->insert('{{%price}}', $this->toAssoc($row, ['product_id', 'price_category_id', 'price']))->execute(); Console::updateProgress($i + 1, $total); } Console::endProgress(); // cogs $rows = (require $sampleDir . '/cogs.php'); $total = count($rows); echo "\ninsert table {{%cogs}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $pc_ids[] = $row[0]; $command->insert('{{%cogs}}', $this->toAssoc($row, ['product_id', 'cogs', 'last_purchase_price']))->execute(); Console::updateProgress($i + 1, $total); } Console::endProgress(); // uom $rows = (require $sampleDir . '/uom.php'); $total = count($rows); echo "\ninsert table {{%uom}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%uom}}', $this->toAssoc($row, ['id', 'code', 'name']))->execute(); // product uom $sql = "insert into {{%product_uom}}([[product_id]],[[uom_id]],[[isi]])\n" . "select [[id]],{$row[0]},{$row[3]} from {{%product}}"; $command->setSql($sql)->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%uom}}')->execute(); Console::endProgress(); // coa $rows = (require $sampleDir . '/coa.php'); $total = count($rows); echo "\ninsert table {{%coa}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%coa}}', $this->toAssoc($row, ['id', 'parent_id', 'code', 'name', 'type', 'normal_balance']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%coa}}')->execute(); Console::endProgress(); // entrisheet $rows = (require $sampleDir . '/entri_sheet.php'); $total = count($rows); echo "\ninsert table {{%entri_sheet}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%entri_sheet}}', $this->toAssoc($row, ['id', 'code', 'name', 'd_coa_id', 'k_coa_id']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%entri_sheet}}')->execute(); Console::endProgress(); // payment method $rows = (require $sampleDir . '/payment_method.php'); $total = count($rows); echo "\ninsert table {{%payment_method}}\n"; Console::startProgress(0, $total); foreach ($rows as $i => $row) { $command->insert('{{%payment_method}}', $this->toAssoc($row, ['id', 'branch_id', 'method', 'coa_id', 'potongan', 'coa_id_potongan']))->execute(); Console::updateProgress($i + 1, $total); } $command->resetSequence('{{%payment_method}}')->execute(); Console::endProgress(); }
/** * Renders a set of files given into target directory. * * @param array $files * @param string $targetDir */ public function render($files, $targetDir) { $this->_targetDir = $targetDir; $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[$file] = file_get_contents($file); if (basename($file) == 'README.md') { continue; // to not add index file to nav } } foreach ($fileData as $file => $content) { $output = ApiMarkdown::process($content); // TODO generate links to yiiframework.com by default $output = $this->fixMarkdownLinks($output); if ($this->layout !== false) { $params = ['chapters' => $chapters, 'currentFile' => $file, 'content' => $output]; $output = $this->getView()->renderFile($this->layout, $params, $this); } $fileName = $this->generateGuideFileName($file); file_put_contents($targetDir . '/' . $fileName, $output); if ($this->controller !== null) { Console::updateProgress(++$done, $fileCount); } } if ($this->controller !== null) { Console::updateProgress(++$done, $fileCount); Console::endProgress(true); $this->controller->stdout('done.' . PHP_EOL, Console::FG_GREEN); } }
/** * @inheritdoc */ public function render($context, $targetDir) { $types = array_merge($context->classes, $context->interfaces, $context->traits); $extTypes = []; foreach ($this->extensions as $k => $ext) { $extType = $this->filterTypes($types, $ext); if (empty($extType)) { unset($this->extensions[$k]); continue; } $extTypes[$ext] = $extType; } // render view files parent::render($context, $targetDir); if ($this->controller !== null) { $this->controller->stdout('generating extension index files...'); } foreach ($extTypes as $ext => $extType) { $readme = @file_get_contents("https://raw.github.com/yiisoft/yii2-{$ext}/master/README.md"); $indexFileContent = $this->renderWithLayout($this->indexView, ['docContext' => $context, 'types' => $extType, 'readme' => $readme ?: null]); file_put_contents($targetDir . "/ext-{$ext}-index.html", $indexFileContent); } if ($this->controller !== null) { $this->controller->stdout("done.\n", Console::FG_GREEN); } // create index.html $yiiTypes = $this->filterTypes($types, 'yii'); $indexFileContent = $this->renderWithLayout($this->indexView, ['docContext' => $context, 'types' => $yiiTypes, 'readme' => null]); file_put_contents($targetDir . '/index.html', $indexFileContent); // create file with page titles $titles = []; foreach ($types as $type) { $titles[$this->generateFileName($type->name)] = StringHelper::basename($type->name) . ", {$type->name}"; } file_put_contents($targetDir . '/titles.php', '<?php return ' . VarDumper::export($titles) . ';'); try { if ($this->controller !== null) { Console::startProgress(0, $count = count($types), 'populating elasticsearch index...', false); } // first delete all records for this version $version = $this->version; SearchApiType::setMappings(); SearchApiPrimitive::setMappings(); // ApiPrimitive::deleteAllForVersion($version); SearchApiType::deleteAllForVersion($version); sleep(1); $i = 0; foreach ($types as $type) { SearchApiType::createRecord($type, $version); if ($this->controller !== null) { Console::updateProgress(++$i, $count); } } if ($this->controller !== null) { Console::endProgress(true, true); $this->controller->stdout("done.\n", Console::FG_GREEN); } } catch (\Exception $e) { if (YII_DEBUG && $this->controller !== null) { $this->controller->stdout("!!! FAILED !!! Search will not be available.\n", Console::FG_RED, Console::BOLD); $this->controller->stdout((string) $e . "\n\n"); } else { throw $e; } } // if ($this->controller !== null) { // $this->controller->stdout('done.' . PHP_EOL, Console::FG_GREEN); // $this->controller->stdout('generating search index...'); // } // // $indexer = new ApiIndexer(); // $indexer->indexFiles(FileHelper::findFiles($targetDir, ['only' => ['*.html']]), $targetDir); // $js = $indexer->exportJs(); // file_put_contents($targetDir . '/jssearch.index.js', $js); // // if ($this->controller !== null) { // $this->controller->stdout('done.' . PHP_EOL, Console::FG_GREEN); // } }
public function actionCity() { $this->stdout('Request API: Cities.', Console::FG_GREEN); $data = TravelPayoutsApi::getCities(); $_count = count($data); $this->stdout(' Get: ' . $_count . ' Cities.' . PHP_EOL, Console::FG_GREEN); Console::startProgress(0, $_count); $count = 0; $count_ = 0; foreach ($data as $value) { $value->lon = !empty($value->coordinates->lon) ? (string) $value->coordinates->lon : ''; $value->lat = !empty($value->coordinates->lat) ? (string) $value->coordinates->lat : ''; $name_translations = $value->name_translations; unset($value->name_translations); unset($value->coordinates); $city = City::find()->where(['code' => $value->code])->one(); if (!$city) { $this->stdout($value->code . ' ', Console::FG_YELLOW); $city = new City(); $city->attributes = (array) $value; $local = ['en-GB', 'en-AU', 'en-CA', 'en-NZ', 'en-IE', 'en-SG', 'en-IN']; foreach ($name_translations as $_key => $_name) { if (array_search($_key, $local) === false) { $city['name_' . $_key] = trim($_name); } } if (!$city->save()) { print_r($value); print_r($city->errors); return Controller::EXIT_CODE_ERROR; } $count++; } else { Console::updateProgress(++$count_, $_count); } } Console::endProgress(); $this->stdout(PHP_EOL . 'Added: ' . $count . ' Cities.' . PHP_EOL, Console::FG_BLUE); return Controller::EXIT_CODE_NORMAL; }
public static function onCronRun($event) { $controller = $event->sender; $interval = ""; if (Yii::$app->controller->action->id == 'hourly') { $interval = CronController::EVENT_ON_HOURLY_RUN; } elseif (Yii::$app->controller->action->id == 'daily') { $interval = CronController::EVENT_ON_DAILY_RUN; } else { return; } $users = User::find()->distinct()->joinWith(['httpSessions', 'profile'])->where(['status' => User::STATUS_ENABLED]); $totalUsers = $users->count(); $done = 0; $mailsSent = 0; $defaultLanguage = Yii::$app->language; Console::startProgress($done, $totalUsers, 'Sending update e-mails to users... ', false); foreach ($users->each() as $user) { if ($user->email === "") { continue; } // Check user should receive an email Yii::$app->user->switchIdentity($user); if ($user->language != "") { Yii::$app->language = $user->language; } else { Yii::$app->language = $defaultLanguage; } $notifications = Yii::$app->getModule('notification')->getMailUpdate($user, $interval); $activities = Yii::$app->getModule('activity')->getMailUpdate($user, $interval); if ($notifications != "" || $activities != "") { try { /************************************** * TEBPATCH (ADD) @fcasanellas 14/01/2016 * #MSS001 Afegeix enviament via GCM * NEWCODE ***************************/ $gcm = new GoogleCloudMessage(); $gcm->apiKey = Setting::Get('gcmAPIKey', 'gcm'); $gcm->url = Setting::Get('gcmURL', 'gcm'); $data = array('message' => 'Noves publicacions'); foreach (GcmRelation::findAll(array('user_id' => $user->id)) as $pair) { $result = $gcm->send($data, array($pair->register_key)); } /************************************** * END TEBPATCH **********************/ $mail = Yii::$app->mailer->compose(['html' => '@humhub/modules/content/views/mails/Update'], ['activities' => $activities, 'notifications' => $notifications]); $mail->setFrom([Setting::Get('systemEmailAddress', 'mailing') => Setting::Get('systemEmailName', 'mailing')]); $mail->setTo($user->email); if ($interval == CronController::EVENT_ON_HOURLY_RUN) { $mail->setSubject(Yii::t('base', "Latest news")); } else { $mail->setSubject(Yii::t('base', "Your daily summary")); } $mail->send(); $mailsSent++; } catch (\Swift_SwiftException $ex) { Yii::error('Could not send mail to: ' . $user->email . ' - Error: ' . $ex->getMessage()); } catch (Exception $ex) { Yii::error('Could not send mail to: ' . $user->email . ' - Error: ' . $ex->getMessage()); } } Console::updateProgress(++$done, $totalUsers); } Console::endProgress(true); $controller->stdout('done - ' . $mailsSent . ' email(s) sent.' . PHP_EOL, \yii\helpers\Console::FG_GREEN); }
/** * @param Query $query * @param string[] $divisions * @return array */ private function divisionsWithId(Query $query, $divisions) { $result = []; $this->stdout("translate division to division_id:\n", Console::FG_GREEN); $total = count($divisions); Console::startProgress(0, $total); $n = 0; $time = Query::time(); foreach ($divisions as $division) { $result[$division] = $query->idByDivision($division); $n++; if ($time < Query::time()) { Console::updateProgress($n, $total); $time = Query::time(); } } Console::updateProgress($total, $total); Console::endProgress(); $this->stdout(" completed!\n", Console::FG_GREEN); return $result; }
public function actionIndex() { $auth = Yii::$app->authManager; $total = 13; Console::startProgress(0, $total, 'Doing Updates: ', false); $i = 1; $auth->removeAll(); // add "view" permission $view = $auth->createPermission('view'); $view->description = 'visualiser un enregistrement'; $auth->add($view); Console::updateProgress($i++, $total); // add "create" permission $create = $auth->createPermission('create'); $create->description = 'créer enregistrement'; $auth->add($create); Console::updateProgress($i++, $total); // add "update" permission $update = $auth->createPermission('update'); $update->description = 'update enregistrement'; $auth->add($update); Console::updateProgress($i++, $total); // add an own rule the rule $rule = new OwnRule(); $auth->add($rule); Console::updateProgress($i++, $total); // add the "updateOwn" permission and associate the rule with it. $updateOwn = $auth->createPermission('updateOwn'); $updateOwn->description = 'update own enregistrement'; $updateOwn->ruleName = $rule->name; $auth->add($updateOwn); $auth->addChild($updateOwn, $update); Console::updateProgress($i++, $total); // add "publish" permission $publish = $auth->createPermission('publish'); $publish->description = 'publish enregistrement'; $auth->add($publish); Console::updateProgress($i++, $total); // add "delete" permission $delete = $auth->createPermission('delete'); $delete->description = 'delete enregistrement'; $auth->add($delete); Console::updateProgress($i++, $total); // add the "deleteOwn" permission and associate the rule with it. $deleteOwn = $auth->createPermission('deleteOwn'); $deleteOwn->description = 'delete own enregistrement'; $deleteOwn->ruleName = $rule->name; $auth->add($deleteOwn); $auth->addChild($deleteOwn, $delete); Console::updateProgress($i++, $total); /** * USER */ // add "normal" role and give this role the "create" permission $normal = $auth->createRole('viewer'); $auth->add($normal); $auth->addChild($normal, $view); Console::updateProgress($i++, $total); // add "editor" role and give this role the "create" permission // as well as the permissions of the "normal" role $editor = $auth->createRole('editor'); $auth->add($editor); $auth->addChild($editor, $create); $auth->addChild($editor, $updateOwn); $auth->addChild($editor, $deleteOwn); $auth->addChild($editor, $normal); Console::updateProgress($i++, $total); // add "publisher" role and give this role the "publish" permission // as well as the permissions of the "editor" role $publisher = $auth->createRole('publisher'); $auth->add($publisher); $auth->addChild($publisher, $update); $auth->addChild($publisher, $publish); $auth->addChild($publisher, $editor); Console::updateProgress($i++, $total); // add "admin" role and give this role the "update" permission // as well as the permissions of the "publisher" role $admin = $auth->createRole('admin'); $auth->add($admin); $auth->addChild($admin, $delete); $auth->addChild($admin, $publisher); Console::updateProgress($i++, $total); // Assign roles to users. 10, 14 and 26 are IDs returned by IdentityInterface::getId() // usually implemented in your User model. $auth->assign($normal, 3); $auth->assign($publisher, 2); $auth->assign($admin, 1); Console::updateProgress($i++, $total); Console::endProgress("done." . PHP_EOL); echo $this->ansiFormat('Structure recreated', Console::FG_YELLOW); }
/** * @param $messages * @param $config * @throws InvalidConfigException * @throws \Exception * @throws \yii\db\Exception */ protected function saveToDbOutput($messages, $config) { $db = Yii::$app->get(isset($config['db']) ? $config['db'] : 'db'); $sourceMessageTable = isset($config['sourceMessageTable']) ? $config['sourceMessageTable'] : '{{%source_message}}'; $messageTable = isset($config['messageTable']) ? $config['messageTable'] : '{{%message}}'; if (!$db instanceof \yii\db\Connection) { throw new \Exception('The "db" option must refer to a valid database application component.'); } $db->createCommand()->truncateTable($messageTable)->execute(); $db->createCommand()->delete($sourceMessageTable)->execute(); $insertedSourceMessages = []; foreach ($messages as $language => $categories) { Console::output("Language: {$language}"); foreach ($categories as $category => $msgs) { $messagesCount = count($msgs, COUNT_RECURSIVE); $i = 0; Console::output("Category: {$category}"); Console::startProgress(0, $messagesCount); foreach ($msgs as $m => $translation) { Console::updateProgress(++$i, $messagesCount); $lastId = array_search($m, ArrayHelper::getValue($insertedSourceMessages, $category, [])); if ($lastId == false) { $db->createCommand()->insert($sourceMessageTable, ['category' => $category, 'message' => $m])->execute(); $lastId = $db->getLastInsertID($db->driverName == 'pgsql' ? 'i18n_source_message_id_seq' : null); $insertedSourceMessages[$category][$lastId] = $m; } $db->createCommand()->insert($messageTable, ['id' => $lastId, 'language' => $language, 'translation' => $translation])->execute(); } Console::endProgress(); } } }
/** * 개찰 처리 */ private function suc_s($workload) { $bidkey = BidKey::findOne($workload['bidid']); if ($bidkey === null) { return; } $out[] = "[i2] [{$bidkey->bidid}] %g{$bidkey->notinum}%n {$bidkey->constnm}"; $bidres = BidRes::findOne($bidkey->bidid); if ($bidres === null) { $bidres = new BidRes(['bidid' => $bidkey->bidid]); } $bidres->yega = $workload['yega']; $bidres->innum = $workload['innum']; $bidres->selms = $workload['selms']; $bidres->multispare = $workload['multispare']; $bidres->officenm1 = $workload['officenm1']; $bidres->prenm1 = $workload['prenm1']; $bidres->officeno1 = $workload['officeno1']; $bidres->success1 = $workload['success1']; $bidres->reswdt = date('Y-m-d H:i:s'); $bidres->save(); $out[] = "%y개찰%n"; $this->stdout(Console::renderColoredString(join(' ', $out)) . "\n"); BidSuccom::deleteAll(['bidid' => $bidkey->bidid]); if (is_array($workload['succoms'])) { $total = $bidres->innum; $cur = 1; Console::startProgress(0, $total); foreach ($workload['succoms'] as $r) { $bidsuccom = new BidSuccom(['bidid' => $bidkey->bidid, 'seq' => $r['seq'], 'officeno' => $r['officeno'], 'officenm' => $r['officenm'], 'prenm' => $r['prenm'], 'success' => $r['success'], 'pct' => $r['pct'], 'rank' => $r['rank'], 'selms' => $r['selms'], 'etc' => $r['etc']]); $bidsuccom->save(); Console::updateProgress($cur++, $total); } Console::endProgress(); } if (($bidkey->opt & pow(2, 5)) == 0) { $bidkey->opt += pow(2, 5); } $bidkey->bidproc = 'S'; $bidkey->resdt = date('Y-m-d H:i:s'); $bidkey->editdt = date('Y-m-d H:i:s'); $bidkey->save(); }
protected function populateElasticsearch1x($source, $target) { // search for files to process if (($files = $this->searchFiles($source)) === false) { return false; } // load context from cache $context = $this->loadContext($target); $this->stdout('Checking for updated files... '); foreach ($context->files as $file => $sha) { if (!file_exists($file)) { $this->stdout('At least one file has been removed. Rebuilding the context...'); $context = new Context(); if (($files = $this->searchFiles($source)) === false) { return false; } break; } if (sha1_file($file) === $sha) { unset($files[$file]); } } $this->stdout('done.' . PHP_EOL, Console::FG_GREEN); // process files $fileCount = count($files); $this->stdout($fileCount . ' file' . ($fileCount == 1 ? '' : 's') . ' to update.' . PHP_EOL); Console::startProgress(0, $fileCount, 'Processing files... ', false); $done = 0; foreach ($files as $file) { if (file_exists("{$target}/api/" . basename($file, '.php') . '.html')) { $context->addFile($file); } Console::updateProgress(++$done, $fileCount); } Console::endProgress(true); $this->stdout('done.' . PHP_EOL, Console::FG_GREEN); // save processed data to cache $this->storeContext($context, $target); $this->updateContext($context); $types = array_merge($context->classes, $context->interfaces, $context->traits); try { Console::startProgress(0, $count = count($types), 'populating elasticsearch index...', false); $version = $this->version; // first delete all records for this version SearchApiType::setMappings(); SearchApiPrimitive::setMappings(); // ApiPrimitive::deleteAllForVersion($version); // SearchApiType::deleteAllForVersion($version); sleep(1); $i = 0; foreach ($types as $type) { SearchApiType::createRecord($type, $version); Console::updateProgress(++$i, $count); } Console::endProgress(true, true); $this->stdout("done.\n", Console::FG_GREEN); } catch (\Exception $e) { if (YII_DEBUG) { $this->stdout("!!! FAILED !!! Search will not be available.\n", Console::FG_RED, Console::BOLD); $this->stdout((string) $e . "\n\n"); } else { throw $e; } } $this->writeJsonFiles1x($target, $types); return true; }
public function actionAirportAlias() { $this->stdout('Generate alias: Airport.' . PHP_EOL, Console::FG_GREEN); $language = ReceivedLanguage::find()->indexBy('id')->asArray()->all(); $airport = ReceivedAirport::find()->indexBy('code')->all(); $translations = ReceivedAirportTranslation::find()->asArray()->all(); $translation = []; foreach ($translations as $value) { $alias = $this->translit($value['name']); if ($value['language_id'] == 3 || $value['language_id'] == 9) { $translation[$value['airport_code']][$value['language_id']] = $alias; } else { $translation[$value['airport_code']][$value['language_id']] = preg_replace('~[^a-z0-9_-]~i', '*', $alias); } } $count = count($airport); Console::startProgress(0, $count); $count_ = 0; foreach ($airport as $value) { $value->alias_de = $value->alias; $value->alias_en = $value->alias; $value['alias_zh-CN'] = $value->alias; $value->alias_tr = $value->alias; $value->alias_ru = $value->alias; $value->alias_fr = $value->alias; $value->alias_es = $value->alias; $value->alias_it = $value->alias; $value->alias_th = $value->alias; foreach ($translation[$value->code] as $key => $_value) { if ($_value != '') { switch ($language[$key]['code']) { case 'de': $value->alias_de = $_value; break; case 'en': $value->alias_en = $_value; break; // case 'zh-CN': // $value['alias_zh-CN'] = $_value; // break; // case 'zh-CN': // $value['alias_zh-CN'] = $_value; // break; case 'tr': $value->alias_tr = $_value; break; case 'ru': $value->alias_ru = $_value; break; case 'fr': $value->alias_fr = $_value; break; case 'es': $value->alias_es = $_value; break; case 'it': $value->alias_it = $_value; break; // case 'th': // $value->alias_th = $_value; // break; } } } if (!$value->save()) { print_r($value->attributes); print_r($value->errors); return Controller::EXIT_CODE_ERROR; } Console::updateProgress(++$count_, $count); } Console::endProgress(); return Controller::EXIT_CODE_NORMAL; }