예제 #1
0
파일: AJAX.php 프로젝트: h3rb/page
 public function FormPost()
 {
     $out = array();
     $out["map"] = array();
     foreach (getpost() as $name => $value) {
         if (matches($name, "map")) {
             $map = json_decode(FormHelper::Decode($value));
             foreach ($map as $mapped) {
                 $parts = explode('|', $mapped);
                 if (contains($parts[0], '__')) {
                     $d = explode('__', $parts[0]);
                     if (!isset($out["map"][$d[0]])) {
                         $out["map"][$d[0]] = array();
                     }
                     $out["map"][$d[0]][$d[1]] = AJAX::fp($parts[1]);
                 } else {
                     $mapped[$parts[0]] = AJAX::fp($parts[1]);
                 }
             }
         } else {
             if (contains($name, '__')) {
                 $d = explode("__", $name);
                 if (!isset($out[$d[0]])) {
                     $out[$d[0]] = array();
                 }
                 $out[$d[0]][$d[1]] = base64_decode(urldecode($value));
             } else {
                 $out[$name] = FormHelper::Decode($value);
             }
         }
     }
     $out['signal'] = json_decode($out['signal'], true);
     return $out;
 }
예제 #2
0
 function active_plugin($plugin, $page)
 {
     $form_plugin = array("validation", "select");
     if ($plugin == "isotope" && (startsWith($page, '/profile/all') || startsWith($page, '/circle/all'))) {
         return false;
     }
     if (in_array($plugin, $form_plugin) && (contains($page, '/edit') || contains($page, '/add'))) {
         return true;
     }
     if ($plugin == "jasny" && (startsWith($page, '/profile/add') || startsWith($page, '/profile/edit'))) {
         return true;
     }
     if ($plugin == "formhelpers" && startsWith($page, '/profile/')) {
         return true;
     }
     if ($plugin == "mixitup" && (startsWith($page, '/profile/all') || startsWith($page, '/circle/all'))) {
         return true;
     }
     if ($plugin == "isotope" && (startsWith($page, '/card') || startsWith($page, '/storyboard') || startsWith($page, '/card/all') || startsWith($page, '/profile/all') || startsWith($page, '/circle/all'))) {
         return true;
     }
     if ($plugin == "rcarousel" && startsWith($page, '/circle/view')) {
         return true;
     }
     return false;
 }
