예제 #1
2
switch ($action) {
    case 'pulldef':
        $content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=def&file=' . $basefile);
        file_put_contents($fileWithoutExt . '.definition.json', $content);
        break;
    case 'pull':
        try {
            $content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
            file_put_contents($fileWithoutExt . '.translation.json', $content);
        } catch (SimpleSAML_Error_Exception $e) {
            echo 'Translation unavailable for ' . $basefile;
            SimpleSAML_Logger::warning("Translation unavailable for {$basefile} in {$base}: " . $e->getMessage());
        }
        break;
    case 'push':
        push($file, $basefile, $application, $type);
        break;
    case 'convert':
        include $file;
        $definition = json_format(convert_definition($lang));
        $translation = json_format(convert_translation($lang)) . "\n";
        file_put_contents($fileWithoutExt . '.definition.json', $definition);
        file_put_contents($fileWithoutExt . '.translation.json', $translation);
        break;
    default:
        throw new Exception('Unknown action [' . $action . ']');
}
function ssp_readline($prompt = '')
{
    echo $prompt;
    return rtrim(fgets(STDIN), "\n");
예제 #2
0
 /**
  * Validate inputs and save to database.
  *
  * @return Response
  */
 protected function validateAndSave($post)
 {
     $validator = Validator::make(Input::all(), Post::$rules);
     if ($validator->fails()) {
         Session::flash('errorMessage', 'Validation failed');
         return Redirect::back()->withInput()->withErrors($validator);
     } else {
         $post->title = Input::get('title');
         $post->content = Input::get('content');
         $post->user_id = Auth::id();
         $image = Input::file('image');
         if ($image) {
             $filename = $image->getClientOriginalName();
             $post->image = '/uploaded/' . $filename;
             $image->move('uploaded/', $filename);
         }
         $result = $post->save();
         $posttags = Input::has('tuttags') ? Input::get('tuttags') : array();
         if (Input::has('addtags')) {
             $addtag = Input::get('addtags');
             $posttags . push($addtag);
         }
         $post->tags()->sync($posttags);
         $post->save();
         if ($result) {
             Session::flash('successMessage', 'Great Success!');
             return Redirect::action('PostsController@show', $post->slug);
         } else {
             Session::flash('errorMessage', 'Post was not saved.');
             return Redirect::back()->withInput();
         }
     }
 }
 public function __invoke()
 {
     $today = $this->getDateInThePast(0);
     $oneWeekAgo = $this->getDateInThePast(7);
     $twoWeeksAgo = $this->getDateInThePast(14);
     $threeWeeksAgo = $this->getDateInThePast(21);
     $service = $this->adwords->getService('AdGroupService');
     $selector = new \Selector();
     $selector->predicates = [new \Predicate('Status', 'EQUALS', 'ENABLED'), new \Predicate('CampaignStatus', 'EQUALS', 'ENABLED')];
     $selector->orderBy = new \OrderBy('ctr', 'ASCENDING');
     $selector->paging = new \Paging(0, \AdWordsConstants::RECOMMENDED_PAGE_SIZE);
     do {
         $page = $service->get($selector);
         if (is_array($page->entries)) {
             foreach ($page->entries as $adGroup) {
                 // Let's look at the trend of the ad group's CTR.
                 $statsThreeWeeksAgo = $this->getStatsFor($adGroup, $threeWeeksAgo, $twoWeeksAgo);
                 $statsTwoWeeksAgo = $this->getStatsFor($adGroup, $twoWeeksAgo, $oneWeekAgo);
                 $statsLastWeek = $this->getStatsFor($adGroup, $oneWeekAgo, $today);
                 // Week over week, the ad group is declining - record that!
                 if ($statsLastWeek->getCtr() < $statsTwoWeeksAgo->getCtr() && $statsTwoWeeksAgo->getCtr() < $statsThreeWeeksAgo->getCtr()) {
                     reportRows . push([adGroup . getCampaign() . getName(), adGroup . getName(), statsLastWeek . getCtr() * 100, statsLastWeek . getCost(), statsTwoWeeksAgo . getCtr() * 100, statsTwoWeeksAgo . getCost(), statsThreeWeeksAgo . getCtr() * 100, statsThreeWeeksAgo . getCost()]);
                 }
             }
         }
         $selector->paging->startIndex += $selector->paging->numberResults;
     } while (!is_null($page->entries));
 }
 public function addSnippet(Tx_T3tt_Domain_Model_XsltSnippet $snippetFile)
 {
     if (strlen($snippetFile->getContent()) > 0) {
         $this->_snippets . push($snippetFile);
     } else {
         throw new Tx_T3tt_Domain_Model_Exception_InvalidParamsException("Snippet `" . $snippetFile . "' is empty.");
     }
 }
 public function addProductToList($productReference, $active)
 {
     //var result = file_put_contents($this->productListFile, $productReference, FILE_APPEND | LOCK_EX);
     if ($active === TRUE) {
         $this->activeProducts . push($productReference);
     } else {
         $this->notActiveProducts . push($productReference);
     }
 }
예제 #6
0
파일: server.php 프로젝트: vitorg/ReactJS
function response_to_POST()
{
    if ($_POST) {
        // if data was sent
        push($GLOBALS['db'], $_POST);
        $_SESSION['db'] = $GLOBALS['db'];
        // save to session (to be avaliable on the next request)
    }
    echo '{"comments": ' . json_encode($GLOBALS['db']) . '}';
}
예제 #7
0
파일: server.php 프로젝트: vitorg/ReactJS
function response_to_POST()
{
    if ($_POST) {
        // if data was sent
        push($GLOBALS['db'], $_POST);
        $_SESSION['db_react_ex11'] = $GLOBALS['db'];
        // save to session (to be avaliable on the next request)
    }
    echo '{"data": ' . json_encode($GLOBALS['db']) . '}';
    //echo '{"data": ' . json_encode( array( array("category" => "Sporting Goods", "price" => "$49.99", "stocked" => "true", "name" => "Football"), array("category" => "Sporting Goods", "price" => "$49.99", "stocked" => "true", "name" => "Football2") ) ) . '}';
}
예제 #8
0
파일: User.php 프로젝트: juckerf/sshAkD
 private function addKey($key)
 {
     push($this->keys, $key);
     $connection = ssh2_connect($this->server->ip);
     $rC = 0;
     do {
         //ssh2_exec($connection, "echo #$key->contact@$this->server >> $this->home/.ssh/authorized_keys");
         //ssh2_exec($connection, "echo $key->pubKey >> $this->home/.ssh/authorized_keys");
         sleep(1);
         $rC++;
     } while (!$stream && $rC < 3);
 }
예제 #9
0
    /**
     * Sign the request when requesting a request token
     * @param $curl
     * @param $urlCallback
     * @param $signatureMethod
     */
    public function signForRequestToken($curl, $urlCallback, $signatureMethod = null)
    {
        if( $signatureMethod === null)
        {
            $signatureMethod = new \Zeflasher\OAuth\SignatureMethods\OAuthSignatureMethodHmacSha1();
        }

        $oauthParameters = new \Zeflasher\OAuth\Client\OAuthParameters($this->_consumerKey, $signatureMethod);
        $oauthParameters->addParameters(urlRequest.data);
        $oauthParameters->addParameters(_getGETParameters(urlRequest));
        $oauthParameters->add(OAuthConstants.CALLBACK, urlCallback);

        $signature = getSignature(urlRequest, oauthParameters, OAuthConstants.EMPTY_TOKEN_SECRET, signatureMethod);
        $oauthParameters->add(\Zeflasher\OAuth\OAuthConstants::OAUTH_CLIENT_SIGNATURE, $signature);
        //
        $headerString = $oauthParameters->getAuthorizationHeaderValue();
        urlRequest.requestHeaders.push(\Zeflasher\OAuth\OAuthConstants::OAUTH_CLIENT_HEADER, $headerString);
    }
예제 #10
0
파일: Server.php 프로젝트: juckerf/sshAkD
 private function getUsers($connection)
 {
     /* get users with dir in /home/. try three times (with 1sec pause) --> planned to make an extra method somewhere else for this */
     $rC = 0;
     do {
         $stream = ssh2_exec($connection, 'cat /etc/passwd | grep "/home" |cut -d: -f1,6');
         sleep(1);
         $rC++;
     } while (!$stream && $rC < 3);
     /* split the output by newline */
     $usersHomes = preg_split('/$\\R?^/m', stream_get_contents($stream));
     /* make a new user for every line and add it to the $users-array */
     foreach ($usersHomes as $uH) {
         $userAttrs = array(explode(':', $uH));
         push($this->users, new User($userAttrs[0], $userAttrs[1], $this->name));
     }
     /* if adminUser is root add it to the array too ('cause he'd not be catched by the "grep /home" below */
     if ($this->adminUser->name == "root") {
         push($this->users, new User("root", "/root/", $this->name));
     }
 }
예제 #11
0
function inp($columnid, $arrayOFchisla, $n)
{
    $massiv = array();
    $res;
    $IDc;
    $massiv . push(columnid);
    $res = 1;
    $IDc = columnid - 1;
    while (IDc != 0) {
        $massiv . push(IDc);
        $res = res + 1;
        $IDc--;
    }
    $IDc = columnid + 1;
    while (IDc != 0) {
        $massiv . push(IDc);
        $res = res + 1;
        $IDc++;
    }
    $a = array();
    $a[1] = ia($massiv, $res, $arrayOFchisla, $inparr);
    $a[0] = $res;
    return $a;
}
예제 #12
0
/**
 * Delete all image given the array ids 
 * @param type $imagesToDelete
 * @param type $options
 * @return array
 */
function DNUI_delete($imagesToDelete, $options)
{
    $updateInServer = $options['updateInServer'];
    $backup = $options["backup"];
    $base = wp_upload_dir();
    $base = $base['basedir'];
    $errors = array();
    $basePlugin = plugin_dir_path(__FILE__) . '../backup/';
    foreach ($imagesToDelete as $key => $imageToDelete) {
        clearstatcache();
        $image = wp_get_attachment_metadata($imageToDelete["id"]);
        $tmp = explode("/", $image["file"]);
        $imageName = array_pop($tmp);
        $folder = implode("/", $tmp);
        $dirBase = $base . '/' . $folder . '/';
        if ($backup) {
            $dirBackup = $basePlugin . '/' . $imageToDelete["id"];
            $backupExist = file_exists($dirBackup . '/' . $imageToDelete["id"] . '.backup');
            if (!$backupExist) {
                $backupInfo = array();
                $backupInfo["dirBase"] = $dirBase;
                $backupInfo["posts"] = DNUI_getRowPost($imageToDelete["id"]);
                $backupInfo["postMeta"] = DNUI_getRowPostMeta($imageToDelete["id"]);
                if (!file_exists($dirBackup)) {
                    mkdir($dirBackup, 0755, true);
                }
            }
        }
        if ($imageToDelete["toDelete"][0] == "original") {
            if ($backup) {
                $dirImage = $dirBase . $imageName;
                DNUI_copy($dirImage, $dirBackup . '/' . $imageName);
                foreach ($image["sizes"] as $size => $imageSize) {
                    $dirImage = $dirBase . $imageSize["file"];
                    DNUI_copy($dirImage, $dirBackup . '/' . $imageSize["file"]);
                }
            }
            wp_delete_attachment($imageToDelete["id"]);
        } else {
            foreach ($imageToDelete["toDelete"] as $keyS => $imageS) {
                $size = $image["sizes"][$imageS];
                clearstatcache();
                $dirImage = $dirBase . $size["file"];
                if (!empty($size)) {
                    if (!file_exists($dirImage)) {
                        if ($updateInServer) {
                            unset($image["sizes"][$imageS]);
                        }
                    } else {
                        if ($backup) {
                            DNUI_copy($dirImage, $dirBackup . '/' . $size["file"]);
                        }
                        if (@unlink($dirImage)) {
                            unset($image["sizes"][$imageS]);
                        } else {
                            $errors . push('Problem with ' . $size["file"] . " try toe active the option for delete the image if not exist");
                        }
                    }
                }
                wp_update_attachment_metadata($imageToDelete["id"], $image);
            }
        }
        if ($backup) {
            if (!$backupExist) {
                file_put_contents($dirBackup . '/' . $imageToDelete["id"] . '.backup', serialize($backupInfo));
            }
        }
    }
    return $errors;
}
예제 #13
0
     // If successful loading the feed
     $intrprtrFeed = new Interpreter();
     // Create an interpreter
     $intrprtrFeed->feed = $feed['id'];
     $intrprtrFeed->source = $feed['source'];
     // Set the source
     $artclFeed = $intrprtrFeed->interpret($domdocFeed);
     // Interpret the article
     foreach ($artclFeed as $artclArticle) {
         // Foreach article
         if (!$artclArticle->exists($conn)) {
             // If it's new
             if ($artclArticle->publish($conn)) {
                 // Add to database
                 if (difference($referenceArticle, $artclArticle) > 0.2) {
                     if (push($secure, $artclArticle)) {
                         // And push
                         print '<a href="' . $artclArticle->link . '">' . $artclArticle->title . '</a>: ' . difference($referenceArticle, $artclArticle) . '<br />';
                     } else {
                         die("Pusher failed. Boo.");
                     }
                 }
             } else {
                 die("There was an error in publishing somewhere.");
             }
         } else {
             // OLD STUFF FOUND
         }
     }
 } else {
     echo $feed['link'] . " won't load. Check it.";
예제 #14
0
파일: push.php 프로젝트: root42/licq
			$method = "updateStatus";
      $txt = "<newstatus><id>" . xmlentities($user['id'])
          . "</id><pp>" . xmlentities($user['pp'])
          . "</pp><nick>" . str_replace("\n", '', xmlentities(kses($user['nick'], array())))
          . "</nick><nummsgs>" . trim(xmlentities($user['newmsgs']))
          . "</nummsgs><status>" . str_replace(' ', '', xmlentities($user['status']))
          . "</status></newstatus>";
      break;
		case CODE_NOTIFYxMESSAGE:
			list($id, $pp, $numMessages) = split(' ', substr($packet, 4), 3);
			$method = "newMessage";
			$txt = "<newmessage><id>$id</id><pp>$pp</pp><nummsgs>$numMessages</nummsgs></newmessage>";
			break;
		case CODE_LOG:
			$method = "log";
			$txt = substr($packet, 4);
			break;
		default:
			continue;
	}
	$message = "
		<response>
		  <method>$method</method>
		  <result>$txt</result>
		</response>
	";
	$message = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" . $message;
	push($message);
}
?>
 public function __invoke()
 {
     $this->createLabel();
     $alert_text = [];
     $history = [];
     $currentTime = new \DateTime();
     $today = $currentTime->format('m') + 1 + "/" + $currentTime . getDate() + "/" + $currentTime->format('Y');
     $keywordIterator;
     $line_counter = 0;
     while ($keywordIterator->hasNext()) {
         $keyword = keywordIterator . next();
         $line_counter++;
         $current_quality_score = $keyword->qualityScore;
         $keywordLabelsIterator = keyword . labels() . withCondition("Name STARTS_WITH 'QS: '") . get();
         if ($keywordLabelsIterator->hasNext()) {
             $keyword_label = $keywordLabelsIterator . next();
             $matches = new RegExp('QS: ([0-9]+)$') . exec($keyword_label . getName());
             $old_quality_score = $matches[1];
         } else {
             $old_quality_score = 0;
         }
         // For the history also note the change or whether this keyword is new
         if ($old_quality_score > 0) {
             $change = $current_quality_score - $old_quality_score;
         } else {
             $change = "NEW";
         }
         $row = [$today, $keyword . getCampaign() . getName(), $keyword . getAdGroup() . getName(), $keyword . getText(), $current_quality_score, $change];
         $history . push(row);
         // If there is a previously tracked quality score and it's different from the current one...
         if ($old_quality_score > 0 && $current_quality_score != $old_quality_score) {
             // Make a note of this to log it and possibly send it via email later
             $alert_text . push($current_quality_score + "\t" + $old_quality_score + "\t" + $change + "\t" + $keyword . getText());
             // Remove the old label
             $keyword . removeLabel($keyword_label . getName());
         }
         // Store the current QS for the next time by using a label
         $keyword . applyLabel("QS: " + $current_quality_score);
     }
     if ($line_counter == 0) {
         $this->logger->log("Couldn't find any keywords marked for quality score tracking. To mark keywords for tracking, apply the label '" + $label_name + "' to those keywords.");
         return;
     }
     $this->logger->log("Tracked " + $line_counter + " keyword quality scores. To select different keywords for tracking, apply the label '" + $label_name + "' to those keywords.");
     // Store history
     $history_sheet = spreadsheet . getSheetByName('QS history');
     $history_sheet . getRange($history_sheet . getLastRow() + 1, 1, $history . length, 6) . setValues($history);
     // If there are notes for alerts then prepare a message to log and possibly send via email
     if ($alert_text . length) {
         $message = "The following quality score changes were discovered:\nNew\tOld\tChange\tKeyword\n";
         for ($i = 0; $i < count($alert_text); $i++) {
             $message += $alert_text[i] + "\n";
         }
         // Also include a link to the spreadsheet
         $message += "\n" + "The complete history is available at " + $spreadsheet . getUrl();
         $this->logger->log($message);
         // If there is an email address send out a notification
         if ($email_address && $email_address != "YOUR_EMAIL_HERE") {
             $this->mailer->sendEmail($email_address, "Quality Score Tracker: Changes detected", $message);
         }
     }
 }
