Exemplo n.º 1
0
 /**
  * Calculate the image size by allowed image size.
  * 
  * @param string|array  $image
  * @param array         $allowSize
  * @return array
  * @throws \Exception 
  */
 public static function scaleImageSize($image, $allowSize)
 {
     if (is_string($image)) {
         $imageSizeRaw = getimagesize($image);
         $imageSize['w'] = $imageSizeRaw[0];
         $imageSize['h'] = $imageSizeRaw[1];
     } else {
         $imageSize = $image;
     }
     if (!isset($imageSize['w']) or !isset($imageSize['h'])) {
         throw \Exception(_a('Raw image width and height data is needed!'));
     }
     if (!isset($allowSize['image_width']) or !isset($allowSize['image_height'])) {
         throw \Exception(_a('The limitation data is needed!'));
     }
     $scaleImage = $imageSize;
     if ($imageSize['w'] >= $imageSize['h']) {
         if ($imageSize['w'] > $allowSize['image_width']) {
             $scaleImage['w'] = (int) $allowSize['image_width'];
             $scaleImage['h'] = (int) ($allowSize['image_width'] * $imageSize['h'] / $imageSize['w']);
         }
     } else {
         if ($imageSize['h'] > $allowSize['image_height']) {
             $scaleImage['h'] = (int) $allowSize['image_height'];
             $scaleImage['w'] = (int) ($allowSize['image_height'] * $imageSize['w'] / $imageSize['h']);
         }
     }
     return $scaleImage;
 }
Exemplo n.º 2
0
 /**
  * Gets the required context.
  *
  * Getting a context you get access to all the steps
  * that uses direct API calls; steps returning step chains
  * can not be executed like this.
  *
  * @throws coding_exception
  * @param string $classname Context identifier (the class name).
  * @return BehatBase
  */
 public static function get($classname)
 {
     if (!self::init_context($classname)) {
         throw Exception('The required "' . $classname . '" class does not exist');
     }
     return self::$contexts[$classname];
 }
 public function save(Gyuser_Model_BankAccounts $bank)
 {
     if (trim($bank->getOpening_date()) == '') {
         $opening_date = null;
     } else {
         $dateArr = explode('/', $bank->getOpening_date());
         if (checkdate($dateArr[1], $dateArr[0], $dateArr[2])) {
             $stampeddate = mktime(12, 0, 0, $dateArr[1], $dateArr[0], $dateArr[2]);
             $opening_date = date("Y-m-d", $stampeddate);
         } elseif (checkdate($dateArr[0], '01', $dateArr[1])) {
             //in case they have entered only month and year format ex: 02/1993
             $stampeddate = mktime(12, 0, 0, $dateArr[0], '01', $dateArr[1]);
             $opening_date = date("Y-m-d", $stampeddate);
         } else {
             throw Exception('The bank opening date is invalid.');
         }
     }
     $data = array("user_id" => $bank->getUser_id(), "bank_name" => $bank->getBank_name(), "account_n" => $bank->getAccount_n(), "branch" => $bank->getBranch(), "opening_date" => $opening_date, "zip_code" => $bank->getZip_code(), "location_capital" => $bank->getLocation_capital());
     if (null === ($id = $bank->getId())) {
         unset($data['id']);
         $id = $this->getDbTable()->insert($data);
         return $id;
     } else {
         unset($data['user_id']);
         $id = $this->getDbTable()->update($data, array('id = ?' => $id));
         return $id;
     }
 }
