Example #1
1
 /**
  * Function that gets called on a job
  * Push::queue('smsSender', $emergency);
  *
  * @param $job
  * @param Emergency $emergency
  */
 public function fire($job, $image)
 {
     $s3 = AWS::get('s3');
     $image = Image::find($image['id']);
     if (!$image) {
         return $job->delete();
     }
     try {
         $imageUtil = new ImageUtil($image->origin);
         $galleryImageUtil = new ImageUtil($image->origin);
     } catch (Exception $e) {
         return $job->delete();
     }
     $image->thumbnail = $this->uploadImage($s3, $imageUtil->resize2('thumbnail')->getImage());
     Log::debug("From queue: Thumbnail: width - {$imageUtil->getWidth()}, height - {$imageUtil->getHeight()}");
     Log::debug("Thumbnail URL: {$image->thumbnail}");
     $this->preventMemoryLeak();
     $image->regular = $this->uploadImage($s3, $galleryImageUtil->resize2('gallery')->getImage());
     Log::debug("From queue: Gallery: width - {$galleryImageUtil->getWidth()}, height - {$galleryImageUtil->getHeight()}");
     Log::debug("Gallery URL: {$image->regular}");
     $this->preventMemoryLeak();
     $image->width = $galleryImageUtil->getWidth();
     $image->height = $galleryImageUtil->getHeight();
     $image->save();
     return $job->delete();
 }
