Exemplo n.º 1
0
/**
 * Merges any number of arrays / parameters recursively, replacing
 * entries with string keys with values from latter arrays.
 * If the entry or the next value to be assigned is an array, then it
 * automagically treats both arguments as an array.
 * Numeric entries are appended, not replaced, but only if they are
 * unique
 *
 * calling: result = array_merge_recursive_distinct(a1, a2, ... aN)
**/
function array_merge_recursive_distinct()
{
    $arrays = func_get_args();
    $base = array_shift($arrays);
    if (!is_array($base)) {
        $base = empty($base) ? array() : array($base);
    }
    foreach ($arrays as $append) {
        if (!is_array($append)) {
            $append = array($append);
        }
        foreach ($append as $key => $value) {
            if (!array_key_exists($key, $base) and !is_numeric($key)) {
                $base[$key] = $append[$key];
                continue;
            }
            if (is_array($value) or is_array($base[$key])) {
                $base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
            } else {
                if (is_numeric($key)) {
                    if (!in_array($value, $base)) {
                        $base[] = $value;
                    }
                } else {
                    $base[$key] = $value;
                }
            }
        }
    }
    return $base;
}
Exemplo n.º 2
0
 /**
  * Registers a taxonomy
  *
  * @param string $slug the slug of the taxonomy
  * @param string $singular singular name
  * @param string $plural plural name
  * @param string $letter letter after "Übergeordnete" and "Neue" -> Could be "n" or "s"
  * @param array $config override the configuration with this array
  * @param array $types the types to be assigned (defaults to array("post"))
  */
 public static function registerTaxonomy($slug, $singular, $plural, $letter = '', $config = array(), $types = array('post'))
 {
     if (!is_array($types)) {
         $types = array($types);
     }
     $labels = array('name' => $singular, 'singular_name' => $singular, 'search_items' => $plural . ' suchen', 'popular_items' => '', 'all_items' => 'Alle ' . $plural, 'view_item' => $singular . ' ansehen', 'parent_item' => 'Übergeordnete' . $letter . ' ' . $singular, 'parent_item_colon' => 'Übergeordnete' . $letter . ' ' . $singular . ':', 'edit_item' => $singular . ' bearbeiten', 'update_item' => $singular . ' speichern', 'add_new_item' => 'Neue' . $letter . ' ' . $singular . ' hinzufügen', 'new_item_name' => 'Neue' . $letter . ' ' . $singular, 'separate_items_with_commas' => $plural . ' durch Komma trennen', 'add_or_remove_items' => $plural . ' hinzufügen oder entfernen', 'menu_name' => $plural);
     $defaults = array('hierarchical' => true, 'public' => true, 'labels' => $labels, 'also_show_in_menu' => false, 'submenu_page_url' => 'edit-tags.php?taxonomy=' . $slug, 'submenu_priority' => 10);
     $arguments = array_merge_recursive_distinct($defaults, $config);
     if ($arguments['also_show_in_menu'] !== false) {
         add_action('admin_menu', function () use($slug, $arguments, $types) {
             add_submenu_page($arguments['also_show_in_menu'], $arguments['labels']['name'], $arguments['labels']['menu_name'], 'manage_categories', $arguments['submenu_page_url']);
         }, $arguments['submenu_priority']);
         // show submenu entry in 'show_in_menu' menu
         add_action('parent_file', function ($parentFile) use($arguments, $types) {
             if ($parentFile == 'edit.php?post_type=' . $types[0]) {
                 $parentFile = $arguments['also_show_in_menu'];
             }
             return $parentFile;
         });
     }
     register_taxonomy($slug, $types, $arguments);
     // make sure it works as suggested by codex (http://codex.wordpress.org/Function_Reference/register_taxonomy#Usage "better be safe than sorry")
     foreach ($types as $type) {
         register_taxonomy_for_object_type($slug, $type);
     }
 }
Exemplo n.º 3
0
/**
 * Merges an array recursively over writting the previous value of an identical associated key.
 * @param array $array1 Array which will be overwritten.
 * @param array $array2 Array who will overwrite.
 * @return array
 */
function array_merge_recursive_distinct($array1, $array2)
{
    $merged = $array1;
    foreach ($array2 as $key => &$value) {
        $merged[$key] = is_array($value) && isset($merged[$key]) && is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $value) : $value;
    }
    return $merged;
}
Exemplo n.º 4
0
function array_merge_recursive_distinct(array &$array1, array &$array2)
{
    $merged = $array1;
    foreach ($array2 as $key => &$value) {
        if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
            $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
        } else {
            $merged[$key] = $value;
        }
    }
    return $merged;
}
Exemplo n.º 5
0
 /**
  * Return all active orders with existing e-mail-adresses
  *
  * @dependencies
  * @return array
  */
 public function getOrderList()
 {
     // Load dependencies
     $this->system->orders->loadAll();
     $this->system->emails->loadOrderMailCount();
     $data = array_merge_recursive_distinct($this->system->order->loadAll()->getOrder(), $this->system->email->loadOrderMailCount()->getOrder());
     foreach ($data as $row) {
         if ($row['has_active_tariff'] == 1 && isset($row['mail_addresses']) && $row['mail_addresses'] > 0) {
             $return[$row['ordnr']] = ['oeid' => $row['oeid'], 'cus_company' => $row['cus_company'], 'cus_first_name' => $row['cus_first_name'], 'cus_last_name' => $row['cus_last_name'], 'mail_addresses' => $row['mail_addresses']];
         }
     }
     return $return;
 }
Exemplo n.º 6
0
function resolve_prefabs($item, &$schema)
{
    if (isset($item["prefab"])) {
        $prefabs = explode(" ", $item["prefab"]);
        foreach ($prefabs as $prefab) {
            $prefab_data = $schema["prefabs"][$prefab];
            if (is_array($prefab_data)) {
                $item = array_merge_recursive_distinct($item, resolve_prefabs($prefab_data, $schema));
            }
        }
    }
    return $item;
}
function values($form_name)
{
    global $wpdb;
    $rows = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s ", 'skip_framework_value_' . $form_name . '%'));
    $start_field = strlen('skip_framework_value_' . $form_name . '_');
    $values = array();
    foreach ($rows as $row) {
        $values_new = array();
        $length_field = strlen($row->option_name);
        $field_name = substr($row->option_name, $start_field, $length_field);
        $fieldname_array = split(SKIP_DELIMITER, $field_name);
        $values_new[$fieldname_array[0]] = _reconstruct_value($fieldname_array, $row->option_value);
        $values = array_merge_recursive_distinct($values, $values_new);
    }
    return $values;
}
Exemplo n.º 8
0
/**
 * Normally recursive merging of arrays
 * @return array
 */