Exemplo n.º 4
0
 public final function getName()
 {
     if (!$this->name) {
         throw Exception('You must define name for your shape');
     }
     return $this->name;
 }
 public function calculateTotalAmount($BillingAgreementDetails, $paymentAmountPreTaxAndShipping, $shippingType)
 {
     $paymentTotal = $paymentAmountPreTaxAndShipping;
     if ($BillingAgreementDetails->getDestination() == null) {
         throw Exception("Error - expected to find destination in billing agreement details response" . ", check that correct versions of the widgets have been" . " used to create the Amazon billing agreement Id");
     }
     $physicalAddress = $BillingAgreementDetails->getDestination()->getPhysicalDestination();
     /* *********************************************************************
      * Add shipping costs to the total order, based on the country of the
      * destination address
      * ******************************************************************
      */
     if (array_key_exists($physicalAddress->getCountryCode(), $this->_countryCostsMatrix)) {
         $paymentTotal = $paymentTotal + $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->shippingRates[$shippingType];
         /* *********************************************************************
          * Add tax to the order if the the state or region exists in our
          * tax rate map
          * ********************************************************************
          */
         if (array_key_exists($physicalAddress->getStateOrRegion(), $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->taxRates)) {
             $paymentTotal = $paymentTotal * $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->taxRates[$physicalAddress->getStateOrRegion()];
         }
     } else {
         $paymentTotal = $paymentTotal + $_this->countryCostsMatrix["Unknown"]->shippingRates[$shippingType];
     }
     return $paymentTotal;
 }
Exemplo n.º 6
0
 public function savePdf()
 {
     $pnr = $this->em->getRepository('AppCoreBundle:Pnr')->find($this->id);
     if (!$pnr) {
         return \Exception('PNR not found');
     }
     //Trick to prevent cache size exceeded
     //set_time_limit(0);
     while (ob_get_level()) {
         ob_end_clean();
     }
     ob_implicit_flush(true);
     /*
      * Construct PDF with Mpdf service
      * Layout based on HTML twig template
      */
     $service = $this->tfox;
     $pdf = $service->getMpdf(array('', 'A4', 8, 'Helvetica', 10, 10, 15, 15, 9, 9, 'L'));
     $pdf->AliasNbPages('{NBPAGES}');
     $pdf->setTitle('billet-' . date('d-m-Y-H-i', time()) . '.pdf');
     $pdf->SetHeader('Billet');
     $pdf->SetFooter('{DATE j/m/Y}|{PAGENO}/{NBPAGES}');
     $html = $this->templating->renderResponse('AppCoreBundle:Pnr:billetpdf.pdf.twig', array('pnr' => $pnr));
     $pdf->WriteHTML($html);
     //$url = 'billet-'.$pnr->getNumero().'.pdf';
     //$pdf->Output($url, 'F');
     $pdf->Output();
     /*$this->get('session')->getFlashBag()->add(
     		 'success',
     				'Le billet a bien été enregistré !'
     		);*/
     //return $this->redirect($this->generateUrl('pnr_emit', array('id' => $id)));
     //return $url;
 }