Example #2
0
 public function index()
 {
     $items = array('items' => ['Pack luggage', 'Go to airport', 'Arrive in San Juan']);
     //dd($items);
     \Log::debug($items);
     return view('welcome');
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     Log::debug('IPN receiver - $_POST array: ' . print_r($_POST, TRUE));
     $ipnOrder = IPN::getOrder();
     Log::debug('IPN receiver - After processing... IPN order: ' . print_r($ipnOrder, TRUE));
     $orderItem = $ipnOrder->items->first();
     $order = Order::find((int) $orderItem->item_number);
     $order->paypal_txn_id = $ipnOrder->txn_id;
     $order->paypal_fee = $ipnOrder->mc_fee;
     $order->ipn_order_id = $ipnOrder->id;
     //$order->id = (int) $orderItem->item_number;
     if ($ipnOrder->memo) {
         $order->order_notes .= "\n\n" . $ipnOrder->memo;
     }
     if ($order->delivery_terms == 'mp3_only') {
         $order->order_status = 'Completed';
     } else {
         $order->order_status = 'Payment Received';
     }
     $order->save();
     // After the order is persisted to IPN tables,
     // we send e-mail notification to customer.
     // This ensures that e-mail confirmation is sent,
     // if customer does NOT return to our site.
     $result = OrdersController::sendEmailConfirmationExternal($order);
 }
 private static function getDbHostipId($dbh, $hostip)
 {
     if ($hostip != "") {
         Log::debug("Retrieving info for ip '{$hostip}'...");
     }
     $host = self::safeGethostbyaddr($hostip);
     $select = $dbh->prepare("SELECT a.id FROM hostip a WHERE hostip = ? AND host = ?");
     $select->bindValue(1, $hostip, PDO::PARAM_STR);
     $select->bindValue(2, $host, PDO::PARAM_STR);
     $select->execute();
     $select->bindColumn(1, $id, PDO::PARAM_STR);
     if ($select->fetch(PDO::FETCH_BOUND) === false) {
         $geoipRecord = self::safeGetGeoipRecord($hostip);
         if (!Options::pretend()) {
             $insert = $dbh->prepare("INSERT INTO hostip (hostip, host, continentcode, countrycode, countryname, region, city, postalcode, latitude, longitude) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
             $insert->bindValue(1, $hostip, PDO::PARAM_STR);
             $insert->bindValue(2, $host, PDO::PARAM_STR);
             $insert->bindValue(3, $geoipRecord["continent_code"], PDO::PARAM_STR);
             $insert->bindValue(4, $geoipRecord["country_code"], PDO::PARAM_STR);
             $insert->bindValue(5, $geoipRecord["country_name"], PDO::PARAM_STR);
             $insert->bindValue(6, $geoipRecord["region"], PDO::PARAM_STR);
             $insert->bindValue(7, $geoipRecord["city"], PDO::PARAM_STR);
             $insert->bindValue(8, $geoipRecord["postal_code"], PDO::PARAM_STR);
             $insert->bindValue(9, $geoipRecord["latitude"], PDO::PARAM_STR);
             $insert->bindValue(10, $geoipRecord["longitude"], PDO::PARAM_STR);
             $insert->execute();
             $id = $dbh->lastInsertId();
         } else {
             $id = false;
         }
     }
     return $id;
 }
Example #5
0
 /**
  * Planet クロールする
  **/
 public static function __setup_crawl__()
 {
     $http_feed = new Feed();
     foreach (C(PlanetSubscription)->find_all() as $subscription) {
         Exceptions::clear();
         Log::debug(sprintf('[crawl] feed: %d (%s)', $subscription->id(), $subscription->title()));
         try {
             $feed = $http_feed->do_read($subscription->rss_url());
             $subscription->title($feed->title());
             if ($feed->is_link()) {
                 $subscription->link(self::_get_link_href($feed->link()));
             }
             $subscription->rss_url($http_feed->url());
             $subscription->save(true);
             foreach ($feed->entry() as $entry) {
                 Exceptions::clear();
                 try {
                     $planet_entry = new PlanetEntry();
                     $planet_entry->subscription_id($subscription->id());
                     $planet_entry->title(Tag::cdata($entry->title()));
                     $planet_entry->description(Text::htmldecode(Tag::cdata($entry->fm_content())));
                     $planet_entry->link($entry->first_href());
                     $planet_entry->updated($entry->published());
                     $planet_entry->save();
                 } catch (Exception $e) {
                     Log::warn($e->getMessage());
                 }
             }
         } catch (Exception $e) {
             Log::error($e);
         }
     }
 }
 public static function create($path)
 {
     Log::debug("Reading monitor configuration from directory '{$path}'...");
     $xmls = self::scanXmls($path);
     $reader = new MonitorXmlReader();
     $monitor = new self();
     foreach ($xmls as $xml) {
         if ($reader->read(Files::path($path, $xml))) {
             foreach ($reader->getSources() as $source) {
                 $monitor->tReadSources[] = $source;
                 Log::debug("Read source '{$source}'");
             }
             foreach ($reader->getNetworkmaps() as $networkmap) {
                 $monitor->tReadNetworkmaps[] = $networkmap;
                 Log::debug("Read network map '{$networkmap}'");
             }
             foreach ($reader->getUserdbs() as $userdb) {
                 $monitor->tReadUserdbs[] = $userdb;
                 Log::debug("Read user db '{$userdb}'");
             }
             foreach ($reader->getEvents() as $event) {
                 $monitor->tReadEvents[] = $event;
                 Log::debug("Read event '{$event}'");
             }
         }
     }
     self::validateSourceReferences($monitor->tReadSources, $monitor->tReadNetworkmaps, $monitor->tReadUserdbs, $monitor->tReadEvents);
     $monitor->tEnabledSources = self::filterUnreferencedSources(self::filterDuplicateSources($monitor->tReadSources), $monitor->tReadNetworkmaps, $monitor->tReadUserdbs, $monitor->tReadEvents);
     if (count($monitor->tEnabledSources) == 0) {
         Log::err("Found no active source/events definitions while reading monitor configuration from directory '{$path}'");
         $monitor = false;
     }
     return $monitor;
 }
 /**
  * sends POST request to REST service via CURL
  * @param string $url URL to call
  * @param string $postArgs POST args
  */
 public function callRest($url, $postArgs)
 {
     if (!function_exists("curl_init")) {
         $this->last_error = 'ERROR_NO_CURL';
         Log::fatal("REST call failed - no cURL!");
         return false;
     }
     $curl = curl_init($url);
     curl_setopt($curl, CURLOPT_POST, true);
     curl_setopt($curl, CURLOPT_HEADER, false);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
     curl_setopt($curl, CURLOPT_TIMEOUT, 10);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
     Log::debug("HTTP client call: {$url} -> {$postArgs}");
     $response = curl_exec($curl);
     if ($response === false) {
         $this->last_error = 'ERROR_REQUEST_FAILED';
         $curl_errno = curl_errno($curl);
         $curl_error = curl_error($curl);
         Log::error("HTTP client: cURL call failed: error {$curl_errno}: {$curl_error}");
         return false;
     }
     Log::debug("HTTP client response: {$response}");
     curl_close($curl);
     return $response;
 }
 public function mainDoor()
 {
     $receivedData = trim(\Input::get('data'));
     //Log::debug("New System. Entry message received: ".$receivedData);
     //What access point is this?
     $this->buildingAccess->setDeviceKey('main-door');
     try {
         //Decode the message and store the message parameters in the building access object
         $this->buildingAccess->decodeDeviceCommand($receivedData);
         //Verify everything is good
         $this->buildingAccess->validateData();
     } catch (\BB\Exceptions\ValidationException $e) {
         \Log::debug("Entry message received - failed: " . $receivedData);
         //The data was invalid or the user doesnt have access
         $response = \Response::make(json_encode(['valid' => '0', 'msg' => $e->getMessage()]) . PHP_EOL, 200);
         $response->headers->set('Content-Length', strlen($response->getContent()));
         return $response;
     }
     //Is this a system message
     if ($this->buildingAccess->isSystemMessage()) {
         return $this->handleSystemMessage($receivedData);
     }
     $this->buildingAccess->logSuccess();
     $userName = substr($this->buildingAccess->getUser()->given_name, 0, 20);
     $responseBody = json_encode(['valid' => '1', 'msg' => $userName]);
     $response = \Response::make($responseBody . PHP_EOL, 200);
     $response->headers->set('Content-Length', strlen($response->getContent()));
     return $response;
 }
Example #9
0
 public static function insert($interaction)
 {
     if (is_null(self::$db)) {
         self::boot();
     }
     // Skip messages that doesn't have content
     if (!isset($interaction['interaction']['content']) || empty($interaction['interaction']['content'])) {
         Log::debug('Skipping due to no content ' . $interaction['interaction']['type'] . ': ' . $interaction['interaction']['author']['name']);
         return;
     }
     // Logging
     Log::debug('Adding ' . $interaction['interaction']['type'] . ': ' . $interaction['interaction']['author']['name']);
     // Strip any HTML tags in the content
     $interaction['interaction']['content'] = strip_tags($interaction['interaction']['content']);
     // Insert into database and broadcast to WebSocket server
     self::ensureStreamConnected();
     // Make sure that filter id is an integer
     $interaction['internal']['filter_id'] = (int) $interaction['internal']['filter_id'];
     try {
         self::$db->interactions->insert($interaction, array('w' => true));
         if (@fwrite(self::$client, json_encode($interaction) . "\n") === false) {
             Log::info('Could not write to client');
         }
     } catch (\MongoCursorException $e) {
         if ($e->getCode() != 11000) {
             // "Duplicate key" errors are ignored
             Log::error($e->getMessage());
         }
     }
 }
Example #10
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     //Create the Phone
     $phone = Phone::firstOrCreate(['name' => $this->device['DeviceName'], 'description' => $this->device['Description'], 'model' => $this->device['Model']]);
     // Create the IpAddress
     $ipAddress = IpAddress::firstOrCreate(['ip_address' => $this->device['IpAddress']]);
     // Attach the Phone and IpAddress
     $phone->ipAddresses()->sync([$ipAddress->id], false);
     //Start creating Eraser
     $tleObj = Eraser::create(['device_id' => $phone->id, 'ip_address_id' => $ipAddress->id, 'type' => $this->device['type']]);
     if (isset($this->device['bulk_id'])) {
         $tleObj->bulks()->attach($this->device['bulk_id']);
     }
     if ($this->device['IpAddress'] == "Unregistered/Unknown") {
         $tleObj->result = 'Fail';
         $tleObj->fail_reason = 'Unregistered/Unknown';
         $tleObj->save();
     }
     $keys = setKeys($this->device['Model'], $this->device['type']);
     if (!$keys) {
         $tleObj->result = 'Fail';
         $tleObj->fail_reason = 'Unsupported Model';
         $tleObj->save();
         \Log::debug('Bulk', [$tleObj]);
         return;
     }
     $dialer = new PhoneDialer($tleObj, $this->cluster);
     $status = $dialer->dial($keys);
     //Successful if returned true
     $passFail = $status ? 'Success' : 'Fail';
     $tleObj->result = $passFail;
     $tleObj->save();
 }
 public static function log($return, $context = array())
 {
     if (is_array($return)) {
         $return = json_encode($return, JSON_UNESCAPED_UNICODE);
     }
     \Log::debug($return, $context);
 }