function &array_merge_recursive_distinct()
{
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];
    for ($i = 1; $i < count($aArrays); $i++) {
        if (is_array($aArrays[$i])) {
            foreach ($aArrays[$i] as $key => $val) {
                if (is_array($aArrays[$i][$key])) {
                    if (isset($aMerged[$key])) {
                        $aMerged[$key] = is_array($aMerged[$key]) ? array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
                    } else {
                        $aMerged[$key] = $aArrays[$i][$key];
                    }
                } else {
                    $aMerged[$key] = $val;
                }
            }
        }
    }
    return $aMerged;
}
Exemplo n.º 9
0
 /**
  * Load the configuration from the various YML files.
  */
 public function getConfig()
 {
     $config = array();
     // Read the config
     $config['general'] = array_merge($this->parseConfigYaml('config.yml'), $this->parseConfigYaml('config_local.yml'));
     $config['taxonomy'] = $this->parseConfigYaml('taxonomy.yml');
     $tempContentTypes = $this->parseConfigYaml('contenttypes.yml');
     $config['menu'] = $this->parseConfigYaml('menu.yml');
     $config['routing'] = $this->parseConfigYaml('routing.yml');
     $config['permissions'] = $this->parseConfigYaml('permissions.yml');
     $config['extensions'] = array();
     // fetch the theme config. requires special treatment due to the path
     $this->app['resources']->initializeConfig($config);
     $paths = $this->app['resources']->getPaths();
     $themeConfigFile = $paths['themepath'] . '/config.yml';
     $config['theme'] = $this->parseConfigYaml($themeConfigFile, array(), false);
     // @todo: If no config files can be found, get them from bolt.cm/files/default/
     $this->paths = $this->app['resources']->getPaths();
     $this->setDefaults();
     // Make sure old settings for 'contentsCss' are still picked up correctly
     if (isset($config['general']['wysiwyg']['ck']['contentsCss'])) {
         $config['general']['wysiwyg']['ck']['contentsCss'] = array(1 => $config['general']['wysiwyg']['ck']['contentsCss']);
     }
     // Make sure old settings for 'accept_file_types' are not still picked up. Before 1.5.4 we used to store them
     // as a regex-like string, and we switched to an array. If we find the old style, fall back to the defaults.
     if (isset($config['general']['accept_file_types']) && !is_array($config['general']['accept_file_types'])) {
         unset($config['general']['accept_file_types']);
     }
     // Merge the array with the defaults. Setting the required values that aren't already set.
     $config['general'] = array_merge_recursive_distinct($this->defaultConfig, $config['general']);
     // Make sure the cookie_domain for the sessions is set properly.
     if (empty($config['general']['cookies_domain'])) {
         if (isset($_SERVER['HTTP_HOST'])) {
             $hostname = $_SERVER['HTTP_HOST'];
         } elseif (isset($_SERVER['SERVER_NAME'])) {
             $hostname = $_SERVER['SERVER_NAME'];
         } else {
             $hostname = '';
         }
         // Don't set the domain for a cookie on a "TLD" - like 'localhost', or if the server_name is an IP-address
         if (strpos($hostname, '.') > 0 && preg_match("/[a-z0-9]/i", $hostname)) {
             if (preg_match("/^www[0-9]*./", $hostname)) {
                 $config['general']['cookies_domain'] = '.' . preg_replace("/^www[0-9]*./", '', $hostname);
             } else {
                 $config['general']['cookies_domain'] = '.' . $hostname;
             }
             // Make sure we don't have consecutive '.'-s in the cookies_domain..
             $config['general']['cookies_domain'] = str_replace('..', '.', $config['general']['cookies_domain']);
         } else {
             $config['general']['cookies_domain'] = '';
         }
     }
     // Make sure Bolt's mount point is OK:
     $config['general']['branding']['path'] = '/' . safeString($config['general']['branding']['path']);
     // Make sure $config['taxonomy'] is an array. (if the file is empty, YAML parses it as NULL)
     if (empty($config['taxonomy'])) {
         $config['taxonomy'] = array();
     }
     // Clean up taxonomies
     foreach ($config['taxonomy'] as $key => $value) {
         if (!isset($config['taxonomy'][$key]['name'])) {
             $config['taxonomy'][$key]['name'] = ucwords($config['taxonomy'][$key]['slug']);
         }
         if (!isset($config['taxonomy'][$key]['singular_name'])) {
             if (isset($config['taxonomy'][$key]['singular_slug'])) {
                 $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['singular_slug']);
             } else {
                 $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['slug']);
             }
         }
         if (!isset($config['taxonomy'][$key]['slug'])) {
             $config['taxonomy'][$key]['slug'] = strtolower(safeString($config['taxonomy'][$key]['name']));
         }
         if (!isset($config['taxonomy'][$key]['singular_slug'])) {
             $config['taxonomy'][$key]['singular_slug'] = strtolower(safeString($config['taxonomy'][$key]['singular_name']));
         }
         if (!isset($config['taxonomy'][$key]['has_sortorder'])) {
             $config['taxonomy'][$key]['has_sortorder'] = false;
         }
         // Make sure the options are $key => $value pairs, and not have implied integers for keys.
         if (!empty($config['taxonomy'][$key]['options']) && is_array($config['taxonomy'][$key]['options'])) {
             $options = array();
             // FIXME using $value variable seems bad idea because of outer loop uses too
             foreach ($config['taxonomy'][$key]['options'] as $optionkey => $value) {
                 if (is_numeric($optionkey)) {
                     $optionkey = makeSlug($value);
                     // was: strtolower(safeString($value));
                 }
                 $options[$optionkey] = $value;
             }
             $config['taxonomy'][$key]['options'] = $options;
         }
         // If taxonomy is like tags, set 'tagcloud' to true by default.
         if ($config['taxonomy'][$key]['behaves_like'] == 'tags' && !isset($config['taxonomy'][$key]['tagcloud'])) {
             $config['taxonomy'][$key]['tagcloud'] = true;
         }
     }
     // Clean up contenttypes
     $config['contenttypes'] = array();
     foreach ($tempContentTypes as $key => $temp) {
         // If the slug isn't set, and the 'key' isn't numeric, use that as the slug.
         if (!isset($temp['slug']) && !is_numeric($key)) {
             $temp['slug'] = makeSlug($key);
         }
         // If neither 'name' nor 'slug' is set, we need to warn the user. Same goes for when
         // neither 'singular_name' nor 'singular_slug' is set.
         if (!isset($temp['name']) && !isset($temp['slug'])) {
             $error = sprintf("In contenttype <code>%s</code>, neither 'name' nor 'slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
             $llc = new Configuration\LowlevelChecks($this->app['resources']);
             $llc->lowlevelError($error);
         }
         if (!isset($temp['singular_name']) && !isset($temp['singular_slug'])) {
             $error = sprintf("In contenttype <code>%s</code>, neither 'singular_name' nor 'singular_slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
             $llc = new Configuration\LowlevelChecks($this->app['resources']);
             $llc->lowlevelError($error);
         }
         if (!isset($temp['slug'])) {
             $temp['slug'] = makeSlug($temp['name']);
         }
         if (!isset($temp['singular_slug'])) {
             $temp['singular_slug'] = makeSlug($temp['singular_name']);
         }
         if (!isset($temp['show_on_dashboard'])) {
             $temp['show_on_dashboard'] = true;
         }
         if (!isset($temp['show_in_menu'])) {
             $temp['show_in_menu'] = true;
         }
         if (!isset($temp['sort'])) {
             $temp['sort'] = '';
         }
         if (!isset($temp['default_status'])) {
             $temp['default_status'] = 'draft';
         }
         // Make sure all fields are lowercase and 'safe'.
         $tempfields = $temp['fields'];
         $temp['fields'] = array();
         // Set a default group and groups array.
         $currentgroup = false;
         $temp['groups'] = array();
         foreach ($tempfields as $key => $value) {
             // FIXME Fix name 'keys' for fields
             $key = str_replace('-', '_', strtolower(safeString($key, true)));
             $temp['fields'][$key] = $value;
             // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == 'file' || $temp['fields'][$key]['type'] == 'filelist') {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array_intersect(array('doc', 'docx', 'txt', 'md', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'csv'), $config['general']['accept_file_types']);
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
             // If field is an "image" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == 'image' || $temp['fields'][$key]['type'] == 'imagelist') {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array_intersect(array('gif', 'jpg', 'jpeg', 'png'), $config['general']['accept_file_types']);
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
             // If the field has a 'group', make sure it's added to the 'groups' array, so we can turn
             // them into tabs while rendering. This also makes sure that once you started with a group,
             // all others have a group too.
             if (!empty($temp['fields'][$key]['group'])) {
                 $currentgroup = $temp['fields'][$key]['group'];
                 $temp['groups'][] = $currentgroup;
             } else {
                 $temp['fields'][$key]['group'] = $currentgroup;
             }
         }
         // Make sure the 'uses' of the slug is an array.
         if (isset($temp['fields']['slug']) && isset($temp['fields']['slug']['uses']) && !is_array($temp['fields']['slug']['uses'])) {
             $temp['fields']['slug']['uses'] = array($temp['fields']['slug']['uses']);
         }
         // Make sure taxonomy is an array.
         if (isset($temp['taxonomy']) && !is_array($temp['taxonomy'])) {
             $temp['taxonomy'] = array($temp['taxonomy']);
         }
         // when adding relations, make sure they're added by their slug. Not their 'name' or 'singular name'.
         if (!empty($temp['relations']) && is_array($temp['relations'])) {
             // FIXME using variable $key seems a bad idea while outer loop uses the same
             foreach ($temp['relations'] as $key => $relation) {
                 if ($key != makeSlug($key)) {
                     $temp['relations'][makeSlug($key)] = $temp['relations'][$key];
                     unset($temp['relations'][$key]);
                 }
             }
         }
         // Make sure the 'groups' has unique elements, if there are any.
         if (!empty($temp['groups'])) {
             $temp['groups'] = array_unique($temp['groups']);
         } else {
             unset($temp['groups']);
         }
         $config['contenttypes'][$temp['slug']] = $temp;
     }
     // Set all the distinctive arrays as part of our Config object.
     $this->data = $config;
 }
Exemplo n.º 10
0
 /**
  * Load server settings from specified ini file
  *
  * @param string $cfgfile ini file to load from
  * @return array server config block (also stored as $this->servers)
  */
 function LoadServers($assign = true)
 {
     //Profiler::StartTimer("ConfigManager::LoadServers()");
     $servers = array();
     // new method
     $this->LoadSettings($this->locations["config"] . "/servers.ini");
     $this->role = $this->GetRoleFromHostname();
     $servers = array_merge_recursive_distinct($servers, $this->GetRoleSettings("default"));
     $servers = array_merge_recursive_distinct($servers, $this->GetRoleSettings($this->role));
     $this->locations = $this->getlocations();
     // DISABLED - old method, had better caching of combined role config
     /*
     if (file_exists($cfgfile)) {
       $mtime = filemtime($cfgfile);
       if (!empty($mtime)) {
         // NOTE - This uses APC directly, since the datamanager object requires this function to execute before initializing
         $apckey = $cfgfile . "." . $mtime;
         //print "check apc for '$apckey'<br />";
         if ($this->apcenabled && ($apccontents = apc_fetch($apckey)) != false) {
           //print "found in apc, unserialize ($apccontents)<br />";
           $servers = unserialize($apccontents);
         } else {
           //print "not found in apc, parse it<br />";
     
           $settings = parse_ini_file($cfgfile, true);
     
           Logger::Info("Loading server config: $hostname");
           // First load the defaults
           if (!empty($settings["default"])) {
             array_set_multi($servers, $settings["default"]);
           }
     
           // set the role
           //$servers["role"] = ($settings["mapping"][$hostname]) ? $settings["mapping"][$hostname] : "live"; // default to live so the site will work if /etc/hostname is missing
           // If our host is part of a grouping, load those settings up
           if (!empty($settings["mapping"]) && !empty($settings["mapping"][$hostname]) && !empty($settings[$settings["mapping"][$hostname]])) {
             Logger::Info("$hostname is currently in the '" . $settings["mapping"][$hostname] . "' group");
             array_set_multi($servers, $settings[$settings["mapping"][$hostname]]);
           }
     
           // And finally, load any host-specific settings
           if (!empty($settings[$hostname])) {
             array_set_multi($servers, $settings[$hostname]);
           }
     
           if ($this->apcenabled) {
             apc_store($apckey, serialize($servers));
           }
         }
       }
     }
     */
     if ($assign) {
         $this->servers =& $servers;
         if (!empty($this->servers["role"])) {
             // ini file specified overridden role
             $this->role = $this->servers["role"];
         }
     }
     //Profiler::StopTimer("ConfigManager::LoadServers()");
     // set logger/profiler settings
     if (isset($this->servers["logger"]["enabled"]) && empty($this->servers["logger"]["enabled"])) {
         Logger::$enabled = false;
     }
     if (isset($this->servers["profiler"]["enabled"]) && empty($this->servers["profiler"]["enabled"])) {
         Profiler::$enabled = false;
     }
     // Update locations to reflect any new settings we got from the ini file
     $this->locations = $this->getLocations();
     // Merge any path settings from the config file into our environment
     if (!empty($this->servers["elation"]["path"])) {
         $elationpath = explode(":", $this->servers["elation"]["path"]);
         $oldincludepath = get_include_path();
         $includepath = explode(":", $oldincludepath);
         $newincludepath = implode(":", array_merge(array_diff($elationpath, $includepath), $includepath));
         if ($newincludepath != $oldincludepath) {
             //        set_include_path($newincludepath);
         }
     }
     // Merge any settings which are overridden by a dev cookie
     if (!empty($_COOKIE["tf-dev"])) {
         $tfdev = json_decode($_COOKIE["tf-dev"], true);
         if (!empty($tfdev["serveroverrides"])) {
             $this->SetServerOverride($tfdev["serveroverrides"]);
         }
     }
     return $servers;
 }
Exemplo n.º 11
0
<?php

include 'config.php';
require_once './system/bootstrap.php';
require_once './system/anti-framework/AF.php';
$default_config = array('log' => array('type' => 'AF_Log_Array', 'params' => array('register_shutdown' => true)), 'db' => array('master' => array('dsn' => 'mysql:dbname=REPLACE_ME;host=127.0.0.1', 'username' => 'root', 'password' => 'password', 'identifier' => 'test')));
$config = array_merge_recursive_distinct($default_config, $config);
AF::setConfig($config);
try {
    AF::bootstrap(AF::PAGE_GEN);
} catch (PDOException $e) {
    die('Error connection to database: ' . $e->getMessage());
}
$table = new AF_Table('wp_options', 'option_name');
//echo '<pre>';
//var_dump();
$results = $table->get('siteurl', AF::DELAY_SAFE);
?>
<!doctype html>
<html>
<head>
	<title>Ideas</title>
	<style>
	@import url("reset.css");
	
	.topic {
		background: #eee;
		padding: 20px;
		margin-bottom: 2em;
		clear: both;
		overflow: auto;
Exemplo n.º 12
0
 /**
  * Get the HTML output of an <input> element of type 'number'.
  *
  * @since 4.8.1
  * @param string|int $value The input element's value.
  * @param array $args Data for the input element.
  * @return string The input element HTML.
  */
 public static function getNumberHtml($value, $args = array())
 {
     $defaults = array('type' => 'number', 'class' => '', 'placeholder' => isset($args['label']) ? $args['label'] : '', 'min' => 0, 'max' => '', 'step' => 1);
     $args = array_merge_recursive_distinct($defaults, $args);
     return sprintf('<input id="%1$s" type="%2$s" name="%3$s" value="%4$s" class="%5$s" placeholder="%6$s" min="%7$s" max="%8$s" step="%9$s" />', esc_attr($args['id']), $args['type'], $args['name'], esc_attr($value), $args['class'], $args['placeholder'], $args['min'], $args['max'], $args['step']);
 }
Exemplo n.º 13
0
 /**
  * __construct();
  *
  * @param array $param Parâmetros de inicialização
  */
 function __construct($param = '')
 {
     /**
      * VARIÁVEIS DE SISTEMA
      *
      * Inicialização de variáveis
      */
     /**
      * Toma todas as configurações do objeto Dispatcher, responsável pela
      * de inicialização do sistema, como análise de URLs, entre outros.
      */
     $this->dispatcher = $param["dispatcher"];
     $this->conn =& $this->dispatcher->conn;
     /**
      * $THIS->PARAMS
      *
      * Configura os parâmetros de sistema
      */
     $this->params["app"] = $this->dispatcher->callApp;
     $this->params["controller"] = $this->dispatcher->callController;
     $this->params["action"] = $this->dispatcher->callAction;
     $this->params["args"] = $this->dispatcher->arguments;
     $this->params["webroot"] = $this->dispatcher->webroot;
     $args = array();
     foreach ($this->params["args"] as $chave => $valor) {
         if (is_int($chave)) {
             $args[$chave] = $valor;
         } else {
             $args[$chave] = $chave . ":" . $valor;
         }
     }
     $this->params["url"] = $_SERVER['REQUEST_URI'];
     /*
      *
      * $THIS->DATA
      *
      * Ajusta $_POST e $_FILES, inserindo os dados organizadamente em
      * $this->data.
      */
     /*
      * $_FILES
      *
      * Guarda tudo de $_FILES em $this->params["files"] e $this->data
      */
     if (!empty($_FILES)) {
         $formattedFilesData = array();
         if (!empty($_FILES["data"])) {
             $data = $_FILES["data"];
             /*
              * O resultado que vem em $_FILES são bagunçados. O código
              * abaixo faz um loop por este comando e organiza as
              * informações.
              */
             /*
              * Loop pelos tipos de dados do arquivo
              */
             foreach ($data as $infoName => $model) {
                 /*
                  * Loop por cada model
                  */
                 foreach ($model as $modelName => $fields) {
                     if (is_array($fields)) {
                         /*
                          * Loop pelos arquivos enviados
                          */
                         foreach ($fields as $fieldName => $fieldData) {
                             $formattedFilesData[$modelName][$fieldName][$infoName] = $fieldData;
                         }
                     }
                 }
             }
             $this->params["files"] = $formattedFilesData;
         } else {
             /**
              * @todo -
              */
             $this->params["files"] = $_FILES;
         }
     }
     /*
      * $_POST
      */
     if (!empty($_POST)) {
         $this->params["post"] = $_POST;
         if (!empty($_POST["data"])) {
             $this->data = $_POST["data"];
         }
     }
     /*
      * $_GET
      */
     if (!empty($_GET)) {
         $this->params["get"] = $_GET;
     }
     if (!empty($formattedFilesData)) {
         if (!empty($this->data)) {
             $this->data = array_merge_recursive($this->data, $formattedFilesData);
         } else {
             $this->data = $formattedFilesData;
         }
     }
     if (!empty($this->data)) {
         $this->params["data"] = $this->data;
     }
     /*
      * Soma em $this->data os dados necessários
      * 
      * Os dados que estiverem na Session no seguinte endereço serão
      * acrescentados em $this->data.
      * 
      * $_SESSION["Sys"]
      *              ["addToThisData"]
      *                  [$modelName]
      *                      [$campo] = $valor;
      */
     /**
      * Cada form tem um id. Se foi enviado um $_POST[formId], vai adiante
      * para inserir dados em $this->data.
      */
     //pr($this->params);
     if (!empty($this->params["post"]["formId"])) {
         /**
          * Pega o valor a ser incrementado em $this->data e guarda em $toAdd
          */
         if (!empty($_SESSION["Sys"]["addToThisData"][$this->params["post"]["formId"]])) {
             $toAdd = $_SESSION["Sys"]["addToThisData"][$this->params["post"]["formId"]];
         }
         /**
          * Se $this->data existe e ha algo a ser inserido
          */
         if (!empty($this->data) and !empty($toAdd)) {
             $this->data = array_merge_recursive_distinct($toAdd, $this->data);
         } else {
             if (!empty($toAdd)) {
                 if ($this->params["url"] !== $_SESSION["Sys"]["options"]["addToThisData"][$this->params["post"]["formId"]]["destLocation"]) {
                     unset($_SESSION["Sys"]["addToThisData"][$this->params["post"]["formId"]]);
                 } else {
                     $this->data = $toAdd;
                 }
             }
         }
     } else {
         if (!empty($_SESSION["Sys"]["addToThisData"])) {
             $toAdd = $_SESSION["Sys"]["addToThisData"];
         }
         /**
          * Se $this->data existe e ha algo a ser inserido
          */
         if (!empty($this->data) and !empty($toAdd)) {
             $this->data = array_merge_recursive_distinct($toAdd, $this->data);
         } else {
             if (!empty($toAdd)) {
                 //echo $this->params["post"]["formId"]."";
                 /*
                                 if( $this->params["url"] !== $_SESSION["Sys"]["options"]["addToThisData"]["destLocation"] ){
                    unset( $_SESSION["Sys"]["addToThisData"] );
                                 } else {
                    $this->data = $toAdd;
                                 }
                 * 
                 */
             }
         }
     }
     $this->webroot = $this->dispatcher->webroot;
     /**
      * VARIÁVEIS DE AMBIENTE
      */
     /**
      * Variáveis de ambiente são ajustadas no método controller::_trigger();
      */
     /**
      * MODELS
      *
      * Carrega models que estão descritos em $this->uses
      */
     if (!empty($this->uses)) {
         /**
          * Loop por cada model requisitado e carrega cada um.
          *
          * Ele estão acessívels através de $this->modelName
          */
         foreach ($this->uses as $valor) {
             $className = $valor;
             $this->loadModel($className);
         }
     }
     /**
      * HELPERS, COMPONENTS, BEHAVIORS
      *
      * Inicialização destes automatizadores de processos.
      */
     /**
      * HELPERS
      * 
      * Cria helpers solicitados
      */
     /**
      * Helpers são criados no método _TRIGGER(), após os actions
      * terem sido rodados.
      *
      * Ver Controller::_trigger()
      */
     /**
      * COMPONENTS
      */
     if (count($this->components)) {
         /**
          * Loop por cada component requisitado.
          *
          * Carrega classe do Component, instancia e envia para o Controller
          */
         foreach ($this->components as $valor) {
             $this->loadComponent($valor);
         }
     }
     /**
      * HELPERS
      *
      * Cria helpers solicitados
      */
     if (!empty($this->helpers)) {
         /**
          * Loop por cada helper requisitado.
          *
          * Carrega classe do Helper, instancia e envia para o View
          */
         foreach ($this->helpers as $valor) {
             include_once CORE_HELPERS_DIR . $valor . ".php";
             $helperName = $valor . HELPER_CLASSNAME_SUFFIX;
             $helperParams = array("params" => &$this->params, "data" => $this->data, "models" => &$this->usedModels, "conn" => &$this->conn, "environment" => &$this->environment, "controller" => &$this, "_loadedHelpers" => &$this->_loadedHelpers);
             ${$valor} = new $helperName($helperParams);
             /*
              * Salva a instância do Helper atual
              */
             $this->_loadedHelpers[$valor] =& ${$valor};
             $this->{$valor} =& ${$valor};
             /**
              * Envia Helper para o view
              */
             $this->set(strtolower($valor), ${$valor});
         }
     }
     /**
      * VARIÁVEIS GLOBAIS
      *
      * Agrega ao objeto atual as variáveis globais necessárias.
      */
     /**
      * $action: que ação será chamada neste módulo
      */
     $this->action = empty($this->dispatcher->callAction) ? 'index' : $this->dispatcher->callAction;
     /**
      * EXECUTA MVC
      *
      * Começa execução de métodos necessários.
      */
     /**
      * _trigger() é responsável por engatilhar todos os métodos
      * automáticos a serem rodados, como beforeFilter, render, etc.
      */
     $this->_trigger(array('action' => $this->action));
 }
Exemplo n.º 14
0
 function AddSource($sourcetype, $cfg)
 {
     if (!empty($cfg)) {
         Profiler::StartTimer("DataManager::Init() - Add source: {$sourcetype}", 3);
         // Check to see if we have a wrapper for this sourcetype in include/datawrappers/*wrapper_class.php
         // If it exists, include the code for it and initialize
         $includefile = "include/datawrappers/" . strtolower($sourcetype) . "wrapper_class.php";
         if (file_exists_in_path($includefile)) {
             include_once $includefile;
             foreach ($cfg as $sourcename => $sourcecfg) {
                 Profiler::StartTimer(" - {$sourcetype}({$sourcename})", 3);
                 // Server groups get special handling at this level so they can be applied to all types
                 if (!empty($sourcecfg["group"]) && ($group = $this->GetGroup($sourcecfg["group"])) !== NULL) {
                     Logger::Notice("Merged source group '{$sourcecfg['group']}' into {$sourcename}");
                     $sourcecfg = array_merge_recursive($sourcecfg, $group);
                 }
                 // If this source references another source, load those settings underneath, and override with my own
                 if (!empty($sourcecfg["source"])) {
                     $othercfg = array_get($this->cfg->servers["sources"], $sourcecfg["source"]);
                     if (!empty($othercfg)) {
                         $sourcecfg = array_merge_recursive_distinct($othercfg, $sourcecfg);
                     }
                 }
                 $classname = $sourcetype . "wrapper";
                 $sourcewrapper = new $classname($sourcename, $sourcecfg, true);
                 if (!empty($sourcecfg["cache"]) && $sourcecfg["cache"] != "none") {
                     if ($cacheobj = array_get($this->caches, $sourcecfg["cache"])) {
                         $sourcewrapper->SetCacheServer($cacheobj, any($sourcecfg["cachepolicy"], true));
                     }
                 }
                 array_set($this->sources, $sourcetype . "." . $sourcename, $sourcewrapper);
                 Logger::Notice("Added source '{$sourcetype}.{$sourcename}': " . $sourcecfg["host"]);
                 Profiler::StopTimer(" - {$sourcetype}({$sourcename})");
             }
         } else {
             Logger::Debug("Tried to instantiate source '{$sourcetype}', but couldn't find class");
         }
         Profiler::StopTimer("DataManager::Init() - Add source: {$sourcetype}");
     }
 }
        $box_title = $user['display_name'];
    }
} else {
    $user = array();
    $deleteLabel = "";
}
$fields_default = ['user_name' => ['type' => 'text', 'label' => 'Username', 'display' => 'disabled', 'validator' => ['minLength' => 1, 'maxLength' => 25, 'label' => 'Username'], 'placeholder' => 'Please enter the user name'], 'display_name' => ['type' => 'text', 'label' => 'Display Name', 'display' => 'disabled', 'validator' => ['minLength' => 1, 'maxLength' => 50, 'label' => 'Display name'], 'placeholder' => 'Please enter the display name'], 'email' => ['type' => 'text', 'label' => 'Email', 'display' => 'disabled', 'icon' => 'fa fa-envelope', 'icon_link' => 'mailto: {{value}}', 'validator' => ['minLength' => 1, 'maxLength' => 150, 'email' => true, 'label' => 'Email'], 'placeholder' => 'Email goes here'], 'title' => ['type' => 'text', 'label' => 'Title', 'display' => 'disabled', 'validator' => ['minLength' => 1, 'maxLength' => 100, 'label' => 'Title'], 'default' => 'New User'], 'sign_up_stamp' => ['type' => 'text', 'label' => 'Registered Since', 'display' => 'disabled', 'icon' => 'fa fa-calendar', 'preprocess' => 'formatSignInDate'], 'last_sign_in_stamp' => ['type' => 'text', 'label' => 'Last Sign-in', 'display' => 'disabled', 'icon' => 'fa fa-calendar', 'preprocess' => 'formatSignInDate', 'default' => 0], 'password' => ['type' => 'password', 'label' => 'Password', 'display' => 'hidden', 'icon' => 'fa fa-key', 'validator' => ['minLength' => 8, 'maxLength' => 50, 'label' => 'Password', 'passwordMatch' => 'passwordc']], 'passwordc' => ['type' => 'password', 'label' => 'Confirm password', 'display' => 'hidden', 'icon' => 'fa fa-key', 'validator' => ['minLength' => 8, 'maxLength' => 50, 'label' => 'Password']], 'groups' => ['display' => 'disabled']];
$fields = array_merge_recursive_distinct($fields_default, $get['fields']);
// Buttons (optional)
// submit: display the submission button for this form.
// edit: display the edit button for panel mode.
// disable: display the enable/disable button.
// delete: display the deletion button.
// activate: display the activate button for inactive users.
$buttons_default = ["btn_submit" => ["type" => "submit", "label" => $button_submit_text, "display" => "hidden", "style" => "success", "size" => "lg"], "btn_edit" => ["type" => "launch", "label" => "Edit", "icon" => "fa fa-edit", "display" => "show"], "btn_activate" => ["type" => "button", "label" => "Activate", "icon" => "fa fa-bolt", "display" => isset($user['active']) && $user['active'] == '0' ? "show" : "hidden", "style" => "success"], "btn_disable" => ["type" => "button", "label" => "Disable", "icon" => "fa fa-minus-circle", "display" => isset($user['enabled']) && $user['enabled'] == '1' ? "show" : "hidden", "style" => "warning"], "btn_enable" => ["type" => "button", "label" => "Enable", "icon" => "fa fa-plus-circle", "display" => isset($user['enabled']) && $user['enabled'] == '1' ? "hidden" : "show", "style" => "warning"], "btn_delete" => ["type" => "launch", "label" => "Delete", "icon" => "fa fa-trash-o", "display" => "show", "data" => array("label" => $deleteLabel), "style" => "danger"], "btn_cancel" => ["type" => "cancel", "label" => "Cancel", "display" => $get['render_mode'] == 'modal' ? "show" : "hidden", "style" => "link", "size" => "lg"]];
$buttons = array_merge_recursive_distinct($buttons_default, $get['buttons']);
$template = "";
if ($get['render_mode'] == "modal") {
    $template .= "<div id='{$get['box_id']}' class='modal fade'>\n        <div class='modal-dialog'>\n            <div class='modal-content'>\n                <div class='modal-header'>\n                    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n                    <h4 class='modal-title'>{$box_title}</h4>\n                </div>\n                <div class='modal-body'>\n                    <form method='post' action='{$target}'>";
} else {
    if ($get['render_mode'] == "panel") {
        $template .= "<div class='panel panel-primary'>\n        <div class='panel-heading'>\n            <h2 class='panel-title pull-left'>{$box_title}</h2>\n            <div class='clearfix'></div>\n            </div>\n            <div class='panel-body'>\n                <form method='post' action='{$target}'>";
    } else {
        echo "Invalid render mode.";
        exit;
    }
}
// Load CSRF token
$csrf_token = $loggedInUser->csrf_token;
$template .= "<input type='hidden' name='csrf_token' value='{$csrf_token}'/>";
$template .= "\n<div class='dialog-alert'>\n</div>\n<div class='row'>\n    <div class='col-sm-6'>\n        {{user_name}}\n    </div>\n    <div class='col-sm-6'>\n        {{display_name}}\n    </div>    \n</div>\n<div class='row'>\n    <div class='col-sm-6'>\n        {{email}}\n    </div>\n    <div class='col-sm-6'>\n        {{title}}\n    </div>    \n</div>\n<div class='row'>\n    <div class='col-sm-6'>\n        {{last_sign_in_stamp}}\n    </div>\n    <div class='col-sm-6'>\n        {{sign_up_stamp}}\n    </div>    \n</div>\n<div class='row'>\n    <div class='col-sm-6'>\n        {{password}}\n        {{passwordc}}\n    </div>";
Exemplo n.º 16
0
 /**
  * _explodeRequest
  *
  * also modifies $this->GET
  * @return array associated array of controller and view template
  */
 function _explodeRequest($request)
 {
     /**
      * 1st method: parse (nearly) standard HTTP GET syntax
      *
      * Add global GET parameters to $this->GET
      */
     // variables, TODO allow variables like sort[by]
     $request = str_replace('&amp;', '&', $request);
     $request = explode('&', $request);
     for ($i = 1; $i < count($request); $i++) {
         parse_str($request[$i], $parsed_get);
         $this->GET = array_merge_recursive_distinct($this->GET, $parsed_get);
     }
     $module = $request[0];
     // view and controller
     $vc = explode('@', $module);
     if (count($vc) > 0) {
         $m['controller'] = $vc[0];
         if (isset($vc[1])) {
             $m['view'] = $vc[1];
         } else {
             $m['view'] = $vc[0];
         }
     } else {
         $m['controller'] = $module;
         $m['view'] = $module;
     }
     /**
      * 2nd method: parse proprietary syntax
      *
      * It was introduces to allow passign different parameters to different controllers using the same variable name/
      * Consider deprication this feature.
      *
      * valid syntax controller@view~param:value~
      * TODO: allow controller~param:value~@view~param:value~
      */
     if (preg_match('/([^\\~]*)\\~([^\\~]*)\\~/i', $m['view'], $match)) {
         // variables
         parse_str(preg_replace('/:/', '&', $match[2]), $parsed_GET);
         $this->GET = array_merge($this->GET, $parsed_GET);
         // view and controller
         if (preg_match('/(.*)@([^~]*)/', $match[1], $module_override)) {
             $m['controller'] = $module_override[1];
             $m['view'] = $module_override[2];
         } else {
             $m['controller'] = $m['view'] = $match[1];
         }
     }
     return $m;
 }
