示例#1
0
 /**
  * Runs the Query against Yahoo's Database
  *
  * @param string $q the query to run
  * @return Result
  */
 public static function execute($q)
 {
     if (!isset(self::$pest)) {
         $p = new \Pest(self::API);
     }
     $json = $p->get('', ['q' => $q, 'format' => 'json', 'diagnostics' => false, 'env' => 'http://datatables.org/alltables.env']);
     return new Result($json);
 }
示例#2
0
function JsonWriter(Pest $pest, $tests)
{
    $jo = new \stdClass();
    $jo->unitName = $pest->getName();
    $jo->testsCount = count($tests);
    $jo->tests = array();
    $passedTests = 0;
    $allRecordsCount = 0;
    $allPassedRecords = 0;
    foreach ($tests as $test) {
        $joTest = new \stdClass();
        $allRecordsCount += $recordsCount = count($test->getRecords());
        $passedRecords = 0;
        foreach ($test->getRecords() as $record) {
            if ($record->getStatus()) {
                $passedRecords++;
                $allPassedRecords++;
            } else {
                if ($record->getSkipped() > 0) {
                    $allRecordsCount += $record->getSkipped();
                    $recordsCount += $record->getSkipped();
                }
            }
        }
        if ($recordsCount === $passedRecords) {
            $passedTests++;
        }
        $joTest->name = $test->getName();
        if (($exception = $test->getException()) != null) {
            $joTest->exception = new \stdClass();
            $joTest->exception->type = get_class($exception);
            $joTest->exception->message = $exception->getMessage();
            $joTest->exception->code = $exception->getCode();
            $joTest->exception->file = $exception->getFile();
            $joTest->exception->line = $exception->getLine();
            $joTest->exception->stacktrace = $exception->getTraceAsString();
        }
        $joTest->assertions = array();
        foreach ($test->getRecords() as $record) {
            $joRecord = new \stdClass();
            $joRecord->status = $record->getStatus();
            $joRecord->function = $record->getStackInfo()->getFunction();
            $joRecord->message = empty($record->getMessage()) ? "" : ": " . $record->getMessage();
            $joRecord->file = $record->getStackInfo()->getFile();
            $joRecord->line = $record->getStackInfo()->getLine();
            $joRecord->code = $record->getStackInfo()->getCode();
            $joRecord->values = $record->getValues();
            $joRecord->skipped = $record->getSkipped();
            $joTest->assertions[] = $joRecord;
        }
        $joTest->output = $test->getOutput();
        $joTest->assertionStatus = array("passed" => $passedRecords, "failed" => $recordsCount - $passedRecords);
        $jo->tests[] = $joTest;
    }
    $jo->assertionStatus = array("passed" => $allPassedRecords, "failed" => $allRecordsCount - $allPassedRecords);
    $jo->testsStatus = array("passed" => $passedTests, "failed" => $jo->testsCount - $passedTests);
    echo json_encode($jo, JSON_PRETTY_PRINT);
}
 /**
  * Return all Pests
  */
 public function actionIndex()
 {
     $response = array();
     $response['PhotoPath'] = Yii::app()->params['siteDomain'] . Yii::app()->params['imagePath'];
     $response['Entries'] = array();
     $response['Photos'] = array();
     $response['PhotoLinker'] = array();
     $pestModels = Pest::model()->findAll();
     if ($pestModels != null) {
         // Have something to return..
         // Get images for each entry.
         foreach ($pestModels as $pestModel) {
             // Get all images for current pestModel entry.
             $images = $pestModel->images;
             if ($images != null) {
                 foreach ($images as $image) {
                     $response['PhotoLinker'][] = array('Id' => $image->Id, 'EntryId' => $image->PestId, 'PhotoId' => $image->PhotoId);
                     $response['Photos'][] = array("Id" => $image->photo->Id, "ImageName" => $image->photo->Name, "EntryId" => $pestModel->Id);
                 }
             }
             $response['Entries'][] = $pestModel;
         }
     }
     $this->sendResponse(200, CJSON::encode($response));
 }
示例#4
0
 protected function prepRequest($opts, $url)
 {
     $opts[CURLOPT_HTTPHEADER][] = 'Accept: application/json';
     $opts[CURLOPT_HTTPHEADER][] = 'Content-Language: application/json';
     $opts[CURLOPT_HTTPHEADER][] = 'Authuser: '******'Authpass: ' . $this->pass;
     return parent::prepRequest($opts, $url);
 }
function campayn_init()
{
    global $campayn_api;
    global $badApi;
    $badApi = false;
    $apikey = get_option('ob_campayn_apikey');
    $apikey = $apikey['text_string'];
    $campayn_api = new Pest('http://api.campayn.com/api/v1/');
    //Test URLs
    //$campayn_api = new Pest('http://campayn.dev/api/v1/');
    //$campayn_api = new Pest('http://localhost:6666');
    $campayn_api->curl_opts[CURLOPT_HTTPHEADER] = array('Authorization:TRUEREST apikey=' . $apikey);
    try {
        $json = $campayn_api->get('/forms.json?filter[form_type]=1');
    } catch (Exception $e) {
        $badApi = true;
    }
}
示例#6
0
 /**
  * Returns (a limited amount of data) about a user's lifetime activity
  * with Uber.
  *
  * @see https://developer.uber.com/v1/endpoints/#user-activity-v1
  * @see https://developer.uber.com/v1/endpoints/#user-activity-v1-1
  * @param boolean $lite
  * @return array
  */
 public function userActivity($lite = false)
 {
     if ($lite) {
         $path = '/v1.1/history';
     } else {
         $path = '/v1/history';
     }
     $result = $this->adapter->get($path, array(), $this->getHeaders());
     return $this->format($result);
 }
