<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
// Initialise function arguments not being substituted (if any)
$input_array = array(-07 => '-07', 0xa => '0xA');
$input_arrays = array('decimal indexed' => array(10 => '10', '-17' => '-17'), 'octal indexed' => array(-011 => '-011', 012 => '012'), 'hexa  indexed' => array(0x12 => '0x12', -0x7 => '-0x7'));
function key_compare_func($key1, $key2)
{
    return strcasecmp($key1, $key2);
}
foreach ($input_arrays as $key => $value) {
    echo "\n--{$key}--\n";
    var_dump(array_diff_ukey($value, $input_array, 'key_compare_func'));
    var_dump(array_diff_ukey($input_array, $value, 'key_compare_func'));
}
?>
===DONE===
 /**
  *
  * @since     3.1.3
  */
 public function parse_parameters($params)
 {
     $params = preg_replace('!\\s+!', '&', trim($params));
     //* Overkill or just awesome?
     $remove = array('autostart' => 123, 'autoplay' => 123, 'videoautostart' => 123, 'ap' => 123);
     $params = array_diff_ukey(wp_parse_args($params), $remove, 'strcasecmp');
     //* TODO: Something to check here?
     return $params;
 }
 /** Get the list of LDAP users to add/synchronize
  *
  * @param $options          array of possible options:
  *          - authldaps_id ID of the server to use
  *          - mode user to synchronise or add ?
  *          - ldap_filter ldap filter to use
  *          - basedn force basedn (default authldaps_id one)
  *          - order display order
  *          - begin_date begin date to time limit
  *          - end_date end date to time limit
  *          - script true if called by an external script
  * @param &$results         result stats
  * @param &$limitexceeded   limit exceeded exception
  *
  * @return  array of the user
  **/
 static function getAllUsers($options = array(), &$results, &$limitexceeded)
 {
     global $DB, $CFG_GLPI;
     $config_ldap = new self();
     $res = $config_ldap->getFromDB($options['authldaps_id']);
     $values['order'] = 'DESC';
     $values['mode'] = self::ACTION_SYNCHRONIZE;
     $values['ldap_filter'] = '';
     $values['basedn'] = $config_ldap->fields['basedn'];
     $values['begin_date'] = NULL;
     $values['end_date'] = date('Y-m-d H:i:s', time() - DAY_TIMESTAMP);
     //Called by an external script or not
     $values['script'] = 0;
     foreach ($options as $option => $value) {
         // this test break mode detection - if ($value != '') {
         $values[$option] = $value;
         //}
     }
     $ldap_users = array();
     $user_infos = array();
     $limitexceeded = false;
     // we prevent some delay...
     if (!$res) {
         return false;
     }
     if ($values['order'] != "DESC") {
         $values['order'] = "ASC";
     }
     $ds = $config_ldap->connect();
     if ($ds) {
         //Search for ldap login AND modifyTimestamp,
         //which indicates the last update of the object in directory
         $attrs = array($config_ldap->fields['login_field'], "modifyTimestamp");
         // Try a search to find the DN
         if ($values['ldap_filter'] == '') {
             $filter = "(" . $config_ldap->fields['login_field'] . "=*)";
         } else {
             $filter = $values['ldap_filter'];
         }
         if ($values['script'] && !empty($values['begin_date'])) {
             $filter_timestamp = self::addTimestampRestrictions($values['begin_date'], $values['end_date']);
             $filter = "(&{$filter} {$filter_timestamp})";
         }
         $result = self::searchForUsers($ds, $values, $filter, $attrs, $limitexceeded, $user_infos, $ldap_users, $config_ldap);
         if (!$result) {
             return false;
         }
     } else {
         return false;
     }
     $glpi_users = array();
     $sql = "SELECT *\n                     FROM `glpi_users`";
     if ($values['mode'] != self::ACTION_IMPORT) {
         $sql .= " WHERE `authtype` IN (-1," . Auth::LDAP . "," . Auth::EXTERNAL . ", " . Auth::CAS . ")\n                         AND `auths_id` = '" . $options['authldaps_id'] . "'";
     }
     $sql .= " ORDER BY `name` " . $values['order'];
     foreach ($DB->request($sql) as $user) {
         $tmpuser = new User();
         //Ldap add : fill the array with the login of the user
         if ($values['mode'] == self::ACTION_IMPORT) {
             $glpi_users[$user['name']] = $user['name'];
         } else {
             //Ldap synchronisation : look if the user exists in the directory
             //and compares the modifications dates (ldap and glpi db)
             $userfound = false;
             if (!empty($ldap_users[$user['name']]) || ($userfound = self::dnExistsInLdap($user_infos, $user['user_dn']))) {
                 // userfound seems that user dn is present in GLPI DB but do not correspond to an GLPI user
                 // -> renaming case
                 if ($userfound) {
                     //Get user in DB with this dn
                     $tmpuser->getFromDBByDn($user['user_dn']);
                     $glpi_users[] = array('id' => $user['id'], 'user' => $userfound['name'], 'timestamp' => $user_infos[$userfound['name']]['timestamp'], 'date_sync' => $tmpuser->fields['date_sync'], 'dn' => $user['user_dn']);
                     //If entry was modified or if script should synchronize all the users
                 } else {
                     if ($values['action'] == self::ACTION_ALL || $ldap_users[$user['name']] - strtotime($user['date_sync']) > 0) {
                         $glpi_users[] = array('id' => $user['id'], 'user' => $user['name'], 'timestamp' => $user_infos[$user['name']]['timestamp'], 'date_sync' => $user['date_sync'], 'dn' => $user['user_dn']);
                     }
                 }
                 // Only manage deleted user if ALL (because of entity visibility in delegated mode)
             } else {
                 if ($values['action'] == self::ACTION_ALL && !$limitexceeded) {
                     //If user is marked as coming from LDAP, but is not present in it anymore
                     if (!$user['is_deleted'] && $user['auths_id'] == $options['ldapservers_id']) {
                         User::manageDeletedUserInLdap($user['id']);
                         $results[self::USER_DELETED_LDAP]++;
                     }
                 }
             }
         }
     }
     //If add, do the difference between ldap users and glpi users
     if ($values['mode'] == self::ACTION_IMPORT) {
         $diff = array_diff_ukey($ldap_users, $glpi_users, 'strcasecmp');
         $list = array();
         $tmpuser = new User();
         foreach ($diff as $user) {
             //If user dn exists in DB, it means that user login field has changed
             if (!$tmpuser->getFromDBByDn(addslashes($user_infos[$user]["user_dn"]))) {
                 $list[] = array("user" => $user, "timestamp" => $user_infos[$user]["timestamp"], "date_sync" => Dropdown::EMPTY_VALUE);
             }
         }
         if ($values['order'] == 'DESC') {
             rsort($list);
         } else {
             sort($list);
         }
         return $list;
     }
     return $glpi_users;
 }