Example #12
0
 /**
  * initializes the cache in question
  */
 protected static function _init()
 {
     $lastPriority = 1000;
     $locations = ['include/SugarCache', 'custom/include/SugarCache'];
     foreach ($locations as $location) {
         if (sugar_is_dir($location) && ($dir = opendir($location))) {
             while (($file = readdir($dir)) !== false) {
                 if ($file == ".." || $file == "." || !is_file("{$location}/{$file}")) {
                     continue;
                 }
                 require_once "{$location}/{$file}";
                 $cacheClass = basename($file, ".php");
                 if (class_exists($cacheClass) && is_subclass_of($cacheClass, 'SugarCacheAbstract')) {
                     Log::debug("Found cache backend {$cacheClass}");
                     $cacheInstance = new $cacheClass();
                     if ($cacheInstance->useBackend() && $cacheInstance->getPriority() < $lastPriority) {
                         Log::debug("Using cache backend {$cacheClass}, since " . $cacheInstance->getPriority() . " is less than " . $lastPriority);
                         self::$_cacheInstance = $cacheInstance;
                         $lastPriority = $cacheInstance->getPriority();
                     }
                 }
             }
         }
     }
 }
 /**
  * Validate the provided session information is correct and current.  Load the session.
  *
  * @param String $session_id -- The session ID that was returned by a call to login.
  * @return true -- If the session is valid and loaded.
  * @return false -- if the session is not valid.
  */
 function validate_authenticated($session_id)
 {
     Log::info('Begin: SoapHelperWebServices->validate_authenticated');
     if (!empty($session_id)) {
         // only initialize session once in case this method is called multiple times
         if (!session_id()) {
             session_id($session_id);
             session_start();
         }
         if (!empty($_SESSION['is_valid_session']) && $this->is_valid_ip_address('ip_address') && $_SESSION['type'] == 'user') {
             global $current_user;
             require_once 'modules/Users/User.php';
             $current_user = new User();
             $current_user->retrieve($_SESSION['user_id']);
             $this->login_success();
             Log::info('Begin: SoapHelperWebServices->validate_authenticated - passed');
             Log::info('End: SoapHelperWebServices->validate_authenticated');
             return true;
         }
         Log::debug("calling destroy");
         session_destroy();
     }
     LogicHook::instance()->call_custom_logic('Users', 'login_failed');
     Log::info('End: SoapHelperWebServices->validate_authenticated - validation failed');
     return false;
 }
 public function register()
 {
     \Log::debug("FrontendServiceProvider registered");
     // Register facades
     $this->app->booting(function () {
     });
 }