Exemplo n.º 7
0
function autoedit_createPath($p, $path = '')
{
    //путь до файла или дирректории со * или без, возвращается тот же путь без звёздочки
    //Если путь приходит от пользователя нужно проверять и префикс infra/data добавляется автоматически чтобы ограничить места создания
    //if(preg_match("/\/\./",$ifolder))return err($ans,'Path should not contain points at the beginning of filename /.');
    //if(!preg_match("/^\*/",$ifolder))return err($ans,'First symbol should be the asterisk *.');
    if (is_string($p)) {
        $p = Path::resolve($p);
        $p = explode('/', $p);
        $f = array_pop($p);
        //достали файл или пустой элемент у дирректории
        $f = Path::tofs($f);
    } else {
        $f = '';
    }
    $dir = array_shift($p);
    //Создаём первую папку в адресе
    $dir = Path::tofs($dir);
    if ($dir) {
        if (!is_dir($path . $dir)) {
            $r = mkdir($path . $dir);
        } else {
            $r = true;
        }
        if ($r) {
            return autoedit_createPath($p, $path . $dir . '/') . $f;
        } else {
            throw Exception('Ошибка при работе с файловой системой');
        }
    }
    return $path . $dir . '/' . $f;
}
 /**
  * @param ContainerBuilder $container
  *
  * @throws \InvalidArgumentException
  */
 public function process(ContainerBuilder $container)
 {
     $config = $container->getExtensionConfig('elastica')[0];
     $jsonLdFrameLoader = $container->get('nemrod.elastica.jsonld.frame.loader.filesystem');
     $confManager = $container->getDefinition('nemrod.elastica.config_manager');
     $filiationBuilder = $container->get('nemrod.filiation.builder');
     $jsonLdFrameLoader->setFiliationBuilder($filiationBuilder);
     foreach ($config['indexes'] as $name => $index) {
         $indexName = isset($index['index_name']) ? $index['index_name'] : $name;
         foreach ($index['types'] as $typeName => $settings) {
             $jsonLdFrameLoader->setEsIndex($name);
             $frame = $jsonLdFrameLoader->load($settings['frame'], null, true, true, true);
             $type = !empty($frame['@type']) ? $frame['@type'] : $settings['type'];
             if (empty($type)) {
                 throw \Exception("You must provide a RDF Type.");
             }
             //type
             $typeId = 'nemrod.elastica.type.' . $name . '.' . $typeName;
             $indexId = 'nemrod.elastica.index.' . $name;
             $typeDef = new DefinitionDecorator('nemrod.elastica.type.abstract');
             $typeDef->replaceArgument(0, $type);
             $typeDef->setFactory(array(new Reference($indexId), 'getType'));
             $typeDef->addTag('nemrod.elastica.type', array('index' => $name, 'name' => $typeName, 'type' => $type));
             $container->setDefinition($typeId, $typeDef);
             //registering config to configManager
             $confManager->addMethodCall('setTypeConfigurationArray', array($name, $typeName, $type, $frame));
         }
     }
 }
Exemplo n.º 9
0
 protected function closureTestMethod($name, $value, $query)
 {
     if (!is_array($value) || count($value) !== 2) {
         throw \Exception("Value for {$name} not correctly passed through closure!");
     }
     return $query->where('name', '=', $value[0])->where('test_related_model_id', '=', $value[1]);
 }
 public function getTotalResults()
 {
     if (!$this->isPaged()) {
         throw Exception("This API result has no paging information");
     }
     return $this->pagingData['total_results'];
 }
Exemplo n.º 11
0
 public function editTourAction()
 {
     $form = $this->view->form = new Yntour_Form_Tour_Create();
     $model = new Yntour_Model_DbTable_Tours();
     $id = $this->_getParam('tour_id', 0);
     $item = $model->find($id)->current();
     $request = $this->getRequest();
     if ($request->isGet()) {
         if (is_object($item)) {
             $form->populate($item->toArray());
         } else {
             $uri = parse_url($request->getServer('HTTP_REFERER'));
             $path = trim($uri['path']);
             $baseURL = $request->getBaseUrl();
             $path = str_replace($baseURL, '', $path);
             $bodyid = $this->_getParam('body', 'global_page_user-index-home');
             $form->populate(array('path' => $path, 'bodyid' => $bodyid));
         }
         return;
     }
     if ($request->isPost() && $form->isValid($request->getPost())) {
         $data = $form->getValues();
         if (!is_object($item)) {
             $item = $model->fetchNew();
             $item->creation_date = date('Y-m-d H:i:s');
             $item->setPath($form->getValue('path'));
             $item->hash = md5(mt_rand(0, 999999) . mt_rand(0, 999999) . mt_rand(0, 99999), false);
         }
         $item->setFromArray($data);
         if (!$item->save()) {
             throw Exception("Invalid data");
         }
         $this->_forward('success', 'utility', 'core', array('smoothboxClose' => 10, 'parentRefresh' => 10, 'messages' => array('Successful.')));
     }
 }