Exemplo n.º 17
0
 /**
  * Load in an environment definition.
  *
  * @param string $env
  *   An environment name.
  */
 private function loadEnvironment($env)
 {
     $this->exec = array_merge_recursive_distinct($this->exec, $this->environments[$env]);
     unset($this->exec['filename']);
 }
Exemplo n.º 18
0
 /**
  * Build meta data cache.
  *
  * @param int $lifetime
  * @return \Recipe_Cache
  */
 public function buildMetaCache($lifetime = self::DEFAULT_CACHE_LIFE_TIME)
 {
     $data = array();
     $applicationDirectory = APP_ROOT_DIR . "app/bootstrap";
     $moduleDirectory = APP_ROOT_DIR . "etc/modules";
     /* @var DirectoryIterator $fileObj */
     foreach (new DirectoryIterator($applicationDirectory) as $fileObj) {
         if (!$fileObj->isDot() && $fileObj->isDir()) {
             $metaFile = $fileObj->getPathname() . "/meta.json";
             if (file_exists($metaFile)) {
                 $temp = json_decode(file_get_contents($metaFile), true);
                 $data = array_merge_recursive_distinct($data, $temp);
             }
         }
     }
     if (is_dir($moduleDirectory)) {
         try {
             foreach (new DirectoryIterator($moduleDirectory) as $fileObj) {
                 if (!$fileObj->isDot() && $fileObj->isFile()) {
                     $temp = json_decode(file_get_contents($fileObj->getPathname()), true);
                     $data = array_merge_recursive_distinct($data, $temp);
                 }
             }
         } catch (UnexpectedValueException $e) {
         }
     }
     $temp = json_decode(file_get_contents(APP_ROOT_DIR . 'etc/local.json'), true);
     $data = array_merge_recursive_distinct($data, $temp);
     $cacheContent = $this->setCacheFileHeader("Meta data");
     $cacheContent .= "\$lifetime=" . (TIME + $lifetime) . ";\n";
     $cacheContent .= "\$data = \"" . $this->compileContent(serialize($data)) . "\";\n";
     $cacheContent .= $this->cacheFileClose;
     $this->putCacheContent($this->cacheDir . "meta.cache.php", $cacheContent);
     return $this;
 }