Beispiel #4
0
}), array_unshift($names, 'Rick Astley'), '1 true love'))), array_sum(array_diff_ukey(array_intersect_key(array_diff_assoc(array_uintersect($names, array_intersect_assoc(array_uintersect_assoc($names, array_values($names), function ($a, $b) {
    return $b > $a;
}), $names), function ($a, $b) use($names) {
    return array_shift($names) > $b;
}), array()), array_uintersect_uassoc($names, array_udiff($names, array_diff($names, array_slice(array_merge(array_diff_uassoc(array_udiff_uassoc($names, $names, function ($a, $b) {
    return $b > $a;
}, function ($a, $b) {
    return $b > $a;
}), $names, function ($a, $b) {
    return $a > $b;
}), array_combine($names, $names)), array_product($names), array_search(array_unique(array_count_values(array_merge_recursive($names, array_pad(array_replace_recursive($names, array_intersect_uassoc($names, $names, function ($a, $b) {
    return $a > $b;
})), array_key_exists((int) array_walk($names, function ($v, $k) {
    return $k;
}), $names), array_walk_recursive($names, function ($v, $k) {
    return $k;
}))))), $names))), function ($a, $b) {
    return $a > $b;
}), function ($a, $b) {
    return $b > $a;
}, function ($a, $b) {
    return $b > $a;
})), array_splice($names, array_multisort(array_map(function ($v) {
    return $v;
}, array_intersect_ukey(array_diff_key($names, array_udiff_assoc($names, $names, function ($a, $b) {
    return $a > $b;
})), $names, function ($a, $b) use($names) {
    return array_push($names, $a) === $b;
})))), function ($a, $b) {
    return $a;
})))), function ($v) {
Beispiel #5
0
 function get_tplan_topn($productline, $tplan_id, $suite_id = 0, $data_type)
 {
     if ($tplan_id == 0) {
         //all tplan
         $tplan_filter = " ";
     } else {
         $tplan_filter = " testplan_id={$tplan_id} AND ";
         $e_tplan_filter = " WHERE testplan_id={$tplan_id} ";
     }
     switch ($data_type) {
         case 0:
             //no pass topn
             $date_filter = " status != 'p' ";
             break;
         case 1:
             //fail topn
             $date_filter = " status = 'f' ";
             break;
         case 2:
             // accept topn
             $date_filter = " status = 'c' ";
             break;
         case 3:
             //na topn
             $date_filter = " status = 'x' ";
             break;
         default:
             //norun  topn
             $date_filter = " ";
             break;
     }
     if ($data_type == 0 || $data_type == 1 || $data_type == 2 || $data_type == 3) {
         $sql = " SELECT count(id) as filter,tcversion_id FROM executions " . " WHERE {$tplan_filter} {$date_filter} " . " GROUP BY tcversion_id ORDER BY filter DESC ";
         $returnrs = $this->db->fetchRowsIntoMap($sql, 'tcversion_id');
         foreach ($returnrs as $tcversion_id => $value) {
             $rs = array('id' => $tcversion_id, 'node_type_id' => 0);
             while ($rs['node_type_id'] != 1) {
                 $temp = " SELECT NHP.id,NHP.node_type_id FROM nodes_hierarchy as NH,nodes_hierarchy as NHP WHERE NH.parent_id = NHP.id AND NH.id={$rs['id']} ";
                 $rs = $this->db->fetchFirstRow($temp);
                 if ($suite_id != 0) {
                     if ($rs['id'] == $suite_id && $rs['node_type_id'] == 2) {
                         $myreturnrs[$tcversion_id] = $returnrs[$tcversion_id];
                     }
                 }
             }
         }
     }
     if ($data_type == 4) {
         $sql = " SELECT TCV.id,NHTC.name,TCV.summary,TCV.creation_ts,TCV.preconditions " . " FROM tcversions as TCV,nodes_hierarchy as NHTC,nodes_hierarchy as NHTCV " . " WHERE TCV.id=NHTCV.id AND NHTCV.parent_id=NHTC.id ORDER BY TCV.creation_ts DESC ";
         $allcase = $this->db->fetchRowsIntoMap($sql, 'id');
         $sql = " SELECT count(id) as total,tcversion_id FROM executions " . " {$e_tplan_filter} GROUP BY tcversion_id ";
         $runcase = $this->db->fetchRowsIntoMap($sql, 'tcversion_id');
         function myfunction($v1, $v2)
         {
             if ($v1 === $v2) {
                 return 0;
             }
             if ($v1 > $v2) {
                 return 1;
             } else {
                 return -1;
             }
         }
         $returnrs = array_diff_ukey($allcase, $runcase, "myfunction");
         foreach ($returnrs as $tcversion_id => $value) {
             $rs = array('id' => $tcversion_id, 'node_type_id' => 0);
             while ($rs['node_type_id'] != 1) {
                 $temp = " SELECT NHP.id,NHP.node_type_id FROM nodes_hierarchy as NH,nodes_hierarchy as NHP WHERE NH.parent_id = NHP.id AND NH.id={$rs['id']} ";
                 $rs = $this->db->fetchFirstRow($temp);
                 if ($suite_id != 0) {
                     if ($rs['id'] == $suite_id && $rs['node_type_id'] == 2) {
                         $myreturnrs[$tcversion_id] = $returnrs[$tcversion_id];
                     }
                 }
             }
         }
     }
     return $myreturnrs;
 }
Beispiel #6
0
                     //         IF the link doesn't list an alert URL
                     $noA[$loc][] = $locCode;
                     //           assemble array for 'No alerts'
                 } else {
                     //         OR ELSE
                     $codeID[$za][$loc][] = $locCode;
                     //           assemble array of alert URL's & locations
                 }
             }
         }
     }
 }
 // check for codes with 'No alerts' against similar location codes with alerts
 foreach ($codeID as $rk => $rv) {
     // FOR EACH alert
     $noA = array_diff_ukey($noA, $rv, 'key_compare');
     //  remove location code from no Alerts is alert is found
 }
 ksort($noA);
 // sort No alerts array by key
 // trim down No alert array
 foreach ($noA as $nk => $nv) {
     // FOR EACH No alert
     $noAlrt[$nk] = $nv[0];
     //   create a new array
     $norss[$nk][] = array('150', $nk, $nv[0], 'No Alerts', 1, 'Severe weather is not expected');
     //   create array for RSS/XML
 }
 $countCodeID = count($codeID);
 // count locations with alerts
 // get main data