Exemplo n.º 12
0
function test_throw()
{
    try {
        throw Exception();
    } catch (Exception $exn) {
    }
}
function testCatchStatementHasExpectedStartLine()
{
    try {
        throw Exception();
    } catch (Exception $e) {
    }
}
Exemplo n.º 14
0
 /**
  * @return string
  */
 public function render(\Zend\Form\ElementInterface $oElement)
 {
     $config = $this->getConfig();
     $name = $oElement->getName();
     // Check whether some options have been passed via the form element
     // options
     $options = $oElement->getOption('ckeditor');
     if (!empty($options) && !is_array($options)) {
         throw \Exception('The options should either be an array or a traversable object');
     } elseif (empty($options)) {
         $options = array();
     }
     $ckfinderLoaded = $this->getModuleManager()->getModule('CKFinderModule') !== null;
     // Because zf merges arrays instead of overwriting them in the config,
     // we allow a callback and use the return as the toolbar array
     if (array_key_exists('toolbar', $config['ckeditor_options']) && is_callable($config['ckeditor_options']['toolbar'])) {
         $toolbar = $config['ckeditor_options']['toolbar']();
         if (is_array($toolbar)) {
             $config['ckeditor_options']['toolbar'] = $toolbar;
         }
     }
     // Merge the defaut edito options with the form element options
     // and turn them into json
     $jsonOptions = JsonFormatter::encode(array_merge($config['ckeditor_options'], $ckfinderLoaded ? $config['ckeditor_ckfinder_options'] : array(), $options), true);
     $loadFunctionName = $this->getTmpLoadFunctionName();
     $src = $config['src'];
     return parent::render($oElement) . '<script type="text/javascript" language="javascript">' . "\n" . 'if(typeof window.ckEditorLoading == "undefined"){' . "\n" . 'window.ckEditorLoading = false;' . "\n" . 'window.ckEditorCallbacks = [];' . "\n" . '}' . "\n" . '(function() {' . "\n" . 'function ' . $loadFunctionName . '(){' . "\n" . 'CKEDITOR.replace("' . $name . '", ' . $jsonOptions . ');' . "\n" . '}' . "\n" . 'if(typeof CKEDITOR == "undefined"){' . "\n" . 'window.ckEditorCallbacks.push(' . $loadFunctionName . ');' . "\n" . 'if(!window.ckEditorLoading) {' . "\n" . 'window.ckEditorLoading = true;' . "\n" . 'var ckScript = document.createElement("script");' . "\n" . 'ckScript.type = "text/javascript";' . "\n" . 'ckScript.async = false;' . "\n" . 'ckScript.src = "' . $src . '";' . "\n" . 'var target = document.getElementsByTagName("script")[0];' . "\n" . 'target.parentNode.insertBefore(ckScript, target);' . "\n" . 'var ckEditorInterval = setInterval(function(){' . "\n" . 'if(typeof CKEDITOR != "undefined"){' . "\n" . 'clearInterval(ckEditorInterval);' . "\n" . 'for(var i in window.ckEditorCallbacks) window.ckEditorCallbacks[i]();' . "\n" . '}' . "\n" . '}, 100);' . "\n" . '}' . "\n" . '}' . "\n" . '})();' . "\n" . '</script>' . "\n";
 }
Exemplo n.º 15
0
 public static function put($key, $value)
 {
     if (!in_array($key, self::$allowedChange)) {
         throw Exception('You cannot change the value');
     }
     self::$configArray[$key] = $value;
 }
Exemplo n.º 16
0
 /**
  * @param string label used to call function
  * @param Callable function with params (value, additional params as array)
  */
 public function addValidator($label, $function)
 {
     if (isset($this->_checks[$label])) {
         throw Exception();
     }
     $this->setValidator($label, $function);
 }
 public function __construct($args)
 {
     if (!empty($args['post_params'])) {
         $this->post_params = $args['post_params'];
     }
     if (!empty($args['filters'])) {
         $this->filters = $args['filters'];
     }
     if (isset($args['paginate'])) {
         $this->paginate = $args['paginate'];
     }
     if (isset($args['per_page'])) {
         $this->per_page = $args['per_page'];
     }
     if (isset($args['debug'])) {
         $this->debug = $args['debug'];
     }
     $this->group_by = $args['group_by'];
     if (empty($args['model'])) {
         throw Exception("Argument 'model' is required for instantiating a DatagridQueryBuilder!");
     } else {
         $this->model = $args['model'];
     }
     if (empty($args['columns'])) {
         throw Exception("Argument 'columns' is required for instantiating a DatagridQueryBuilder!");
     } else {
         $this->columns = $args['columns'];
     }
     $this->joins = $args['joins'];
     $this->sql_conditions = $args['sql_conditions'];
     $this->calling_table = $this->columns[0]->table;
     $this->build_sql();
 }