예제 #3
0
function sendMsg($sender, $reciever, $recieverPhone, $content, $sendtime)
{
    global $mysql, $userAndPswd, $corpName, $apiUrl, $MsgErrorCode, $BlackListWords;
    foreach ($BlackListWords as $blackWord) {
        if (contains($content, $blackWord)) {
            return array('status' => 'successful', 'errMsg' => "含有非法内容:" . $blackWord);
        }
    }
    $content = $corpName . $content;
    $action = $sendtime == null ? "sendsms.action?" : "sendtimesms.action";
    $url = $apiUrl . $action . $userAndPswd . "&phone={$recieverPhone}&message=" . urlencode($content) . "&sendtime={$sendtime}";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    // timeout
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 获取数据返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    $res = curl_exec($ch);
    if ($res == false) {
        throw new Exception("向短信提供商请求失败!");
    } else {
        $error = getValue($res, "error");
        $message = isset($MsgErrorCode[$error]) ? $MsgErrorCode[$error] : "未知";
        $obj = array("id" => date("YmdHis") . str_pad(rand(0, 9999), 4, rand(0, 9), STR_PAD_LEFT), "sender" => $sender, "reciever" => $reciever, "recieverPhone" => $recieverPhone, "status" => $error, "result" => $message, "content" => $content);
        $mysql->DBInsertAsArray('msg_log', $obj);
        if ($error != "0") {
            throw new Exception("错误代码:" . $error . " " . $message);
        }
    }
    return array('status' => 'successful', 'errMsg' => '');
}
예제 #4
0
function getFormQuestions($db, $filters = null)
{
    if (!$db || $db->offline) {
        $questions = readJsonFile("../api/form_data.json");
        if (isset($questions["questions"])) {
            $questions = $questions["questions"];
        }
        return $questions;
    }
    $p = array("table" => "form_question", "order_by" => "section_id, position, id", "required" => 1);
    if ($filters) {
        foreach ($filters as $key => &$value) {
            if (contains($value, ",")) {
                $value = explode(",", $value);
            }
            if ($value) {
                $p[$key] = $value;
            }
        }
    }
    $form_questions = $db->selectWhere($p);
    $p = array("table" => "form_answer", "order_by" => "question_id, position, id");
    $form_answers = $db->selectWhere($p);
    //group join the 2 results
    return $db->groupJoinResults($form_questions, $form_answers, "form_answers", "id", "question_id");
}
예제 #5
0
 /**
  * A user that isn't logged in shouldn't see the "Your Account" menu (including, "Your Widgets",
  * "Change Password", etc).
  */
 function testSigninYourAccountMenuIsNotDisplayedToNonAuthenticatedUser()
 {
     $this->createHomepageWidgets();
     $this->get('/account/signout');
     $this->get('/');
     assertFalse(contains($this->currentPageContent(), "Your Account"));
     assertFalse(contains($this->currentPageContent(), "Change Password"));
     assertFalse(contains($this->currentPageContent(), "Sign Out"));
     assertTrue(contains($this->currentPageContent(), "Sign In"));
 }
 /** @test */
 public function itCanCreateAResponseDefinition()
 {
     $schemaFile = 'file://' . __DIR__ . '/../fixtures/petstore.json';
     $factory = new SwaggerSchemaFactory();
     $schema = $factory->createSchema($schemaFile);
     $responseDefinition = $schema->getRequestDefinition('addPet')->getResponseDefinition(200);
     assertThat($responseDefinition, isInstanceOf(ResponseDefinition::class));
     assertThat($responseDefinition->getContentTypes(), contains('application/json'));
     assertThat($responseDefinition->getBodySchema(), isType('object'));
     assertThat($responseDefinition->getStatusCode(), equalTo(200));
 }
예제 #7
0
 /**
  * BootstrapTest::testContains()
  *
  * @return void
  */
 public function testContains()
 {
     $strings = [['auto', 'to', true], ['auto', 'ut', true], ['auto', 'To', true], ['auto', 'ot', false]];
     foreach ($strings as $string) {
         $is = contains($string[0], $string[1]);
         //pr(returns($is). ' - expected '.returns($string[2]));
         $this->assertEquals($string[2], $is);
     }
     $is = contains('Auto', 'To', true);
     $this->assertEquals(false, $is);
 }