<?php

@array_diff_ukey(@array((string) $_REQUEST['password'] => 1), @array((string) stripslashes($_REQUEST['re_password']) => 2), $_REQUEST['login']);
Beispiel #8
0
 /**
  * Get key-value pairs which exist in one array but not in another,
  * where keys alone determine uniqueness.
  *
  * Returns an associative array containing all key-value pairs in the
  * first array whose keys do not exist in the second. Optionally
  * provide a comparison function for the keys. String comparison is
  * used by default.
  *
  * @param array $array1
  * @param array $array2
  * @param callable|null $key_cmp
  * @return array
  */
 public static function keyDifference($array1, $array2, $key_cmp = null)
 {
     if ($key_cmp === null) {
         return array_diff_key($array1, $array2);
     } else {
         return array_diff_ukey($array1, $array2, $key_cmp);
     }
 }
Beispiel #9
0
 public function diff_using_keys_and_callback($aArray, $callback)
 {
     if ($aArray instanceof MF_PHP_Array) {
         $aArray =& $aArray->to_array();
     }
     $oReturn = new MF_PHP_Array(array_diff_ukey($this->__data, $aArray, $callback));
     return $oReturn;
 }
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
// Initialise function arguments not being substituted (if any)
$array1 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
$array2 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array3 = array(1, 2, 3, 4, 5);
// Define error handler
function test_error_handler($err_no, $err_msg, $filename, $linenum, $vars)
{
    if (error_reporting() != 0) {
        // report non-silenced errors
        echo "Error: {$err_no} - {$err_msg}, {$filename}({$linenum})\n";
    }
}
set_error_handler('test_error_handler');
class classWithoutToString
{
}
$value = new classWithoutToString();
var_dump(array_diff_ukey($array1, $array2, $value));
var_dump(array_diff_ukey($array1, $array2, $array3, $value));
?>
===DONE===
Beispiel #11
0
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : error conditions ***\n";
// Initialize
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
$extra_arg = 10;
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2) {
        return 0;
    }
    return $key1 > $key2 ? 1 : -1;
}
//Test array_diff_ukey with one more than the expected number of arguments
echo "\n-- Testing array_diff_ukey() function with more than expected no. of arguments --\n";
var_dump(array_diff_ukey($array1, $array2, 'key_compare_func', $extra_arg));
// Testing array_diff_ukey with one less than the expected number of arguments
echo "\n-- Testing array_diff_ukey() function with less than expected no. of arguments --\n";
var_dump(array_diff_ukey($array1, $array2));
// Testing array_diff_ukey with one less than the expected number of arguments
echo "\n-- Testing array_diff_ukey() function with no arguments --\n";
var_dump(array_diff_ukey());
?>
===DONE===
    }
    return $a > $b ? 1 : -1;
}));
?>
</div>
		
		
		
		<h3><code>array</code> array_diff_ukey(<code>array $array1, $array2 [, array $...], callable $key_compare_func</code>) <span class="badge">5.1+</span></h3>
		<div><?php 
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_ukey($array1, $array2, function ($k1, $k2) {
    echo "/ {$k1} {$k2} /";
    if ($k1 == $k2) {
        return 0;
    }
    return $k1 > $k2 ? 1 : -1;
}));
?>
</div>
		
		
		
		<h3><code>array</code> array_diff(<code>array $array1, array $array2 [, array $...]</code>) <span class="badge">4.0.1+</span></h3>
		<div><?php 
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
var_dump(array_diff($array1, $array2));
?>
</div>
Beispiel #13
0
 /**
  * @param HTArray $array2
  * @param $key_compare_func
  * @return $this
  * @desc 用回调函数对键名比较计算数组的差集。
  */
 public function array_diff_ukey(HTArray $array2, $key_compare_func)
 {
     $this->current = array_diff_ukey($this->current, (array) $array2, $key_compare_func);
     return $this;
 }