示例#7
0
function ThreeLineLinuxWriter(Pest $pest, $tests, $config)
{
    $colored = function ($text, $color) {
        return "[" . $color . "m" . $text . "";
    };
    $testsCount = count($tests);
    $passedTests = 0;
    $allRecordsCount = 0;
    $allPassedRecords = 0;
    foreach ($tests as $test) {
        $allRecordsCount += $recordsCount = count($test->getRecords());
        $passedRecords = 0;
        foreach ($test->getRecords() as $record) {
            if ($record->getStatus()) {
                $passedRecords++;
                $allPassedRecords++;
            } else {
                if ($record->getSkipped() > 0) {
                    $allRecordsCount += $record->getSkipped();
                    $recordsCount += $record->getSkipped();
                }
            }
        }
        if ($recordsCount === $passedRecords && $test->getException() == null) {
            $passedTests++;
        }
    }
    if ($testsCount == $passedTests) {
        if (isset($config[\Pest\Pest::CONFIG_ONLY_FAILED])) {
            return;
        }
        echo $colored($pest->getName(), 42);
    } else {
        echo $colored($pest->getName(), 41);
    }
    echo PHP_EOL;
    printf("   Assertion status: [passed: %d, failed: %d], success rate: %01.2f%%\n", $allPassedRecords, $allRecordsCount - $allPassedRecords, $allPassedRecords / $allRecordsCount * 100);
    printf("   Test status: [passed: %d, failed: %d], success rate: %01.2f%%\n", $passedTests, $testsCount - $passedTests, $passedTests / $testsCount * 100);
    echo PHP_EOL;
}
示例#8
0
 /**
  * Gets a new API key from the bridge
  * Hint: You have to press the button on the bridge first and then
  * call this function
  *
  * @param $bridgeAddress string The IP or FQDN to the hue bridge
  * @return string with the API key
  * @throws HueError If no connection to the bridge could be established
  *          or the bridge refused to give one
  * @throws InvalidArgumentException If the bridge address is not valid
  **/
 public static function fetchAPIAccessKey($bridgeAddress)
 {
     if (strlen($bridgeAddress) == 0) {
         throw new InvalidArgumentException('Parameter $bridgeAddress is empty');
     }
     $pest = new Pest('http://' . $bridgeAddress . '/api');
     $data = json_encode(array('devicetype' => 'phpHue'));
     $result = json_decode($pest->post('', $data), true);
     if (is_null($result)) {
         throw new HueError('No connection to the Hue bridge');
     } else {
         if (array_key_exists('error', $result[0])) {
             throw new HueError($result[0]['error']['description']);
         } else {
             if (array_key_exists('success', $result[0])) {
                 return $result[0]['success']['username'];
             } else {
                 throw new HueError('Something went terribly bad. Should not happen');
             }
         }
     }
 }
示例#9
0
 public function post($url, $data, $headers = array())
 {
     $success = false;
     for ($i = 0; $i < $this->retries && !$success; $i++) {
         try {
             $result = parent::post($url, $data, $headers);
             $success = true;
         } catch (Exception $e) {
             $success = false;
         }
     }
     if (!$success) {
         throw $e;
     }
     return $result;
 }
 /**
  * Get either a Gravatar URL or complete image tag for a specified email address.
  *
  * @param string $email The email address
  * @source https://gravatar.com/site/implement/images/php/
  */
 function getGravatar($email)
 {
     $s = 75;
     //Size in pixels, defaults to 80px [ 1 - 2048 ]
     $d = '404';
     //Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
     $r = 'g';
     //Maximum rating (inclusive) [ g | pg | r | x ]
     $pest = new \Pest('https://www.gravatar.com/avatar/');
     $email = md5(strtolower(trim($email)));
     try {
         return $pest->get($email . '?s=' . $s . '&d=' . $d . '&r=' . $r);
     } catch (\Exception $e) {
         switch (get_class($e)) {
             case "Pest_NotFound":
                 return false;
                 break;
             default:
                 return false;
                 break;
         }
     }
 }