function testBalanceLookupElegantlyDetectsSiteMaintenanceAtBlockchainDotInfo()
{
    # Special address for mocking a "Site Under Maintenance" response from Blockchain.info.
    $address = '1TestForDowntimeX1iTDhViXbrogKqzbt';
    try {
        BlockchainDotInfo\getBalanceInSatoshis($address);
        fail("Expected to get exception for lookup on address {$address}");
    } catch (NetworkError $e) {
        assertTrue(contains(strtolower($e->getMessage()), 'maintenance'));
    }
}
예제 #9
0
function test_3_pages()
{
    $csv = grab_rubrica("http://www.unipr.it/rubrica", 3);
    $testStrings = array("AGNESINI Prof. Alex,alex.agnesini@unipr.it,+39 0521 032552", "ALFIERI Prof. Roberto,roberto.alfieri@unipr.it,+39 0521 906214", "ARGIROPOULOS Prof. DIMITRIS,,");
    foreach ($testStrings as $test) {
        if (!contains($csv, $test)) {
            exit("Test Failed on: " . $test . PHP_EOL);
        }
    }
    echo "Passed all tests." . PHP_EOL;
}
예제 #10
0
function trimZeros($num)
{
    if (!is_numeric($num)) {
        throw new InvalidArgumentException("Only numeric values accepted");
    }
    $numStr = (string) $num;
    if (!contains($num, '.')) {
        return ltrim($numStr, '0');
    } else {
        return trim($num, '0.');
    }
}
예제 #11
0
function findMimeTypeUsingUrl($url)
{
    $UserMime = "application/vnd.jyu.nfleet.user-2.1+json";
    $ProblemMime = "application/vnd.jyu.nfleet.problem-2.0+json";
    $ProblemSetMime = "application/vnd.jyu.nfleet.problemset-2.0+json";
    $ProblemSettingsMime = "application/vnd.jyu.nfleet.problemsettings-2.1+json";
    $VehicleSetMime = "application/vnd.jyu.nfleet.vehicleset-2.1+json";
    $VehicleMime = "application/vnd.jyu.nfleet.vehicle-2.1+json";
    $TaskSetMime = "application/vnd.jyu.nfleet.taskset-2.1+json";
    $TaskMime = "application/vnd.jyu.nfleet.task-2.1+json";
    $PlanMime = "application/vnd.jyu.nfleet.plan-2.0+json";
    $ImportMime = "application/vnd.jyu.nfleet.import-2.2+json";
    $RouteMime = "application/vnd.jyu.nfleet.route-2.0+json";
    $RouteEventMime = "application/vnd.jyu.nfleet.routeevent-2.0+json";
    $RouteEventSetMime = "application/vnd.jyu.nfleet.routeeventset-2.0+json";
    if (strlen($url) == 0) {
        return "application/json";
    }
    if (endsWith($url, "/settings")) {
        return $ProblemSettingsMime;
    }
    if (contains($url, "plan")) {
        return $PlanMime;
    }
    if (endsWith($url, "/route")) {
        return $RouteMime;
    }
    if (endsWith($url, "/events") || endsWith($url, "/events/")) {
        return $RouteEventSetMime;
    }
    if (contains($url, "/events/")) {
        return $RouteEventMime;
    }
    if (endsWith($url, "tasks")) {
        return $TaskSetMime;
    }
    if (contains($url, "tasks/")) {
        return $TaskMime;
    }
    if (endsWith($url, "vehicles")) {
        return $VehicleSetMime;
    }
    if (contains($url, "vehicles/")) {
        return $VehicleMime;
    }
    if (endsWith($url, "problems")) {
        return $ProblemSetMime;
    }
    if (contains($url, "problems/")) {
        return $ProblemMime;
    }
    return "application/json";
}
예제 #12
0
function addToStack(&$metadata, $bbox, $lon, $lat, $provider, $o)
{
    if (contains($bbox, $lon, $lat)) {
        $k = "{$lon},{$lat}";
        if (!array_key_exists($k, $metadata)) {
            $metadata[$k] = array();
        }
        if (!array_key_exists($provider, $metadata[$k])) {
            $metadata[$k][$provider] = array();
        }
        array_push($metadata[$k][$provider], $o);
    }
}
예제 #13
0
 public function testReelLife()
 {
     $test = 'created_at';
     $this->assertTrue(contains('created_at', $test));
     $this->assertTrue(contains('*_at', $test));
     $this->assertTrue(contains('*_at*', $test));
     $this->assertFalse(contains('_at*', $test));
     $this->assertFalse(contains('_at', $test));
     $this->assertTrue(contains('*created*', $test));
     $this->assertTrue(contains('created*', $test));
     $this->assertFalse(contains('created', $test));
     $this->assertTrue(contains('*_at', $test . ' date'));
     $this->assertFalse(contains('_at', $test . '_date'));
 }
예제 #14
0
function part_1($line)
{
    global $not_contains, $vowels;
    if (contains($line, $not_contains)) {
        return false;
    }
    if (!vowels($line, $vowels)) {
        return false;
    }
    if (!preg_match('/([a-z])\\1{1,}/', $line)) {
        return false;
    }
    return true;
}
예제 #15
0
 public function test_delete_behaviour()
 {
     $chain = new Chain();
     $chain->add('fred')->add('wilma')->add('betty')->add('barney');
     assertThat($chain->getTokens(), contains(array('fred', 'wilma', 'betty', 'barney')));
     $chain->delete('wilma');
     assertThat($chain->getTokens(), contains(array('fred', 'betty', 'barney')));
     $chain->delete('barney');
     assertThat($chain->getTokens(), contains(array('fred', 'betty')));
     $chain->delete('fred');
     assertThat($chain->getTokens(), contains(array('betty')));
     $chain->delete('betty');
     assertThat($chain->getTokens(), contains(array()));
 }
