예제 #1
2
파일: Helper.php 프로젝트: chinazan/zzcrm
 /**
  * Get link definition defined in 'fields' metadata. In linkDefs can be used as value (e.g. "type": "hasChildren") and/or variables (e.g. "entityName":"{entity}"). Variables should be defined into fieldDefs (in 'entityDefs' metadata).
  *
  * @param  string $entityName
  * @param  array  $fieldDef
  * @param  array  $linkFieldDefsByType
  * @return array | null
  */
 public function getLinkDefsInFieldMeta($entityName, $fieldDef, array $linkFieldDefsByType = null)
 {
     if (!isset($fieldDefsByType)) {
         $fieldDefsByType = $this->getFieldDefsByType($fieldDef);
         if (!isset($fieldDefsByType['linkDefs'])) {
             return null;
         }
         $linkFieldDefsByType = $fieldDefsByType['linkDefs'];
     }
     foreach ($linkFieldDefsByType as $paramName => &$paramValue) {
         if (preg_match('/{(.*?)}/', $paramValue, $matches)) {
             if (in_array($matches[1], array_keys($fieldDef))) {
                 $value = $fieldDef[$matches[1]];
             } else {
                 if (strtolower($matches[1]) == 'entity') {
                     $value = $entityName;
                 }
             }
             if (isset($value)) {
                 $paramValue = str_replace('{' . $matches[1] . '}', $value, $paramValue);
             }
         }
     }
     return $linkFieldDefsByType;
 }
예제 #2
2
 /**
  *
  * @param array $current_import
  * @return bool
  */
 function import(array $current_import)
 {
     // fetch the remote content
     $html = wp_remote_get($current_import['file']);
     // Something failed
     if (is_wp_error($html)) {
         $redirect_url = get_admin_url(get_current_blog_id(), '/tools.php?page=pb_import');
         error_log('\\PressBooks\\Import\\Html import error, wp_remote_get() ' . $html->get_error_message());
         $_SESSION['pb_errors'][] = $html->get_error_message();
         $this->revokeCurrentImport();
         \Pressbooks\Redirect\location($redirect_url);
     }
     $url = parse_url($current_import['file']);
     // get parent directory (with forward slash e.g. /parent)
     $path = dirname($url['path']);
     $domain = $url['scheme'] . '://' . $url['host'] . $path;
     // get id (there will be only one)
     $id = array_keys($current_import['chapters']);
     // front-matter, chapter, or back-matter
     $post_type = $this->determinePostType($id[0]);
     $chapter_parent = $this->getChapterParent();
     $body = $this->kneadandInsert($html['body'], $post_type, $chapter_parent, $domain);
     // Done
     return $this->revokeCurrentImport();
 }
예제 #3
2
 public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result)
 {
     $m = $this->getConfig('methods');
     if (@count($m) == 1) {
         $a = new Am_Paysystem_Action_Form(self::URL . $m[0] . '/event/');
     } else {
         $a = new Am_Paysystem_Action_HtmlTemplate_Micropayment($this->getDir(), 'micropayment-confirm.phtml');
         $methods = array();
         if (@count($m)) {
             $a->url = self::URL . $m[0] . '/event/';
             foreach ($m as $title) {
                 $methods[self::URL . $title . '/event/'] = $this->getConfig($title . '.title');
             }
         } else {
             foreach ($this->getConfig() as $k => $v) {
                 if (is_array($v) && !empty($v['title'])) {
                     $methods[self::URL . $k . '/event/'] = $v['title'];
                 }
             }
             $a->url = array_shift(array_keys($methods));
         }
         $a->methods = $methods;
     }
     $a->project = $this->getConfig('project');
     $a->amount = $invoice->first_total * 100;
     $a->freepaymentid = $invoice->public_id;
     $a->seal = md5("project={$a->project}&amount={$a->amount}&freepaymentid={$a->freepaymentid}" . $this->getConfig('key'));
     $result->setAction($a);
 }
