public static function fmap(callable $f, $a) { assert($a instanceof Instance, 'Second argument must be Writer'); return bind($a, function ($inner) use($f) { return Monad\Writer::ret($f($inner)); }); }
/** * Checks whether the form builder is validated after validation. * * @access private * @return boolean * * @author Etienne de Longeaux <*****@*****.**> * @since 2012-09-11 */ private function isSubmitted() { if ($this->getName() == $this->_id_form) { if ($this->getTypeForm() == "zend") { $form_instance = $this->container->get('request')->query->get('form_instance'); if ($form_instance) { $instance = App_Tools_Post::get('form_instance'); if ($this->_session->_isValidInstance($instance)) { // IMPORTANT :: permet d'éviter qu'une instance soit utilisé par un robot pour lancer x fois un même formulaire $this->_session->_removeInstance($instance); return true; } } return false; } elseif ($this->getTypeForm() == "symfony") { $request = $this->container->get('request'); if ($request->getMethod() == 'POST') { // we apply the pre event bind request $this->preEventBindRequest(); // we bind the form $this->_form->bind($request); if ($this->_form->isValid()) { return true; } else { return false; } } return false; } } return false; }
/** * Internal function used for the main currying functionality * @param callable $fn * @param $appliedArgs * @param $requiredParameters * @return callable */ function _curry(callable $fn, $appliedArgs, $requiredParameters) { return function (...$args) use($fn, $appliedArgs, $requiredParameters) { $originalArgs = $appliedArgs; $newArgs = $args; array_push($appliedArgs, ...$args); // Get the number of arguments currently applied $appliedArgsCount = count(array_filter($appliedArgs, function ($v) { if ($v instanceof Placeholder) { return false; } return true; })); // If we have the required number of arguments call the function if ($appliedArgsCount >= $requiredParameters) { foreach ($appliedArgs as $k => $v) { if ($v instanceof Placeholder) { $appliedArgs[$k] = array_shift($newArgs); unset($appliedArgs[count($originalArgs) + $k]); } } return $fn(...$appliedArgs); // If we will have the required arguments on the next call, return an optimized function } elseif ($appliedArgsCount + 1 === $requiredParameters) { return bind($fn, ...$appliedArgs); // Return the standard full curry } else { return _curry($fn, $appliedArgs, $requiredParameters); } }; }
function test_reduce_two_parameters() { $make_strlen = bind(__NAMESPACE__ . '\\bind', 'strlen', 'asdf'); $expect = strlen('asdf'); $strlen = $make_strlen(); $actual = $strlen(); $this->assertEquals($expect, $actual); }
public function create_user($username, $password) { Db::bind("username", $username); Db: bind("password", $password); $response = Db::query("INSERT INTO users (username, password) VALUES(:username, :password)"); if ($response) { return true; } else { return false; } }
/** * Internal function used for the main currying functionality * @param callable $fn * @param $appliedArgs * @param $requiredParameters * @return callable */ function _curry(callable $fn, $appliedArgs, $requiredParameters) { return function (...$args) use($fn, $appliedArgs, $requiredParameters) { array_push($appliedArgs, ...$args); // Get the number of arguments currently applied $appliedArgsCount = count($appliedArgs); // If we have the required number of arguments call the function if ($appliedArgsCount >= $requiredParameters) { return $fn(...$appliedArgs); // If we will have the required arguments on the next call, return an optimized function } elseif ($appliedArgsCount + 1 === $requiredParameters) { return bind($fn, ...$appliedArgs); // Return the standard full curry } else { return _curry($fn, $appliedArgs, $requiredParameters); } }; }
{ bnick(rand_name()); } bind('raw_002_handle', 'raw002'); function raw_002_handle($user, $params) { ircserver('set', $user); return; } function ircserver() { global $ircserver; if (func_num_args() == 2 && func_get_arg(0) == 'set') { $ircserver = func_get_arg(1); } return $ircserver; } bind('WhoisHandle', 'raw311'); function WhoisHandle($user, $params) { array_shift($params); // this is bot's nick, not useful $arr['nick'] = array_shift($params); $arr['ident'] = array_shift($params); $arr['host'] = array_shift($params); array_shift($params); // useless * $arr['ircname'] = strip_colon_and_join($params); return $arr; } echo ">> Raw module loaded \n";
/** * @expectedException InvalidArgumentException * @expectedExceptionMessage Cannot resolve parameter placeholder at position 0. Parameter stack is empty */ public function testStringConversion() { $add = $this->createAddFunction(); $addTwo = bind($add, …(), 2); $addTwo(); }
/** * Maps a callback or invokes a callback for requests * on $pattern. If $callback is not set, $pattern * is matched against all routes for $method, and the * the mapped callback for the match is invoked. If $callback * is set, that callback is mapped against $pattern for $method * requests. * * @param string $method HTTP request method or method + path * @param string $pattern path or callback * @param callable $callback optional, handler to map * * @return void */ function on($method, $path, $callback = null) { // state (routes and cache util) static $routes = array(); $regexp = null; $path = trim($path, '/'); // a callback was passed, so we create a route definition if (is_callable($callback)) { // if we're inside a resouce, use the path if (strlen($pref = prefix())) { $path = trim("{$pref}/{$path}", '/'); } // add bracketed optional sections and "match anything" $path = str_replace(array(')', '*'), array(')?', '.*?'), $path); // revised regex that allows named capture groups with optional regexes // (uses @ to separate param name and regex) $regexp = preg_replace_callback('#:([\\w]+)(@([^/\\(\\)]*))?#', function ($matches) { // 2 versions of named capture groups: // with and without a following regex. if (isset($matches[3])) { return '(?P<' . $matches[1] . '>' . $matches[3] . ')'; } else { return '(?P<' . $matches[1] . '>[^/]+)'; } }, $path); $method = array_map('strtoupper', (array) $method); foreach ($method as $m) { $routes[$m]['@^' . $regexp . '$@'] = $callback; } return; } // setup method and rexp for dispatch $method = strtoupper($method); // cache miss, do a lookup $finder = function ($routes, $path) { $found = false; foreach ($routes as $regexp => $callback) { if (preg_match($regexp, $path, $values)) { return array($regexp, $callback, $values); } } return array(null, null, null); }; // lookup a matching route if (isset($routes[$method])) { list($regexp, $callback, $values) = $finder($routes[$method], $path); } // if no match, try the any-method handlers if (!$regexp && isset($routes['*'])) { list($regexp, $callback, $values) = $finder($routes['*'], $path); } // we got a match if ($regexp) { // construct the params for the callback $tokens = array_filter(array_keys($values), 'is_string'); $values = array_map('urldecode', array_intersect_key($values, array_flip($tokens))); // setup + dispatch ob_start(); params($values); filter($values); before($method, "@{$path}"); // adjust $values array to suit the number of args that the callback is expecting. // null padding is added to the array to stop error if optional args don't match // the number of parameters. $ref = new ReflectionFunction($callback); $num_args_expected = $ref->getNumberOfParameters(); // append filler array. (note: can't call array_fill with zero quantity - throws error) $values += ($diff = $num_args_expected - count($values)) > 0 ? array_fill(0, $diff, null) : array(); call_user_func_array($callback, array_values(bind($values))); after($method, $path); $buff = ob_get_clean(); if ($method !== 'HEAD') { echo $buff; } } else { error(404); } }
send_file('./README.md', 'readme.txt', 60 * 60 * 24 * 365); }); prefix('books', function () { on('GET', '/list', function () { echo "book list"; }); prefix('chapters', function () { on('GET', '/list', function () { echo "chapter list"; }); }); }); bind('hashable', function ($hashable) { return md5($hashable); }); on('GET', '/md5/:hashable', function ($hash) { echo $hash . '-' . params('hashable'); }); bind('author', function ($name) { return strtoupper($name); }); bind('title', function ($title) { return sprintf('%s by %s', strtoupper($title), bind('author')); }); on('GET', '/authors/:author/books/:title', function ($author, $title) { echo $title; }); on('GET', '/list', function () { echo "different list"; }); dispatch();
} break; case "detect_by_openid": if (usernameAvailable($username)) { $userId = insertUserRow($username, $email); $user->session_create($userId); } else { trigger_error("Username unavailable, please login with your openid make another choice."); } break; case "bind_existed": default: $password = request_var('password', '', true); $result = $auth->login($username, $password, false, 1, false); if ($result['status'] == LOGIN_SUCCESS) { $userId = bind($username); $user->session_create($result["user_row"]["user_id"]); } else { trigger_error("Authenticate failed, please login with your openid and retry."); } break; } header("Location: index.php"); } else { trigger_error("Access denied, please login with your openid first."); } function usernameAvailable($username) { global $db; $sql = "SELECT user_id\n FROM " . USERS_TABLE . "\n WHERE username = '******' "; if (!($result = $db->sql_query($sql))) {
/** * Bind event to this model. */ function bind($event, $callback, $level = 0) { return bind(get_class($this), $event, $callback, $level); }
it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ $nspass = "******"; $debug = "on"; // debug on/off $debugchan = "#debug"; bind('nsident', "NOTICE"); function nsident($user, $whom, $msg) { global $nspass, $debugchan; if (get_nick($user) == "NS") { if ("This nickname is owned by someone else" == $msg) { msg("NS", "identify {$nspass}"); irclog("NS", "Trying to identify myself"); msg($debugchan, "trying to id"); } elseif ("Password accepted - you are now recognized" == $msg) { irclog("NS", "Identification successful, yuppie!"); if ($debug == "on") { msg($debugchan, "Identification successful: yuppie!"); } msg("CS", "op all"); } elseif ("Password Incorrect" == $msg) {
} function count_words($str) { return count(preg_split('/\\s+/', strip_tags($str), null, PREG_SPLIT_NO_EMPTY)); } function pluralise($amount, $str, $alt = '') { return intval($amount) === 1 ? $str : $str . ($alt !== '' ? $alt : 's'); } function relative_time($date) { $elapsed = time() - $date; if ($elapsed <= 1) { return 'Just now'; } $times = array(31104000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second'); foreach ($times as $seconds => $title) { $rounded = $elapsed / $seconds; if ($rounded > 1) { $rounded = round($rounded); return $rounded . ' ' . pluralise($rounded, $title) . ' ago'; } } } /** * Binding custom functions * This is just an example of what can be done */ bind('about', function () { return 'about page'; });
* enabled: true * gateway: stripe * secret_key: <stripe-secret-key> * publishable_key: <stripe-publishable-key> */ bind('payments', 'post', function ($event, $model) { $data =& $event['data']; // Is this payment method card, status pending? if ($data['method'] != 'card' || $data['status'] != 'pending') { return; } // Get card payment settings. $settings = get("/settings/payments/card"); // Is card payment enabled? Is the gateway stripe? if ($settings['enabled'] && $settings['gateway'] == 'stripe') { try { // Process stripe payment data. $data = fwd_stripe_process($data, $settings); } catch (Exception $e) { $model->error($e->getMessage(), 'method'); return false; } } // Success or pass. return; }); /** * Prepare stripe data for processing. */ function fwd_stripe_prepare($data, $settings) {
(at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Public/private commands for slappy. Use /msg <#chan,botnick> <cmd> or /notice <botnick> <cmd> Currently support the commands: server, join, part, action, do, bindings, rehash (not done yet), quit, die, mysql (not ready yet). */ bind('pubcmd', "PRIVMSG", "NOTICE"); function pubcmd($user, $whom, $msg) { global $bnick, $version; $params = explode(" ", $msg); if (ereg("^#", $whom)) { // if they're calling the bot in a channel $mecalled = array_shift($params); // getting bots nick out } else { // private msg to the bot $mecalled = $bnick; $whom = get_nick($user); } $command = strtoupper(array_shift($params)); if ($mecalled == $bnick) {
/** * Maps a callback or invokes a callback for requests * on $pattern. If $callback is not set, $pattern * is matched against all routes for $method, and the * the mapped callback for the match is invoked. If $callback * is set, that callback is mapped against $pattern for $method * requests. * * @param string $method HTTP request method or method + path * @param string $pattern path or callback * @param callable $callback optional, handler to map * * @return void */ function on($method, $path, $callback = null) { // callback map by request type static $routes = array('HEAD' => array(), 'GET' => array(), 'POST' => array(), 'PUT' => array(), 'PATCH' => array(), 'DELETE' => array()); // we don't want slashes on ends $path = trim($path, '/'); // a callback was passed, so we create a route definition if (is_callable($callback)) { // if we're inside a resouce, use the path if (strlen($pref = prefix())) { $path = trim("{$pref}/{$path}", '/'); } // create the regex for this route $regex = preg_replace('@:(\\w+)@', '(?<\\1>[^/]+)', $path); // create the list of methods to map to $method = (array) $method; // wildcard method means for all supported methods if (!in_array('*', $method)) { $method = array_intersect(array_keys($routes), array_map('strtoupper', $method)); } else { $method = array_keys($routes); } // create a route entry for this path on every method foreach ($method as $m) { $routes[$m][$path] = array('regex' => '@^' . $regex . '$@', 'callback' => $callback); } // exit early return; } // we're in a routing call, so normalize and search $method = strtoupper($method); // check for method support or routes for method !in_array($method, array_keys($routes)) && error(400, 'Method not supported'); !isset($routes[$method]) && error(404, 'Page not found'); // callback is null, so this is a route invokation. look up the callback. foreach ($routes[$method] as $pattern => $info) { // skip non-matching routes if (!preg_match($info['regex'], $path, $values)) { continue; } // construct the params for the callback array_shift($values); preg_match_all('@:([\\w]+)@', $pattern, $symbols); $symbols = $symbols[1]; $values = array_intersect_key($values, array_flip($symbols)); // decode values $values = array_map('urldecode', $values); // if we have symbols, init params and run filters if (count($symbols)) { params($values); filter($values); $values = bind($values); } // call our before filters before($method, $path); // invoke callback call_user_func_array($info['callback'], array_values($values)); // call our after filters after($method, $path); return; } // if we got here, then we didn't get a route error(404, 'Page not found'); }
return; } // Expire time? if (is_numeric($query['expire'])) { $expire = (int) $query['expire']; } return $memcache->set($id, $result, $expire ?: 0) ? $result : false; }); bind('cache', 'delete', function ($result, $id) { if (!$id || !($memcache = fwd_memcache_connect())) { return; } $value = $memcache->get($id); $target =& $value; foreach ((array) $stack as $index) { if (!is_array($target)) { $target = array($target); } $target =& $target[$index]; } $target = null; return $memcache->set($id, $value); }); function fwd_memcache_connect() { static $memcache; static $connected; // Already connected? if ($connected) { return $memcache; }
$rdata['return_type'] = $matches[1][0]; } if (preg_match_all('/class="methodparam"><span class="type">(.*?)<\\/span>[\\s]*<tt class="parameter reference">(.*?)<\\/tt>/', $data, $matches)) { array_shift($matches); $fargs = array(); for ($i = 0; $i < count($matches); $i += 2) { $fargs[] = $matches[$i][0] . ' ' . $matches[$i + 1][0]; } $rdata['args'] = $fargs; } return count($rdata) >= 4 ? $rdata : null; } function lookup($net, $nick, $uhost, $hand, $chan, $arg) { print "Lookup handler called"; $function = $arg; $file = MANUAL_BASE_DIR . '/function.' . xform_function($function) . '.html'; if (file_exists($file)) { $data = parse_func_data($file, $function); $line1 = $data['return_type'] . ' ' . $data['name'] . '(' . implode(",", $data['args']) . ')'; $line2 = $data['version'] . ' ' . str_replace($function, '', $data['purpose']); putserv($net, 'PRIVMSG ' . $chan . ' :' . $line1); putserv($net, 'PRIVMSG ' . $chan . ' :' . $line2); putserv($net, 'PRIVMSG ' . $chan . ' :' . 'http://php.net/' . xform_function($function)); print $line1 . "\n"; } else { /* noop */ } } bind("DALnet", "pub", "-", "!php", "lookup");
<?php ini_set("max_execution_time", 0); bind("DALnet", "pub", "-", "!bmi", "do_bmi"); bind("severed", "pub", "-", "!bmi", "do_bmi"); bind("DALnet", "pub", "-", "!mbmi", "do_mbmi"); bind("severed", "pub", "-", "!mbmi", "do_mbmi"); function weight_stat($bmi) { if ($bmi < 18.5) { return "underweight"; } else { if ($bmi >= 18.5 && $bmi < 24.9) { return "normal"; } else { if ($bmi > 25 && $bmi < 29.9) { return "overweight"; } else { return "a fat f*****g piece of shit"; } } } } function do_bmi($net, $nick, $uhost, $hand, $chan, $arg) { $arrarg = explode(' ', $arg); if (count($arrarg) < 2) { putserv($net, "PRIVMSG {$chan} :!bmi <weight> [<feet><inches>][<total inches>]"); return; } if (count($arrarg == 2)) {
* * Config example (yml): * settings: * mailgun: * enabled: true * domain: <mailgun-domain> * api_key: <mailgun-api-key> */ bind('emails', 'post', function ($event, $model) { $settings = get("/settings/mailgun"); // Mailgun enabled? if ($settings['enabled']) { try { // Process mailgun post message. fwd_mailgun_send($event['data'], $settings); // Indicate gateway for logs. $event['data']['gateway'] = 'mailgun'; } catch (Exception $e) { $model->error($e->getMessage()); return false; } return bind_stop(true); } }); /** * Post message to the mailgun API. */ function fwd_mailgun_send($data, $settings) { // Use type as message tag. if ($data['type']) { $data['o:tag'] = $data['type'];
if ($value == $func) { array_splice($bind[$event], $key, 1); } } } break; case 'list': if (array_key_exists($event, $bind)) { return $bind[$event]; } else { return array(); } break; } } bind("changenick", "NICK"); function changenick($user, $newnick) { if (get_nick($user) == bnick()) { bnick($newnick); } } function bnick() { global $bnick; if (func_num_args()) { $bnick = func_get_arg(0); ircwrite("raw", "NICK {$bnick}"); } return $bnick; }
<?php ini_set("max_execution_time", 0); /* bind(string network, string type, string flags, string mask, string function) */ bind("DALnet", "pub", "-", "hi", "testing"); bind("severed", "dcc", "-", ".help", "do_help"); bind("DALnet", "pub", "-", ".version", "do_version"); function do_version($net, $nick, $uhost, $hand, $chan, $arg) { putserv($net, "PRIVMSG {$chan} :" . phpversion()); } function do_help($handle, $idx, $text) { putserv($net, "PRIVMSG poutine :this is a test"); } function testing($net, $nick, $uhost, $hand, $chan, $arg) { putserv($net, "PRIVMSG {$chan} :triggered from PHP: net={$net} nick={$nick} uhost={$uhost} hand={$hand} chan={$chan} arg=({$arg})"); } ?> echo "test loaded";
if (is_admin($user) == true) { if ($msg == bnick() . " oper") { if ($debug == "on") { msg($debugchan, "trying to oper..."); } dump("oper {$nick} {$pass}"); } } } bind('operok', 'raw381'); function operok($user, $params) { global $debugchan, $omodes; if ($user == ircserver()) { $smsg = array(); $smsg = explode(" ", $params); if ($debug == "on") { msg($debugchan, "operation successful!"); } dump("MODE " . bnick() . " {$omodes}"); } } bind('opernotok', 'raw491'); function opernotok($user, $params) { global $debugchan; if ($debug == "on") { msg($debugchan, "operation failed!;("); } } echo ">> Oper module loaded\n";
try { // Process UPS service rating. $ups_methods = fwd_ups_rates($params, $settings); // Merge with existing methods. $methods = array_merge((array) $methods, $ups_methods); } catch (Exception $e) { $model->error($e->getMessage(), 'ups'); return false; } } // Return combined methods. return $methods; }); bind('shipments', 'after:get', function ($result, $event, $model) { if (strcasecmp($result['carrier'], 'UPS') == 0) { $result['tracking_info'] = fwd_ups_tracking_info($result); } }); /** * Get UPS rate quotes. */ function fwd_ups_rates($params, $settings) { // Configurable UPS service methods. $service_list = array('01' => 'UPS Next Day Air', '02' => 'UPS Second Day Air', '03' => 'UPS Ground', '11' => 'UPS Standard', '12' => 'UPS Three-Day Select', '13' => 'UPS Next Day Air Saver', '65' => 'UPS Worldwide Saver', '07' => 'UPS Worldwide Express', '08' => 'UPS Worldwide Expedited', '14' => 'UPS Next Day Air Early A.M.', '54' => 'UPS Worldwide Express Plus', '59' => 'UPS Second Day Air A.M.'); // If params are empty, return available methods only. if (empty($params)) { $methods = array(); foreach ((array) $settings['methods'] as $key => $method) { if ($method) { $method = is_array($method) ? $method : array();
/** * Returns a goal that succeeds if both given goals succeed. * * @param callable $g1 a goal * @param callable $g2 a goal */ function conj($g1, $g2) { return function ($sC) use($g1, $g2) { return bind($g1($sC), $g2); }; }
/** * Takes a callable $f taking several arguments and converts it into a cascade * of functions of a single argument, e.g. given a function * * $f = function($x1, $x2, $x3) { ... }; * * curry($f) produces a new function $g such that: * * $g = function($x1) { * return function($x2) { * return function($x3) { * return $f($x1, $x2, $x3); * }; * }; * }; * * By default, curry "curries" all the **required** arguments of a function * If $n is given, the "cascade of functions" is only created for that many arguments * This is useful for functions that are variadic or have optional arguments */ function curry(callable $f, $n = -1) { if ($n < 0) { $n = n_required_args($f); } // If we have a function of 0 or 1 arguments, there is nothing to do if ($n < 2) { return $f; } // Otherwise return a new function that gathers the arguments // We know that $f takes at least 2 arguments return function ($x) use($f, $n) { return curry(bind($f, $x), $n - 1); }; }
} else { /* $query = pg_query("select * from system_users where name = '$username'"); $result = pg_fetch_assoc($query); if (($username_ldap == 'admin') && ($password_ldap == 'p@ssw0rd')) { $expire = time()-(60*60*24); $_SESSION['loggedin'] = 1; setcookie('logged', $result['name'], $expire); $_SESSION['username'] = $result['name']; $_SESSION['fullname'] = $result['friendly_name']; $_SESSION['username_ldap'] = 'ADMIN'; //implode("",); header("location:index.php?modul=home"); } else{ */ $loginTelkomLdap = authTelkomLdap($username_ldap, $password_ldap); $nameldap = bind($username_ldap); if ($loginTelkomLdap == 1) { $expire = time() - 60 * 60 * 24; $_SESSION['loggedin'] = 1; $nama = implode("", $nameldap[0]['cn']); $truename = substr($nama, 1, strlen($nama)); $_SESSION['username_ldap'] = $truename; //implode("",); /*$cek=mysql_query("Select * from log where username = '******'"); $a=mysql_fetch_row($cek); if($a > 1 ){ $log=mysql_query("Update log set password='******',waktu_login=NOW() where username='******'"); }else{ $log=mysql_query("Insert into log (username,password,waktu_login) Values ('$username_ldap', '$password_ldap', NOW())"); }*/ setcookie('logged', $result['name'], $expire);