Exemplo n.º 19
0
 /**
  * Load configuration file
  * @param $fileName
  * @throws \Exception
  */
 protected function loadConf($fileName)
 {
     if (is_array($fileName)) {
         foreach ($fileName as $subFile) {
             $this->loadConf($subFile);
         }
         return;
     }
     if (!file_exists($fileName)) {
         throw new \Exception('Configuration file does not exist');
     }
     $conf = Yaml::parse(file_get_contents($fileName));
     // execute requires
     if (array_key_exists('require', $conf)) {
         $require = $conf['require'];
         $reqPath = dirname($fileName) . '/';
         if (is_array($require) && count($require) > 0) {
             foreach ($require as $reqFile) {
                 $this->loadConf($reqPath . $reqFile);
             }
         }
         if (is_string($require) && strlen($require) > 0) {
             $this->loadConf($reqPath . $require);
         }
     }
     // merge configurations
     $this->conf = array_merge_recursive_distinct($this->conf, $conf);
 }
Exemplo n.º 20
0
function array_merge_recursive_distinct($arr1, $arr2)
{
    foreach ($arr2 as $key => $value) {
        if (array_key_exists($key, $arr1) && is_array($value)) {
            $arr1[$key] = array_merge_recursive_distinct($arr1[$key], $arr2[$key]);
        } else {
            $arr1[$key] = $value;
        }
    }
    return $arr1;
}
Exemplo n.º 21
0
 protected function _fetchModelInstanceData(&$rows, $eagerLoad = false, $next = true)
 {
     // If there is no eager load, we are sure that one row equals one model
     // instance.
     if (!$eagerLoad) {
         return $this->_getNextOrPendingRow($rows, $next);
     }
     // Otherwise, it is more complicated: several rows can be returned for
     // only one model instance.
     $model = $this->_root;
     $pk = array_flip($model::table()->getPrimaryKey());
     $res = array();
     $instanceId = null;
     while (($row = $this->_getNextOrPendingRow($rows, $next)) !== false) {
         // Get the ID of the row.
         $rowId = array_intersect_key($row, $pk);
         // I remind us of that we want *one* model instance: we have to stop
         // when the next row does not concern the same model instance than
         // the previous.
         if ($instanceId && $instanceId !== $rowId) {
             $this->_pendingRow = $row;
             break;
         }
         $instanceId = $rowId;
         // Parse result (parse eager load).
         $row = $this->_parseRow($row);
         // Construct result.
         $res = $res ? array_merge_recursive_distinct($res, $row) : $row;
     }
     return $res;
 }