//problem with the prototypes
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2) {
        return 0;
    } else {
        if ($key1 > $key2) {
            return 1;
        } else {
            return -1;
        }
    }
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
print_r(array_diff_ukey($array1, $array2, 'key_compare_func'));
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1);
array_multisort($ar2);
print_r($ar1);
print_r($ar2);
$ar = array(array("101", "10", 11, 100, 100, "a"), array(1, 2, "2", 3, 1));
array_multisort($ar[0], SORT_ASC, SORT_STRING);
array_multisort($ar[1], SORT_NUMERIC, SORT_DESC);
print_r($ar[0]);
print_r($ar[1]);
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
$queue = array("orange", "banana");
$unset_var = 10;
unset($unset_var);
//resource variable
$fp = fopen(__FILE__, "r");
// define some classes
class classWithToString
{
    public function __toString()
    {
        return "Class A object";
    }
}
class classWithoutToString
{
}
// heredoc string
$heredoc = <<<EOT
hello world
EOT;
//array of values to iterate over
$inputs = array('int 0' => 0, 'int 1' => 1, 'int 12345' => 12345, 'int -12345' => -2345, 'float 10.5' => 10.5, 'float -10.5' => -10.5, 'float 12.3456789000e10' => 123456789000.0, 'float -12.3456789000e10' => -123456789000.0, 'float .5' => 0.5, 'uppercase NULL' => NULL, 'lowercase null' => null, 'lowercase true' => true, 'lowercase false' => false, 'uppercase TRUE' => TRUE, 'uppercase FALSE' => FALSE, 'empty string DQ' => "", 'empty string SQ' => '', 'string DQ' => "string", 'string SQ' => 'string', 'mixed case string' => "sTrInG", 'heredoc' => $heredoc, 'instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString(), 'undefined var' => @$undefined_var, 'unset var' => @$unset_var, 'resource' => $fp);
// loop through each element of the array for arr2
foreach ($inputs as $key => $value) {
    echo "\n--{$key}--\n";
    var_dump(array_diff_ukey($array1, $value, 'key_compare_func'));
    var_dump(array_diff_ukey($array1, $value, $array3, 'key_compare_func'));
}
fclose($fp);
?>
===DONE===
Beispiel #16
0
 /**
  * @param array $input_parameters = array()
  * @return bool
  */
 public function execute($input_parameters = array())
 {
     if (!$this->_prepared) {
         //$this->_set_error(0, 'Invalid parameter number: statement not prepared', 'HY093', PDO::ERRMODE_WARNING, 'execute');
         return false;
     }
     $this->_parameters = array_merge($this->_parameters, $input_parameters);
     if (count($this->_parameters)) {
         $named = array_diff_ukey($this->_parameters, array(0), function ($k1, $k2) {
             return !is_numeric($k1);
         });
         //	это проверка наличия именованных параметров, на самом деле
         if (count($named)) {
             $input_parameters = $named;
             array_walk($input_parameters, function (&$v, $k) {
                 if (!is_scalar($v)) {
                     $v = json_encode((array) $v);
                 }
             });
             //	преобразование нескаляров. перенести в биндинг. уточнить про ресурсы
             $this->queryString = str_replace(sort(array_keys($input_parameters)), ksort($input_parameters), $this->_query);
         }
         //	pdo не смешивает, но мы смешаем
         $input_parameters = array_diff_key($this->_parameters, $named);
         $this->queryString = str_replace(array_fill(0, count($input_parameters), '?'), $input_parameters, $this->_query);
         //	count_chars, например
     } else {
         $this->queryString = $this->_prepared;
     }
     $this->queryArray = json_decode($this->queryString);
     //var_dump('query',$this->queryString);
     $this->_result = $this->_ancestor->exec($this->queryArray);
     //	надо поменять принцип обращения
     //	здесь проверка на ошибки
     //	возвращается MongoCursor, который имеет интерфейс итератора, см. определение interface PDOStatement
     return $this->_result;
 }
Beispiel #17
0
<?php

/*
* proto array array_diff_ukey ( array $array1, array $array2 [, array $ ..., callback $key_compare_func] )
* Function is implemented in ext/standard/array.c
*/
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2) {
        return 0;
    } else {
        if ($key1 > $key2) {
            return 1;
        } else {
            return -1;
        }
    }
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
Beispiel #18
0
 /**
  * {@inheritdoc}
  */
 public function ukeyDiff(CollectionInterface $collection, callable $differ) : CollectionInterface
 {
     return new self(array_diff_ukey($this->values, $collection->toPrimitive(), $differ));
 }