예제 #16
0
 function push($m)
 {
     $a = func_get_args();
     $f = $a[0];
     if (!isIn($f, array('replace', 'byIndex', 'auto', 'distinct', 'begin'))) {
         $f = 'auto';
     } else {
         mov_next($a);
     }
     while (list($i, $v) = each($a)) {
         push($this->O, $f, $v);
     }
     return $this;
 }
예제 #17
0
 public function getParts($vehicleID = 0, $mount = "", $year = "", $make = "", $model = "", $style = "")
 {
     $req = "";
     if ($vehicleID > 0) {
         $req = $this->config->getDomain() . "GetParts";
         $req .= "&dataType=" . $this->config->getDataType();
     } else {
     }
     $resp = $this->helper->curlGet($req);
     $part_arr = array();
     foreach (json_decode($resp) as $part) {
         $part_arr . push($part);
     }
     return $part_arr;
 }
예제 #18
0
function getStudents($courseid)
{
    $conn = new mysqli("localhost", "root", "admin", "moodledb");
    if ($conn->connect_errno) {
        echo "failed to connect to mysql:(" . $conn->connect_errno . ") " . $mysql->connect_error;
    }
    $code = "select " . "ue.userid " . "from " . "mdl_user_enrolments ue, mdl_enrol e " . "where " . "e.roleid = 5 and ue.enrolid = e.id " . "and e.courseid=Y;";
    $resp = $conn->query($code);
    $users = array();
    while ($row = $resp->fetch_assoc()) {
        $users . push($row['userid']);
    }
    print_r($users);
}
예제 #19
0
 function parser_performAction(&$thisS, $yytext, $yyleng, $yylineno, $yystate, $S, $_S, $O)
 {
     switch ($yystate) {
         case 1:
             return $S[$O - 1];
             break;
         case 2:
             return [['']];
             break;
         case 3:
             $thisS = [$S[$O]];
             break;
         case 4:
             $thisS = [];
             break;
         case 5:
             $thisS = [''];
             break;
         case 6:
             $thisS = $S[$O - 1];
             break;
         case 7:
             $S[$O - 1][$S[$O - 1] . length - 1] . push('');
             $thisS = $S[$O - 1];
             break;
         case 8:
             $S[$O - 2] . push($S[$O]);
             $thisS = $S[$O - 2];
             break;
         case 9:
             $S[$O - 2][$S[$O - 2] . length - 1] . push('');
             $S[$O - 2] . push($S[$O]);
             $thisS = $S[$O - 2];
             break;
         case 10:
             $thisS = [$S[$O]];
             break;
         case 11:
             $thisS = $S[$O - 1];
             break;
         case 12:
             $thisS = [''];
             break;
         case 13:
             //$thisS = [];
             break;
         case 14:
             $S[$O - 1] . push('');
             $thisS = $S[$O - 1];
             break;
         case 15:
             //$S[$O-1].push('');
             $thisS = $S[$O - 1];
             break;
         case 16:
             $S[$O - 2] . push('');
             $S[$O - 2] . push($S[$O]);
             $thisS = $S[$O - 2];
             break;
         case 17:
             //$S[$O-2].push('');
             $S[$O - 2] . push($S[$O]);
             $thisS = $S[$O - 2];
             break;
         case 18:
             $thisS = '';
             break;
         case 19:
             $thisS = $S[$O - 1];
             break;
         case 15:
             $thisS = $S[$O];
             break;
         case 20:
             $thisS = $S[$O - 1] + '' + $S[$O];
             break;
     }
 }