Exemplo n.º 22
0
 /**
  * Load the configuration from the various YML files.
  */
 public function getConfig()
 {
     $config = array();
     // Read the config
     $config['general'] = array_merge($this->parseConfigYaml('config.yml'), $this->parseConfigYaml('config_local.yml'));
     $config['taxonomy'] = $this->parseConfigYaml('taxonomy.yml');
     $tempcontenttypes = $this->parseConfigYaml('contenttypes.yml');
     $config['menu'] = $this->parseConfigYaml('menu.yml');
     $config['routing'] = $this->parseConfigYaml('routing.yml');
     $config['permissions'] = $this->parseConfigYaml('permissions.yml');
     $config['extensions'] = array();
     // @todo: If no config files can be found, get them from bolt.cm/files/default/
     $this->paths = getPaths($config);
     $this->setDefaults();
     if (isset($config['general']['wysiwyg']['ck']['contentsCss'])) {
         $config['general']['wysiwyg']['ck']['contentsCss'] = array(1 => $config['general']['wysiwyg']['ck']['contentsCss']);
     }
     $config['general'] = array_merge_recursive_distinct($this->defaultconfig, $config['general']);
     // Make sure the cookie_domain for the sessions is set properly.
     if (empty($config['general']['cookies_domain'])) {
         if (isset($_SERVER['HTTP_HOST'])) {
             $hostname = $_SERVER['HTTP_HOST'];
         } elseif (isset($_SERVER['SERVER_NAME'])) {
             $hostname = $_SERVER['SERVER_NAME'];
         } else {
             $hostname = "";
         }
         // Don't set the domain for a cookie on a "TLD" - like 'localhost', or if the server_name is an IP-address
         if (strpos($hostname, ".") > 0 && preg_match("/[a-z0-9]/i", $hostname)) {
             if (preg_match("/^www[0-9]*./", $hostname)) {
                 $config['general']['cookies_domain'] = "." . preg_replace("/^www[0-9]*./", "", $hostname);
             } else {
                 $config['general']['cookies_domain'] = "." . $hostname;
             }
             // Make sure we don't have consecutive '.'-s in the cookies_domain..
             $config['general']['cookies_domain'] = str_replace("..", ".", $config['general']['cookies_domain']);
         } else {
             $config['general']['cookies_domain'] = "";
         }
     }
     // Make sure Bolt's mount point is OK:
     $config['general']['branding']['path'] = "/" . safeString($config['general']['branding']['path']);
     // Clean up taxonomies
     foreach ($config['taxonomy'] as $key => $value) {
         if (!isset($config['taxonomy'][$key]['name'])) {
             $config['taxonomy'][$key]['name'] = ucwords($config['taxonomy'][$key]['slug']);
         }
         if (!isset($config['taxonomy'][$key]['singular_name'])) {
             $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['singular_slug']);
         }
         if (!isset($config['taxonomy'][$key]['slug'])) {
             $config['taxonomy'][$key]['slug'] = strtolower(safeString($config['taxonomy'][$key]['name']));
         }
         if (!isset($config['taxonomy'][$key]['singular_slug'])) {
             $config['taxonomy'][$key]['singular_slug'] = strtolower(safeString($config['taxonomy'][$key]['singular_name']));
         }
         if (!isset($config['taxonomy'][$key]['has_sortorder'])) {
             $config['taxonomy'][$key]['has_sortorder'] = false;
         }
         // Make sure the options are $key => $value pairs, and not have implied integers for keys.
         if (!empty($config['taxonomy'][$key]['options']) && is_array($config['taxonomy'][$key]['options'])) {
             $options = array();
             foreach ($config['taxonomy'][$key]['options'] as $optionkey => $value) {
                 if (is_numeric($optionkey)) {
                     $optionkey = makeSlug($value);
                     // was: strtolower(safeString($value));
                 }
                 $options[$optionkey] = $value;
             }
             $config['taxonomy'][$key]['options'] = $options;
         }
         // If taxonomy is like tags, set 'tagcloud' to true by default.
         if ($config['taxonomy'][$key]['behaves_like'] == "tags" && !isset($config['taxonomy'][$key]['tagcloud'])) {
             $config['taxonomy'][$key]['tagcloud'] = true;
         }
     }
     // Clean up contenttypes
     $config['contenttypes'] = array();
     foreach ($tempcontenttypes as $temp) {
         if (!isset($temp['slug'])) {
             $temp['slug'] = makeSlug($temp['name']);
         }
         if (!isset($temp['singular_slug'])) {
             $temp['singular_slug'] = makeSlug($temp['singular_name']);
         }
         if (!isset($temp['show_on_dashboard'])) {
             $temp['show_on_dashboard'] = true;
         }
         if (!isset($temp['sort'])) {
             $temp['sort'] = "id";
         }
         // Make sure all fields are lowercase and 'safe'.
         $tempfields = $temp['fields'];
         $temp['fields'] = array();
         foreach ($tempfields as $key => $value) {
             // Fix name 'keys' for fields
             $key = str_replace("-", "_", strtolower(safeString($key, true)));
             $temp['fields'][$key] = $value;
             // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == "file") {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array('pdf', 'txt', 'md', 'doc', 'docx', 'zip', 'tgz');
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
         }
         // Make sure the 'uses' of the slug is an array.
         if (isset($temp['fields']['slug']) && isset($temp['fields']['slug']['uses']) && !is_array($temp['fields']['slug']['uses'])) {
             $temp['fields']['slug']['uses'] = array($temp['fields']['slug']['uses']);
         }
         // Make sure taxonomy is an array.
         if (isset($temp['taxonomy']) && !is_array($temp['taxonomy'])) {
             $temp['taxonomy'] = array($temp['taxonomy']);
         }
         $config['contenttypes'][$temp['slug']] = $temp;
     }
     // Set all the distinctive arrays as part of our Config object.
     $this->data = $config;
 }