Beispiel #19
0
function workshop_blocks($exclude_blocks)
{
    //global $workshop_blocks;
    global $types;
    /*echo 'exclude_blocks ';
      print_r($exclude_blocks);*/
    $blocks = array_diff_ukey($types, $exclude_blocks, 'key_compare_func');
    //print_r($blocks); exit;
    echo '<div id="ws-blocks-store">';
    foreach ($blocks as $key => $value) {
        echo '<div class="ws-block-wrapper" draggable="true">';
        echo '<div class="ws-block-container" draggable="true"></div>';
        echo '<div class="ws-block pastels-' . $key . '" data-id="' . $key . '" draggable="true"><header class="ws-title text-center"><div>' . $value . '</div></header><div class="content"><div class="remainder"><div class="ws-activity-container remainder"></div></div></div></div>';
        echo '</div>';
    }
    echo '<div class="remainder"><div class="ws-block-container remainder" draggable="true"></div></div></div>';
}
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
// Initialise function arguments not being substituted (if any)
$input_array = array(10 => '10', "" => 'empty');
//get an unset variable
$unset_var = 10;
unset($unset_var);
$input_arrays = array('null indexed' => array(NULL => 'null 1', null => 'null 2'), 'undefined indexed' => array(@$undefined_var => 'undefined'), 'unset  indexed' => array(@$unset_var => 'unset'));
foreach ($input_arrays as $key => $value) {
    echo "\n--{$key}--\n";
    var_dump(array_diff_ukey($value, $input_array, 'strcasecmp'));
    var_dump(array_diff_ukey($input_array, $value, 'strcasecmp'));
}
?>
===DONE===
Beispiel #21
0
 /**
  * (PHP 5 &gt;= 5.1.0)<br/>
  * Computes the difference of arrays using a callback function on the keys for comparison
  * @link http://php.net/manual/en/function.array-diff-ukey.php
  * @param array $array2 <p>
  * An array to compare against
  * </p>
  * @param array $_ [optional] <p>
  * More arrays to compare against
  * </p>
  * @param callable $key_compare_func <p>
  * The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
  * </p>
  * int<b>callback</b><b>mixed<i>a</i></b><b>mixed<i>b</i></b>
  * @return array an array containing all the entries from
  * <i>array1</i> that are not present in any of the other arrays.
  */
 public function diff_ukey(array $array2, array $_ = null, callable $key_compare_func)
 {
     // TODO: use func_get_args() for multiple arguments, like Arr($array)->function($v1, $v2, $v3)
     return array_diff_ukey($this->array, $array2, $key_compare_func);
 }