예제 #20
0
function lookup_Description($BCN, $sessionID)
{
    //this function is not called by any other code currently
    //function takes description and compares outpan description and calcuates probability of match
    //declare errorLog as a global variable in order to write debug output to main function
    global $errorLog;
    global $itemDescription;
    global $_email;
    $outpanDescription = outpanQuery($BCN);
    $outpanDescriptionExploded = explode(' ', $outpanDescription);
    $outpanDescriptionExploded = array_map('strtolower', $outpanDescription);
    echo "<pre>";
    print_r($outpanDescriptionExploded);
    echo "</pre>";
    //$sessionID = get session id key from file
    $lookup_JSON = APIrequest("command=PRODUCTSEARCH&searchtext=" . urlencode($outpanDescription) . "&page=1&sessionkey=" . $sessionID);
    $decoded_JSON = json_decode($lookup_JSON, true);
    echo "<br>BCN lookup data<br><pre>";
    print_r($lookup_JSON);
    echo "</pre>";
    if ($decoded_JSON['TotalProductCount'] > "0") {
        $resultCount = $decoded_JSON['TotalProductCount'];
        $resultsArray = array_fill(0, $resultCount, NULL);
        for ($i = 0; $i < $resultCount && $i < 10; $i++) {
            $resultsArray[$i] = array($decoded_JSON['Products'][$i]['Name'], $decoded_JSON['Products'][$i]['ProductId'], 0);
            $resultsArray[$i][0] = explode(' ', $resultsArray[$i][0]);
            $resultsArray[$i][0] = array_map('strtolower', $resultsArray[$i][0]);
            $comparison = array_intersect($outpanDescriptionExploded, $resultsArray[$i][0]);
            $resultsArray[$i][2] = count($comparison);
        }
        $currentHighest = NULL;
        //variable to store highest value
        $currentHighestSKU = NULL;
        for ($i = 0; $i < count($resultsArray); $i++) {
            if ($resultsArray[$i][2] > $currentHighest) {
                $currentHighest = $resultsArray[$i][2];
                $currentHighestSKU = $resultsArray[$i][1];
            }
        }
        echo "Best Match = " . $currentHighestSKU;
        push("Was that " . $currentHighestSKU . "?", $_email);
        echo "<pre>";
        print_r($resultsArray);
        echo "</pre>";
        //return $tescoSKU;
    } else {
        $errorLog = $errorLog . "<br>Lookup_Description: No results returned!";
        //send push to user
        push("ERROR : Item not added no items found", $_email);
        //return "ERROR_NO_results";
    }
}
예제 #21
0
파일: Stack.php 프로젝트: Just-Man/PHP
<?php