示例#11
0
 public function doConfigPageInit($page)
 {
     //Reassign $_REQUEST as it will be immutable in the future.
     $request = $_REQUEST;
     global $amp_conf;
     if ($page == "advancedsettings") {
         $freepbx_conf = $this->config;
         $settings = $freepbx_conf->get_conf_settings();
         foreach ($request as $key => $val) {
             if (isset($settings[$key])) {
                 if ($key == 'CRONMAN_UPDATES_CHECK') {
                     $cm = \cronmanager::create($db);
                     if ($val == 'true') {
                         $cm->enable_updates();
                     } else {
                         $cm->disable_updates();
                     }
                 }
                 switch ($settings[$key]['type']) {
                     case CONF_TYPE_BOOL:
                         $val = $val == 'true' ? 1 : 0;
                         break;
                     default:
                         $val = trim($val);
                         break;
                 }
                 $freepbx_conf->set_conf_values(array($key => $val), true, $amp_conf['AS_OVERRIDE_READONLY']);
                 $status = $freepbx_conf->get_last_update_status();
                 if ($status[$key]['saved']) {
                     //debug(sprintf(_("Advanced Settings changed freepbx_conf setting: [$key] => [%s]"),$val));
                     needreload();
                 }
             }
         }
     }
     // $page == "advancedsettings"
     if ($page == "dahdichandids") {
         if (!isset($_REQUEST['action'])) {
             return;
         }
         $type = isset($request['type']) ? $request['type'] : 'setup';
         $action = isset($request['action']) ? $request['action'] : '';
         if (isset($request['delete'])) {
             $action = 'delete';
         }
         $extdisplay = isset($request['extdisplay']) ? $request['extdisplay'] : '';
         $channel = isset($request['channel']) ? $request['channel'] : false;
         $description = isset($request['description']) ? $request['description'] : '';
         $did = isset($request['did']) ? $request['did'] : '';
         switch ($action) {
             case 'add':
                 if (core_dahdichandids_add($description, $channel, $did)) {
                     needreload();
                     $_REQUEST['extdisplay'] = $channel;
                     $this->freepbx->View->redirect_standard('extdisplay');
                 }
                 break;
             case 'edit':
                 if (core_dahdichandids_edit($description, $channel, $did)) {
                     needreload();
                 }
                 break;
             case 'delete':
                 core_dahdichandids_delete($channel);
                 needreload();
                 break;
         }
     }
     // $page == "dahdichandids"
     if ($page == "routing") {
         $display = 'routing';
         $extdisplay = isset($request['extdisplay']) ? $request['extdisplay'] : '';
         $action = isset($request['action']) ? $request['action'] : '';
         if (isset($request['copyroute'])) {
             $action = 'copyroute';
         }
         $repotrunkdirection = isset($request['repotrunkdirection']) ? $request['repotrunkdirection'] : '';
         //this was effectively the sequence, now it becomes the route_id and the value past will have to change
         $repotrunkkey = isset($request['repotrunkkey']) ? $request['repotrunkkey'] : '';
         // Check if they uploaded a CSV file for their route patterns
         //
         if (isset($_FILES['pattern_file']) && $_FILES['pattern_file']['tmp_name'] != '') {
             $fh = fopen($_FILES['pattern_file']['tmp_name'], 'r');
             if ($fh !== false) {
                 $csv_file = array();
                 $index = array();
                 // Check first row, ingoring empty rows and get indices setup
                 //
                 while (($row = fgetcsv($fh, 5000, ",", "\"")) !== false) {
                     if (count($row) == 1 && $row[0] == '') {
                         continue;
                     } else {
                         $count = count($row) > 4 ? 4 : count($row);
                         for ($i = 0; $i < $count; $i++) {
                             switch (strtolower($row[$i])) {
                                 case 'prepend':
                                 case 'prefix':
                                 case 'match pattern':
                                 case 'callerid':
                                     $index[strtolower($row[$i])] = $i;
                                     break;
                                 default:
                                     break;
                             }
                         }
                         // If no headers then assume standard order
                         if (count($index) == 0) {
                             $index['prepend'] = 0;
                             $index['prefix'] = 1;
                             $index['match pattern'] = 2;
                             $index['callerid'] = 3;
                             if ($count == 4) {
                                 $csv_file[] = $row;
                             }
                         }
                         break;
                     }
                 }
                 $row_count = count($index);
                 while (($row = fgetcsv($fh, 5000, ",", "\"")) !== false) {
                     if (count($row) == $row_count) {
                         $csv_file[] = $row;
                     }
                 }
             }
         }
         // If we have a CSV file it replaces any existing patterns
         //
         if (!empty($csv_file)) {
             foreach ($csv_file as $row) {
                 $this_prepend = isset($index['prepend']) ? htmlspecialchars(trim($row[$index['prepend']])) : '';
                 $this_prefix = isset($index['prefix']) ? htmlspecialchars(trim($row[$index['prefix']])) : '';
                 $this_match_pattern = isset($index['match pattern']) ? htmlspecialchars(trim($row[$index['match pattern']])) : '';
                 $this_callerid = isset($index['callerid']) ? htmlspecialchars(trim($row[$index['callerid']])) : '';
                 if ($this_prepend != '' || $this_prefix != '' || $this_match_pattern != '' || $this_callerid != '') {
                     $dialpattern_insert[] = array('prepend_digits' => $this_prepend, 'match_pattern_prefix' => $this_prefix, 'match_pattern_pass' => $this_match_pattern, 'match_cid' => $this_callerid);
                 }
             }
         } else {
             if (isset($request["prepend_digit"])) {
                 $prepend_digit = $request["prepend_digit"];
                 $pattern_prefix = $request["pattern_prefix"];
                 $pattern_pass = $request["pattern_pass"];
                 $match_cid = $request["match_cid"];
                 foreach (array_keys($prepend_digit) as $key) {
                     if ($prepend_digit[$key] != '' || $pattern_prefix[$key] != '' || $pattern_pass[$key] != '' || $match_cid[$key] != '') {
                         $dialpattern_insert[] = array('prepend_digits' => htmlspecialchars(trim($prepend_digit[$key])), 'match_pattern_prefix' => htmlspecialchars(trim($pattern_prefix[$key])), 'match_pattern_pass' => htmlspecialchars(trim($pattern_pass[$key])), 'match_cid' => htmlspecialchars(trim($match_cid[$key])));
                     }
                 }
             } else {
                 if (isset($request["bulk_patterns"])) {
                     $prepend = '/^([^+]*)\\+/';
                     $prefix = '/^([^|]*)\\|/';
                     $match_pattern = '/([^/]*)/';
                     $callerid = '/\\/(.*)$/';
                     $data = explode("\n", $request['bulk_patterns']);
                     foreach ($data as $list) {
                         if (preg_match('/^\\s*$/', $list)) {
                             continue;
                         }
                         $this_prepend = $this_prefix = $this_callerid = '';
                         if (preg_match($prepend, $list, $matches)) {
                             $this_prepend = $matches[1];
                             $list = preg_replace($prepend, '', $list);
                         }
                         if (preg_match($prefix, $list, $matches)) {
                             $this_prefix = $matches[1];
                             $list = preg_replace($prefix, '', $list);
                         }
                         if (preg_match($callerid, $list, $matches)) {
                             $this_callerid = $matches[1];
                             $list = preg_replace($callerid, '', $list);
                         }
                         $dialpattern_insert[] = array('prepend_digits' => htmlspecialchars(trim($this_prepend)), 'match_pattern_prefix' => htmlspecialchars(trim($this_prefix)), 'match_pattern_pass' => htmlspecialchars(trim($list)), 'match_cid' => htmlspecialchars(trim($this_callerid)));
                         $i++;
                     }
                 }
             }
         }
         if (isset($request['reporoutedirection']) && $request['reporoutedirection'] != '' && isset($request['reporoutekey']) && $request['reporoutekey'] != '') {
             $request['route_seq'] = core_routing_setrouteorder($request['reporoutekey'], $request['reporoutedirection']);
         }
         $trunkpriority = array();
         if (isset($request["trunkpriority"])) {
             $trunkpriority = $request["trunkpriority"];
             if (!$trunkpriority) {
                 $trunkpriority = array();
             }
             // delete blank entries and reorder
             foreach (array_keys($trunkpriority) as $key) {
                 if ($trunkpriority[$key] == '') {
                     // delete this empty
                     unset($trunkpriority[$key]);
                 } else {
                     if ($key == $repotrunkkey - 1 && $repotrunkdirection == "up") {
                         // swap this one with the one before (move up)
                         $temptrunk = $trunkpriority[$key];
                         $trunkpriority[$key] = $trunkpriority[$key + 1];
                         $trunkpriority[$key + 1] = $temptrunk;
                     } else {
                         if ($key == $repotrunkkey && $repotrunkdirection == "down") {
                             // swap this one with the one after (move down)
                             $temptrunk = $trunkpriority[$key + 1];
                             $trunkpriority[$key + 1] = $trunkpriority[$key];
                             $trunkpriority[$key] = $temptrunk;
                         }
                     }
                 }
             }
             unset($temptrunk);
             $trunkpriority = array_unique(array_values($trunkpriority));
             // resequence our numbers
             if ($action == '') {
                 $action = "updatetrunks";
             }
         }
         $routename = isset($request['routename']) ? $request['routename'] : '';
         $routepass = isset($request['routepass']) ? $request['routepass'] : '';
         $emergency = isset($request['emergency']) ? $request['emergency'] : '';
         $intracompany = isset($request['intracompany']) ? $request['intracompany'] : '';
         $mohsilence = isset($request['mohsilence']) ? $request['mohsilence'] : '';
         $outcid = isset($request['outcid']) ? $request['outcid'] : '';
         $outcid_mode = isset($request['outcid_mode']) ? $request['outcid_mode'] : '';
         $time_group_id = isset($request['time_group_id']) ? $request['time_group_id'] : '';
         $route_seq = isset($request['route_seq']) ? $request['route_seq'] : '';
         $goto = isset($request['goto0']) ? $request['goto0'] : '';
         $dest = $goto ? $request[$goto . '0'] : '';
         //if submitting form, update database
         switch ($action) {
             case 'ajaxroutepos':
                 $ret = core_routing_setrouteorder($repotrunkkey, $repotrunkdirection);
                 needreload();
                 header("Content-type: application/json");
                 echo json_encode(array('position' => $ret));
                 exit;
                 break;
             case "copyroute":
                 $routename .= "_copy_{$extdisplay}";
                 $extdisplay = '';
                 $route_seq++;
                 // Fallthrough to addtrunk now...
                 //
             // Fallthrough to addtrunk now...
             //
             case "addroute":
                 $extdisplay = core_routing_addbyid($routename, $outcid, $outcid_mode, $routepass, $emergency, $intracompany, $mohsilence, $time_group_id, $dialpattern_insert, $trunkpriority, $route_seq, $dest);
                 needreload();
                 break;
             case "editroute":
                 $extdisplay = $_REQUEST['id'];
                 core_routing_editbyid($extdisplay, $routename, $outcid, $outcid_mode, $routepass, $emergency, $intracompany, $mohsilence, $time_group_id, $dialpattern_insert, $trunkpriority, $route_seq, $dest);
                 needreload();
                 break;
             case "delroute":
                 if (!function_exists('core_routing_delbyid')) {
                     if (file_exists(__DIR__ . "/functions.inc.php")) {
                         include __DIR__ . "/functions.inc.php";
                     }
                 }
                 $ret = core_routing_delbyid($_REQUEST['id']);
                 // re-order the routes to make sure that there are no skipped numbers.
                 // example if we have 001-test1, 002-test2, and 003-test3 then delete 002-test2
                 // we do not want to have our routes as 001-test1, 003-test3 we need to reorder them
                 // so we are left with 001-test1, 002-test3
                 needreload();
                 return $ret;
                 break;
             case "updatetrunks":
                 $ret = core_routing_updatetrunks($extdisplay, $trunkpriority, true);
                 header("Content-type: application/json");
                 echo json_encode(array('result' => $ret));
                 needreload();
                 exit;
                 break;
             case 'prioritizeroute':
                 needreload();
                 break;
             case 'getnpanxxjson':
                 try {
                     $npa = $request['npa'];
                     $nxx = $request['nxx'];
                     $url = 'http://www.localcallingguide.com/xmllocalprefix.php?npa=602&nxx=930';
                     $request = new \Pest('http://www.localcallingguide.com/xmllocalprefix.php');
                     $data = $request->get('?npa=' . $npa . '&nxx=' . $nxx);
                     $xml = new \SimpleXMLElement($data);
                     $pfdata = $xml->xpath('//lca-data/prefix');
                     $retdata = array();
                     foreach ($pfdata as $item) {
                         $inpa = (string) $item->npa;
                         $inxx = (string) $item->nxx;
                         $retdata[$inpa . $inxx] = array('npa' => $inpa, 'nxx' => $inxx);
                     }
                     $ret = json_encode($retdata);
                     header("Content-type: application/json");
                     echo $ret;
                     exit;
                 } catch (Pest_NotFound $e) {
                     header("Content-type: application/json");
                     echo json_encode(array('error' => $e));
                     exit;
                 }
                 break;
             case 'populatenpanxx':
                 $dialpattern_array = $dialpattern_insert;
                 if (preg_match("/^([2-9]\\d\\d)-?([2-9]\\d\\d)\$/", $_REQUEST["npanxx"], $matches)) {
                     // first thing we do is grab the exch:
                     $ch = curl_init();
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                     curl_setopt($ch, CURLOPT_URL, "http://www.localcallingguide.com/xmllocalprefix.php?npa=" . $matches[1] . "&nxx=" . $matches[2]);
                     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; Ringfree PBX Local Trunks Configuration)");
                     $str = curl_exec($ch);
                     curl_close($ch);
                     // quick 'n dirty - nabbed from PEAR
                     global $amp_conf;
                     require_once $amp_conf['AMPWEBROOT'] . '/admin/modules/core/XML_Parser.php';
                     require_once $amp_conf['AMPWEBROOT'] . '/admin/modules/core/XML_Unserializer.php';
                     $xml = new xml_unserializer();
                     $xml->unserialize($str);
                     $xmldata = $xml->getUnserializedData();
                     $hash_filter = array();
                     //avoid duplicates
                     if (isset($xmldata['lca-data']['prefix'])) {
                         // we do the loops separately so patterns are grouped together
                         // match 1+NPA+NXX (dropping 1)
                         foreach ($xmldata['lca-data']['prefix'] as $prefix) {
                             if (isset($hash_filter['1' . $prefix['npa'] . $prefix['nxx']])) {
                                 continue;
                             } else {
                                 $hash_filter['1' . $prefix['npa'] . $prefix['nxx']] = true;
                             }
                             $dialpattern_array[] = array('prepend_digits' => '', 'match_pattern_prefix' => '1', 'match_pattern_pass' => htmlspecialchars($prefix['npa'] . $prefix['nxx']) . 'XXXX', 'match_cid' => '');
                         }
                         // match NPA+NXX
                         foreach ($xmldata['lca-data']['prefix'] as $prefix) {
                             if (isset($hash_filter[$prefix['npa'] . $prefix['nxx']])) {
                                 continue;
                             } else {
                                 $hash_filter[$prefix['npa'] . $prefix['nxx']] = true;
                             }
                             $dialpattern_array[] = array('prepend_digits' => '', 'match_pattern_prefix' => '', 'match_pattern_pass' => htmlspecialchars($prefix['npa'] . $prefix['nxx']) . 'XXXX', 'match_cid' => '');
                         }
                         // match 7-digits
                         foreach ($xmldata['lca-data']['prefix'] as $prefix) {
                             if (isset($hash_filter[$prefix['nxx']])) {
                                 continue;
                             } else {
                                 $hash_filter[$prefix['nxx']] = true;
                             }
                             $dialpattern_array[] = array('prepend_digits' => '', 'match_pattern_prefix' => '', 'match_pattern_pass' => htmlspecialchars($prefix['nxx']) . 'XXXX', 'match_cid' => '');
                         }
                         unset($hash_filter);
                     } else {
                         $errormsg = _("Error fetching prefix list for: ") . $request["npanxx"];
                     }
                 } else {
                     // what a horrible error message... :p
                     $errormsg = _("Invalid format for NPA-NXX code (must be format: NXXNXX)");
                 }
                 if (isset($errormsg)) {
                     echo "<script language=\"javascript\">alert('" . addslashes($errormsg) . "');</script>";
                     unset($errormsg);
                 }
                 break;
         }
     }
     // $page == "routing"
     if ($page == "did") {
         $extdisplay = htmlspecialchars(isset($request['extdisplay']) ? $request['extdisplay'] : '');
         $old_extdisplay = $extdisplay;
         $dispnum = 'did';
         //used for switch on config.php
         $account = isset($request['account']) ? $request['account'] : '';
         $action = isset($request['action']) ? $request['action'] : '';
         $goto = isset($request['goto0']) ? $request['goto0'] : '';
         $ringing = isset($request['ringing']) ? $request['ringing'] : '';
         $reversal = isset($request['reversal']) ? $request['reversal'] : '';
         $description = htmlspecialchars(isset($request['description']) ? $request['description'] : '');
         $privacyman = isset($request['privacyman']) ? $request['privacyman'] : '0';
         $pmmaxretries = isset($request['pmmaxretries']) ? $request['pmmaxretries'] : '';
         $pmminlength = isset($request['pmminlength']) ? $request['pmminlength'] : '';
         $alertinfo = htmlspecialchars(isset($request['alertinfo']) ? $request['alertinfo'] : '');
         $mohclass = isset($request['mohclass']) ? $request['mohclass'] : 'default';
         $grppre = isset($request['grppre']) ? $request['grppre'] : '';
         $delay_answer = isset($request['delay_answer']) && $request['delay_answer'] ? $request['delay_answer'] : '0';
         $pricid = isset($request['pricid']) ? $request['pricid'] : '';
         $rnavsort = isset($request['rnavsort']) ? $request['rnavsort'] : 'description';
         $didfilter = isset($request['didfilter']) ? $request['didfilter'] : '';
         if (isset($request['submitclear']) && isset($request['goto0'])) {
             $request[$request['goto0'] . '0'] = '';
         }
         if (isset($request['extension']) && isset($request['cidnum'])) {
             $extdisplay = $request['extension'] . "/" . $request['cidnum'];
         }
         if (isset($request['old_extension']) && isset($request['old_cidnum'])) {
             $old_extdisplay = $request['old_extension'] . "/" . $request['old_cidnum'];
         }
         //update db if submiting form
         switch ($action) {
             case 'addIncoming':
                 //create variables from request
                 extract($request, EXTR_SKIP);
                 //add details to the 'incoming' table
                 if (core_did_add($request)) {
                     needreload();
                     $_REQUEST['extdisplay'] = $_REQUEST['extension'] . "/" . $_REQUEST['cidnum'];
                     $this->freepbx->View->redirect_standard('extdisplay', 'didfilter', 'rnavsort');
                 }
                 break;
             case 'delIncoming':
                 $extarray = explode('/', $extdisplay, 2);
                 core_did_del($extarray[0], $extarray[1]);
                 needreload();
                 break;
             case 'edtIncoming':
                 $extarray = explode('/', $old_extdisplay, 2);
                 if (core_did_edit($extarray[0], $extarray[1], $_REQUEST)) {
                     needreload();
                 }
                 break;
         }
     }
     // $page == "did"
     if ($page == "astmodules") {
         $action = !empty($request['action']) ? $request['action'] : "";
         $section = !empty($request['section']) ? $request['section'] : "";
         $module = !empty($request['module']) ? $request['module'] : "";
         switch ($action) {
             case 'add':
                 switch ($section) {
                     case 'amodload':
                         $this->ModulesConf->load($module);
                         return true;
                         break;
                     case 'amodnoload':
                         $this->ModulesConf->noload($module);
                         return true;
                         break;
                     case 'amodpreload':
                         $this->ModulesConf->preload($module);
                         return true;
                         break;
                     default:
                         return false;
                         break;
                 }
                 break;
             case 'del':
                 switch ($section) {
                     case 'amodnoload':
                         $this->ModulesConf->removenoload($module);
                         return true;
                         break;
                     case 'amodpreload':
                         $this->ModulesConf->removepreload($module);
                         return true;
                         break;
                     default:
                         return false;
                         break;
                 }
                 break;
             default:
                 return false;
                 break;
         }
     }
     // $page == "astmodules"
 }