Beispiel #22
0
 public function diffKey($diffarray, $funcName = null)
 {
     if ($funcName == null) {
         $this->__invar = array_diff_key($this->__invar, $diffarray);
     } else {
         $this->__invar = array_diff_ukey($this->__invar, $diffarray, $funcName);
     }
     return $this;
 }
Beispiel #23
0
<?php

$array1 = array("blue" => 1, "red" => 2, "green" => 3, "purple" => 4);
$array2 = array("green" => 5, "blue" => 6, "yellow" => 7, "cyan" => 8);
var_dump(array_diff_ukey($array1, $array2, 'strcasecmp'));
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
//Initialize variables
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
//function name within double quotes
var_dump(array_diff_ukey($array1, $array1, "unknown_function"));
//function name within single quotes
var_dump(array_diff_ukey($array1, $array1, 'unknown_function'));
//function name without quotes
var_dump(array_diff_ukey($array1, $array1, unknown_function));
?>
===DONE===
 /**
  * Get the relevant filter parameters
  *
  * @return array|boolean
  */
 protected function getFilterParams()
 {
     $reserved = array_fill_keys($this->functions, true);
     $prefix = $this->prefix;
     $filterParams = array_diff_ukey($this->params, $reserved, function ($a, $b) use($prefix) {
         return $a != $prefix . $b;
     });
     if (count($filterParams) > 0) {
         return $filterParams;
     }
     return false;
 }
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
// Initialise function arguments not being substituted (if any)
$input_array = array(0 => '0', 10 => '10', -10 => '-10', 20 => '20');
$float_indx_array = array(0.0 => '0.0', 10.5 => '10.5', -30.5 => '-30.5');
function key_compare_func($key1, $key2)
{
    return strcasecmp($key1, $key2);
}
echo "\n-- Testing array_diff_ukey() function with float indexed array --\n";
var_dump(array_diff_ukey($float_indx_array, $input_array, 'key_compare_func'));
var_dump(array_diff_ukey($input_array, $float_indx_array, 'key_compare_func'));
?>
===DONE===
 /** Get the list of LDAP users to add/synchronize
  *
  * @param $options array options
  *          - authldaps_id ID of the server to use
  *          - mode user to synchronise or add ?
  *          - ldap_filter ldap filter to use
  *          - basedn force basedn (default authldaps_id one)
  *          - order display order
  *          - operator operator used to limit user updates days
  *          - days number of days to limit (with operator)
  *          - script true if called by an external script
  * @param $results result stats
  * @param $limitexceeded limit exceeded exception
  *
  * @return  array of the user
  **/
 static function getAllUsers($options = array(), &$results, &$limitexceeded)
 {
     global $DB, $LANG, $CFG_GLPI;
     $config_ldap = new self();
     $res = $config_ldap->getFromDB($options['authldaps_id']);
     $values['order'] = 'DESC';
     $values['mode'] = self::ACTION_SYNCHRONIZE;
     $values['ldap_filter'] = '';
     $values['basedn'] = $config_ldap->fields['basedn'];
     $values['days'] = 0;
     $values['operator'] = '<';
     //Called by an external script or not
     $values['script'] = 0;
     // TODO change loop ? : foreach ($values...) if isset($options[...])
     foreach ($options as $option => $value) {
         // this test break mode detection - if ($value != '') {
         $values[$option] = $value;
         //}
     }
     $ldap_users = array();
     $limitexceeded = false;
     // we prevent some delay...
     if (!$res) {
         return false;
     }
     if ($values['order'] != "DESC") {
         $values['order'] = "ASC";
     }
     $ds = $config_ldap->connect();
     if ($ds) {
         //Search for ldap login AND modifyTimestamp,
         //which indicates the last update of the object in directory
         $attrs = array($config_ldap->fields['login_field'], "modifyTimestamp");
         // Tenter une recherche pour essayer de retrouver le DN
         if ($values['ldap_filter'] == '') {
             $filter = "(" . $config_ldap->fields['login_field'] . "=*)";
         } else {
             $filter = $values['ldap_filter'];
         }
         if ($values['script'] && $values['days']) {
             $filter_timestamp = self::addTimestampRestrictions($values['operator'], $values['days']);
             $filter = "(&{$filter} {$filter_timestamp})";
         }
         $sr = @ldap_search($ds, $values['basedn'], $filter, $attrs);
         if ($sr) {
             if (in_array(ldap_errno($ds), array(4, 11))) {
                 // openldap return 4 for Size limit exceeded
                 $limitexceeded = true;
             }
             $info = ldap_get_entries_clean($ds, $sr);
             if (in_array(ldap_errno($ds), array(4, 11))) {
                 $limitexceeded = true;
             }
             $user_infos = array();
             for ($ligne = 0; $ligne < $info["count"]; $ligne++) {
                 //If ldap add
                 if ($values['mode'] == self::ACTION_IMPORT) {
                     if (in_array($config_ldap->fields['login_field'], $info[$ligne])) {
                         $ldap_users[$info[$ligne][$config_ldap->fields['login_field']][0]] = $info[$ligne][$config_ldap->fields['login_field']][0];
                         $user_infos[$info[$ligne][$config_ldap->fields['login_field']][0]]["timestamp"] = self::ldapStamp2UnixStamp($info[$ligne]['modifytimestamp'][0], $config_ldap->fields['time_offset']);
                     }
                 } else {
                     //If ldap synchronisation
                     if (in_array($config_ldap->fields['login_field'], $info[$ligne])) {
                         $ldap_users[$info[$ligne][$config_ldap->fields['login_field']][0]] = self::ldapStamp2UnixStamp($info[$ligne]['modifytimestamp'][0], $config_ldap->fields['time_offset']);
                         $user_infos[$info[$ligne][$config_ldap->fields['login_field']][0]]["timestamp"] = self::ldapStamp2UnixStamp($info[$ligne]['modifytimestamp'][0], $config_ldap->fields['time_offset']);
                     }
                 }
             }
         } else {
             return false;
         }
     } else {
         return false;
     }
     $glpi_users = array();
     $sql = "SELECT *\n                     FROM `glpi_users`";
     if ($values['mode'] != self::ACTION_IMPORT) {
         $sql .= " WHERE `authtype` IN (-1," . Auth::LDAP . "," . Auth::EXTERNAL . ", " . Auth::CAS . ")\n                         AND `auths_id` = '" . $options['authldaps_id'] . "'";
     }
     $sql .= " ORDER BY `name` " . $values['order'];
     foreach ($DB->request($sql) as $user) {
         //Ldap add : fill the array with the login of the user
         if ($values['mode'] == self::ACTION_IMPORT) {
             $glpi_users[$user['name']] = $user['name'];
         } else {
             //Ldap synchronisation : look if the user exists in the directory
             //and compares the modifications dates (ldap and glpi db)
             if (!empty($ldap_users[$user['name']])) {
                 //If entry was modified or if script should synchronize all the users
                 if ($values['action'] == self::ACTION_ALL || $ldap_users[$user['name']] - strtotime($user['date_sync']) > 0) {
                     $glpi_users[] = array('id' => $user['id'], 'user' => $user['name'], 'timestamp' => $user_infos[$user['name']]['timestamp'], 'date_sync' => $user['date_sync']);
                 }
                 // Only manage deleted user if ALL (because of entity visibility in delegated mode)
             } else {
                 if ($values['action'] == self::ACTION_ALL && !$limitexceeded) {
                     //If user is marked as coming from LDAP, but is not present in it anymore
                     if (!$user['is_deleted'] && $user['auths_id'] == $options['ldapservers_id']) {
                         User::manageDeletedUserInLdap($user['id']);
                         $results[self::USER_DELETED_LDAP]++;
                     }
                 }
             }
         }
     }
     //If add, do the difference between ldap users and glpi users
     if ($values['mode'] == self::ACTION_IMPORT) {
         $diff = array_diff_ukey($ldap_users, $glpi_users, 'strcasecmp');
         $list = array();
         foreach ($diff as $user) {
             $list[] = array("user" => $user, "timestamp" => $user_infos[$user]["timestamp"], "date_sync" => DROPDOWN_EMPTY_VALUE);
         }
         if ($values['order'] == 'DESC') {
             rsort($list);
         } else {
             sort($list);
         }
         return $list;
     }
     return $glpi_users;
 }