/**
 * Created by PhpStorm.
 * User: just
 * Date: 24.11.15
 * Time: 09:27
 */
$stack = [];
function pop()
{
    global $stack;
    return array_pop($stack);
}
function push($entry)
{
    global $stack;
    return array_push($stack, $entry);
}
foreach (['clubs', 'diamonds', 'hearts', 'spades'] as $color) {
    foreach (array_merge(range(2, 10), ['J', 'D', 'K', 'A']) as $value) {
        push(['Color' => $color, 'Value' => $value]);
    }
}
shuffle($stack);
$cardToGive = 12;
while ($cardToGive -= 1) {
    pop();
}
$trump = pop();
print_r($trump);
예제 #22
0
 /**
  * Push notification
  */
 public function push_notification()
 {
     if ($this->isAjax()) {
         $id = isset($_POST['id']) ? intval($_POST['id']) : $this->redirect('/');
         $vip_only = isset($_POST['vip_only']) ? intval($_POST['vip_only']) : $this->redirect('/');
         $flag = false;
         $message = M('Notification')->field(array('content'))->where(array('id' => $id))->find();
         if ($vip_only) {
             $result = M('Member')->field(array('id'))->where(array('is_vip' => 1))->select();
             $vips = array();
             if (!empty($result)) {
                 $i = ceil(count($result) / 1000);
                 for ($j = 1; $j <= $i; $j++) {
                     $alias = "";
                     $length = min(array($j * 1000, count($result)));
                     for ($k = ($j - 1) * 1000; $k < $length; $k++) {
                         $alias .= $result[$k]['id'] . ",";
                     }
                     $vips[] = rtrim($alias, ",");
                 }
             }
             if ($vips) {
                 for ($i = 0; $i < count($vips); $i++) {
                     if (push($message['content'], 3, $vips[$i])) {
                         $flag = true;
                     } else {
                         break;
                     }
                 }
             }
         } else {
             $flag = push($message['content']);
         }
         if ($flag) {
             // Update the notification status to is pushed.
             M('Notification')->where(array('id' => $id))->save(array('is_pushed' => 1));
             $this->ajaxReturn(array('status' => true, 'msg' => 'Push notificatio successful'));
         } else {
             $this->ajaxReturn(array('status' => false, 'msg' => 'Push notificatio failed,please try again later'));
         }
     } else {
         $this->redirect('/');
     }
 }