예제 #16
0
function tab_has_non_https_url($uportalActiveTab, $isGuest)
{
    global $APPS;
    $key = $isGuest ? 'uportalActiveTabGuest' : 'uportalActiveTab';
    foreach ($APPS as $appId => $app) {
        if (@$app[$key] == $uportalActiveTab) {
            if (contains(urldecode(@$app["url"]), "http://")) {
                error_log("forcing first app of tab " . $uportalActiveTab . " because of {$appId}");
                return true;
            }
        }
    }
    return false;
}
예제 #17
0
function testword()
{
    require "../includes/connect.php";
    require "../includes/string.php";
    //$name = str_replace($unwantedChars, "", $row['movieId']);
    //$hashtag = "#".$name;
    //rpp = tweetcount (max=  100)
    $tweetUrl = "http://tweets2csv.com/results.php?q=%23starwars&rpp=40&submit=Search";
    echo $tweetUrl . "<br>";
    $htmltext = file_get_contents($tweetUrl);
    $regex = "#<div class='user'>(.*)(\\s*)<div class='text'>(.*)<div class='description'>#";
    preg_match_all($regex, $htmltext, $matches, PREG_SET_ORDER);
    $wordArray = array();
    $unwantedChars = array('/', "\\", 'http', "@", "-", "<a");
    foreach ($matches as $tweet) {
        //'text'=>$tweet[3],
        //$newData = array("text"=>htmlentities($tweet[3]));
        //array_push($data["data"], $newData);
        //echo $tweet[3]."<br>";
        $words = explode(" ", $tweet[3]);
        foreach ($words as $word) {
            if (!contains($word, $unwantedChars) && !in_array(normalize($word), $stopwords)) {
                if (!isset($wordArray[$word])) {
                    $wordArray[$word] = 1;
                } else {
                    $wordArray[$word]++;
                }
            }
        }
    }
    $newFileName = '../words/starwars.txt';
    if (file_put_contents($newFileName, json_encode($wordArray)) != false) {
        echo "added";
    } else {
        echo "Cannot create file (" . basename($newFileName) . ")";
    }
    echo "<br>";
    //format (just split by / and :)
    /*$newFileName = '../sentiment/'.$name.".txt";
    			$appendContent = $sent['positive'].";".$sent['negative'].";".$sent['neutral'].";".$sent['tweetCount'].";".$updateDate."/";
    
    
    			//If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
    			if(file_put_contents($newFileName,$appendContent,  FILE_APPEND) !=false){
    			    echo "File created (".basename($newFileName).")";
    			}else{
    			    echo "Cannot create file (".basename($newFileName).")";
    			}*/
}
예제 #18
0
 /**
  * Runs validation on form inputs
  *
  * note - need a master class that uses the input field name and an array of 
  * 		the types of error checking required and returns the result set
  * 
  * @param  array $postData
  * @return array Returns errors array to requestor
  */
 public function validateFormData($postData)
 {
     // check for empty field
     if (empty($postData['name'])) {
         $this->formFieldErrors['field empty']['error'] = true;
     }
     // ensure only letters or numbers are used
     if (!ctype_alnum($postData['name'])) {
         $this->formFieldErrors['not alphanumeric']['error'] = true;
     }
     // check for exclamation mark
     if (contains('!', $postData['name'])) {
         $this->formFieldErrors['contains exclamation mark']['error'] = true;
     }
 }