Exemplo n.º 18
0
 /**
  * Construct the service base d on the provided resource id.
  * @param ResourceId $id
  * 		The resource id, not null not empty
  */
 function __construct(ResourceId $id)
 {
     parent::__construct($id);
     if (is_null($this->searchClassName)) {
         throw \Exception("Please provide a search class name to be used.");
     }
 }
Exemplo n.º 19
0
 /**
  * 通过call变相直接调用pdo方法
  * @return [type] [description]
  */
 public function __call($key, $args)
 {
     if (!method_exists($this->pdo, $key)) {
         throw \Exception(sprintf("method %s is not exist!", $key));
     }
     call_user_func_array(array($this->pdo, $key), $args);
 }
Exemplo n.º 20
0
 /**
  * @param string $styleKey
  * @return string
  */
 public function get($styleKey)
 {
     if (!isset($this->array[$styleKey])) {
         return \Exception('The style for the key "' . $styleKey . '" is not defined');
     }
     return $this->array[$styleKey];
 }
function testCatchStatementHasExpectedEndColumn()
{
    try {
        throw Exception();
    } catch (Exception $e) {
    }
}
Exemplo n.º 22
0
 public static function echo_test()
 {
     $featureCode = new FeatureCode();
     $featureCode['name'] = 'Echo Test';
     $featureCode['registry'] = array('feature' => 'echo');
     $featureCode->save();
     try {
         $location = Doctrine::getTable('Location')->findAll();
         if (!$location->count()) {
             throw Exception('Could not find location id');
         }
         $location_id = arr::get($location, 0, 'location_id');
         $number = new Number();
         $number['user_id'] = users::getAttr('user_id');
         $number['number'] = '9999';
         $number['location_id'] = $location_id;
         $number['registry'] = array('ignoreFWD' => '0', 'ringtype' => 'ringing', 'timeout' => 20);
         $dialplan = array('terminate' => array('transfer' => 0, 'voicemail' => 0, 'action' => 'hangup'));
         $number['dialplan'] = $dialplan;
         $number['class_type'] = 'FeatureCodeNumber';
         $number['foreign_id'] = $featureCode['feature_code_id'];
         $context = Doctrine::getTable('Context')->findOneByName('Outbound Routes');
         $number['NumberContext']->fromArray(array(0 => array('context_id' => $context['context_id'])));
         $numberType = Doctrine::getTable('NumberType')->findOneByClass('FeatureCodeNumber');
         if (empty($numberType['number_type_id'])) {
             return FALSE;
         }
         $number['NumberPool']->fromArray(array(0 => array('number_type_id' => $numberType['number_type_id'])));
         $number->save();
         return $number['number_id'];
     } catch (Exception $e) {
         kohana::log('error', 'Unable to initialize device number: ' . $e->getMessage());
         throw $e;
     }
 }
Exemplo n.º 23
0
 private function getActionName($requestMethod)
 {
     if (!array_key_exists($requestMethod, $this->actions)) {
         throw \Exception("Method not allowed");
     }
     return $this->actions[$requestMethod];
 }
