public static function onAny(callable $listener) { Event::on('core.error', $listener); }
// Configure a plugin App::router()->any('plugin-settings', 'plugins/{plugin}/settings', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.settings')); // Search for a plugin on the remote platform App::router()->get('search-plugins', 'plugins/search', array('action' => 'PluginController.search')); // Download and install a remote plugin App::router()->get('download-plugin', 'plugins/{plugin}/download', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.download')); // Definitively remove a plugin App::router()->get('delete-plugin', 'plugins/{plugin}/remove', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.delete')); // Create a new plugin structure App::router()->any('create-plugin', 'plugins/_new', array('action' => 'PluginController.create')); // Update a plugin App::router()->get('update-plugin', 'plugins/{plugin}/update', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.update')); // Display number of updates in menu if (App::session()->isAllowed('admin.all')) { Event::on(\Hawk\Plugins\Main\MainController::EVENT_AFTER_GET_MENUS, function (Event $event) { SearchUpdatesWidget::getInstance()->display(); }); } }); /** * Manage the languages and languages keys */ App::router()->auth(App::session()->isAllowed('admin.languages'), function () { // list all the supported languages App::router()->any('manage-languages', 'languages/', array('action' => 'LanguageController.index')); App::router()->get('language-keys-list', 'languages/keys', array('action' => 'LanguageController.listKeys')); // Save the translations App::router()->post('save-language-keys', 'languages/keys/save', array('action' => 'LanguageController.editKeys')); // Edit a language App::router()->any('edit-language', 'languages/{tag}', array('where' => array('tag' => '[a-z]{2}|new'), 'action' => 'LanguageController.editLanguage')); // Delete a language
* @param string $plugin The plugin name * @param string $language The language tag * @param array $data The translations to save */ public static function saveUserTranslations($plugin, $language, $data) { $lang = new self($plugin, $language); $file = $lang->getTranslatedFile(); $lines = array(); foreach ($data as $key => $value) { if (!is_array($value)) { $lines[] = $key . ' = "' . addcslashes($value, '"') . '"'; } else { foreach ($value as $multiplier => $val) { $lines[] = $key . '[' . $multiplier . '] = "' . addcslashes($val, '"') . '"'; } } } $content = implode(PHP_EOL, $lines); $dir = dirname($file); if (!is_dir($dir)) { mkdir($dir, 0755, true); } file_put_contents($file, $content); touch($file, time() + 3); } } /*** Save the language cache ***/ Event::on('process-end', function (Event $event) { Lang::saveOriginCache(); });
foreach ($plugins as $plugin) { if (is_file($plugin->getStartFile())) { include $plugin->getStartFile(); } } /*** Initialize the theme ***/ if (is_file(Theme::getSelected()->getStartFile())) { include Theme::getSelected()->getStartFile(); } (new Event('before-routing'))->trigger(); /*** Execute action just after routing ***/ Event::on('after-routing', function ($event) { $route = $event->getData('route'); if (!App::conf()->has('db') && App::request()->getUri() == App::router()->getUri('index')) { // The application is not installed yet App::logger()->notice('Hawk is not installed yet, redirect to install process page'); App::response()->redirectToAction('install'); return; } }); /*** Compute the routage ***/ App::router()->route(); } catch (HTTPException $err) { App::response()->setStatus($err->getStatusCode()); $response = array('message' => $err->getMessage(), 'details' => $err->getDetails()); if (App::request()->getWantedType() === 'json') { App::response()->setContentType('json'); App::response()->setBody($response); } else { App::response()->setBody($response['message']); }
/** * use coupon before create order * @author cangzhou.wu(wucangzhou@gmail.com) * @param $event */ public function useCoupon($event) { /** @var $order Order */ $order = $event->sender; /** @var $couponModel Coupon */ $couponModel = Coupon::findOne(Yii::$app->getSession()->get(self::SESSION_COUPON_MODEL_KEY)); if ($couponModel) { $couponRuleModel = $couponModel->couponRule; $result = Json::decode($couponRuleModel->result); if ($result['type']) { $order->total_price = $order->total_price * $result['number']; } else { $order->total_price = $order->total_price - $result['number']; } switch ($result['shipping']) { case 1: $order->shipping_fee = $order->shipping_fee - $result['shippingFee']; break; case 2: $order->shipping_fee = 0; } Event::on(Order::className(), Order::EVENT_AFTER_INSERT, [ShoppingCoupon::className(), 'updateCouponStatus'], ['couponModel' => $couponModel]); } }
/** * View, create, or update a tree node via ajax * * @return string json encoded response */ public function actionManage() { Yii::$app->response->format = Response::FORMAT_JSON; static::checkValidRequest(); $parentKey = $action = null; $modelClass = 'Category'; $isAdmin = $softDelete = $showFormButtons = $showIDAttribute = false; $currUrl = $nodeView = $formOptions = $formAction = ''; $iconsList = $nodeAddlViews = []; extract(static::getPostData()); if (!isset($id) || empty($id)) { $node = new $modelClass(); $node->initDefaults(); } else { $node = $modelClass::findOne($id); } $module = TreeView::module(); $params = $module->treeStructure + $module->dataStructure + ['node' => $node, 'parentKey' => $parentKey, 'action' => $formAction, 'formOptions' => empty($formOptions) ? [] : Json::decode($formOptions), 'modelClass' => $modelClass, 'currUrl' => $currUrl, 'isAdmin' => $isAdmin, 'iconsList' => $iconsList, 'softDelete' => $softDelete, 'showFormButtons' => $showFormButtons, 'showIDAttribute' => $showIDAttribute, 'nodeView' => $nodeView, 'nodeAddlViews' => $nodeAddlViews]; if (!empty($module->unsetAjaxBundles)) { Event::on(View::className(), View::EVENT_AFTER_RENDER, function ($e) use($module) { foreach ($module->unsetAjaxBundles as $bundle) { unset($e->sender->assetBundles[$bundle]); } }); } $callback = function () use($nodeView, $params) { return $this->renderAjax($nodeView, ['params' => $params]); }; return self::process($callback, Yii::t('kvtree', 'Error while viewing the node. Please try again later.'), null); }
public static function errors() { return static::$errors; } } Event::on('core.check.init', function () { Check::method(['required' => function ($value) { return is_numeric($value) && $value == 0 || empty($value) ? 'This value cant\' be empty.' : true; }, 'alphanumeric' => function ($value) { return preg_match('/^\\w+$/', $value) ? true : 'Value must be alphanumeric.'; }, 'numeric' => function ($value) { return preg_match('/^\\d+$/', $value) ? true : 'Value must be numeric.'; }, 'email' => function ($value) { return filter_var($value, FILTER_VALIDATE_EMAIL) ? true : 'This is not a valid email.'; }, 'url' => function ($value) { return filter_var($value, FILTER_VALIDATE_URL) ? true : 'This is not a valid URL.'; }, 'max' => function ($value, $max) { return $value <= $max ? true : 'Value must be less than ' . $max . '.'; }, 'min' => function ($value, $min) { return $value >= $min ? true : 'Value must be greater than ' . $min . '.'; }, 'range' => function ($value, $min, $max) { return $value >= $min && $value <= $max ? true : "This value must be in [{$min},{$max}] range."; }, 'words' => function ($value, $max) { return str_word_count($value) <= $max ? true : 'Too many words, max count is ' . $max . '.'; }, 'length' => function ($value, $max) { return strlen($value) <= $max ? true : 'Too many characters, max count is ' . $max . '.'; }, 'same_as' => function ($value, $fieldname) { $x = isset(Check::$data[$fieldname]) ? Check::$data[$fieldname] : ''; return $value == $x ? true : 'Field must be equal to ' . $fieldname . '.'; }]); });
<?php namespace Hawk\Plugins\LangSwitcher; Event::on(\Hawk\Plugins\Main\MainController::EVENT_AFTER_GET_MENUS, function (Event $event) { $languages = Language::getAllActive(); if (count($languages) > 0) { $menus = $event->getData('menus'); $menu = new MenuItem(array('id' => uniqid(), 'plugin' => 'lang-switcher', 'name' => 'selector', 'label' => strtoupper(LANGUAGE))); foreach ($languages as $language) { $menu->visibleItems[] = new MenuItem(array('id' => uniqid(), 'plugin' => 'lang-switcher', 'name' => $language->tag, 'label' => Icon::make(array('size' => 'fw', 'icon' => $language->tag == LANGUAGE ? 'check' : '')) . strtoupper($language->tag), 'action' => 'javascript: $.cookie("language", "' . $language->tag . '", {path : "/"}); location = app.getUri("index");')); } $menus['settings'][] = $menu; $event->setData('menus', $menus); } });
/** * Return the URL of a public CSS file, * or the URL of the directory containing public CSS files if $basename is empty * * @param string $basename The Less file basename * * @return string The URL */ public function getCssUrl($basename = "") { $cssUrl = $this->getStaticUrl() . 'css/'; if (empty($basename)) { return $cssUrl; } else { $privateFilename = $this->getLessDir() . $basename; $cssBasename = preg_replace('/\\.less$/', '.css', $basename); $publicFilename = $this->getPublicCssDir() . $cssBasename; if (is_file($privateFilename)) { Event::on('built-less', function (Event $event) use($privateFilename) { if ($event->getData('source') === $privateFilename) { // Copy all static files except less and JS foreach (glob($this->getStaticDir() . '*') as $elt) { if (!in_array(basename($elt), array('less', 'js'))) { App::fs()->copy($elt, $this->getPublicStaticDir()); } } } }); Less::compile($privateFilename, $publicFilename); } return $cssUrl . $cssBasename . '?' . filemtime($publicFilename); } }
/** * Defer callback execution after script execution * @param callable $callback The deferred callback */ public static function after(callable $callback) { static::$inited_shutdown || static::install_shutdown(); Event::on('core.shutdown', $callback); }
/** * Compute an action on a plugin (install, uninstal, activate, deactivate) * * @param string $action The action to perform : 'install', 'uninstall', 'activate', 'deactivate' */ private function computeAction($action) { App::response()->setContentType('json'); $response = array(); Event::on('menuitem.added menuitem.deleted', function () use(&$response) { $response['menuUpdated'] = true; }); try { Plugin::get($this->plugin)->{$action}(); } catch (\Exception $e) { $errorMessage = Lang::get($this->_plugin . '.plugin-' . $action . '-error', array('plugin' => $this->plugin)); if (DEBUG_MODE) { $errorMessage .= preg_replace('/\\s/', ' ', $e->getMessage()); } throw new InternalErrorException($errorMessage); } return $response; }
self::$cacheUpdated = true; return true; } } if (strpos($namespace, 'Hawk\\Plugins\\') === 0) { // If the class is an hawk class called from a plugin , // create an alias from the Hawk class to the plugin namespace $alias = '\\Hawk\\' . $class; if (class_exists($alias) || trait_exists($alias)) { class_alias($alias, $classname); return true; } } } /** * Save the autoload cache at the end of a script processing. It is not registered any times it is updated, * to improve the performances of the application. */ public static function saveCache() { if (self::$cacheUpdated) { Cache::getInstance()->save(self::CACHE_FILE, '<?php return ' . var_export(self::$cache, true) . ';'); } } } // register autoload function spl_autoload_register('\\Hawk\\Autoload::load', true, false); // Save the autoload cache Event::on('process-end', function (Event $event) { Autoload::saveCache(); });
<?php Event::on(404, function () { Response::html(View::from('special/error', ['code' => 404, 'message' => 'Page not found'])); }); Route::on('/', function () { return View::from('index'); });
?> </table> <strong>Important: </strong>Pour profiter du gestionnaire d'événements de yana <code>coté serveur</code>, vous devez ajouter une tâche planifiée sur le raspberry PI, pour cela tapez : <code>sudo crontab -e</code> puis ajoutez la ligne <?php $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; $url = $protocol . str_replace('//', '/', 'localhost/' . str_replace('index.php', '', $_SERVER['PHP_SELF']) . '/action.php?action=GET_EVENT&checker=server'); echo '<code>*/1 * * * * wget ' . $url . ' -O /dev/null 2>&1</code>'; ?> puis sauvegardez (<code>ctrl</code>+<code>x</code> puis <code>O</code> puis <code>Entrée</code>) <br/><br/> <br/><br/> </div> <?php } } Plugin::addJs('/js/main.js'); Plugin::addHook("action_post_case", "eventmanager_action"); Plugin::addHook("menubar_pre_home", "eventmanager_plugin_menu"); Plugin::addHook("home", "eventmanager_plugin_page"); //Exemple vide d'interception d'évenement sur un plugin tiers (plugin radiorelay, changement d'etat) Event::on('relay_change_state', function ($data, $state) { // $data = classe RadioRelay correspondante à la machine // $state = etat de la machine });
/** * Add static content at the end of the DOM * * @param string $content The content to add */ private final function addContentAtEnd($content) { $method = $this->executingMethod; Event::on($this->_plugin . '.' . $this->getClassname() . '.' . $method . '.' . self::AFTER_ACTION, function ($event) use($content) { if (App::response()->getContentType() === 'html') { $dom = $event->getData('result'); if ($dom->find('body')->length) { $dom->find('body')->append($content); } else { $dom->find("*:first")->parent()->children()->slice(-1)->after($content); } } }); }