/** * Ethna_Container constructor. * @param $directory (absolute) */ public function __construct(string $base, array $directory, array $class, string $appid, $locale, $sessionName) { $this->base = $base; $this->class = $class; $this->appid = $appid; $this->locale = $locale; $this->sessionName = $sessionName; /** * ディレクトリ設定を絶対パスに変換 */ // ディレクトリ名の設定(相対パス->絶対パス) foreach ($directory as $key => $value) { if ($key == 'plugins') { // Smartyプラグインディレクトリは配列で指定する $tmp = array(); foreach (to_array($value) as $elt) { $tmp[] = $this->base . '/' . $elt; } $directory[$key] = $tmp; } else { $directory[$key] = $this->base . '/' . $value; } } $this->directory = $directory; static::$instance = $this; }
public function getJsParams() { $params = to_array($this->data->getJsParams()); //Всегда в параметрах js будет идентификатор текущей акции, для выполнения действия ajax $params[STOCK_IDENT_PARAM] = $this->stock->getStockIdent(); return $params; }
private static function assertPrepeared($tableExists = null) { PsConnectionPool::assertConnectiedTo(PsConnectionParams::sdkTest()); foreach (to_array($tableExists) as $table) { check_condition(PsTable::exists($table), "Таблица {$table} не существует"); } }
function get_user($where = "") { $koneksi = connection(); $data = mysql_query("select * from userapp {$where};") or die("query error"); destroy_connection($koneksi); return to_array($data); }
/** @return ADORecordSet */ private static function executeQuery($query, $params = false, &$queryFinal = null, array &$paramsFinal = null) { $queryFinal = $query instanceof Query ? $query->build($params) : $query; $queryFinal = normalize_string($queryFinal); $paramsFinal = to_array($params); $LOGGER = PsLogger::inst(__CLASS__); $PROFILER = PsProfiler::inst(__CLASS__); $PROFILER->start(strtolower($queryFinal)); try { if ($LOGGER->isEnabled()) { $LOGGER->info("[{$queryFinal}]" . ($paramsFinal ? ', PARAMS: ' . array_to_string($paramsFinal) : '')); } $rs = PsConnectionPool::conn()->execute($queryFinal, $paramsFinal); if (is_object($rs)) { $PROFILER->stop(); return $rs; } $error = PsConnectionPool::conn()->ErrorMsg(); $LOGGER->info('ERROR: {}', $error); throw new DBException($error, DBException::ERROR_NOT_CLASSIFIED, $queryFinal, $paramsFinal); } catch (Exception $ex) { $PROFILER->stop(false); if ($ex instanceof DBException) { ExceptionHandler::dumpError($ex); } throw $ex; } }
function smarty_block_box($params, $content, Smarty_Internal_Template &$smarty) { if ($content) { $params['class'] = to_array(array_get_value('class', $params)); $params['class'][] = 'psbox'; return PsHtml::div($params, PsHtml::div(array('class' => 'psboxctt'), $content)); } }
/** * Метод возвращает <img /> элемент, готовый для вставки на страницу */ public static function getAvatarImg(PsUser $user = null, $dim = false, array $params = array()) { $params['src'] = self::getAvatarDi($user, $dim); $params['alt'] = $user ? $user->getName() : 'Аноним'; $params['data'] = $user ? array('uid' => $user->getId()) : null; $params['class'] = to_array(array_get_value('class', $params)); $params['class'][] = array('avatar', $user ? 'user' : null); return PsHtml::img($params); }
private function spanImpl($itemName, array $attrs = array(), $class = null) { $attrs['class'] = to_array(array_get_value('class', $attrs)); $attrs['class'][] = $class; $attrs['class'][] = 'sprite'; $attrs['class'][] = 'sprite-' . $this->name; $attrs['class'][] = 'sprite-' . $this->name . '-' . $itemName; return PsHtml::span($attrs); }
public function getSmartyParams4Resources() { $result = array(); /* @var $item ShowcasesControllerItem */ foreach ($this->items as $item) { $result = array_merge($result, to_array($item->getSmartyParams4Resources())); } return $result; }
/** * Sort values of a traversable and return new array with values in sorted order. * * @param callable|int $flags_or_comparator either one of SORT_* constants * or a comparator function * @param array|\Traversable $traversable a traversable to sort * @return array array with sorted values */ function traversable_sort($flags_or_comparator, $traversable) : array { $array = to_array($traversable); if (is_callable($flags_or_comparator)) { usort($array, $flags_or_comparator); } else { sort($array, $flags_or_comparator); } return $array; }
public static function psctrl(array $params) { $id = array_get_value_unset('id', $params); $class = to_array(array_get_value_unset('class', $params)); $class[] = 'pscontrols'; if (!empty($params)) { array_remove_keys($params, array_diff(array_keys($params), PsUtil::getClassConsts(__CLASS__, 'ACTION_'))); } return empty($params) ? '' : PSSmarty::template('common/pscontrols.tpl', array('id' => $id, 'class' => PsHtml::classes2string($class), 'actions' => $params))->fetch(); }
/** * Array. * @param iter $arg * @param bool $deep * @return array */ function to_array($arg, bool $deep = true) : array { $arg = (array) $arg; if ($deep) { foreach ($arg as $key => $value) { $arg[$key] = is_iter($value) ? to_array($value, $deep) : $value; } } return $arg; }
/** * Convert an iterable to array. * @param iter $input * @param bool $deep * @return array */ function to_array($input, bool $deep = true) : array { $input = (array) $input; if ($deep) { foreach ($input as $key => $value) { $input[$key] = is_iter($value) ? to_array($value, $deep) : $value; } } return $input; }
/** * フォーム値の型チェックを行う * * @access public * @param string $name フォームの名前 * @param mixed $var フォームの値 * @param array $params プラグインのパラメータ */ function &validate($name, $var, $params) { $true = true; $type = $params['type']; if ($type == VAR_TYPE_FILE || $this->isEmpty($var, $type)) { return $true; } foreach (array_keys(to_array($var)) as $key) { switch ($type) { case VAR_TYPE_INT: if (!preg_match('/^-?\\d+$/', $var)) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = "{form}には数字(整数)を入力して下さい"; } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_INT); } break; case VAR_TYPE_FLOAT: if (!preg_match('/^-?\\d+$/', $var) && !preg_match('/^-?\\d+\\.\\d+$/', $var)) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = "{form}には数字(小数)を入力して下さい"; } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_FLOAT); } break; case VAR_TYPE_BOOLEAN: if ($var != "1" && $var != "0") { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = "{form}には1または0のみ入力できます"; } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_BOOLEAN); } break; case VAR_TYPE_DATETIME: $r = strtotime($var); if ($r == -1 || $r === false) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = "{form}には日付を入力して下さい"; } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_DATETIME); } break; } } return $true; }
function to_array(&$obj) { if ($obj instanceof data) { $obj = $obj->to_array(); } if (is_array($obj)) { foreach ($obj as &$el) { to_array($el); } } }
public static function submit($buttons, $canReset) { $submits = ''; foreach (to_array($buttons) as $button) { $submits .= PsHtml::input('submit', '', $button, array('class' => 'button')); } if ($canReset) { $submits .= PsHtml::input('reset', '', 'Очистить', array('class' => 'button')); } return self::field(null, $submits); }
/** * フォーム値の型チェックを行う * * @access public * @param string $name フォームの名前 * @param mixed $var フォームの値 * @param array $params プラグインのパラメータ */ public function validate($name, $var, $params) { $true = true; $type = $params['type']; if ($type == VAR_TYPE_FILE || $this->isEmpty($var, $type)) { return $true; } foreach (array_keys(to_array($var)) as $key) { switch ($type) { case VAR_TYPE_INT: if (!preg_match('/^-?\\d+$/', $var)) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = _et('Please input integer value to {form}.'); } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_INT); } break; case VAR_TYPE_FLOAT: if (!preg_match('/^-?\\d+$/', $var) && !preg_match('/^-?\\d+\\.\\d+$/', $var)) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = _et('Please input float value to {form}.'); } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_FLOAT); } break; case VAR_TYPE_BOOLEAN: if ($var != "1" && $var != "0") { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = _et('You can input 0 or 1 to {form}.'); } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_BOOLEAN); } break; case VAR_TYPE_DATETIME: $r = strtotime($var); if ($r == -1 || $r === false) { if (isset($params['error'])) { $msg = $params['error']; } else { $msg = _et('Please input valid datetime to {form}.'); } return Ethna::raiseNotice($msg, E_FORM_WRONGTYPE_DATETIME); } break; } } return $true; }
/** * Проверяет, является ли переданная страница - текущей * * @param type $page */ public static function isCurPage($page) { $curPage = self::loadCurPage(false); if (!$curPage instanceof WebPage) { //Текущей вообще нет return false; } foreach (to_array($page) as $page) { if ($curPage->isIt($page)) { return true; } } return false; }
/** * Основная функция, выполняющая всю работу. * Она следит за тем, что страница была корректно построена и в ответ вурнулся PageParams. * * @return PageParams */ public final function buildPage(PageContext $ctxt, PageBuilderContext $builderCtxt, RequestArrayAdapter $requestParams, ArrayAdapter $buildParams) { $this->profilerStart(__FUNCTION__); try { $smartyParams = to_array($this->doBuild($ctxt, $builderCtxt, $requestParams, $buildParams)); $pageParams = $this->foldedEntity->fetchTpl($smartyParams, FoldedResources::FETCH_RETURN_FULL_OB, true); check_condition($pageParams instanceof PageParams, 'После фетчинга шаблона должен быть возвращен объект PageParams'); $this->profilerStop(); return $pageParams; } catch (Exception $ex) { $this->profilerStop(false); throw $ex; } }
public function getParentBlock($blockNames, $__FUNCTION__, $mandatory) { $blockNames = to_array($blockNames); foreach ($blockNames as $name) { if ($this->hasContext($name)) { return $name; } } if ($mandatory) { $text = "Function {$__FUNCTION__} must have one of this parents: " . implode(',', $blockNames); $this->LOGGER->info($text); check_condition(false, $text); } return null; }
/** * Основной метод, который строит содержимое диалогового окна. */ public final function getWindowContent() { //Логгер $LOGGER = $this->LOGGER(); $CACHE = $this->cacheGroup(); $CACHE = $CACHE instanceof PSCacheInst ? $CACHE : null; $CACHE_KEY = $this->foldedEntity->getUnique('DIALOG_WINDOW_CONTENT'); /* * Проверим, можно ли работать с кешем и есть ли закешированная версия */ $LOGGER->info("Loading dialog content."); if ($CACHE) { $LOGGER->info("Can use cache, key: {$CACHE_KEY}."); $CONTENT = $CACHE->getFromCache($CACHE_KEY); if ($CONTENT) { $LOGGER->info("Found in cache."); return $CONTENT; } else { $LOGGER->info("Not found in cache."); } } else { $LOGGER->info("Cannot use cache."); } $this->profilerStart(__FUNCTION__); try { //Получим параметры для шаблона smarty $smartyParams = to_array($this->getWindowTplSmartyParams()); //Отлогируем параметры if ($LOGGER->isEnabled()) { $LOGGER->info("Tpl smarty params: {}", array_to_string($smartyParams, true)); } //Произведём фетчинг шаблона $CONTENT = $this->foldedEntity->fetchTpl($smartyParams); //Останавливаем профилирование $this->profilerStop(); //Сохраним в кеш if ($CACHE && $CONTENT) { $CACHE->saveToCache($CONTENT, $CACHE_KEY); $LOGGER->info("Data saved to cache."); } //Вернём результат return $CONTENT; } catch (Exception $ex) { $this->profilerStop(false); throw $ex; } }
function insert_function_analytics($server_cfg, $game_cfg, $time_slots = '*') { $root_upload_directory = sprintf($server_cfg["root_upload_directory"], $game_cfg["name"]); $function_markers = glob("{$root_upload_directory}/{$time_slots}/" . $server_cfg['profile_upload_directory'] . "/.functions", GLOB_BRACE); if (empty($function_markers)) { $game_cfg['logger']->log("insert_function_analytics", "function_analytics for {$time_slots}" . " are not enabled", Logger::INFO); error_log("function_analytics for {$time_slots} are not enabled\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); return; } foreach ($function_markers as $marker) { $profile_upload_directory = dirname($marker); $timestamp = (int) (basename(dirname($profile_upload_directory)) * 1800); $profile_blob_directory = $profile_upload_directory . "/" . $server_cfg['blob_dir']; $top_functions_analytics_file = $profile_blob_directory . "/" . $server_cfg['profile_blob_filename']; //Check for validity of the file/path if (!file_exists($top_functions_analytics_file)) { $game_cfg['logger']->log("insert_function_analytics", "{$top_functions_analytics_file} doesn't exist", Logger::ERR); error_log("{$top_functions_analytics_file} doesn't exist\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); continue; } //Get the multi-D array of analytics $analytics_array = to_array($top_functions_analytics_file); if ($analytics_array == null) { $game_cfg['logger']->log("insert_function_analytics", "Invalid xhprof_extract file at {$top_functions_analytics_file}", Logger::ERR); error_log("Invalid xhprof_extract file at {$top_functions_analytics_file}\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); continue; } //Remove duplicates remove_duplicates_from_top_functions_and_insert_analytics($analytics_array, $server_cfg, $game_cfg, $timestamp); error_log("Deleting {$marker}... " . (unlink($marker) ? "OK" : "FAILED") . "\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); } $queries = array("call pivot_tracked_functions('incl_time')", "call rank_top5_functions('excl_time')"); //"call rank_top5_functions('incl_time')"); try { $query_res = execute_queries($server_cfg, $game_cfg, $queries); if ($query_res == 0) { $game_cfg['logger']->log("insert_function_analytics", "Call to pivot functions and rank functions are successful", Logger::INFO); } else { $game_cfg['logger']->log("insert_function_analytics", "Call to pivot functions and rank functions are unsuccessful", Logger::ERR); } } catch (Exception $ex) { //TODO: // syslog it. For now echo-ing it error_log("Stack Trace: " . print_r($ex->getTrace() . TRUE), "\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); $game_cfg['logger']->log("insert_function_analytics", "Error in inserting function analytics for " . $game_cfg['name'], Logger::ERR); } }
public function appendMlComment($comments) { $comments = to_array($comments); if (empty($comments)) { return; //--- } $this->di->writeLineToFile(); $this->di->writeLineToFile('/*'); foreach ($comments as $comment) { $comment = trim($comment); if ($comment) { $this->di->writeLineToFile(" * {$comment}"); } } $this->di->writeLineToFile(' */'); }
/** * easy getopt :) * * @param array $lopts long options * @return array list($opts, $args) * @access protected */ function &_getopt($lopts = array()) { // create opts // ex: $lopts = array('foo', 'bar='); $lopts = to_array($lopts); $sopts = ''; $opt_def = array(); foreach ($lopts as $lopt) { if ($lopt[strlen($lopt) - 2] === '=') { $opt_def[$lopt[0]] = substr($lopt, 0, strlen($lopt) - 2); $sopts .= $lopt[0] . '::'; } else { if ($lopt[strlen($lopt) - 1] === '=') { $opt_def[$lopt[0]] = substr($lopt, 0, strlen($lopt) - 1); $sopts .= $lopt[0] . ':'; } else { $opt_def[$lopt[0]] = $lopt; $sopts .= $lopt[0]; } } } // do getopt // ex: $sopts = 'fb:'; $opt = new Ethna_Getopt(); $opts_args = $opt->getopt($this->arg_list, $sopts, $lopts); if (Ethna::isError($opts_args)) { return $opts_args; } // parse opts // ex: "-ff --bar=baz" gets // $opts = array('foo' => array(true, true), // 'bar' => array('baz')); $opts = array(); foreach ($opts_args[0] as $opt) { $opt[0] = $opt[0][0] === '-' ? $opt_def[$opt[0][2]] : $opt_def[$opt[0][0]]; $opt[1] = $opt[1] === null ? true : $opt[1]; if (isset($opts[$opt[0]]) === false) { $opts[$opt[0]] = array($opt[1]); } else { $opts[$opt[0]][] = $opt[1]; } } $opts_args[0] = $opts; return $opts_args; }
function smarty_block_ol($params, $content, Smarty_Internal_Template &$smarty) { if (isEmpty($content)) { return; //--- } $params['class'] = to_array(array_get_value('class', $params)); $params['class'][] = 'block_ol'; $strings = explode("\n", trim($content)); $lis = array(); foreach ($strings as $string) { if (!isEmpty($string)) { $lis[] = '<li>' . trim($string) . '</li>'; } } $content = join('', $lis); return PsHtml::html2('ol', $params, $content); }
/** * Returns the json encoded version of the passed data. * * @param mixed $data * @param array $options * * @author Jack P. * @copyright Copyright (c) Jack P. * @package Traq * @subpackage Helpers */ function to_json($data, $options = array()) { // Merge options with defaults $defaults = array('hide' => array('password', 'login_hash', 'api_key', 'private_key')); $options = array_merge($defaults, $options); // Convert the data to an array, if possible.. if (!is_array($data)) { $data = to_array($data); } foreach ($data as $k => $v) { $data[$k] = to_array($v); } // Remove the parts we don't want... if (isset($options['hide']) and is_array($data)) { $data = array_remove_keys($data, $options['hide']); } return json_encode($data); }
/** * xml转数组 * @param $xml * @return array */ public static function xml_to_array($xml) { $res = array(); foreach ($xml as $key => $value) { if (count($value) >= 1) { isset($keys[$key]) ? $keys[$key] += 1 : ($keys[$key] = 1); if ($keys[$key] == 1) { $res[$key] = to_array($value); } elseif ($keys[$key] == 2) { $res[$key] = array($res[$key], to_array($value)); } else { $res[$key][] = to_array($value); } } else { $res[$key] = (string) $value; } } return $res; }
/** * Метод получает фактический контект для всплывающей страницы. * Сама страница может вернуть или IdentPageFilling, и тогда содержимое * будет обработано за неё. Или непосредственно IdentPageContent, * если ей самой нужно обработать содержимое (например - акции). * * @return IdentPageContent */ public final function getContent(ArrayAdapter $params) { $this->checkAccess(); $this->profilerStart(__FUNCTION__); $fillingOrContent = $this->processRequest($params); /** @var IdentPageContent */ $content = null; if (is_object($fillingOrContent)) { if ($fillingOrContent instanceof IdentPageFilling) { $div = $this->getFoldedEntity()->fetchTpl(to_array($fillingOrContent->getSmartyParams())); $content = new IdentPageContent($div, $fillingOrContent->getJsParams()); } if ($fillingOrContent instanceof IdentPageContent) { $content = $fillingOrContent; } } $this->profilerStop(); check_condition(is_object($content) && $content instanceof IdentPageContent, "Страница [{$this}] обработана некорректно"); return $content; }
/** * Основной метод, выполняющий выполнение Ajax действия. * * @return AjaxSuccess */ public final function execute() { $id = get_called_class(); check_condition(!$this->processed, "Действие [{$id}] уже выполнено."); $this->processed = true; //Не будем портить глобальный массив $_REQUEST, создав копию адаптера $params = RequestArrayAdapter::inst()->copy(); check_condition($params->str(AJAX_ACTION_PARAM) == $id, "Действие [{$id}] не может быть выполнено."); $params->remove(AJAX_ACTION_PARAM); $params->remove(AJAX_ACTION_GROUP_PARAM); //Проверка доступа AuthManager::checkAccess($this->getAuthType()); //Если пользователь зарегистрирован, как администратор - подключим ресурсы админа //ps_admin_on(); //Проверка обязательных параметров foreach (to_array($this->getRequiredParamKeys()) as $key) { if (!$params->has($key)) { return "Не передан обязательный параметр [{$key}]."; } } //Проверка активности if ($this->isCheckActivity() && !ActivityWatcher::isCanMakeAction()) { return 'Таймаут не закончился.'; } //Вызываем обработку данных PsProfiler::inst('AjaxProfiler')->start($id); $result = $this->executeImpl($params); PsProfiler::inst('AjaxProfiler')->stop(); if (isEmpty($result)) { return "Действие [{$id}] выполнено некорректно - возвращён пустой результат."; } if (is_object($result) && $result instanceof AjaxSuccess) { //SUCCESS //Зарегистрируем активноcть пользователя (только в случае успеха, так как пользователь мог просто ошибиться в воде данных) if ($this->isCheckActivity()) { ActivityWatcher::registerActivity(); } } return $result; }
public function index($folders = [], $style = '', $url = '', $tips = '') { $files = array(); $folders = to_array($folders); foreach ($folders as $v) { $_folder = APPPATH . $v; if (!is_dir($_folder)) { continue; } $_f = file_list($_folder, array(APPPATH . 'static' . DIRECTORY_SEPARATOR . '*')); foreach ($_f as $_v) { $files[] = str_replace(APPPATH, '', $_v); } } $styles = ['ball-pulse' => 3, 'ball-grid-pulse' => 9, 'ball-clip-rotate' => 1, 'ball-clip-rotate-pulse' => 2, 'square-spin' => 1, 'ball-clip-rotate-multiple' => 2, 'ball-pulse-rise' => 5, 'ball-rotate' => 1, 'cube-transition' => 2, 'ball-zig-zag' => 2, 'ball-zig-zag-deflect' => 2, 'ball-triangle-path' => 3, 'ball-scale' => 1, 'line-scale' => 5, 'line-scale-party' => 4, 'ball-scale-multiple' => 3, 'ball-pulse-sync' => 3, 'ball-beat' => 3, 'line-scale-pulse-out' => 5, 'line-scale-pulse-out-rapid' => 5, 'ball-scale-ripple' => 1, 'ball-scale-ripple-multiple' => 3, 'ball-spin-fade-loader' => 8, 'line-spin-fade-loader' => 8, 'triangle-skew-spin' => 1, 'pacman' => 5, 'semi-circle-spin' => 1, 'ball-grid-beat' => 9, 'ball-scale-random' => 3]; !array_key_exists($style, $styles) && ($style = 'square-spin'); $this->_files = $files; $this->_style = $style; $this->_loading_divs = $styles[$style] ?: 1; $this->_url = url($url); $this->_tips = $tips; return $this->view('tools::system.loading'); }