Exemplo n.º 24
0
 public static function arrayExtend(&$first_array)
 {
     $arrays = func_get_args();
     if (!count($arrays)) {
         \Exception('You must pass in at least one array');
     }
     $array = count($arrays) ? array_shift($arrays) : array();
     $is_assoc = function ($a) {
         if (is_array($a) && count($keys = array_keys($a))) {
             return (bool) (implode(',', $keys) !== implode(',', array_keys($keys)));
         }
         return false;
     };
     $extender = function ($a1, $a2) use($is_assoc) {
         if ($is_assoc($a2)) {
             foreach ($a2 as $key => $value) {
                 if (isset($a1[$key]) && $is_assoc($a1[$key]) && $is_assoc($value)) {
                     $a1[$key] = Utils::arrayExtend($a1[$key], $value);
                 } else {
                     $a1[$key] = $value;
                 }
             }
         } else {
             $a1 = $a2;
         }
         return $a1;
     };
     foreach ($arrays as $extendee) {
         $array = $extender($array, $extendee);
     }
     return $array;
 }
Exemplo n.º 25
0
function cropImage_common($filename, $newWidth, $newHeight)
{
    $originalFile = $filename;
    $info = getimagesize($originalFile);
    $mime = $info['mime'];
    switch ($mime) {
        case 'image/jpeg':
            $image_create_func = 'imagecreatefromjpeg';
            $image_save_func = 'imagejpeg';
            $new_image_ext = 'jpg';
            break;
        case 'image/png':
            $image_create_func = 'imagecreatefrompng';
            $image_save_func = 'imagepng';
            $new_image_ext = 'png';
            break;
        case 'image/gif':
            $image_create_func = 'imagecreatefromgif';
            $image_save_func = 'imagegif';
            $new_image_ext = 'gif';
            break;
        default:
            throw Exception('Unknown image type.');
    }
    header('Content-Type: ' . $mime);
    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);
    $newHeight = $height / $width * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    $image_save_func($tmp, null);
    imagedestroy($tmp);
}
Exemplo n.º 26
0
function resizeImage($originalFile, $targetFile, $newWidth, $newHeight)
{
    $info = getimagesize($originalFile);
    $mime = $info['mime'];
    switch ($mime) {
        case 'image/jpeg':
            $image_create_func = 'imagecreatefromjpeg';
            $image_save_func = 'imagejpeg';
            $new_image_ext = 'jpg';
            break;
        case 'image/png':
            $image_create_func = 'imagecreatefrompng';
            $image_save_func = 'imagepng';
            $new_image_ext = 'png';
            break;
        case 'image/gif':
            $image_create_func = 'imagecreatefromgif';
            $image_save_func = 'imagegif';
            $new_image_ext = 'gif';
            break;
        default:
            throw Exception('Unknown image type.');
    }
    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);
    // $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    $white = imagecolorallocate($tmp, 0, 0, 127);
    imagecolortransparent($tmp, $white);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    $image_save_func($tmp, "{$targetFile}");
}
/**
 * resize uploaded images into medium and small sizes
 * @param  string $src        original image file name
 * @param  string $mime       resized image mime type
 * @param  string $new_width  resized image width
 * @param  string $path       resized image storing path
 * @return string             resized imag path
 */