Exemplo n.º 23
0
 public function get($name)
 {
     $type = $this->get_type($name);
     if (empty($type)) {
         throw new Exception('Type not exist');
     }
     $return = $this->get_empty($name, $type);
     switch ($type['type']) {
         case 'structure':
             $fetched = $this->fetch_structure($name, $type);
             if ($fetched !== NULL) {
                 $return = array_merge_recursive_distinct($return, $fetched);
             }
             break;
         case 'enum':
             $fetched = $this->fetch_enum($name, $type);
             if ($fetched !== NULL) {
                 $return = $fetched;
             }
             break;
         case 'text':
             $fetched = $this->fetch_text($name, $type);
             if ($fetched !== NULL) {
                 $return = $fetched;
             }
             break;
         case 'simple':
         case 'file':
             $fetched = $this->fetch($name, $type);
             if ($fetched !== NULL) {
                 $return = $fetched;
             }
             break;
     }
     return $return;
 }
Exemplo n.º 24
0
 private function _walk_through($type, $configs)
 {
     if (isset($configs["{$type}"])) {
         $this->_data["{$type}"] = array_merge_recursive_distinct($this->_data["{$type}"], $configs["{$type}"]);
     }
     return $this;
 }
Exemplo n.º 25
0
$home_dir = home_dir();
if (file_exists($home_dir . DIRECTORY_SEPARATOR . ".mooshrc.php")) {
    $moodlerc = $home_dir . DIRECTORY_SEPARATOR . ".mooshrc.php";
} elseif (file_exists("/etc/moosh/mooshrc.php")) {
    $moodlerc = "/etc/moosh/mooshrc.php";
} elseif (file_exists($home_dir . DIRECTORY_SEPARATOR . "mooshrc.php")) {
    $moodlerc = $home_dir . DIRECTORY_SEPARATOR . "mooshrc.php";
}
$options = NULL;
if ($moodlerc) {
    if (isset($app_options['verbose'])) {
        echo "Using '{$moodlerc}' as moosh runtime configuration file\n";
    }
    $options = array();
    require $moodlerc;
    $options = array_merge_recursive_distinct($defaultOptions, $options);
} else {
    $options = $defaultOptions;
}
/**
 * @var Moosh\MooshCommand $subcommand
 *
 */