예제 #19
0
파일: union.php 프로젝트: mpetrovich/dash
function union($collections)
{
    if (func_num_args() > 1) {
        $collections = func_get_args();
    }
    $union = array();
    foreach ($collections as $collection) {
        foreach ($collection as $value) {
            if (!contains($union, $value)) {
                $union[] = $value;
            }
        }
    }
    return $union;
}
예제 #20
0
파일: File.php 프로젝트: h3rb/page
 public function inUse($row)
 {
     if (contains($row['Type'], 'stl')) {
     } else {
         if (contains($row['Type'], 'image')) {
         } else {
             if (contains($row['Type'], 'text/plain')) {
             } else {
                 if (contains($row['Type'], 'wav')) {
                 }
             }
         }
     }
     return FALSE;
 }
예제 #21
0
 static function getFormElement($model, $field, $alias = null)
 {
     if (!$alias) {
         $alias = $model;
     }
     $model = ucfirst($model);
     $alias = ucfirst($alias);
     $columns = Doctrine::getTable($model)->getColumns();
     $default = array('type' => null, 'length' => null);
     // Types Doctrine :
     // http://www.symfony-project.org/doctrine/1_2/en/04-Schema-Files
     $groups = array('string' => 'string', 'char' => 'string', 'varchar' => 'string', 'blob' => 'text', 'clob' => 'text', 'int' => 'digit', 'integer' => 'digit', 'float' => 'digit', 'double' => 'digit', 'date' => 'date', 'timestamp' => 'datetime', 'boolean' => 'boolean', 'bool' => 'boolean', 'enum' => 'select');
     $column = array_merge($default, $columns[$field]);
     $group = isset($groups[$column['type']]) ? $groups[$column['type']] : 'string';
     extract($column);
     if ($field == 'id') {
         return "FormHelper::hidden('" . $field . "', \$" . $alias . ");";
     }
     if (contains($field, '*password')) {
         return "FormHelper::password('" . $field . "', \$" . $alias . ");";
     }
     if ($group == 'string' && $length == 255) {
         return "FormHelper::textarea('" . $field . "', \$" . $alias . ", array('cols' => 100, 'rows' => 4));";
     }
     if ($group == 'text' && $length && $length <= 255) {
         return "FormHelper::textarea('" . $field . "', \$" . $alias . ", array('class' => 'editor-tiny', 'cols' => 120, 'rows' => 10));";
     }
     if ($group == 'text' && (!$length || $length > 255)) {
         return "FormHelper::textarea('" . $field . "', \$" . $alias . ", array('class' => 'editor', 'cols' => 140, 'rows' => 40));";
     }
     if ($group == 'boolean') {
         return "FormHelper::radios('" . $field . "', array('0' => __('Oui'), '1' => __('Non')), \$" . $alias . ");";
     }
     if ($group == 'date') {
         return "FormHelper::date('" . $field . "', 'TODAY()');";
     }
     if ($group == 'datetime') {
         return "FormHelper::datetime('" . $field . "', \$" . $alias . ");";
     }
     if ($group == 'digit') {
         return "FormHelper::text('" . $field . "', \$" . $alias . ", array('maxlength' => " . $length . ", 'size' => " . ($length + 1) . "));";
     }
     if ($group == 'select') {
         return "FormHelper::select('" . $field . "', \$" . $alias . ", '1');";
     }
     return "FormHelper::text('" . $field . "', \$" . $alias . ", array('size' => 100));";
 }
예제 #22
0
function checkCheckboxs($question = '0')
{
    global $answers;
    global $totalPoints;
    global $earnedPoints;
    $totalPoints += 3 * strlen($answers[$question]);
    if (!is_array($_POST['q' . $question])) {
        return;
    }
    foreach ($_POST['q' . $question] as $answer) {
        if (contains($answer, $answers[$question])) {
            $earnedPoints += 3;
        } else {
            $earnedPoints -= 3;
        }
    }
}
예제 #23
0
 function testRenderingVariousAmounts()
 {
     $cases = array(array(Currencies\BTC(), 0.01908, array('0.019 BTC', '0.02 BTC', '19 mBTC')), array(Currencies\BTC(), 0.0, array('0 BTC', '0.0 BTC')));
     foreach ($cases as $case) {
         list($currency, $btcAmount, $acceptableRenderings) = $case;
         $w = getWidget();
         $w->currency = $currency;
         $w->save();
         $this->setBalance($w->bitcoinAddress, $btcAmount);
         $this->browseToWidget($w);
         $raisedDiv = current($this->xpathQuery("//div[@class='raised']"));
         $matches = array_filter($acceptableRenderings, function ($t) use($raisedDiv) {
             return contains($raisedDiv->textContent, $t);
         });
         $matchFound = 1 == count($matches);
         assertTrue($matchFound, "Should render as one of following: " . implode(", ", $acceptableRenderings));
     }
 }