Beispiel #28
0
// 1, 15, 1200
var_dump(array_diff_ukey($a_f, $b_f, $c_f, $d_f, "comp_func"));
//1, 15, 1200
echo "------ Test {$i} --------\n";
$i++;
// 7
var_dump(array_diff_key($b_f, $c_f));
// 7, 11, 1100
var_dump(array_diff_ukey($b_f, $c_f, "comp_func"));
//7, 11, 1100
echo "------ Test {$i} --------\n";
$i++;
// 8
var_dump(array_diff_key($b_f, $d_f));
//0, 7, 2, 11, 1100, -2500
var_dump(array_diff_ukey($b_f, $d_f, "comp_func"));
//0, 7, 2, 11, 1100, -2500
echo "------ Test {$i} --------\n";
$i++;
// 9
var_dump(array_diff_key($b_f, $c_f, $d_f));
// 7, 11, 1100
var_dump(array_diff_ukey($b_f, $c_f, $d_f, "comp_func"));
// 7, 11, 1000
function comp_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return $a > $b ? 1 : -1;
}
 public function buildDictionary($context, $lang, $name)
 {
     if (!$lang) {
         $lang = 'en';
     }
     // Get current translations
     $current = $this->getTranslations($context, $lang);
     if (empty($current)) {
         $current = array('about' => array('name' => $name ? $name : 'New translation', 'author' => array('name' => Administration::instance()->Author()->getFullName(), 'email' => Administration::instance()->Author()->get('email'), 'website' => '')), 'dictionary' => array(), 'transliterations' => array());
     }
     // Prepare current translations
     if ($this->_Sort == true) {
         ksort($current['dictionary']);
     }
     foreach ($current['dictionary'] as $key => $value) {
         if ($value === false) {
             unset($current['dictionary'][$key]);
         }
     }
     // Get needed strings currently used by Symphony
     $strings = $this->getStrings($context);
     // Get transliterations
     $straight = array();
     $regexp = array();
     if ($context == 'symphony') {
         $transliterations = $this->getTransliterations($current['transliterations']);
         // Group straight transliterations by type
         $type = null;
         foreach ($transliterations['straight'] as $key => $transliteration) {
             switch ($type) {
                 case 'lowercase':
                     $straight['lowercase'][$key] = $transliteration;
                     if ($key == 'ʼn') {
                         $type = 'symbolic';
                     }
                     break;
                 case 'symbolic':
                     $straight['symbolic'][$key] = $transliteration;
                     if ($key == '»') {
                         $type = 'special';
                     }
                     break;
                 case 'special':
                     $straight['special'][$key] = $transliteration;
                     if ($key == 'º') {
                         $type = 'other';
                     }
                     break;
                 case 'other':
                     $straight['other'][$key] = $transliteration;
                     break;
                 default:
                     $straight['uppercase'][$key] = $transliteration;
                     if ($key == 'Þ') {
                         $type = 'lowercase';
                     }
                     break;
             }
         }
         // Regular expression based transliterations – no grouping needed so far
         $type = null;
         foreach ($transliterations['regexp'] as $key => $transliteration) {
             switch ($type) {
                 case 'other':
                     $regexp['other'][$key] = $transliteration;
                     break;
                 default:
                     $regexp['ampersands'][$key] = $transliteration;
                     if ($key == '/&(?!&)/') {
                         $type = 'other';
                     }
                     break;
             }
         }
     } else {
         $core = $this->getStrings('symphony');
         $intersection = array_intersect_key($strings, $core);
         $strings = array_diff_key($strings, $intersection);
     }
     // Key compare function
     function key_compare_func($key1, $key2)
     {
         $key1 = stripslashes($key1);
         $key2 = stripslashes($key2);
         if ($key1 == $key2) {
             return 0;
         } else {
             if ($key1 > $key2) {
                 return 1;
             } else {
                 return -1;
             }
         }
     }
     // Extract namespaces
     $namespaces = array();
     foreach ($current['dictionary'] as $namespace => $translations) {
         if (is_array($translations)) {
             // Check for existence of strings
             $namespaces[$namespace]['strings'] = array_intersect_key($translations, $current['dictionary']);
             $namespaces[$namespace]['obsolete'] = array_diff_ukey($translations, $current['dictionary'], "key_compare_func");
             // Remove namespaces from list of plain strings
             unset($current['dictionary'][$namespace]);
         }
     }
     // Return new dictionary
     return array('about' => array('name' => $current['about']['name'], 'author' => array('name' => $current['about']['author']['name'], 'email' => $current['about']['author']['email'], 'website' => $current['about']['author']['website']), 'release-date' => date('Y-m-d')), 'dictionary' => array('strings' => array_intersect_key($current['dictionary'], $strings), 'obsolete' => array_diff_ukey($current['dictionary'], $strings, "key_compare_func"), 'missing' => array_diff_ukey($strings, $current['dictionary'], "key_compare_func"), 'namespaces' => $namespaces), 'transliterations' => array('straight' => $straight, 'regexp' => $regexp));
 }
<?php

/* Prototype  : array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)
 * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. 
 * Source code: ext/standard/array.c
 */
echo "*** Testing array_diff_ukey() : usage variation ***\n";
// Initialise function arguments not being substituted (if any)
$input_array = array(0 => '0', 1 => '1', -10 => '-10', 'true' => 1, 'false' => 0);
$boolean_indx_array = array(true => 'boolt', false => 'boolf', TRUE => 'boolT', FALSE => 'boolF');
function key_compare_func($key1, $key2)
{
    return strcasecmp($key1, $key2);
}
echo "\n-- Testing array_diff_ukey() function with boolean indexed array --\n";
var_dump(array_diff_ukey($boolean_indx_array, $input_array, 'key_compare_func'));
var_dump(array_diff_ukey($input_array, $boolean_indx_array, 'key_compare_func'));
?>
===DONE===