function resizeImage($src, $mime, $new_width, $path)
{
    list($src_width, $src_height) = getimagesize('upload/original/' . $src);
    $ratio = $new_width / $src_width;
    $new_height = $src_height * $ratio;
    switch ($mime) {
        case 'image/jpeg':
            $create_image_from = 'imagecreatefromjpeg';
            break;
        case 'image/png':
            $create_image_from = 'imagecreatefrompng';
            break;
        default:
            throw Exception('Unknown image type.');
    }
    $create_image_to = 'imagejpeg';
    // $new_file_ext = '.jpg';
    $image_paper = imagecreatetruecolor($new_width, $new_height);
    $original_image = $create_image_from('upload/original/' . $src);
    imagecopyresampled($image_paper, $original_image, 0, 0, 0, 0, $new_width, $new_height, $src_width, $src_height);
    $create_image_to($image_paper, $path . $src, 100);
    imagedestroy($image_paper);
    imagedestroy($original_image);
    return $path . $src;
}
Exemplo n.º 28
0
 public function hooks($name, $payload = null)
 {
     $dispatcher = Engine_Hooks_Dispatcher::getInstance();
     $event = $dispatcher->callEvent($name, $payload);
     $responses = $event->getResponses();
     if (!is_array($responses) || empty($responses)) {
         return '';
     }
     $content = '';
     foreach ($responses as $response) {
         if (is_string($response)) {
             $content .= $response;
         } else {
             if (is_array($response) && !empty($response['type'])) {
                 if ($response['type'] == 'partial') {
                     $content .= $this->view->partial(@$response['args'][0], @$response['args'][1], @$response['args'][2], @$response['args'][3]);
                 } else {
                     if ($response['type'] == 'action') {
                         $content .= $this->view->action(@$response['args'][0], @$response['args'][1], @$response['args'][2], @$response['args'][3]);
                     }
                 }
             } else {
                 throw new Zend_View() - Exception('Unknown data type returned in ' . get_class($this));
                 continue;
             }
         }
         $content .= $this->getSeparator();
     }
     return $content;
 }
Exemplo n.º 29
0
 /**
  * 发起GET请求
  * @param null $params
  * @return mixed
  * @throws
  */
 public function GET($params = null)
 {
     //组合带参数的URL
     $url = $this->url;
     if (empty($url)) {
         throw \Exception('url can not be empty!');
     }
     if ($params && \is_array($params)) {
         $url .= '?';
         $amp = '';
         foreach ($params as $paramKey => $paramValue) {
             $url .= $amp . $paramKey . '=' . \urlencode($paramValue);
             $amp = '&';
         }
     }
     //初始化curl
     $curl = \curl_init();
     if ($this->proxy_ip && $this->proxy_port) {
         $proxy = "http://{$this->proxy_ip}:{$this->proxy_port}";
         \curl_setopt($curl, CURLOPT_PROXY, $proxy);
     }
     \curl_setopt($curl, CURLOPT_URL, $url);
     \curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     \curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
     \curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->time_out);
     \curl_setopt($curl, CURLOPT_TIMEOUT, $this->transfer_time_out);
     $content = \curl_exec($curl);
     \curl_close($curl);
     return $content;
 }
Exemplo n.º 30
0
 public function processAction($args)
 {
     $config = array();
     if (isset($_GET['template'])) {
         $config['template'] = $_GET['template'];
     }
     if (isset($_GET['posts_per_page'])) {
         $config['postsPerPage'] = $_GET['posts_per_page'];
     }
     try {
         switch ($args['action']) {
             case "get_html":
                 $post = isset($args['ebl-post']) ? $args['ebl-post'] : null;
                 $isNew = isset($args['ebl-new']) ? filter_var($args['ebl-new'], FILTER_VALIDATE_BOOLEAN) : false;
                 $pageNumber = isset($args['ebl-page']) ? $args['ebl-page'] : 0;
                 $renderRes = $this->getHtml($post, $isNew, $pageNumber, $config);
                 break;
             case "get_post":
                 $postId = isset($args['id']) ? $args['id'] : null;
                 $renderRes = $this->getPost($postId, $config);
                 break;
             case "get_page":
                 $pageNumber = isset($args['number']) ? $args['number'] : 0;
                 $renderRes = $this->getPostsPage($pageNumber, $config);
                 break;
             default:
                 throw Exception("unknown action " . $args['action']);
                 break;
         }
     } catch (Exception $e) {
         http_response_code($e->getCode());
         $renderRes = "<div class=\"ebl-error\">There is a problem with Ebl! Here are some information: <pre class=\"ebl-pre\">" . "Message: '" . $e->getMessage() . "'<br />In file: '" . $e->getFile() . "' | Line " . $e->getLine() . "</pre></div>";
     }
     echo $renderRes;
 }