Example #15
0
 /**
  * Convert IDN names and verify the validity and specification constraints
  * @param string $domainName Domain name
  * @return string
  */
 private function verifyDomainName($domainName)
 {
     Log::debug('Verify domain: ' . $domainName);
     // Since PHP does not support IDN domain names, convert to ASCII by default
     $domainName = strtolower(idn_to_ascii(trim($domainName)));
     // Validate domain name length, max length 253
     if (strlen($domainName) > 253) {
         Log::error('Domain name exceedes the max length of 253 characters: ' . $domainName);
         return false;
     }
     // Make sure there is at least one "dot"
     if (strpos($domainName, '.') === false) {
         Log::error('Domain name is missing a dot character: ' . $domainName);
         return false;
     }
     // Explode "dot" separated parts
     $parts = explode('.', $domainName);
     // Validate parts
     foreach ($parts as $p) {
         // Max length 63 characters
         if (strlen($p) > 63) {
             Log::error('A domain name part exceedes the mas length of 63 characters: ' . $p);
             return false;
         }
         // Validate characters
         if (preg_match('/^[-a-z0-9]+$/i', $p) !== 1) {
             Log::error('Invalid characters in the domain name part: ' . $p);
             return false;
         }
     }
     return $domainName;
 }
Example #16
0
 public function index()
 {
     Log::debug('aaa');
     //Test::get();
     Test::query()->select('*')->get();
     return View::make('pages.test.index');
 }