예제 #23
0
function checkValidInputs($staffId, $tagsArrayString, $setId, $studentId)
{
    $returns = [];
    if (checkIdInputIsValid($setId)) {
        $returns["set"] = intval($setId);
    }
    if (checkIdInputIsValid($staffId)) {
        $returns["staff"] = intval($staffId);
    }
    if (checkIdInputIsValid($studentId)) {
        $returns["student"] = intval($studentId);
    }
    if (isset($tagsArrayString) && $tagsArrayString !== "") {
        $tagsArray = json_decode($tagsArrayString, true);
        $validatedArray = [];
        if (is_array($tagsArray)) {
            foreach ($tagsArray as $tagid) {
                if (checkIdInputIsValid($tagid)) {
                    $validatedArray . push(intval($tagid));
                }
            }
        }
        if (count($validatedArray) > 0) {
            $returns["tags"] = $validatedArray;
        }
    }
    if (count($returns) === 0) {
        failRequest("No valid inputs were entered");
    } else {
        return $returns;
    }
}
예제 #24
0
function socket_get_http($file_url, $request_features = array())
{
    if ($request_features['Server']) {
        # the submitted request fields contains http responce fields
        return array("", "");
    }
    $url_parse = parse_url($file_url);
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
        echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
        return;
    }
    $address = gethostbyname($url_parse['host']);
    $service_port = getservbyname('www', 'tcp');
    $result = socket_connect($socket, $address, $service_port);
    if ($result < 0) {
        echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
        exit;
    }
    if ($request_features['method'] == "POST") {
        $requests[] = "POST {$url_parse['path']} HTTP/1.1";
        push(@request, "Content-type: application/x-www-form-urlencoded");
        push(@request, "Content-length: " . length($url_parse['query']));
        push(@request, $url_parse['query']);
    } else {
        if (!$request_features['method']) {
            $request_features['method'] = "GET";
        }
        if ($url_parse['query']) {
            $requests[] = "{$request_features['method']} {$url_parse['path']}?{$url_parse['query']} HTTP/1.1";
        } else {
            $requests[] = "{$request_features['method']} {$url_parse['path']} HTTP/1.1";
        }
    }
    $requests[] = "Host: {$url_parse['host']}";
    foreach ($request_features as $key => $value) {
        if ($value and $key != "method") {
            $requests[] = "{$key}: {$value}";
        }
    }
    #$requests[] = "Referer: $request_features[refferal_url]";
    #$requests[] = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10)";
    if (!$request_features['Connection']) {
        # The following line is a must if using HTTP/1.1
        $requests[] = "Connection: Close";
    }
    $http_request = join("\r\n", $requests) . "\r\n\r\n";
    socket_write($socket, $http_request, strlen($http_request));
    $out = '';
    while ($out = socket_read($socket, 2048)) {
        $output_text .= $out;
    }
    socket_close($socket);
    #print "<pre>";
    #print_r( $http_request );
    #print "</pre>";
    #exit;
    $responce_lines = explode("\n", $output_text);
    #$http_responce_code = trim( array_shift( $http_responces ) );
    #$http_responce = trim( array_shift( $responce_lines ) );
    while ($http_responce = trim(array_shift($responce_lines))) {
        list($http_responce_name, $http_responce_value) = explode(": ", $http_responce, 2);
        if (!$http_responce_value) {
            $http_responce_value = $http_responce_name;
            $http_responce_name = "0";
        }
        $http_responces[$http_responce_name] = $http_responce_value;
    }
    if ($responce_lines) {
        $responce_file = join("\n", $responce_lines);
    }
    return array($responce_file, $http_responces);
}
예제 #25
0
<?php