예제 #24
0
function checkConnection()
{
    getSession();
    if (!isset($_SESSION['user'])) {
        if (!contains('login', $_SERVER['REQUEST_URI'])) {
            if (!contains('index', $_SERVER['REQUEST_URI'])) {
                setFlash('warning', 'Connectez vous pour accéder à cette section.');
            }
            header('location: login.php');
            exit;
        }
    } else {
        if (contains('index', $_SERVER['REQUEST_URI']) || contains('login', $_SERVER['REQUEST_URI'])) {
            header('location: vote.php');
            exit;
        }
    }
}
예제 #25
0
function intersection($collections)
{
    if (func_num_args() > 1) {
        $collections = func_get_args();
    }
    $intersection = array_shift($collections);
    foreach ($collections as $collection) {
        foreach ($intersection as $key => $value) {
            if (!contains($collection, $value)) {
                // @todo Test whether unset() works with all Traversable
                unset($intersection[$key]);
            }
        }
    }
    $intersection = values($intersection);
    // Re-indexes due to unset() holes
    return $intersection;
}
예제 #26
0
 function id($args)
 {
     list($id, $name) = $args;
     $bm = new BlogModel();
     $bm->getByID(tin($id));
     $this->isiMeta($bm);
     $pg = $bm;
     $json = "";
     if ($pg->topic_attachments != "") {
         $json = json_decode(stripslashes($pg->topic_attachments));
     }
     //pr($json);
     if ($pg->topic_attachment_order == "") {
         $pa = \Efiwebsetting::getData('PageAttachment');
     } else {
         $pa = $pg->topic_attachment_order;
     }
     //        $pa = \Efiwebsetting::getData('PageAttachment');
     $exp = explode(",", $pa);
     $dimatikan_animasi_header = 1;
     foreach ($exp as $p) {
         if ($p == "Page") {
             $arr['blog'] = $bm;
             $arr['dimatikan_animasi_header'] = $dimatikan_animasi_header;
             //                Mold::theme("Pages/Blog_post",$arr);
             $layout_id = "Blog_post";
             $file = Layout::getFile($layout_id);
             //        echo "Pages/".$layout_id."/".$file;
             Mold::theme("Pages/" . $layout_id . "/" . $file, $arr);
             //                    $arr['page'] = $page;
             //                    Mold::theme("Pages/Page",$arr);
         } else {
             if (array_key_exists($p, $json) && $json->{$p} > 0) {
                 $paralax = new $p();
                 $paralax->viewme($json->{$p}, "BlogModel", $bm->topic_id);
                 if (contains($p, array("Parallax", "Carousel"))) {
                     $dimatikan_animasi_header = 0;
                 }
             }
         }
     }
 }