Example #17
0
 /**
  * Create new Core object and initialize our own settings
  *
  * @param  string   $text    Text string to filter html
  * @param  integer  $format  Format id [Optional]
  * @param  array    $filter  Array of allowed tags [Optional]
  *
  * @used   Config::load
  * @used   Config::get
  * @used   Profiler::start
  */
 public function __construct($text, $format = 1, array $filter = NULL)
 {
     // Be sure to only profile if it's enabled
     if (Gleez::$profiling) {
         // Start a new benchmark
         $this->benchmark = Profiler::start('Gleez Filter', __FUNCTION__);
     }
     // Load the configuration for this type
     $config = Config::load('inputfilter');
     if ($config->allowed_protocols and is_array($config->allowed_protocols)) {
         $this->allowed_protocols = $config->allowed_protocols;
     }
     if ($config->allowed_tags and is_array($config->allowed_tags)) {
         $this->allowed_tags = $config->allowed_tags;
     }
     if (!array_key_exists($format, $config->formats)) {
         // make sure a valid format id exists, if not set default format id
         $format = (int) $config->get('default_format', 1);
     }
     if (isset($filter['settings']['allowed_html'])) {
         $this->allowed_tags = preg_split('/\\s+|<|>/', $filter['settings']['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
     }
     $this->_text = (string) $text;
     $this->_config = $config;
     if (Kohana::PRODUCTION !== Kohana::$environment) {
         Log::debug('HTML Filter Library initialized');
     }
 }
Example #18
0
 /**
  * Closes the socket
  */
 public function close()
 {
     fclose(static::$socket);
     static::$socket = false;
     // FuelPHP logger
     @\Log::debug('SOCKET CLOSED');
 }
Example #19
0
 function get_releases($add_blank = false, $status = 'Active', $where = '')
 {
     if ($where != '') {
         $query = "SELECT id, name FROM {$this->table_name} where " . $where . " and deleted=0 ";
     } else {
         $query = "SELECT id, name FROM {$this->table_name} where deleted=0 ";
     }
     if ($status == 'Active') {
         $query .= " and status='Active' ";
     } elseif ($status == 'Hidden') {
         $query .= " and status='Hidden' ";
     } elseif ($status == 'All') {
     }
     $query .= " order by list_order asc";
     $result = $this->db->query($query, false);
     Log::debug("get_releases: result is " . var_export($result, true));
     $list = [];
     if ($add_blank) {
         $list[''] = '';
     }
     //if($this->db->getRowCount($result) > 0){
     // We have some data.
     while (($row = $this->db->fetchByAssoc($result)) != null) {
         //while ($row = $this->db->fetchByAssoc($result)) {
         $list[$row['id']] = $row['name'];
         Log::debug("row id is:" . $row['id']);
         Log::debug("row name is:" . $row['name']);
     }
     //}
     return $list;
 }
	public function render()
	{
		$tag = "ListUlDrafter: render()";
		Log::debug("$tag");
		
		// convenience pointer
		$id = $this->id;
		$entityBP = $this->entityBlueprint;
		$listBP = $this->listBlueprint;
		$listRows = $this->listRows;
		$params = $this->params;
		
		// encode params for inclusion in html
		$encodedParams = ParamEncoder::encode($params);
		
		// turn on output buffering
		@ob_end_flush();
		ob_start();
		
		?><div class="bp-draft-rendering" id="<?= $id ?>" type="list" renderer="ListUlDrafter" entitySignature="<?= $entityBP->signature(); ?>" listSignature="<?= ($listBP) ? $listBP->signature() : ""; ?>" params="<?= $encodedParams ?>"><?

			if((is_array($listRows)) && (count($listRows > 0)) )
			{
				?><ul><?
					foreach($listRows as $row)
					{
						?><li entityId="<?= $row->id ?>"><?
							foreach($row->columns as $key=>$listColumn)
							{
								$value = $listColumn->value;
								$href = $listColumn->href;
								
								if(!empty($href))
								{
									?><a href="<?= $href ?>"><?= $value ?></a> <?
								}
								else
								{
									?><?= $value ?> <?
								}
								
							}
						?></li><?
					}	
				?></ul><?
			}
			else
			{
				?>
				Empty
				<?
			}
		
		?></div><?
		
		// return contents of output buffer
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
 public static function initWithStandardAction($standardListAction = LIST_ACTION_STANDARD_VIEW)
 {
     $tag = "ListAction::initWithStandardAction()";
     Log::debug("{$tag}: <{$standardListAction}>");
     $action = array();
     switch ($standardListAction) {
         case ListAction::LIST_ACTION_STANDARD_VIEW:
             $action["name"] = "View";
             $action["displayText"] = "View";
             $action["targetType"] = ListAction::LIST_ACTION_TARGET_TYPE_ENTITY;
             $action["javascript"] = "\$.fn.conduit.dialogWithEntity('EntityDrafter', entitySignature, listSignature, entityId);";
             $action["icon"] = "ui-icon-search";
             break;
         case ListAction::LIST_ACTION_STANDARD_EDIT:
             $action["name"] = "Edit";
             $action["displayText"] = "Edit";
             $action["targetType"] = ListAction::LIST_ACTION_TARGET_TYPE_ENTITY;
             $action["javascript"] = "\$.fn.conduit.dialogWithForm('FormDrafter', entitySignature, formSignature, entityId);";
             $action["icon"] = "ui-icon-pencil";
             break;
         case ListAction::LIST_ACTION_STANDARD_DELETE:
             $action["name"] = "Delete";
             $action["displayText"] = "Trash";
             $action["targetType"] = ListAction::LIST_ACTION_TARGET_TYPE_ENTITY;
             $action["javascript"] = "\$rendering.conduit('trash', entityId);";
             $action["icon"] = "ui-icon-trash";
             break;
         case ListAction::LIST_ACTION_STANDARD_DELETE_COLLECTION:
             $action["name"] = "Delete";
             $action["displayText"] = "Delete";
             $action["targetType"] = ListAction::LIST_ACTION_TARGET_TYPE_COLLECTION;
             $action["javascript"] = "\$rendering.conduit('trash', entityId);";
     }
     return $action;
 }
 /**
  * Generates XML response
  */
 protected function handle_response()
 {
     $xml = new DOMDocument('1.0', Autodiscover::CHARSET);
     // create main elements
     $doc = $xml->createElement('clientConfig');
     $doc = $xml->appendChild($doc);
     $doc->setAttribute('version', '1.1');
     $provider = $xml->createElement('emailProvider');
     $provider = $doc->appendChild($provider);
     $provider->setAttribute('id', $this->config['domain']);
     // provider description tags
     foreach (array('domain', 'displayName', 'displayShortName') as $tag_name) {
         if (!empty($this->config[$tag_name])) {
             $element = $xml->createElement($tag_name);
             $element->appendChild($xml->createTextNode($this->config[$tag_name]));
             $provider->appendChild($element);
         }
     }
     foreach (array('imap', 'pop3', 'smtp') as $type) {
         if (!empty($this->config[$type])) {
             $server = $this->add_server_element($xml, $type, $this->config[$type]);
             $provider->appendChild($server);
         }
     }
     $xml->formatOutput = true;
     $response = $xml->saveXML();
     Log::debug('Response [mozilla]: ' . $response);
     header('Content-Type: application/xml; charset=' . Autodiscover::CHARSET);
     echo $response;
     exit;
 }
Example #23
0
 public function home()
 {
     // var_dump(Article::count());
     $data = ['title' => '你是谁??', 'email' => '1@baiducom'];
     $validator = $this->validate($data, ['title' => 'required|numeric|integer|min:3|max:4', 'email' => 'required|email']);
     if (!$validator->success) {
         foreach ($validator->errors as $error) {
             echo $error . '<br>';
         }
     }
     Log::debug('First Debug Info.');
     /*
     // mail sample
     Mail::to('*****@*****.**')->from('*****@*****.**')
                           ->title('Foo Bar')
                           ->content('<h1>Hello~~</h1>')
                           ->send();
     // redis sample
     Redis::set('key','value',3000,'ms');
     echo Redis::get('key');
     */
     // return View
     return View::make('home')->with('article', Article::first())->withTitle('TinyLara :-D')->withFooBar('foo_bar');
     // return String
     return 'Hello TinyLara!';
     // or you can return Nothing.
 }
Example #24
0
 public static function render($template, $vars = array())
 {
     Log::debug(__CLASS__ . ': Attempting to render template "' . $template . '"');
     $template_file = 'tpl.' . $template . '.php';
     if (!self::$template_dir && !(self::$template_dir = Config::get('template_dir'))) {
         $included_dirs = ini_get('include_path');
         foreach (explode(':', $included_dirs) as $dir) {
             if (is_readable($dir . '/templates')) {
                 self::$template_dir = $dir . '/templates';
                 break;
             }
         }
     }
     if (is_readable(self::$template_dir . '/' . $template_file)) {
         ob_start();
         extract($vars);
         include self::$template_dir . '/' . $template_file;
         $output = ob_get_contents();
         ob_end_clean();
         return $output;
     } else {
         Log::warning(__CLASS__ . ': Could not render template ' . self::$template_dir . '/' . $template_file);
     }
     return '';
 }
Example #25
0
 /**
  * Returns the show entity view.
  * Requires the id of the entity.
  *
  * @param int id The id of the entity to show
  * @param string $view_name The name of the view, defaults to 'show'.
  */
 public function getShow($id = null, $view_name = 'show')
 {
     $model_class = self::MODEL_CLASS;
     try {
         $entity = $this->getDetailsCustomQuery(false, $model_class, $id);
     } catch (ModelNotFoundException $ex) {
         // Prepare the error message
         $error = $this->LMessage->{$model_class::one_entity() . '_not_found'}(compact('id'));
         // Redirect to the entities index page with an error message
         return $this->getRedirectFor('index')->with('error', $error);
     }
     $entity_ref = $model_class::one_entity();
     ${$entity_ref} = $entity;
     $view_params = array_merge(compact($model_class::one_entity()), $this->getDetailsAdditionalEntities());
     //ajax view, maybe will be fixed in the future ...
     if (Input::has('select') && $this->select_from_show === true) {
         UsageHelper::deprecated(Input::has('select'), 'Input', 'select', 'ajax');
         UsageHelper::deprecated($this->select_from_show, 'controller variable', 'select_from_show', 'enable_ajax_show');
         \Log::debug('Use dedicated controller method.');
         //select from show is used for showing the entity details with ajax,
         //so no external layout is involved
         $view_name = 'select_from_show';
     }
     // Return the right view with its parameters
     return $this->getViewFor($view_name, $view_params);
 }
Example #26
0
 static function send($url, $headers = [], $options = [], $set = ['ret' => 'body', 'post' => ''])
 {
     $default_headers = ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'];
     $default_options = ['follow_redirects' => false, 'timeout' => 30];
     $headers = $headers + $default_headers;
     $options = $options + $default_options;
     //出错的话就访问10次
     for ($i = 1; $i < 10; $i++) {
         \Log::debug("第{$i}次访问" . $url);
         try {
             if (isset($set['post']) && $set['post'] != "") {
                 $html = \Requests::post($url, $headers, $set['post'], $options);
             } else {
                 $html = \Requests::get($url, $headers, $options);
             }
         } catch (\Requests_Exception $e) {
             continue;
             //表示url访问出错了
         }
         if ($html->body != "") {
             break;
         }
         //表示访问正确
     }
     if ($set['ret'] == 'body') {
         return $html->body;
     } else {
         return $html;
     }
 }
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     \Log::debug('Firing new FetchDuoGroups Job');
     $this->dispatch(new FetchDuoGroups());
     \Log::debug('Firing new FetchDuoUsers Job');
     $this->dispatch(new FetchDuoUsers());
 }
Example #28
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     set_time_limit(0);
     \Log::debug('Set PHP time limit to zero (no limit)');
     //Create the Duo Admin Client and set the timeout higher than default
     $duoAdmin = new DuoAdmin();
     $duoAdmin->setRequesterOption('timeout', '6000000');
     \Log::debug('Created new DuoAdmin object', [$duoAdmin]);
     $response = $duoAdmin->groups();
     $groups = $response['response']['response'];
     \Log::debug('Obtained Groups from Duo API - ', [count($groups)]);
     //Loop Duo Groups
     foreach ($groups as $group) {
         \Log::debug('Processing Duo Group', [$group]);
         //Get an existing Duo Group or create a new one
         $duoGroup = Group::firstOrCreate(['group_id' => $group['group_id']]);
         //Update Duo Group Settings
         $duoGroup->name = $group['name'];
         $duoGroup->desc = $group['desc'];
         $duoGroup->status = $group['status'];
         $duoGroup->mobile_otp_enabled = $group['mobile_otp_enabled'];
         $duoGroup->push_enabled = $group['push_enabled'];
         $duoGroup->sms_enabled = $group['sms_enabled'];
         $duoGroup->voice_enabled = $group['voice_enabled'];
         //Save Duo Group
         $duoGroup->touch();
         $duoGroup->save();
     }
     \Log::debug('Completed FetchDuoGroups Job');
 }
Example #29
0
 public static function Device($model, $method)
 {
     if ($method == 'before_update') {
         //\Log::debug('device update'.$model->hostname);
         $old_data = \DB::select('rack', 'rack_pos')->from('device')->where('id', $model->id)->as_object()->execute();
         if (count($old_data) > 0) {
             $rack = $old_data[0]->rack;
             $pos = $old_data[0]->rack_pos;
             if ($rack != $model->rack or $pos != $model->rack_pos) {
                 \Log::debug('device update' . $model->hostname);
                 $network = $model->network;
                 foreach ($network as $net) {
                     $ips = \Basic\Model_Network_Ip::find()->where('networkID', $net->id)->get();
                     foreach ($ips as $ip) {
                         // \Log::debug('ip::'.print_r($ip,true));
                         $sub = \Ipm\Model_Subnet::find()->where('range_from', '<=', $ip->addrint)->where('range_to', '>=', $ip->addrint)->get_one();
                         if ($sub) {
                             \Ipm\Observer::IsValidLocation($sub, $model, $ip);
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * Returns a reference to the ChartEngine object for instance $chartEngine, or the default
  * instance if one is not specified
  *
  * @param string $chartEngine optional, name of the chart engine from $sugar_config['chartEngine']
  * @param string $module optional, name of module extension for chart engine (see JitReports or SugarFlashReports)
  * @return object ChartEngine instance
  */
 public static function getInstance($chartEngine = '', $module = '')
 {
     global $sugar_config;
     $defaultEngine = "Jit";
     //fall back to the default Js Engine if config is not defined
     if (empty($sugar_config['chartEngine'])) {
         $sugar_config['chartEngine'] = $defaultEngine;
     }
     if (empty($chartEngine)) {
         $chartEngine = $sugar_config['chartEngine'];
     }
     $file = "include/SugarCharts/" . $chartEngine . "/" . $chartEngine . $module . ".php";
     if (file_exists('custom/' . $file)) {
         require_once 'custom/' . $file;
     } else {
         if (file_exists($file)) {
             require_once $file;
         } else {
             Log::debug("using default engine include/SugarCharts/" . $defaultEngine . "/" . $defaultEngine . $module . ".php");
             require_once "include/SugarCharts/" . $defaultEngine . "/" . $defaultEngine . $module . ".php";
             $chartEngine = $defaultEngine;
         }
     }
     $className = $chartEngine . $module;
     return new $className();
 }