$dockerRegistryDomain = 'registry.localserver.com:5443/';
$dockerRegistryPush = "{$dockerRegistryDomain}v2/";
$userName = '******';
$password = '******';
$email = '*****@*****.**';
echo login($dockerRegistryDomain, $userName, $password, $email);
echo PHP_EOL;
foreach (getImages() as $image) {
    echo $image;
    echo PHP_EOL;
    echo tag($image, $dockerRegistryPush);
    echo PHP_EOL;
    echo push($image, $dockerRegistryPush);
    echo PHP_EOL;
}
function login($registry, $userName, $password, $email = '')
{
    return myExec(sprintf('docker login --username="******" --password="******" --email="%s" %s', $userName, $password, $email, $registry));
}
function tag($imageName, $registry = 'my-registry.com:5000/')
{
    if (preg_match("~{$registry}~i", $imageName)) {
        return "skip\n";
    }
    return myExec(sprintf('docker tag %s %s%s', $imageName, $registry, $imageName));
}
function push($imageName, $registry = 'my-registry.com:5000/')
{
    $registry = preg_match("~{$registry}~i", $imageName) ? $imageName : $registry . $imageName;
예제 #26
0
//add a MOD10/Luhn alogrithm check here check here
//set login result to $loginResult
$loginResult = login();
if ($loginResult != "ERROR:LOGIN_FAILED") {
    //if login was ok
    $sessionID = $loginResult;
    //call function lookup_BCN with barcode and session ID and save result into tescoSKU variable
    $tescoSKU = lookup_BCN($barcode, $sessionID);
    if ($tescoSKU != "ERROR: No uniquie SKU found!") {
        $add_status = addToBasket($tescoSKU, $sessionID);
        if ($add_status == "BASKET_ADD:OK") {
            //echo $add_status;
            echo "<br>";
            echo "STATUS: Item added OK.";
            push($itemDescription . " added to basket", $_email);
        } else {
            //echo $add_status;
            echo "<br>";
            echo "STATUS: Error while adding.";
        }
    } else {
        //$errorLog = $errorLog."<br>Lookup_BCN failed!"; //error already generated inside lookup_BCN function
        //remove error reporting from SKU lookup function as there is now an alternate lookup route
    }
} else {
    //error catch
    echo "STATUS: Login failure.";
    push("Error at login stage", $_email);
}
$errorLog = $errorLog . "<br>---END ERROR LOG---";
saveDebug();
예제 #27
0
파일: new.php 프로젝트: TomWis97/CallTom
        default:
            die('Error: Invalid cause!');
    }
    $time = time();
    $response = 0;
    $message = htmlentities($_POST['text']);
    $db = new PDO($dbpdodsn, $dbuser, $dbpassword, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    $st_addcall = $db->prepare('INSERT INTO calls (callid, deviceid, type, time, response, message, reminded) VALUES (:cid, :did, :ty, :ti, :re, :m, 0)');
    $st_addcall->bindParam(':cid', $callid);
    $st_addcall->bindParam(':did', $deviceid);
    $st_addcall->bindParam(':ty', $type);
    $st_addcall->bindParam(':ti', $time);
    $st_addcall->bindParam(':re', $response);
    $st_addcall->bindParam(':m', $message);
    $st_addcall->execute();
    push($deviceid, $callid, $type, $time, $message, false);
    header('Location: wait.php?callid=' . $callid);
    die('Redirecting...');
}
pageheader(0, "Choosing cause");
?>
<p>Enter the cause by pressing the corresponding button. If you want to add text (optional), enter your message before pressing the button.</p>
<form method="post">
	<button class="submitbutton" type="submit" name="cause" value="1">Food</button>
	<button class="submitbutton" type="submit" name="cause" value="2">IT help</button>
    <!-- TODO: Better translation. -->
	<button class="submitbutton" type="submit" name="cause" value="3">Contact gewenst</button>
	<p class="title">Extra tekst (Optioneel)</p>
	<input type="text" name="text">