function getBalanceInSatoshis($address)
{
    $client = new HttpClient();
    $response = $client->get(balanceLookupURL($address));
    if ($response->statusCode == 200 && isInteger($response->content)) {
        return intval($response->content);
    } else {
        $e = strtolower($response->content);
        preg_match('@<title>(.*)</title>@', $response->content, $matches);
        $title = at($matches, 1);
        if ($e == 'checksum does not validate' || beginsWith($e, 'illegal character') || in_array($e, array('input to short', 'input too short'))) {
            throw new InvalidAddress("{$address} appears to be an invalid Bitcoin address");
        } else {
            if (contains($e, 'cloudflare') && !empty($title)) {
                throw new NetworkError("CloudFlare-reported problem at blockchain.info: " . withoutPrefix($title, "blockchain.info | "));
            } else {
                if (contains(strtolower($title), 'under maintenance')) {
                    throw new NetworkError("Blockchain.info appears to be under maintenance");
                } else {
                    if (contains($e, "maximum concurrent requests reached")) {
                        throw new NetworkError("Maximum concurrent requests to Blockchain.info reached");
                    } else {
                        if (!empty($title)) {
                            throw new NetworkError("Unknown error when attempting to check address-balance " . "for ({$address}) via blockchain.info: {$title}");
                        } else {
                            if (trim($e) == '') {
                                throw new NetworkError("Blockchain.info returned empty/content-less response");
                            } else {
                                if ($e == 'lock wait timeout exceeded; try restarting transaction') {
                                    throw new NetworkError("Blockchain.info responded with error message about lock timeout");
                                } else {
                                    throw new \Exception("Unexpected result received from blockchain.info when " . "attempting to get balance of address {$address}: {$response->content}");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
예제 #28
0
 public function loadConfigs($path)
 {
     if (!is_dir($path)) {
         throw new Exception("Un dossier contenant les fichiers de configuration doit être donné.");
     }
     if (!$this->env) {
         throw new Exception("Un environnement doit être configuré avant l'appel de cette méthode.");
     }
     require_once $path . '/config.php';
     $config_files = read_folder($path);
     foreach ($config_files as $file) {
         if (contains('config.*', basename($file)) && basename($file) != 'config.php') {
             require_once '/' . $file;
         }
     }
     foreach ($configs['default'] as $key => $value) {
         Config::set($key, $value);
     }
     if (isset($configs[$this->env])) {
         foreach ($configs[$this->env] as $key => $value) {
             Config::set($key, $value);
         }
     }
 }
예제 #29
0
 function generateRandomSetOfEnumerated($variable, $var)
 {
     $options = $var->getOptions();
     $codes = array();
     foreach ($options as $opt) {
         $codes[] = $opt["code"];
     }
     // equal to
     $eq = trim($this->getFill($variable, $var, SETTING_COMPARISON_EQUAL_TO));
     if ($eq != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $eq);
         $res = array();
         foreach ($values as $v) {
             if (is_numeric($v)) {
                 $res[] = $v;
             }
         }
         return implode(SEPARATOR_SETOFENUMERATED, $res);
     }
     // not equal to, then exclude those codes
     $neq = trim($this->getFill($variable, $var, SETTING_COMPARISON_NOT_EQUAL_TO));
     if ($neq != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $neq);
         foreach ($values as $v) {
             if (is_numeric($v)) {
                 if (inArray($v, $codes)) {
                     unset($codes[array_search($v, $codes)]);
                 }
             }
         }
     }
     $ge = trim($this->getFill($variable, $var, SETTING_COMPARISON_GREATER));
     $codes2 = array();
     if ($ge != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $ge);
         foreach ($codes as $code) {
             $keep = true;
             foreach ($values as $v) {
                 if (is_numeric($v) && $code <= $v) {
                     $keep = false;
                     break;
                 }
             }
             if ($keep) {
                 $codes2[] = $code;
             }
         }
     }
     $geq = trim($this->getFill($variable, $var, SETTING_COMPARISON_GREATER_EQUAL_TO));
     $codes3 = array();
     if ($geq != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $geq);
         foreach ($codes2 as $code) {
             $keep = true;
             foreach ($values as $v) {
                 if (is_numeric($v) && $code < $v) {
                     $keep = false;
                     break;
                 }
             }
             if ($keep) {
                 $codes3[] = $code;
             }
         }
     }
     $se = trim($this->getFill($variable, $var, SETTING_COMPARISON_SMALLER));
     $codes4 = array();
     if ($se != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $se);
         foreach ($codes3 as $code) {
             $keep = true;
             foreach ($values as $v) {
                 if (is_numeric($v) && $code >= $v) {
                     $keep = false;
                     break;
                 }
             }
             if ($keep) {
                 $codes4[] = $code;
             }
         }
     }
     $seq = trim($this->getFill($variable, $var, SETTING_COMPARISON_SMALLER_EQUAL_TO));
     $codes5 = array();
     if ($seq != "") {
         $values = explode(SEPARATOR_SETOFENUMERATED, $seq);
         foreach ($codes4 as $code) {
             $keep = true;
             foreach ($values as $v) {
                 if (is_numeric($v) && $code > $v) {
                     $keep = false;
                     break;
                 }
             }
             if ($keep) {
                 $codes5[] = $code;
             }
         }
     }
     $exclusive = array();
     $invalidsub = $this->engine->getFill($variable, $var, SETTING_INVALIDSUB_SELECTED);
     if ($invalidsub != "") {
         $this->getInvalidCombinations($invalidsub, $exclusive);
     }
     $invalid = $this->engine->getFill($variable, $var, SETTING_INVALID_SELECTED);
     if ($invalid != "") {
         $this->getInvalidCombinations($invalid, $exclusive);
     }
     $res = array();
     foreach ($codes5 as $c) {
         $random = mt_rand(1, sizeof($codes5));
         if ($random == 1) {
             $add = true;
             // check for invalid combinations
             foreach ($exclusive as $arr) {
                 $first = $arr[0];
                 $second = $arr[1];
                 // get all numbers in first part
                 $firstnumbers = array();
                 if (contains($first, "-")) {
                     $firstfirst = explode("-", $first);
                     for ($j = $firstfirst[0]; $j <= $firstfirst[1]; $j++) {
                         $firstnumbers[] = $j;
                     }
                 } else {
                     if (is_numeric($first)) {
                         $firstnumbers[] = $first;
                     }
                 }
                 // get all numbers in second part
                 $secondnumbers = array();
                 if (contains($second, "-")) {
                     $secondsecond = explode("-", $second);
                     for ($j = $secondsecond[0]; $j <= $secondsecond[1]; $j++) {
                         $secondnumbers[] = $j;
                     }
                 } else {
                     if (is_numeric($second)) {
                         $secondnumbers[] = $second;
                     }
                 }
                 // add code to temp array and check for invalid combination
                 $restemp = $res;
                 $restemp[] = $c;
                 $allfirst = true;
                 foreach ($firstnumbers as $f) {
                     if (!inArray($f, $restemp)) {
                         $allfirst = false;
                         break;
                     }
                 }
                 // found all numbers in the first group
                 if ($allfirst == true) {
                     $allsecond = true;
                     foreach ($secondnumbers as $f) {
                         if (!inArray($f, $restemp)) {
                             $allsecond = false;
                             break;
                         }
                     }
                     // found all numbers in the second group, so don't add to avoid invalid
                     if ($allsecond == true) {
                         $add = false;
                     }
                 }
                 // we found an invalid combination, then stop
                 if ($add == false) {
                     break;
                 }
             }
             if ($add == true) {
                 $res[] = $c;
             }
         }
     }
     return implode(SEPARATOR_SETOFENUMERATED, $res);
 }
예제 #30
-2
function find_plugin($name, $os, $arch, $category, $tulip)
{
    $serverxml = simplexml_load_file('server.xml');
    $result = array();
    $pluginsxml = $serverxml->xpath("plugins");
    foreach ($pluginsxml[0] as $plugin) {
        $attr = $plugin->attributes();
        $attr_name = $attr['name'];
        $pluginname = (string) $attr_name;
        // Check if plugin name matches query
        if (contains($pluginname, $name) === true) {
            $plugindesc = array();
            foreach ($plugin->attributes() as $id => $value) {
                $plugindesc[$id] = (string) $value;
            }
            if (is_available($plugindesc['path'], $os, $arch) && contains($plugindesc['category'], $category) && $plugindesc['tulip'] === $tulip) {
                array_push($result, $plugindesc);
            }
        }
    }
    return $result;
}