$subcommand = $subcommands[$subcommand];
if ($bootstrap_level = $subcommand->bootstrapLevel()) {
    if ($bootstrap_level == MooshCommand::$BOOTSTRAP_FULL_NOCLI) {
        $_SERVER['REMOTE_ADDR'] = 'localhost';
        $_SERVER['SERVER_PORT'] = 80;
        $_SERVER['SERVER_PROTOCOL'] = 'HTTP 1.1';
        $_SERVER['SERVER_SOFTWARE'] = 'PHP/' . phpversion();
        $_SERVER['REQUEST_URI'] = '/';
Exemplo n.º 26
0
Arquivo: Core.php Projeto: VOMVC/VOMVC
/**
 *
 * Merges the second array onto the first array with distinct data for each key.
 * Essentially "replacing" the data at any recursive string from array 2, onto array 1.
 * @param (array) $array1 // To Be Replaced
 * @param (array) $array2 // Replacing With
 */
function array_merge_recursive_distinct($array1, $array2 = null)
{
    /* array_merge_recursive_distinct */
    // Start our '$merged' array as the initial $array1
    $merged = $array1;
    if (is_array($array1)) {
        if (is_array($array2)) {
            // Loop over $array2
            foreach ($array2 as $key => $val) {
                // If $val or $array2[$key] is an array
                if (is_array($array2[$key])) {
                    $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $array2[$key]) : $array2[$key];
                } else {
                    $merged[$key] = $val;
                }
            }
        }
        if (is_object($array2)) {
            $merged = $array2;
        }
    }
    if (is_bool($array1)) {
        if (is_bool($array2)) {
            $merged = $array2;
        }
    }
    if (is_null($array2)) {
        $merged = $array2;
    }
    if (is_closure($array1) && is_closure($array2)) {
        $merged = $array2;
    }
    return $merged;
}
Exemplo n.º 27
0
 /**
  * Exports variables for the VIEW to interpret.
  * @param string|array $key variable name or an array of variable names with their corresponding values.
  * @param mixed $data <b>Default</b>. Value of the variable.
  * @final
  */
 protected final function show($key, $data = null)
 {
     $key = !is_array($key) ? array($key => $data) : $key;
     $this->data = array_merge_recursive_distinct($this->data, $key);
 }
Exemplo n.º 28
0
 /**
  * Calls the function of this command with the given arguments.
  *
  * @since 4.8.1
  * @param array $args_override A different set of arguments that will override the original.
  * @return mixed The return value of the function of the command.
  * @throws CommandException If the function of the command is not callable.
  */
 public function call($args_override = array())
 {
     $args = $this->getArgs();
     $args = array_merge_recursive_distinct($args, $args_override);
     if (!is_callable($callable = $this->getFunction())) {
         throw $this->exception('Could not call function: function must be callable', array(__NAMESPACE__, 'CommandException'));
     }
     $result = call_user_func_array($callable, $args);
     return $result;
 }
Exemplo n.º 29
0
Arquivo: lib.php Projeto: LeonB/site
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 * @author Bob for bolt-specific excludes
 */
function array_merge_recursive_distinct(array &$array1, array &$array2)
{
    $merged = $array1;
    foreach ($array2 as $key => &$value) {
        // if $key = 'accept_file_types, don't merge..
        if ($key == 'accept_file_types') {
            $merged[$key] = $array2[$key];
            continue;
        }
        if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
            $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
        } else {
            $merged[$key] = $value;
        }
    }
    return $merged;
}
Exemplo n.º 30
0
 /**
  * drawBox
  * 
  * Draws a box from the co-ordinates in array start to the co-ordinates in array finish using the GD library function
  *
  * @param array $start The start point index 0 should be the x co-ordinate, 1 the y
  * @param array $finish The end point index 0 should be the x co-ordinate, 1 the y
  * @param array $options The options
  * @return mixed The result from imagerectangle()
  * @author Dom Hastings
  */
 function drawBox($start, $finish, $options = array())
 {
     // merge in the options
     $options = array_merge_recursive_distinct(is_array($this->options['box']) ? $this->options['box'] : array(), is_array($options) ? $options : array());
     imagesetthickness($this->current, $options['size']);
     if (!is_array($start) || !is_array($finish)) {
         throw new Exception('Image::drawLine: Arguments 0 and 1 must be arrays.');
     }
     list($sX, $sY, $fX, $fY) = array_merge(array_values($start), array_values($finish));
     list($r, $g, $b) = $this->hexToRGB($options['color']);
     $colour = imagecolorallocatealpha($this->current, $r, $g, $b, $options['transparency']);
     if (empty($options['filled'])) {
         if (!empty($options['style'])) {
             imagesetstyle($this->current, $options['style']);
         }
         return imagerectangle($this->current, $sX, $sY, $fX, $fY, $colour);
     } else {
         return imagefilledrectangle($this->current, $sX, $sY, $fX, $fY, $colour);
     }
 }