예제 #4
2
 public function getAllClassNames()
 {
     if (null === $this->classCache) {
         $this->initialize();
     }
     $classes = array();
     if ($this->paths) {
         foreach ((array) $this->paths as $path) {
             if (!is_dir($path)) {
                 throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
             }
             $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY);
             foreach ($iterator as $file) {
                 $fileName = $file->getBasename($this->fileExtension);
                 if ($fileName == $file->getBasename() || $fileName == $this->globalBasename) {
                     continue;
                 }
                 // NOTE: All files found here means classes are not transient!
                 if (isset($this->prefixes[$path])) {
                     $classes[] = $this->prefixes[$path] . '\\' . str_replace('.', '\\', $fileName);
                 } else {
                     $classes[] = str_replace('.', '\\', $fileName);
                 }
             }
         }
     }
     return array_merge($classes, array_keys($this->classCache));
 }
 /**
  * s2Member's PayPal Auto-Return/PDT handler (inner processing routine).
  *
  * @package s2Member\PayPal
  * @since 110720
  *
  * @param array $vars Required. An array of defined variables passed by {@link s2Member\PayPal\c_ws_plugin__s2member_paypal_return_in::paypal_return()}.
  * @return array|bool The original ``$paypal`` array passed in (extracted) from ``$vars``, or false when conditions do NOT apply.
  */
 public static function cp($vars = array())
 {
     extract($vars);
     foreach (array_keys(get_defined_vars()) as $__v) {
         $__refs[$__v] =& ${$__v};
     }
     do_action("ws_plugin__s2member_during_paypal_return_before_no_return_data", get_defined_vars());
     unset($__refs, $__v);
     $paypal["s2member_log"][] = "No Return-Data. Customer MUST wait for Email Confirmation.";
     $paypal["s2member_log"][] = "Note. This can sometimes happen when/if you are offering an Initial/Trial Period. There are times when a Payment Gateway will NOT supply s2Member with any data immediately after checkout. When/if this happens, s2Member must process the transaction via IPN only (i.e. behind-the-scene), and the Customer must wait for Email Confirmation in these cases.";
     $paypal["s2member_log"][] = var_export($_REQUEST, true);
     foreach (array_keys(get_defined_vars()) as $__v) {
         $__refs[$__v] =& ${$__v};
     }
     do_action("ws_plugin__s2member_during_paypal_return_during_no_return_data", get_defined_vars());
     unset($__refs, $__v);
     if ($custom_success_redirection) {
         $paypal["s2member_log"][] = "Redirecting Customer to a custom URL: " . $custom_success_redirection . ".";
         wp_redirect($custom_success_redirection);
     } else {
         $paypal["s2member_log"][] = "Redirecting Customer to the Home Page (after asking Customer to check their email).";
         echo c_ws_plugin__s2member_return_templates::return_template($paypal["subscr_gateway"], _x('<strong>Thank you! (you MUST check your email before proceeding).</strong><br /><br />* Note: It can take <em>(up to 15 minutes)</em> for Email Confirmation with important details. If you don\'t receive email confirmation in the next 15 minutes, please contact Support.', "s2member-front", "s2member") . ($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["paypal_sandbox"] || c_ws_plugin__s2member_utils_conds::pro_is_installed() && !empty($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_" . $paypal["subscr_gateway"] . "_sandbox"]) ? '<br /><br />' . _x('<strong>** Sandbox Mode **</strong> You may NOT receive this Email in Sandbox Mode. Sandbox addresses are usually bogus (for testing).', "s2member-front", "s2member") : ''), _x("Back To Home Page", "s2member-front", "s2member"), home_url("/"));
     }
     foreach (array_keys(get_defined_vars()) as $__v) {
         $__refs[$__v] =& ${$__v};
     }
     do_action("ws_plugin__s2member_during_paypal_return_after_no_return_data", get_defined_vars());
     unset($__refs, $__v);
     return apply_filters("c_ws_plugin__s2member_paypal_return_in_no_tx_data", $paypal, get_defined_vars());
 }
예제 #6
1
/**
 * Provide expansion arguments for dynamic menu items, i.e. menu paths
 * containing one or more %placeholders.
 *
 * The map items must be keyed by the dynamic path to expand. Each map item may
 * have the following properties:
 *
 * - parent: The parent menu path to link the expanded items to.
 * - arguments: An array of argument sets that will be used in the
 *   expansion. Each set consists of an array of one or more placeholders with
 *   an array of possible expansions as value. Upon expansion, each argument
 *   is combined with every other argument from the set (ie., the cartesian
 *   product of all arguments is created). The expansion values may be empty,
 *   that is, you don't need to insert logic to skip map items for which no
 *   values exist, since admin menu will take care of that.
 * - hide: (optional) Used to hide another menu item, usually a superfluous
 *   "List" item.
 *
 * @see admin_menu.map.inc
 */
function hook_admin_menu_map()
{
    // Expand content types in Structure >> Content types.
    // The key denotes the dynamic path to expand to multiple menu items.
    $map['admin/structure/types/manage/%node_type'] = array('parent' => 'admin/structure/types', 'hide' => 'admin/structure/types/list', 'arguments' => array(array('%node_type' => array_keys(node_type_get_types()))));
    return $map;
}
예제 #7
1
 public static function convertDateMomentToPhp($format)
 {
     $tokens = ["M" => "n", "Mo" => "nS", "MM" => "m", "MMM" => "M", "MMMM" => "F", "D" => "j", "Do" => "jS", "DD" => "d", "DDD" => "z", "DDDo" => "zS", "DDDD" => "zS", "d" => "w", "do" => "wS", "dd" => "D", "ddd" => "D", "dddd" => "l", "e" => "w", "E" => "N", "w" => "W", "wo" => "WS", "ww" => "W", "W" => "W", "Wo" => "WS", "WW" => "W", "YY" => "y", "YYYY" => "Y", "gg" => "o", "gggg" => "o", "GG" => "o", "GGGG" => "o", "A" => "A", "a" => "a", "H" => "G", "HH" => "H", "h" => "g", "hh" => "h", "m" => "i", "mm" => "i", "s" => "s", "ss" => "s", "S" => "", "SS" => "", "SSS" => "", "z or zz" => "T", "Z" => "P", "ZZ" => "O", "X" => "U", "LT" => "g:i A", "L" => "m/d/Y", "l" => "n/j/Y", "LL" => "F jS Y", "ll" => "M j Y", "LLL" => "F js Y g:i A", "lll" => "M j Y g:i A", "LLLL" => "l, F jS Y g:i A", "llll" => "D, M j Y g:i A"];
     // find all tokens from string, using regular expression
     $regExp = "/(\\[[^\\[]*\\])|(\\\\)?(LT|LL?L?L?|l{1,4}|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/";
     $matches = array();
     preg_match_all($regExp, $format, $matches);
     //  if there is no match found then return the string as it is
     //  TODO: might return escaped string
     if (empty($matches) || is_array($matches) === false) {
         return $format;
     }
     //  to match with extracted tokens
     $momentTokens = array_keys($tokens);
     $phpMatches = array();
     //  ----------------------------------
     foreach ($matches[0] as $id => $match) {
         // if there is a matching php token in token list
         if (in_array($match, $momentTokens)) {
             // use the php token instead
             $string = $tokens[$match];
         } else {
             $string = $match;
         }
         $phpMatches[$id] = $string;
     }
     // join and return php specific tokens
     return implode("", $phpMatches);
 }
예제 #8
1
 /**
  * displays the topics on a forums
  * @return [type] [description]
  */
 public function action_list()
 {
     //in case performing a search
     if (strlen($search = core::get('search')) >= 3) {
         return $this->action_search($search);
     }
     $this->template->styles = array('css/forums.css' => 'screen');
     $this->template->scripts['footer'][] = 'js/forums.js';
     $forum = new Model_Forum();
     $forum->where('seoname', '=', $this->request->param('forum', NULL))->cached()->limit(1)->find();
     if ($forum->loaded()) {
         //template header
         $this->template->title = $forum->name . ' - ' . __('Forum');
         $this->template->meta_description = $forum->description;
         Breadcrumbs::add(Breadcrumb::factory()->set_title($forum->name));
         //count all topics
         $count = DB::select(array(DB::expr('COUNT("id_post")'), 'count'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->cached()->execute();
         $count = array_keys($count->as_array('count'));
         $pagination = Pagination::factory(array('view' => 'pagination', 'total_items' => isset($count[0]) ? $count[0] : 0))->route_params(array('controller' => $this->request->controller(), 'action' => $this->request->action(), 'forum' => $this->request->param('forum')));
         $pagination->title($this->template->title);
         //getting all the topic for the forum
         $topics = DB::select('p.*')->select(array(DB::select(DB::expr('COUNT("id_post")'))->from(array('posts', 'pc'))->where('pc.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('pc.id_forum', '=', $forum->id_forum)->where('pc.status', '=', Model_Post::STATUS_ACTIVE)->group_by('pc.id_post_parent'), 'count_replies'))->select(array(DB::select('ps.created')->from(array('posts', 'ps'))->where('ps.id_post', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->or_where('ps.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('ps.id_forum', '=', $forum->id_forum)->where('ps.status', '=', Model_Post::STATUS_ACTIVE)->order_by('ps.created', 'DESC')->limit(1), 'last_message'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->where('status', '=', Model_Post::STATUS_ACTIVE)->order_by('last_message', 'DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->as_object()->execute();
         $pagination = $pagination->render();
         $this->template->bind('content', $content);
         $this->template->content = View::factory('pages/forum/list', array('topics' => $topics, 'forum' => $forum, 'pagination' => $pagination));
     } else {
         //throw 404
         throw HTTP_Exception::factory(404, __('Page not found'));
     }
 }
 /**
  * Validates a partial array. Some data may be missing from the given $array, then it will be taken from the
  * full array.
  *
  * Since the array can be incomplete, this method does not validate required parameters.
  *
  * @param array $array
  * @param array $fullArray
  *
  * @return bool
  */
 public function validatePartial(array $array, array $fullArray)
 {
     $unvalidatedFields = array_flip(array_keys($array));
     // field validators
     foreach ($this->validators as $field => $validator) {
         unset($unvalidatedFields[$field]);
         // if the value is present
         if (isset($array[$field])) {
             // validate it if a validator is given, skip it otherwise
             if ($validator && !$validator->validate($array[$field])) {
                 $this->setError($validator->getError());
                 return false;
             }
         }
     }
     // check if any unsupported fields remain
     if ($unvalidatedFields) {
         reset($unvalidatedFields);
         $field = key($unvalidatedFields);
         $this->error($this->messageUnsupported, $field);
         return false;
     }
     // post validators
     foreach ($this->postValidators as $validator) {
         if (!$validator->validatePartial($array, $fullArray)) {
             $this->setError($validator->getError());
             return false;
         }
     }
     return true;
 }
 public function beforeAction($action)
 {
     if (!$this->owner instanceof MobileController && !in_array($this->owner->action->getId(), array_keys($this->actions()))) {
         return true;
     }
     Yii::app()->user->loginUrl = array('/mobile/login');
     Yii::app()->params->isMobileApp = true;
     // fix profile linkable behavior since model was instantiated before action
     if (!preg_match('/\\/mobileView$/', Yii::app()->params->profile->asa('X2LinkableBehavior')->viewRoute)) {
         Yii::app()->params->profile->asa('X2LinkableBehavior')->viewRoute .= '/mobileView';
     }
     $this->dataUrl = $this->owner->createAbsoluteUrl($action->getId());
     $this->pageId = lcfirst(preg_replace('/Controller$/', '', get_class($this->owner))) . '-' . $action->getId();
     $cookie = new CHttpCookie('isMobileApp', 'true');
     // create cookie
     $cookie->expire = 2147483647;
     // max expiration time
     Yii::app()->request->cookies['isMobileApp'] = $cookie;
     // save cookie
     if (!$this->owner instanceof MobileController) {
         $this->owner->layout = $this->pathAliasBase . 'views.layouts.main';
         if ($this->owner->module) {
             $this->owner->setAssetsUrl(Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($this->pathAliasBase . 'assets'), false, -1, true));
             $this->owner->module->assetsUrl = $this->owner->assetsUrl;
             Yii::app()->clientScript->packages = MobileModule::getPackages($this->owner->module->assetsUrl);
         } else {
             Yii::app()->clientScript->packages = MobileModule::getPackages($this->owner->assetsUrl);
         }
     }
     return true;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $ids = $args->getArg('id');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht("Use the '%s' flag to specify one or more SMS messages to show.", '--id'));
     }
     $messages = id(new PhabricatorSMS())->loadAllWhere('id IN (%Ld)', $ids);
     if ($ids) {
         $ids = array_fuse($ids);
         $missing = array_diff_key($ids, $messages);
         if ($missing) {
             throw new PhutilArgumentUsageException(pht('Some specified SMS messages do not exist: %s', implode(', ', array_keys($missing))));
         }
     }
     $last_key = last_key($messages);
     foreach ($messages as $message_key => $message) {
         $info = array();
         $info[] = pht('PROPERTIES');
         $info[] = pht('ID: %d', $message->getID());
         $info[] = pht('Status: %s', $message->getSendStatus());
         $info[] = pht('To: %s', $message->getToNumber());
         $info[] = pht('From: %s', $message->getFromNumber());
         $info[] = null;
         $info[] = pht('BODY');
         $info[] = $message->getBody();
         $info[] = null;
         $console->writeOut('%s', implode("\n", $info));
         if ($message_key != $last_key) {
             $console->writeOut("\n%s\n\n", str_repeat('-', 80));
         }
     }
 }
예제 #12
1
 private function transformToRegex()
 {
     $patternArray = $this->getPatterns();
     $tokenArray = $this->routeArray['tokens'] ?? [];
     $routeArray = $this->routeArray['routes'] ?? [];
     $defaultsArray = $this->routeArray['defaults'] ?? [];
     foreach ($routeArray as $name => $route) {
         $patternKey = array_keys($patternArray);
         $tokens = [];
         $defaults = [];
         $subpatterns = [];
         $search = [];
         $m = [];
         if (preg_match_all('/{(\\w+)}/', $route['path'], $m)) {
             foreach ($m[1] as $token) {
                 $search[] = "{{$token}}";
                 $tokens[$token] = str_replace($patternKey, $patternArray, $route['tokens'][$token] ?? $tokenArray[$token]);
                 $subpatterns[$token] = "(?P<{$token}>{$tokens[$token]})";
                 $tokens[$token] = $this->preparePattern($tokens[$token]);
                 $defaultValue = $route['defaults'][$token] ?? $defaultsArray[$token] ?? [];
                 if (!empty($defaultValue)) {
                     $defaults[$token] = $defaultValue;
                 }
             }
         }
         $route['tokens'] = $tokens;
         $route['defaults'] = $defaults;
         $route['route'] = $route['path'];
         $route['path'] = str_replace($search, $subpatterns, $route['path']);
         $route['path'] = $this->preparePattern(str_replace($patternKey, $patternArray, $route['path']));
         $this->validPattern($route['path'], (string) $name);
         $this->convertedRouteArray[$name] = $route;
     }
 }
예제 #13
0
파일: Util.php 프로젝트: rexmac/zf2
 /** Find the greatest key that is less than or equal to a given upper
  * bound, and return the value associated with that key.
  *
  * @param integer|null $maximumKey The upper bound for keys. If null, the
  *        maxiumum valued key will be found.
  * @param array $collection An two-dimensional array of key/value pairs
  *        to search through.
  * @returns mixed The value corresponding to the located key.
  * @throws \Zend\GData\App\Exception Thrown if $collection is empty.
  */
 public static function findGreatestBoundedValue($maximumKey, $collection)
 {
     $found = false;
     $foundKey = $maximumKey;
     // Sanity check: Make sure that the collection isn't empty
     if (sizeof($collection) == 0) {
         throw new Exception("Empty namespace collection encountered.");
     }
     if ($maximumKey === null) {
         // If the key is null, then we return the maximum available
         $keys = array_keys($collection);
         sort($keys);
         $found = true;
         $foundKey = end($keys);
     } else {
         // Otherwise, we optimistically guess that the current version
         // will have a matching namespce. If that fails, we decrement the
         // version until we find a match.
         while (!$found && $foundKey >= 0) {
             if (array_key_exists($foundKey, $collection)) {
                 $found = true;
             } else {
                 $foundKey--;
             }
         }
     }
     // Guard: A namespace wasn't found. Either none were registered, or
     // the current protcol version is lower than the maximum namespace.
     if (!$found) {
         throw new Exception("Namespace compatible with current protocol not found.");
     }
     return $foundKey;
 }
 /**
  * Creates a Redisent interface to a cluster of Redis servers
  * @param array $servers The Redis servers in the cluster. Each server should be in the format array('host' => hostname, 'port' => port)
  */
 function __construct($servers)
 {
     $this->ring = array();
     $this->aliases = array();
     foreach ($servers as $alias => $server) {
         $this->redisents[] = new Redisent($server['host'], $server['port']);
         if (is_string($alias)) {
             // 用key作为alias标记redis实例
             $this->aliases[$alias] = $this->redisents[count($this->redisents) - 1];
         }
         for ($replica = 1; $replica <= $this->replicas; $replica++) {
             // crc32 — 计算一个字符串的 crc32 多项式,生成 str 的 32 位循环冗余校验码多项式。这通常用于检查传输的数据是否完整。返回值为int类型。
             $this->ring[crc32($server['host'] . ':' . $server['port'] . '-' . $replica)] = $this->redisents[count($this->redisents) - 1];
         }
     }
     // ksort — 对数组按照键名排序
     // 排序类型标记:
     // SORT_REGULAR - 正常比较单元(不改变类型)
     // SORT_NUMERIC - 单元被作为数字来比较
     // SORT_STRING - 单元被作为字符串来比较
     // SORT_LOCALE_STRING - 根据当前的区域(locale)设置来把单元当作字符串比较,可以用 setlocale() 来改变。
     // SORT_NATURAL - 和 natsort() 类似对每个单元以“自然的顺序”对字符串进行排序。 PHP 5.4.0 中新增的。
     // SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并(OR 位运算),不区分大小写排序字符串。
     ksort($this->ring, SORT_NUMERIC);
     // 将redis实例集合的索引放到$this->nodes中
     $this->nodes = array_keys($this->ring);
 }
예제 #15
0
 function art_load_config()
 {
     static $moduleConfig;
     if (isset($moduleConfig[$GLOBALS["artdirname"]])) {
         return $moduleConfig[$GLOBALS["artdirname"]];
     }
     //load_functions("config");
     //$moduleConfig[$GLOBALS["artdirname"]] = mod_loadConfig($GLOBALS["artdirname"]);
     if (isset($GLOBALS["xoopsModule"]) && is_object($GLOBALS["xoopsModule"]) && $GLOBALS["xoopsModule"]->getVar("dirname", "n") == $GLOBALS["artdirname"]) {
         if (!empty($GLOBALS["xoopsModuleConfig"])) {
             $moduleConfig[$GLOBALS["artdirname"]] =& $GLOBALS["xoopsModuleConfig"];
         } else {
             return null;
         }
     } else {
         $module_handler =& xoops_gethandler('module');
         $module = $module_handler->getByDirname($GLOBALS["artdirname"]);
         $config_handler =& xoops_gethandler('config');
         $criteria = new CriteriaCompo(new Criteria('conf_modid', $module->getVar('mid')));
         $configs =& $config_handler->getConfigs($criteria);
         foreach (array_keys($configs) as $i) {
             $moduleConfig[$GLOBALS["artdirname"]][$configs[$i]->getVar('conf_name')] = $configs[$i]->getConfValueForOutput();
         }
         unset($configs);
     }
     if ($customConfig = @(include XOOPS_ROOT_PATH . "/modules/" . $GLOBALS["artdirname"] . "/include/plugin.php")) {
         $moduleConfig[$GLOBALS["artdirname"]] = array_merge($moduleConfig[$GLOBALS["artdirname"]], $customConfig);
     }
     return $moduleConfig[$GLOBALS["artdirname"]];
 }
예제 #16
0
파일: CsvHandler.php 프로젝트: sulu/sulu
 /**
  * Handles response for csv-request.
  *
  * @param ViewHandler $handler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  *
  * @throws ObjectNotSupportedException
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (!$view->getData() instanceof ListRepresentation) {
         throw new ObjectNotSupportedException($view);
     }
     $viewData = $view->getData();
     $data = new CallbackCollection($viewData->getData(), [$this, 'prepareData']);
     $fileName = sprintf('%s.csv', $viewData->getRel());
     $config = new ExporterConfig();
     $exporter = new Exporter($config);
     $data->rewind();
     if ($row = $data->current()) {
         $config->setColumnHeaders(array_keys($row));
     }
     $config->setDelimiter($this->convertValue($request->get('delimiter', ';'), self::$delimiterMap));
     $config->setNewline($this->convertValue($request->get('newLine', '\\n'), self::$newLineMap));
     $config->setEnclosure($request->get('enclosure', '"'));
     $config->setEscape($request->get('escape', '\\'));
     $response = new StreamedResponse();
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName, $fileName);
     $response->headers->set('Content-Type', 'text/csv');
     $response->headers->set('Content-Disposition', $disposition);
     $response->setCallback(function () use($data, $exporter) {
         $exporter->export('php://output', $data);
     });
     $response->send();
     return $response;
 }
예제 #17
0
 public function test_login()
 {
     global $phpbb_root_path, $phpEx;
     $db = $this->new_dbal();
     $config = new \phpbb\config\config(array('ip_login_limit_max' => 0, 'ip_login_limit_use_forwarded' => 0, 'max_login_attempts' => 0));
     $lang_loader = new \phpbb\language\language_file_loader($phpbb_root_path, $phpEx);
     $lang = new \phpbb\language\language($lang_loader);
     $request = $this->getMock('\\phpbb\\request\\request');
     $user = new \phpbb\user($lang, '\\phpbb\\datetime');
     $driver_helper = new \phpbb\passwords\driver\helper($config);
     $passwords_drivers = array('passwords.driver.bcrypt_2y' => new \phpbb\passwords\driver\bcrypt_2y($config, $driver_helper), 'passwords.driver.bcrypt' => new \phpbb\passwords\driver\bcrypt($config, $driver_helper), 'passwords.driver.salted_md5' => new \phpbb\passwords\driver\salted_md5($config, $driver_helper), 'passwords.driver.phpass' => new \phpbb\passwords\driver\phpass($config, $driver_helper));
     $passwords_helper = new \phpbb\passwords\helper();
     // Set up passwords manager
     $passwords_manager = new \phpbb\passwords\manager($config, $passwords_drivers, $passwords_helper, array_keys($passwords_drivers));
     $phpbb_container = new phpbb_mock_container_builder();
     $provider = new \phpbb\auth\provider\db($db, $config, $passwords_manager, $request, $user, $phpbb_container, $phpbb_root_path, $phpEx);
     if (version_compare(PHP_VERSION, '5.3.7', '<')) {
         $password_hash = '$2a$10$e01Syh9PbJjUkio66eFuUu4FhCE2nRgG7QPc1JACalsPXcIuG2bbi';
     } else {
         $password_hash = '$2y$10$4RmpyVu2y8Yf/lP3.yQBquKvE54TCUuEDEBJYY6FDDFN3LcbCGz9i';
     }
     $expected = array('status' => LOGIN_SUCCESS, 'error_msg' => false, 'user_row' => array('user_id' => '1', 'username' => 'foobar', 'user_password' => $password_hash, 'user_passchg' => '0', 'user_email' => '*****@*****.**', 'user_type' => '0', 'user_login_attempts' => '0'));
     $login_return = $provider->login('foobar', 'example');
     $this->assertEquals($expected['status'], $login_return['status']);
     $this->assertEquals($expected['error_msg'], $login_return['error_msg']);
     foreach ($expected['user_row'] as $key => $value) {
         $this->assertEquals($value, $login_return['user_row'][$key]);
     }
     // Check if convert works
     $login_return = $provider->login('foobar2', 'example');
     $password_start = version_compare(PHP_VERSION, '5.3.7', '<') ? '$2a$10$' : '$2y$10$';
     $this->assertStringStartsWith($password_start, $login_return['user_row']['user_password']);
 }
예제 #18
0
 function plgAcymailingContentplugin(&$subject, $config)
 {
     parent::__construct($subject, $config);
     if (!isset($this->params)) {
         $plugin = JPluginHelper::getPlugin('acymailing', 'contentplugin');
         $this->params = new acyParameter($plugin->params);
     }
     $this->paramsContent = JComponentHelper::getParams('com_content');
     JPluginHelper::importPlugin('content');
     $this->dispatcherContent = JDispatcher::getInstance();
     $excludedHandlers = array('plgContentEmailCloak', 'pluginImageShow');
     $excludedNames = array('system' => array('SEOGenerator', 'SEOSimple'), 'content' => array('webeecomment', 'highslide', 'smartresizer', 'phocagallery'));
     $excludedType = array_keys($excludedNames);
     if (!ACYMAILING_J16) {
         foreach ($this->dispatcherContent->_observers as $id => $observer) {
             if (is_array($observer) and in_array($observer['handler'], $excludedHandlers)) {
                 $this->dispatcherContent->_observers[$id]['event'] = '';
             } elseif (is_object($observer)) {
                 if (in_array($observer->_type, $excludedType) and in_array($observer->_name, $excludedNames[$observer->_type])) {
                     $this->dispatcherContent->_observers[$id] = null;
                 }
             }
         }
     }
     if (!class_exists('JSite')) {
         include_once ACYMAILING_ROOT . 'includes' . DS . 'application.php';
     }
 }
예제 #19
0
파일: valider.php 프로젝트: genma/spip_ynh
 function validerAttribut($phraseur, $name, $val, $bal)
 {
     // Si la balise est inconnue, eviter d'insister
     if (!isset($this->dtc->attributs[$bal])) {
         return;
     }
     $a = $this->dtc->attributs[$bal];
     if (!isset($a[$name])) {
         $bons = join(', ', array_keys($a));
         if ($bons) {
             $bons = " title=' " . _T('zxml_connus_attributs') . '&nbsp;: ' . $bons . "'";
         }
         $bons .= " style='font-weight: bold'";
         coordonnees_erreur($this, " <b>{$name}</b> " . _T('zxml_inconnu_attribut') . ' ' . _T('zxml_de') . " <a{$bons}>{$bal}</a> (" . _T('zxml_survoler') . ")");
     } else {
         $type = $a[$name][0];
         if (!preg_match('/^\\w+$/', $type)) {
             $this->valider_motif($phraseur, $name, $val, $bal, $type);
         } else {
             if (method_exists($this, $f = 'validerAttribut_' . $type)) {
                 $this->{$f}($phraseur, $name, $val, $bal);
             }
         }
         #		else spip_log("$type type d'attribut inconnu");
     }
 }
예제 #20
0
 public function process(Vtiger_Request $request)
 {
     $recordId = $request->get('record');
     $qualifiedModuleName = $request->getModule(false);
     $mode = '';
     $selectedFieldsList = $allFieldsList = array();
     if ($recordId) {
         $recordModel = Settings_Webforms_Record_Model::getInstanceById($recordId, $qualifiedModuleName);
         $selectedFieldsList = $recordModel->getSelectedFieldsList();
         $allFieldsList = $recordModel->getAllFieldsList();
         $sourceModule = $recordModel->get('targetmodule');
         $mode = 'edit';
     } else {
         $recordModel = Settings_Webforms_Record_Model::getCleanInstance($qualifiedModuleName);
         $sourceModule = $request->get('sourceModule');
         if (!$sourceModule) {
             $sourceModule = reset(array_keys(Settings_Webforms_Module_Model::getSupportedModulesList()));
         }
         $allFieldsList = $recordModel->getAllFieldsList($sourceModule);
     }
     $recordStructure = Vtiger_RecordStructure_Model::getInstanceFromRecordModel($recordModel, Vtiger_RecordStructure_Model::RECORD_STRUCTURE_MODE_EDIT);
     $viewer = $this->getViewer($request);
     $viewer->assign('MODE', $mode);
     $viewer->assign('RECORD_ID', $recordId);
     $viewer->assign('RECORD_MODEL', $recordModel);
     $viewer->assign('MODULE', $qualifiedModuleName);
     $viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
     $viewer->assign('SOURCE_MODULE', $sourceModule);
     $viewer->assign('ALL_FIELD_MODELS_LIST', $allFieldsList);
     $viewer->assign('SELECTED_FIELD_MODELS_LIST', $selectedFieldsList);
     $viewer->assign('RECORD_STRUCTURE_MODEL', $recordStructure);
     $viewer->assign('RECORD_STRUCTURE', $recordStructure->getStructure());
     $viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
     $viewer->view('EditView.tpl', $qualifiedModuleName);
 }
예제 #21
0
 /**
  * Extract keys on 2 levels.
  *
  * @param array $array The array to extract keys.
  *
  * @return array
  */
 public function getL2Keys(array $array)
 {
     foreach ($array as $key => $rules) {
         $vals[$key] = array_keys($rules);
     }
     return $vals;
 }
 /**
  * Returns an array of public variable names (instead of properties names of parent class)
  *
  * @return array
  */
 public function getPublicProperties()
 {
     // return $this->table->getPublicProperties();
     return array_filter(array_keys(get_object_vars($this)), function ($k) {
         return substr($k, 0, 1) != '_';
     });
 }
예제 #23
0
function mytabs_blockShow($pageid, $tabid, $placement = '', $remove = '')
{
    $block = array();
    $visblocks = array();
    $blocks_handler = xoops_getmodulehandler('pageblock', 'mytabs');
    $blocks = $blocks_handler->getBlocks($pageid, $tabid, $placement, $remove);
    $groups = $GLOBALS['xoopsUser'] ? $GLOBALS['xoopsUser']->getGroups() : array(XOOPS_GROUP_ANONYMOUS);
    foreach (array_keys($blocks) as $key) {
        foreach ($blocks[$key] as $thisblock) {
            if ($thisblock->isVisible() && array_intersect($thisblock->getVar('groups'), $groups)) {
                $visblocks[] = $thisblock;
            }
        }
    }
    $count = count($visblocks);
    for ($i = 0; $i < $count; $i++) {
        $logger_name = $visblocks[$i]->getVar('title') . "(" . $visblocks[$i]->getVar('pageblockid') . ")";
        $GLOBALS['xoopsLogger']->startTime($logger_name);
        $thisblock = $visblocks[$i]->render($GLOBALS['xoopsTpl'], $tabid . '_' . $visblocks[$i]->getVar('pageblockid'));
        if ($thisblock != false) {
            if (strlen($thisblock['title']) > 0) {
                if ($thisblock['title'][0] == '-') {
                    $thisblock['title'] = '';
                }
            }
            $block[] = $thisblock;
        }
        $GLOBALS['xoopsLogger']->stopTime($logger_name);
    }
    return $block;
}
예제 #24
0
 /**
  * 
  * Sanitizes a file-upload information array.  If no file has been 
  * uploaded, the information will be returned as null.
  * 
  * @param array $value An array of file-upload information.
  * 
  * @return mixed The sanitized upload information array, or null.
  * 
  */
 public function sanitizeUpload($value)
 {
     // if the value is not required, and is blank, sanitize to null
     $null = !$this->_filter->getRequire() && $this->_filter->validateBlank($value);
     if ($null) {
         return null;
     }
     // has to be an array
     if (!is_array($value)) {
         return null;
     }
     // presorted list of expected keys
     $expect = array('error', 'name', 'size', 'tmp_name', 'type');
     // remove unexpected keys
     foreach ($value as $key => $val) {
         if (!in_array($key, $expect)) {
             unset($value[$key]);
         }
     }
     // sort the list of remaining actual keys
     $actual = array_keys($value);
     sort($actual);
     // make sure the expected and actual keys match up
     if ($expect != $actual) {
         return null;
     }
     // if all the non-error values are empty, still null
     $empty = empty($value['name']) && empty($value['size']) && empty($value['tmp_name']) && empty($value['type']);
     if ($empty) {
         return null;
     }
     // everything looks ok, return as-is
     return $value;
 }
예제 #25
0
 private function process_fields($records, $class)
 {
     foreach ($records as $rec) {
         if ($class == "vernacular") {
             $c = new \eol_schema\VernacularName();
         } elseif ($class == "agent") {
             $c = new \eol_schema\Agent();
         } elseif ($class == "reference") {
             $c = new \eol_schema\Reference();
         }
         $keys = array_keys($rec);
         foreach ($keys as $key) {
             $temp = pathinfo($key);
             $field = $temp["basename"];
             // some fields have '#', e.g. "http://schemas.talis.com/2005/address/schema#localityName"
             $parts = explode("#", $field);
             if ($parts[0]) {
                 $field = $parts[0];
             }
             if (@$parts[1]) {
                 $field = $parts[1];
             }
             $c->{$field} = $rec[$key];
             if ($field == "taxonID") {
                 $c->{$field} = str_ireplace("urn:lsid:marinespecies.org:taxname:", "", $c->{$field});
             }
         }
         $this->archive_builder->write_object_to_file($c);
     }
 }
예제 #26
0
 public function testConstructor()
 {
     $application = new Application('foo', 'bar');
     $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
     $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument');
     $this->assertEquals(array('help', 'list'), array_keys($application->all()), '__construct() registered the help and list commands by default');
 }
 protected function initColumns()
 {
     if (empty($this->columns)) {
         if ($this->dataProvider instanceof CActiveDataProvider) {
             $this->columns = $this->dataProvider->model->attributeNames();
         } elseif ($this->dataProvider instanceof IDataProvider) {
             $data = $this->dataProvider->getData();
             if (isset($data[0]) && is_array($data[0])) {
                 $this->columns = array_keys($data[0]);
             }
         }
     }
     foreach ($this->columns as $i => $column) {
         if (is_string($column)) {
             $this->_columns[] = $column;
         } elseif (is_array($column)) {
             if ($column['header']) {
                 $this->_columns[] = $column['header'];
             } else {
                 $this->_columns[] = $column['name'];
             }
             if ($this->dataProvider instanceof CActiveDataProvider) {
                 if (!$this->_columns[$i]) {
                     $this->_columns[$i] = $this->dataProvider->model->getAttributeLabel($column['name']);
                 }
                 $this->_select[] = $column['name'];
             }
         }
     }
 }
예제 #28
0
 public function execute(CommandSender $sender, array $args)
 {
     if (count($args) !== 1) {
         return false;
     }
     $player = $sender->getServer()->getPlayer($sender->getName());
     $biome = strtoupper($args[0]);
     $plot = $this->getPlugin()->getPlotByPosition($player->getPosition());
     if ($plot === null) {
         $sender->sendMessage(TextFormat::RED . "You are not standing on an island");
         return true;
     }
     if ($plot->owner !== $sender->getName()) {
         $sender->sendMessage(TextFormat::RED . "You are not the owner of this island");
         return true;
     }
     if (!isset($this->biomes[$biome])) {
         $sender->sendMessage(TextFormat::RED . "That biome doesn't exist");
         $biomes = implode(", ", array_keys($this->biomes));
         $sender->sendMessage(TextFormat::RED . "The possible biomes are: {$biomes}");
         return true;
     }
     $biome = Biome::getBiome($this->biomes[$biome]);
     if ($this->getPlugin()->setPlotBiome($plot, $biome)) {
         $sender->sendMessage(TextFormat::GREEN . "Changed the island biome");
     } else {
         $sender->sendMessage(TextFormat::RED . "Could not change the island biome");
     }
     return true;
 }
예제 #29
0
 public function run($args)
 {
     global $connect, $dbprefix;
     $field = $args[0];
     $srid = $_SESSION['srid'];
     $sid = $_POST['sid'];
     $query = "SELECT {$field} FROM {$dbprefix}survey_{$sid} WHERE id = {$srid}";
     if (!($result = $connect->Execute($query))) {
         throw new Exception("Couldn't get question '{$field}' answer<br />" . $connect->ErrorMsg());
         //Checked
     }
     $row = $result->fetchRow();
     $value = $row[$field];
     $found = array_keys($args, $value);
     if (count($found)) {
         while ($e = each($found)) {
             if ($e['value'] % 2 != 0) {
                 // we check this, as only at odd indexes there are 'cases'
                 return $args[$e['value'] + 1];
             }
         }
         // returns value associated with found 'case'
     }
     // return empty string if none of cases matches user's answer
     return "";
 }
예제 #30
-1
 /**
  * Constructs a Drush alias for an environment. Used to supply
  *   organizational Drush aliases not provided by the API.
  *
  * @param Environment $environment Environment to create an alias for
  * @return string
  * @throws TerminusException
  */
 private function constructAlias($environment)
 {
     $site_name = $environment->site->get('name');
     $site_id = $environment->site->get('id');
     $env_id = $environment->get('id');
     $db_bindings = $environment->bindings->getByType('dbserver');
     $hostnames = array_keys((array) $environment->getHostnames());
     if (empty($hostnames) || empty($db_bindings)) {
         throw new TerminusException('No hostname entry for {site}.{env}', ['site' => $site_name, 'env' => $env_id], 1);
     }
     $db_binding = array_shift($db_bindings);
     $uri = array_shift($hostnames);
     $db_pass = $db_binding->get('password');
     $db_port = $db_binding->get('port');
     if (strpos(TERMINUS_HOST, 'onebox') !== false) {
         $remote_user = "******";
         $remote_host = TERMINUS_HOST;
         $db_url = "mysql://*****:*****@{$remote_host}:{$db_port}";
         $db_url .= '/pantheon';
     } else {
         $remote_user = "******";
         $remote_host = "appserver.{$env_id}.{$site_id}.drush.in";
         $db_url = "mysql://*****:*****@dbserver.{$environment}.{$site_id}";
         $db_url .= ".drush.in:{$db_port}/pantheon";
     }
     $output = "array(\n    'uri'              => {$uri},\n    'db-url'           => {$db_url},\n    'db-allows-remote' => true,\n    'remote-host'      => {$remote_host},\n    'remote-user'      => {$remote_user},\n    'ssh-options'      => '-p 2222 -o \"AddressFamily inet\"',\n    'path-aliases'     => array(\n      '%files'        => 'code/sites/default/files',\n      '%drush-script' => 'drush',\n    ),\n  );";
     return $output;
 }