示例#12
0
文件: PestJSON.php 项目: battis/pest
 /**
  * Prepare request
  *
  * @param array $opts
  * @param string $url
  * @return resource
  */
 protected function prepRequest($opts, $url)
 {
     $opts[CURLOPT_HTTPHEADER][] = 'Accept: application/json';
     $opts[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
     return parent::prepRequest($opts, $url);
 }
示例#13
0
 /**
  * Запрос статистики по SMS-рассылкам
  *
  * @access public
  * @static	 
  *
  * @param string $sessionID ID сессии. @see getSessionID_St
  * @param mixed  $startDate начало периода выборки. Строка вида (YYYY-MM-DDTHH:MM:SS) или Timestamp
  * @param mixed  $stopDate конец периода выборки. Строка вида (YYYY-MM-DDTHH:MM:SS) или Timestamp	 
  *
  * @return array массив с информацией по статистике
  * @throws SMSError_Exception
  */
 public static function getStatistics_St($sessionID, $startDate, $stopDate)
 {
     $requestString = '/Sms/Statistics?sessionId=' . $sessionID;
     if (gettype($startDate) == "string") {
         $requestString .= '&startDateTime=' . $startDate;
     } else {
         if (gettype($startDate) == "integer") {
             $requestString .= '&startDateTime=' . date("Y-m-d", $startDate) . 'T' . date("H:i:s", $startDate);
         }
     }
     if (gettype($stopDate) == "string") {
         $requestString .= '&endDateTime=' . $stopDate;
     } else {
         if (gettype($stopDate) == "integer") {
             $requestString .= '&endDateTime=' . date("Y-m-d", $stopDate) . 'T' . date("H:i:s", $stopDate);
         }
     }
     $pest = new Pest(SMSClient::m_baseURL);
     $result = array();
     try {
         $result = json_decode($pest->get($requestString), true);
     } catch (Exception $e) {
         $errorInfo = json_decode($e->getMessage());
         unset($pest);
         throw new SMSError_Exception($errorInfo->Desc, $errorInfo->Code);
     }
     unset($pest);
     return $result;
 }
 /**
  * Perform a RESTful API call
  * @param str $verb The RESTful verb (use constants: CANVAS_API_DELETE, CANVAS_API_GET, CANVAS_API_POST, CANVAS_API_PUT)
  * @param str $path Path to the particular RESTful command
  * @param array $data Associative array of parameters to for the RESTful command
  * @param bool $throwsExceptions = false Catch or throw Pest exceptions (sometimes useful to catch them elsewhere...)
  * @param bool $paginated = false Internal use only
  */
 public function call($verb, $path, $data = array(), $throwsExceptions = false, $paginated = false)
 {
     $response = null;
     /* Get as much information from the API at a time as possible (reducing API calls, etc. */
     if (!isset($data['per_page'])) {
         $data['per_page'] = '50';
     }
     $clientRetryCount = 0;
     $serverRetryCount = 0;
     do {
         $retry = false;
         try {
             if ($paginated) {
                 $response = $this->pagePest->{$verb}($path, $data, $this->buildCanvasAuthorizationHeader());
             } else {
                 $this->pagePest = $this->pest;
                 $this->lastCall['verb'] = $verb;
                 $this->lastCall['path'] = $path;
                 $this->lastCall['data'] = $data;
                 $this->lastCall['throwsExceptions'] = $throwsExceptions;
                 $response = $this->pest->{$verb}($path, $data, $this->buildCanvasAuthorizationHeader());
             }
         } catch (Pest_ServerError $e) {
             if ($throwsExceptions & CANVAS_API_EXCEPTION_SERVER) {
                 throw $e;
             } else {
                 /* who knows what goes on in the server's mind... try again */
                 $serverRetryCount++;
                 $retry = true;
                 debug_log('Retrying after Canvas API server error. ' . substr($e->getMessage(), 0, CANVAS_API_EXCEPTION_MAX_LENGTH));
             }
         } catch (Pest_ClientError $e) {
             if ($throwsExceptions & CANVAS_API_EXCEPTION_CLIENT) {
                 throw $e;
             } else {
                 /* I just watched the Canvas API throw an unauthorized error when, in fact,
                    I was authorized. Everything gets retried a few times before I give up */
                 $clientRetryCount++;
                 $retry = true;
                 debug_log('Retrying after Canvas API client error. ' . substr($e->getMessage(), 0, CANVAS_API_EXCEPTION_MAX_LENGTH));
             }
         } catch (Exception $e) {
             // treat an empty reply as a server error (which, BTW, it dang well is)
             if ($e->getMessage() == 'Empty reply from server') {
                 $serverRetryCount++;
                 $retry = true;
                 debug_log('Retrying after empty reply from server. ' . substr($e->getMessage(), 0, CANVAS_API_EXCEPTION_MAX_LENGTH));
             } else {
                 displayError(array('Error' => $e->getMessage(), 'Verb' => $verb, 'Path' => $path, 'Data' => $data), true, 'API Error', 'Something went awry in the API');
                 exit;
             }
         }
     } while ($retry == true && $clientRetryCount < API_CLIENT_ERROR_RETRIES && $serverRetryCount < API_SERVER_ERROR_RETRIES);
     if ($clientRetryCount == API_CLIENT_ERROR_RETRIES) {
         displayError(array('Status' => $this->pest->lastStatus(), 'Error' => $this->pest->lastBody(), 'Verb' => $verb, 'Path' => $path, 'Data' => $data), true, 'Probable Client Error', 'After trying ' . API_CLIENT_ERROR_RETRIES . ' times, we still got this error message from the API. (Remember to check to be sure that the object ID passed to the API is valid and exists if the API tells you that you\'re not authorized... because you\'re not authorized to work with things that don\'t exist!)');
         exit;
     }
     if ($serverRetryCount == API_SERVER_ERROR_RETRIES) {
         displayError(array('Status' => $this->pest->lastStatus(), 'Error' => $this->pest->lastBody(), 'Verb' => $verb, 'Path' => $path, 'Data' => $data), true, 'Probable Server Error', 'After trying ' . API_CLIENT_ERROR_RETRIES . ' times, we still got this error message from the API.');
         exit;
     }
     $this->lastCall['response'] = json_decode($response, true);
     $this->processPaginationLinks();
     displayError(array('API Call' => array('Verb' => $verb, 'Path' => $path, 'Data' => $data), 'Response' => $this->lastCall['response']), true, 'API Call', null, DEBUGGING_CANVAS_API);
     return $this->lastCall['response'];
 }
示例#15
0
$logindomain = "DOMAIN";
$password = "******";
// Test data
$contactId;
// Received after creating the contact.
$firstname = "John";
$lastname = "Doe";
$phonenumber = "4712345678";
// Modify to a valid mobile number.
$description = "This info was input with a REST PUT request";
$messagetext = "Hello! This message was sent by posting to the Intouch REST API.";
$sendernumber = "IntouchAPI";
// Must be a valid sendernumber set up for your account
// Setting up Pest with URL for the Intouch API and basic HTTP authentication
require_once '../Pest.php';
$pest = new Pest('http://intouchapi.pswin.com/1/');
$pest->setupAuth($user . "@" . $logindomain, $password);
$pest->curl_opts[CURLOPT_FOLLOWLOCATION] = false;
// Not supported on hosts running safe_mode!
echo "<h1>1. Creating a contact in the address book</h1>";
try {
    $contactdata = array('Firstname' => $firstname, 'Lastname' => $lastname, 'PhoneNumber' => $phonenumber);
    $contactjson = $pest->post('/contacts', $contactdata);
    $contactarray = json_decode($contactjson, true);
    $contactId = $contactarray[ContactId];
    echo "<br>Created contact with id: " . $contactId;
} catch (Exception $e) {
    echo "<br>Caught exception when creating contact : " . $e->getMessage() . "<br>";
}
echo "<h1>2. Getting the contact by its phonenumber and updating it.</h1>";
try {
示例#16
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return Pest the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = Pest::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
示例#17
0
function post_data($data_array)
{
    $CI =& get_instance();
    $CI->load->model('sync_server/sync_server_model', 'plugin_model');
    $config = $CI->plugin_model->get_rest_server_url()->row();
    $rest_client = new Pest($config->rest_server_url);
    $result = $rest_client->post('/sync_sms', $data_array);
    return $result;
}
示例#18
0
 public function get_keys()
 {
     // Generate merchant hash code
     $hash = HashGenerator::generate($this->merchant_id, $this->merchant_hash_key, $this->settlement_type, $this->order_id, $this->gross_amount);
     // populate parameters for the post request
     $data = array('SETTLEMENT_TYPE' => '01', 'MERCHANT_ID' => $this->merchant_id, 'ORDER_ID' => $this->order_id, 'SESSION_ID' => $this->session_id, 'GROSS_AMOUNT' => $this->gross_amount, 'PREVIOUS_CUSTOMER_FLAG' => $this->previous_customer_flag, 'CUSTOMER_STATUS' => $this->customer_status, 'MERCHANTHASH' => $hash, 'PROMO_ID' => $this->promo_id, 'CUSTOMER_SPECIFICATION_FLAG' => $this->billing_address_different_with_shipping_address, 'EMAIL' => $this->email, 'FIRST_NAME' => $this->first_name, 'LAST_NAME' => $this->last_name, 'POSTAL_CODE' => $this->postal_code, 'ADDRESS1' => $this->address1, 'ADDRESS2' => $this->address2, 'CITY' => $this->city, 'COUNTRY_CODE' => $this->country_code, 'PHONE' => $this->phone, 'SHIPPING_FLAG' => $this->required_shipping_address, 'SHIPPING_FIRST_NAME' => $this->shipping_first_name, 'SHIPPING_LAST_NAME' => $this->shipping_last_name, 'SHIPPING_ADDRESS1' => $this->shipping_address1, 'SHIPPING_ADDRESS2' => $this->shipping_address2, 'SHIPPING_CITY' => $this->shipping_city, 'SHIPPING_COUNTRY_CODE' => $this->shipping_country_code, 'SHIPPING_POSTAL_CODE' => $this->shipping_postal_code, 'SHIPPING_PHONE' => $this->shipping_phone, 'SHIPPING_METHOD' => $this->shipping_method, 'CARD_NO' => $this->card_no, 'CARD_EXP_DATE' => $this->card_exp_date, 'FINISH_PAYMENT_RETURN_URL' => $this->finish_payment_return_url, 'UNFINISH_PAYMENT_RETURN_URL' => $this->unfinish_payment_return_url, 'ERROR_PAYMENT_RETURN_URL' => $this->error_payment_return_url, 'LANG_ENABLE_FLAG' => $this->lang_enable_flag, 'LANG' => $this->lang, 'enable_3d_secure' => $this->enable_3d_secure);
     // data query string only without commodity
     $query_string = http_build_query($data);
     // Build Commodity
     if (isset($this->commodity)) {
         $commodity_query_string = $this->build_commodity_query_string($this->commodity);
         $query_string = "{$query_string}&{$commodity_query_string}";
     }
     // Build Installment Banks
     if (isset($this->installment_banks)) {
         foreach ($this->installment_banks as $bank) {
             $query_string = "{$query_string}&installment_banks[]={$bank}";
         }
     }
     // Build Installment Terms
     if (isset($this->installment_terms)) {
         foreach ($this->installment_terms as $install) {
             $query_string = "{$query_string}&installment_terms[]={$install}";
         }
     }
     // Build Promo Bins
     if (isset($this->promo_bins)) {
         foreach ($this->promo_bins as $bin) {
             $query_string = "{$query_string}&promo_bins[]={$bin}";
         }
     }
     // Build Point Banks
     if (isset($this->point_banks)) {
         foreach ($this->point_banks as $bank) {
             $query_string = "{$query_string}&point_banks[]={$bank}";
         }
     }
     $client = new Pest(self::REQUEST_KEY_URL);
     $result = $client->post('', $query_string);
     $key = $this->extract_keys_from($result);
     return $key;
 }
示例#19
0
//Permit/Deny
if ($_SERVER["REMOTE_ADDR"] != "70.36.146.245") {
    //die('Not Authorized');
}
$regex = '/\\/(.*)\\/accounts\\/(.*)\\/(.*)\\/(.*)/';
preg_match($regex, $_SERVER['REQUEST_URI'], $matches);
$version = $matches[1];
$account_id = $matches[2];
$phone = $matches[3];
$file = $matches[4];
$path = str_replace('servers/rest/generate', '', dirname(__FILE__));
define('PROVISIONER_BASE', $path);
require PROVISIONER_BASE . 'autoload.php';
require 'pest.php';
$pest = new Pest('http://www.provisioner.net/r/v1/accounts');
if (preg_match('/[0-9A-Fa-f]{12}/i', $file, $matches) && !preg_match('/[0]{10}[0-9]{2}/i', $file)) {
    $mac = $matches[0];
    //Ironically we call our own rest here
    $data = $pest->get('/' . $account_id . '/provision/' . strtoupper($mac));
    $data = json_decode($data, TRUE);
    if (isset($data['data']['success']) && !$data['data']['success']) {
        $data = $pest->get('/' . $account_id . '/provision/' . strtolower($mac));
        $data = json_decode($data, TRUE);
        if (isset($data['data']['success']) && !$data['data']['success']) {
            die($data['data']['message']);
        }
    }
    $brand = isset($data['phone_data']['brand']) ? $data['phone_data']['brand'] : $data['data']['statics']['brand'];
    $family = isset($data['phone_data']['product']) ? $data['phone_data']['product'] : $data['data']['statics']['brand'];
    $model = isset($data['phone_data']['model']) ? $data['phone_data']['model'] : $data['data']['statics']['brand'];
示例#20
0
function LinuxWriter(Pest $pest, $tests, $config)
{
    $colored = function ($text, $color) {
        return "[" . $color . "m" . $text . "";
    };
    $dump = function ($mixed) {
        switch (gettype($mixed)) {
            case 'string':
                return "string[" . strlen($mixed) . "](" . var_export($mixed, true) . ")";
            default:
                return gettype($mixed) . "(" . var_export($mixed, true) . ")";
        }
    };
    echo str_pad("", 80, '#') . PHP_EOL;
    echo PHP_EOL;
    echo "   " . $pest->getName() . PHP_EOL;
    echo PHP_EOL;
    echo str_pad("", 80, '#') . PHP_EOL;
    $testsCount = count($tests);
    $passedTests = 0;
    $allRecordsCount = 0;
    $allPassedRecords = 0;
    foreach ($tests as $test) {
        $allRecordsCount += $recordsCount = count($test->getRecords());
        $passedRecords = 0;
        foreach ($test->getRecords() as $record) {
            if ($record->getStatus()) {
                $passedRecords++;
                $allPassedRecords++;
            } else {
                if ($record->getSkipped() > 0) {
                    $allRecordsCount += $record->getSkipped();
                    $recordsCount += $record->getSkipped();
                }
            }
        }
        if ($recordsCount === $passedRecords && ($exception = $test->getException()) == null) {
            $status = "[" . $colored("passed", 42) . "] ";
            $passedTests++;
            if (isset($config[\Pest\Pest::CONFIG_ONLY_FAILED])) {
                continue;
            }
        } else {
            $status = "[" . $colored("failed", 41) . "] ";
        }
        echo "   " . $status . $test->getName() . PHP_EOL . PHP_EOL;
        if (($exception = $test->getException()) != null) {
            $exception instanceof \Exception;
            echo "    Uncought exception:" . PHP_EOL . PHP_EOL;
            echo "        Type:    " . get_class($exception) . PHP_EOL;
            echo "        Message: " . $exception->getMessage() . PHP_EOL;
            echo "        Code:    " . $exception->getCode() . PHP_EOL;
            echo "        File:    " . $exception->getFile() . PHP_EOL;
            echo "        Line:    " . $exception->getLine() . PHP_EOL;
            echo "        Stacktrace:    " . PHP_EOL;
            echo "            " . str_replace("\n", "\n            ", $exception->getTraceAsString()) . PHP_EOL;
            continue;
        }
        foreach ($test->getRecords() as $record) {
            if ($record->getStatus()) {
                if (isset($config[\Pest\Pest::CONFIG_ONLY_FAILED])) {
                    continue;
                }
                $status = "      [" . $colored("passed", 42) . "] ";
            } else {
                $status = "      [" . $colored("failed", 41) . "] ";
            }
            echo $status . $record->getStackInfo()->getFunction() . (empty($record->getMessage()) ? "" : ": " . $record->getMessage()) . PHP_EOL . PHP_EOL;
            echo "         File: " . $record->getStackInfo()->getFile() . PHP_EOL;
            echo "         Line: " . $record->getStackInfo()->getLine() . PHP_EOL;
            echo "         " . $record->getStackInfo()->getCode() . PHP_EOL . PHP_EOL;
            if (!$record->getStatus()) {
                for ($i = 0; $i < count($record->getValues()); $i++) {
                    $value = $record->getValues()[$i];
                    echo "            #{$i} " . $dump($value) . PHP_EOL;
                }
            }
            echo PHP_EOL;
            if ($record->getSkipped() > 0) {
                echo "         " . $colored("SKIPPED", 43) . " " . $record->getSkipped() . " assertions because of this assertion" . PHP_EOL . PHP_EOL;
            }
        }
        if (!empty($test->getOutput())) {
            echo "   Test output:" . PHP_EOL;
            foreach (explode(PHP_EOL, $test->getOutput()) as $line) {
                echo "         " . $line . PHP_EOL;
            }
        }
        printf("   Assertion status: [passed: %d, failed: %d], success rate: %01.2f%%\n", $passedRecords, $recordsCount - $passedRecords, $passedRecords / $recordsCount * 100);
        echo "   " . str_pad("", 77, '-') . PHP_EOL;
    }
    echo PHP_EOL;
    echo str_pad("", 80, '#') . PHP_EOL;
    printf("\n   Assertion status: [passed: %d, failed: %d], success rate: %01.2f%%\n", $allPassedRecords, $allRecordsCount - $allPassedRecords, $allPassedRecords / $allRecordsCount * 100);
    printf("\n   Test status: [passed: %d, failed: %d], success rate: %01.2f%%\n", $passedTests, $testsCount - $passedTests, $passedTests / $testsCount * 100);
    echo PHP_EOL;
}
 public function ajaxHandler()
 {
     switch ($_REQUEST['command']) {
         case 'getJSON':
             switch ($_REQUEST['jdata']) {
                 case 'grid':
                     $data = array_values($this->getAllUsers());
                     if ($data) {
                         return $data;
                     } else {
                         return array();
                     }
                     break;
                 default:
                     return false;
                     break;
             }
             break;
         case 'listApps':
             $ariuser = $this->Conf->get_conf_setting('FPBX_ARI_USER');
             $aripass = $this->Conf->get_conf_setting('FPBX_ARI_PASSWORD');
             $pest = new \Pest('http://localhost:8088/ari/');
             $pest->setupAuth($ariuser, $aripass);
             $apps = $pest->get('/applications');
             return json_decode($apps);
             break;
         default:
             return false;
             break;
     }
 }