</form>
<?php 
예제 #28
0
<?php

require_once 'stack.php';
/**
 * one card 
 * [
 * 	'color' => 'pika',
 *  'value' => 'D'
 * ]
 */
foreach (['clubs', 'diamonds', 'hearts', 'spades'] as $color) {
    foreach (array_merge(range(2, 10), ['J', 'D', 'K', 'A']) as $value) {
        push(['color' => $color, 'value' => $value]);
    }
}
shuffle($stack);
$cardsToGive = 12;
while ($cardsToGive--) {
    pop();
}
$trump = pop();
print_r($trump);
예제 #29
0
파일: PushTest.php 프로젝트: nodes-php/push
 public function testGlobalFunction()
 {
     $this->bindProviderToServiceContainer();
     $this->assertInstanceOf(ProviderInterface::class, push());
 }
function push($arr, $value)
{
    array_push($arr, $value);
    return $arr;
}
function pop($arr)
{
    array_pop($arr);
    return $arr;
}
$fh = fopen($argv[1], "r");
while (!feof($fh)) {
    $heap = array();
    $phrase = "";
    $test = trim(fgets($fh));
    if ($test != "") {
        $arr = explode(" ", $test);
        for ($i = 0; $i < count($arr); $i++) {
            $heap = push($heap, $arr[$i]);
        }
        $ct = count($heap);
        while ($ct > 0) {
            $phrase .= $heap[count($heap) - 1] . " ";
            $heap = pop($heap);
            $heap = pop($heap);
            $ct = $ct - 2;
        }
        echo trim($phrase) . "\n";
    }
}
fclose($fh);