/**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $input = Input::all();
     $validation = Validator::make($input, Image::$rules);
     if ($validation->passes()) {
         $this->image->create($input);
         return Redirect::route('images.index');
     }
     return Redirect::route('images.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
 }
 /**
  * Downloads a random image from a public website and installs it into the filesystem
  *
  * @todo This should really be an injectable service. It locks the user into a specific URL.
  * @return Image
  */
 public static function download_lorem_image()
 {
     $url = 'http://lorempixel.com/1024/768?t=' . uniqid();
     $img_filename = "mock-file-" . uniqid() . ".jpeg";
     $img = self::get_mock_folder()->getFullPath() . $img_filename;
     if (ini_get('allow_url_fopen')) {
         file_put_contents($img, file_get_contents($url));
     } else {
         $ch = curl_init($url);
         $fp = fopen($img, 'wb');
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_exec($ch);
         curl_close($ch);
         fclose($fp);
     }
     if (!file_exists($img) || !filesize($img)) {
         return false;
     }
     $i = Image::create();
     $i->Filename = self::get_mock_folder()->Filename . $img_filename;
     $i->Title = $img_filename;
     $i->Name = $img_filename;
     $i->ParentID = self::get_mock_folder()->ID;
     $i->write();
     return $i;
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     // get POST data
     $input = Input::all();
     // set validation rules
     $rules = array('title' => 'required', 'text' => 'required', 'image' => 'required');
     // validate input
     $validation = Validator::make($input, $rules);
     // if validation fails, return the user to the form w/ validation errors
     if ($validation->fails()) {
         return Redirect::back()->withErrors($validation)->withInput();
     } else {
         // create new Post instance
         $post = Post::create(array('title' => $input['title']));
         // create Text instance w/ text body
         $text = Text::create(array('text' => $input['text']));
         // save new Text and associate w/ new post
         $post->text()->save($text);
         // create the new Image
         $image = Image::create(array('url' => $input['image']));
         // save new Text and associate w/ new post
         $post->image()->save($image);
         if (isset($input['tags'])) {
             foreach ($input['tags'] as $tagId) {
                 $tag = Tag::find($tagId);
                 $post->tags()->save($tag);
             }
         }
         // associate the post with the current user
         $post->author()->associate(Auth::user())->save();
         // redirect to newly created post page
         return Redirect::route('post.show', array($post->id));
     }
 }
Example #4
0
 public function add()
 {
     if (!$_FILES['image']['name']) {
         return call('pages', 'error');
     }
     $uploadOk = 1;
     // check if image file is a actual image or fake image
     if (isset($_POST['submit'])) {
         $check = getimagesize($_FILES['image']['tmp_name']);
         if ($check !== false) {
             $uploadOk = 1;
         } else {
             $_SESSION['alert'] = "File is not an image.";
             $uploadOk = 0;
         }
     }
     if ($uploadOk == 0) {
         $_SESSION['alert'] = $_SESSION['alert'] . " Sorry, your file was not uploaded.";
     } else {
         $image = \Cloudinary\Uploader::upload($_FILES["image"]["tmp_name"]);
         if (!empty($image)) {
             Image::create($image['public_id'], $image['url'], basename($image['url']));
             $_SESSION['notice'] = "The image " . basename($_FILES['image']['name']) . " has been uploaded.";
         } else {
             $_SESSION['alert'] = "Sorry, there was an error uploading your file. ";
         }
     }
     redirect_to('images', 'index');
 }
 public function testHeaderWithSlideshow()
 {
     $header = Header::create()->withTitle(H1::create()->appendText('Big Top Title ')->appendText(Bold::create()->appendText('in Bold')))->withSubTitle(H2::create()->appendText('Smaller SubTitle ')->appendText(Bold::create()->appendText('in Bold')))->withKicker(H3::create()->appendText('Kicker ')->appendText(Bold::create()->appendText('in Bold')))->withCover(SlideShow::create()->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home.jpg'))->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home2.jpg'))->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home3.jpg')));
     $expected = '<header>' . '<figure class="op-slideshow">' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home.jpg"/>' . '</figure>' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home2.jpg"/>' . '</figure>' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home3.jpg"/>' . '</figure>' . '</figure>' . '<h1>Big Top Title <b>in Bold</b></h1>' . '<h2>Smaller SubTitle <b>in Bold</b></h2>' . '<h3 class="op-kicker">Kicker <b>in Bold</b></h3>' . '</header>';
     $rendered = $header->render();
     $this->assertEquals($expected, $rendered);
 }
 public function testInstantArticleAlmostEmpty()
 {
     $article = InstantArticle::create()->withCanonicalUrl('')->withHeader(Header::create())->addChild(Paragraph::create()->appendText('Some text to be within a paragraph for testing.'))->addChild(Paragraph::create())->addChild(Paragraph::create()->appendText(" \n \t "))->addChild(Image::create())->addChild(Image::create()->withURL(''))->addChild(SlideShow::create()->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home.jpg'))->addImage(Image::create()))->addChild(Ad::create())->addChild(Paragraph::create()->appendText('Other text to be within a second paragraph for testing.'))->addChild(Analytics::create())->withFooter(Footer::create());
     $expected = '<!doctype html>' . '<html>' . '<head>' . '<link rel="canonical" href=""/>' . '<meta charset="utf-8"/>' . '<meta property="op:generator" content="facebook-instant-articles-sdk-php"/>' . '<meta property="op:generator:version" content="' . InstantArticle::CURRENT_VERSION . '"/>' . '<meta property="op:markup_version" content="v1.0"/>' . '</head>' . '<body>' . '<article>' . '<p>Some text to be within a paragraph for testing.</p>' . '<figure class="op-slideshow">' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home.jpg"/>' . '</figure>' . '</figure>' . '<p>Other text to be within a second paragraph for testing.</p>' . '</article>' . '</body>' . '</html>';
     $result = $article->render();
     $this->assertEquals($expected, $result);
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Image::create([]);
     }
 }
Example #8
0
 /**
  * Store a newly created resource in storage.
  * POST /adminimages
  *
  * @return Response
  */
 public function store()
 {
     $validator = Validator::make($data = Input::all(), Image::$rules);
     if ($validator->fails()) {
         //return Redirect::back()->withErrors($validator)->withInput();
         return Response::json('Upload Error', 400);
     }
     if ($data['code'] !== 0) {
         $building = Building::where('code', '=', $data['code'])->firstOrFail();
         $building_id = $building->id;
     } else {
         $building_id = '0';
     }
     $file = Input::file('file');
     $img_destination = 'public/assets/uploads/img/';
     $extension = $file->getClientOriginalExtension();
     $img_name = rand(11111, 99999) . '.' . $extension;
     $data = array('file' => $img_name, 'building_id' => $building_id);
     //dd($building->id);
     $upload = $file->move($img_destination, $img_name);
     if ($upload) {
         Image::create($data);
         return Response::json($file, 200);
     }
     return Response::json('error', 400);
     //return Redirect::route('admin.images');
 }
Example #9
0
 /**
  * Store a newly created resource in storage.
  * POST /brewer
  *
  * @return Response
  */
 public function store()
 {
     if (Input::get('brewer_id')) {
         $brewer = Brewer::find(Input::get('brewer_id'));
     } else {
         $brewer = new Brewer();
     }
     $locality = Locality::find(Input::get('locality_id'));
     if (!$locality) {
         return Redirect::back()->withInput()->withMessage('Invalid Locality');
     }
     $brewer->name = Input::get('name');
     $brewer->url = Input::get('url');
     $brewer->locality_id = $locality->id;
     $brewer->save();
     if (Input::hasFile('logo')) {
         $f = Input::file('logo');
         //Change the image name: s<number_of_service>-<filename>.
         $filename = 'brewer-' . $brewer->id . '-' . $f->getClientOriginalName();
         //Move it to our public folder
         $f->move(public_path() . '/upload/', $filename);
         //This is the path to show it on the web
         $complete_path = '/upload/' . $filename;
         //create the gallery
         $image = array('path' => $complete_path, 'brewer_id' => $brewer->id, 'beer_id' => NULL);
         if ($brewer->logoUrl()) {
             $brewer->logo()->fill($image)->save();
         } else {
             Image::create($image);
         }
     }
     return Redirect::to('/dashboard/brewers');
 }
 /**
  * Setup this test. Creates a 1x1 pixel image filled with white.
  *
  */
 public function setUp()
 {
     if (!Runtime::getInstance()->extensionAvailable('gd')) {
         throw new PrerequisitesNotMetError('GD extension not available');
     }
     $this->image = Image::create(1, 1);
     $this->image->fill($this->image->allocate(new Color('#ffffff')));
 }
 public function run()
 {
     $faker = Faker\Factory::create();
     for ($i = 0; $i < 100; $i++) {
         $file = $faker->image('public/uploads', 640, 480, 'cats');
         $image = Image::create(array('image' => substr($file, 6), 'thumbnail' => substr($file, 6), 'original_filename' => substr($file, 15)));
     }
 }
Example #12
0
 public function copyResampled($newWidth, $newHeight)
 {
     $tmp = Image::create($newWidth, $newHeight);
     if (!imagecopyresampled($tmp->h, $this->h, 0, 0, 0, 0, $newWidth, $newHeight, $this->width(), $this->height())) {
         throw new \Exception('imagecopyresampled failed');
     }
     return $tmp;
 }
 public function testRenderWithAudio()
 {
     $audio = Audio::create()->withURL('http://foo.com/mp3')->withTitle('audio title')->enableMuted()->enableAutoplay();
     $expected_audio = '<audio title="audio title" autoplay="autoplay" muted="muted">' . '<source src="http://foo.com/mp3"/>' . '</audio>';
     $slideshow = SlideShow::create()->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home.jpg'))->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home2.jpg'))->addImage(Image::create()->withURL('https://jpeg.org/images/jpegls-home3.jpg'))->withAudio($audio);
     $expected = '<figure class="op-slideshow">' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home.jpg"/>' . '</figure>' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home2.jpg"/>' . '</figure>' . '<figure>' . '<img src="https://jpeg.org/images/jpegls-home3.jpg"/>' . '</figure>' . $expected_audio . '</figure>';
     $rendered = $slideshow->render();
     $this->assertEquals($expected, $rendered);
 }
Example #14
0
 public function run()
 {
     $faker = Faker::create();
     $count = 50;
     $ids = Estate::lists('estate_id');
     $images = read_dir(dir_path('estates'));
     $images = array_values(array_diff($images, ['alien.png']));
     for ($i = 0; $i < $count; $i++) {
         Image::create(['image' => $images[$i], 'estate_id' => $faker->randomElement($ids), 'preview' => $faker->boolean(30)]);
     }
 }
 public function run()
 {
     DB::table('images')->delete();
     Image::create(array('url' => 'https://pbs.twimg.com/profile_images/378800000607588261/dad9f009a228a78a14f1f4bed0c54f76.png', 'imageable_id' => 1, 'imageable_type' => 'User'));
     Image::create(array('url' => 'https://pbs.twimg.com/profile_images/3047681237/0dae20f6642d52ca86482c7d0d63358c.png', 'imageable_id' => 2, 'imageable_type' => 'User'));
     Image::create(array('url' => '/images/code.png', 'imageable_id' => 1, 'imageable_type' => 'Post'));
     Image::create(array('url' => '/images/code.png', 'imageable_id' => 2, 'imageable_type' => 'Post'));
     Image::create(array('url' => '/images/code.png', 'imageable_id' => 3, 'imageable_type' => 'Post'));
     Image::create(array('url' => '/images/code.png', 'imageable_id' => 4, 'imageable_type' => 'Post'));
     Image::create(array('url' => '/images/code.png', 'imageable_id' => 5, 'imageable_type' => 'Post'));
 }
 /**
  * Convert an image. Returns TRUE when successfull, FALSE if image is
  * not a truecolor image.
  *
  * @param   img.Image image
  * @return  bool
  * @throws  img.ImagingException
  */
 public function convert($image)
 {
     if (!imageistruecolor($image->handle)) {
         return FALSE;
     }
     $tmp = Image::create($image->getWidth(), $image->getHeight(), IMG_TRUECOLOR);
     $tmp->copyFrom($image);
     imagetruecolortopalette($image->handle, $this->dither, $this->ncolors);
     imagecolormatch($tmp->handle, $image->handle);
     delete($tmp);
     return TRUE;
 }
 /**
  * @param Member $xmember
  * @param string $type
  * @param integer $folderid
  */
 public function grabRUGImage($call, $xmember, $type, $folderid)
 {
     $newimage = file_get_contents($call['results']['0']['user']['picture'][$type]);
     $imagename = $xmember->FirstName . '-' . $xmember->Surname . '-' . $type . '.jpg';
     $imagepath = 'assets/' . $type . '/' . $imagename;
     file_put_contents(BASE_PATH . '/' . $imagepath, $newimage);
     $imagefile = Image::create();
     $imagefile->Name = $imagename;
     $imagefile->ParentID = $folderid;
     $imagefile->write();
     return $imagefile->ID;
 }
Example #18
0
 public function run()
 {
     Eloquent::unguard();
     $this->command->info('Borrando imágenes existentes en la tabla ...');
     DB::table('images')->delete();
     // Las imágenes de usuario por defecto.
     $img = Image::create(array('id' => 1, 'nombre' => 'default_male.jpg'));
     $img = Image::create(array('id' => 2, 'nombre' => 'default_female.jpg'));
     /*
     $cont = 2;
     foreach(range(1, 8) as $index)
     {
     	$cont++;
     	$img = Image::create(array(
     		'id'		=> $cont,
     		'nombre'	=> 'ejemplo/'.$index.'.jpg',
     		'user_id'	=> $index,
     	));
     
     }
     
     // Repetiré algunas imágenes para que pertenezcan al Admin
     $img = Image::create(array(
     	'id'		=> 11,
     	'nombre'	=> 'ejemplo/2.jpg',
     	'user_id'	=> 1,
     ));
     $img = Image::create(array(
     	'id'		=> 12,
     	'nombre'	=> 'ejemplo/3.jpg',
     	'user_id'	=> 1,
     ));
     $img = Image::create(array(
     	'id'		=> 13,
     	'nombre'	=> 'ejemplo/5.jpg',
     	'user_id'	=> 1,
     ));
     $img = Image::create(array(
     	'id'		=> 14,
     	'nombre'	=> 'ejemplo/6.jpg',
     	'user_id'	=> 1,
     ));
     $img = Image::create(array(
     	'id'		=> 15,
     	'nombre'	=> 'ejemplo/8.jpg',
     	'user_id'	=> 1,
     ));
     */
     $this->command->info('Imágenes insertadas.');
 }
 public function testImageModule()
 {
     $module = ImageModule::create();
     $module->Title = 'Test';
     $module->ResizeMethod = 'SetWidth';
     $module->ResizeWidth = 900;
     $module->ResizeHeight = 600;
     $module->write();
     $this->assertTrue($module->ID > 0);
     $image = Image::create();
     $image->Title = 'Test';
     $image->write();
     $module->Images()->add($image);
     $this->assertEquals($module->Images()->count(), 1);
 }
Example #20
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Account $account)
 {
     $input = Input::all();
     $input['account_id'] = $account->id;
     $input['parameters'] = NULL;
     $validation = Validator::make($input, Image::$rules);
     if ($validation->passes()) {
         $image = Image::create($input);
         if ($image) {
             $account->images()->save($image);
             Event::fire('image.process', [$image]);
             return Response::json(['status' => ['message' => 'Created', 'code' => 1], 'data' => $image->toArray(), 'meta' => []], 201);
         }
     }
     return Response::json(['status' => ['message' => 'Not Acceptable', 'code' => 2], 'data' => [], 'meta' => ['errors' => $validation->errors()->all()]], 406);
 }
 public function getDummyPortrait()
 {
     $dummyName = $this->stat('dummy_image');
     $uploadPath = $this->stat('upload_path');
     $uploadFolder = Folder::find_or_make($uploadPath);
     $dummyPic = Image::find(join('/', [$uploadPath, $dummyName]));
     if (!$dummyPic) {
         //create it
         $defaultDummy = join('/', [BASE_PATH, $this->stat('default_dummy')]);
         $assetsDummy = join('/', [BASE_PATH, 'assets', $uploadPath, $dummyName]);
         if (copy($defaultDummy, $assetsDummy)) {
             $dummyPic = Image::create();
             $dummyPic->setFilename(join('/', [$uploadFolder->getRelativePath(), $dummyName]));
             $dummyPic->ParentID = $uploadFolder->ID;
             $dummyPic->write();
         }
     }
     return $dummyPic;
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if ($this->isChanged('YouTubeID') && $this->YouTubeID) {
         // if($this->VideoThumbnail()->exists()) {
         // 	$this->VideoThumbnail()->delete();
         // }
         $img = @file_get_contents("http://img.youtube.com/vi/{$this->YouTubeID}/0.jpg");
         if ($img) {
             $folder = Folder::find_or_make('video-thumbnails');
             $path = $folder->Filename . "presentation-{$this->ID}-" . uniqid() . ".jpg";
             $fh = fopen(Director::baseFolder() . "/" . $path, 'wb');
             fwrite($fh, $img);
             fclose($fh);
             $image = Image::create(array('Filename' => $path, 'Name' => "presentation-{$this->ID}.jpg", 'Title' => "presentation-{$this->ID}"));
             $image->write();
             $this->VideoThumbnailID = $image->ID;
         }
     }
 }
Example #23
0
 /**
  * Submit locality form
  */
 public function saveLocality()
 {
     if (Input::get('locality_id') != null) {
         //edit style
         $locality = Locality::find(Input::get('locality_id'));
     } else {
         //create style
         $locality = new Locality();
     }
     $parent_locality_id = null;
     if (Input::get('parent_locality') != null) {
         $parent_locality = Locality::find(Input::get('parent_locality_id'));
         if ($parent_locality) {
             $parent_locality_id = $parent_locality->id;
         }
     }
     $locality->name = Input::get('name');
     $locality->type = Input::get('type');
     $locality->locality_id = $parent_locality_id;
     $locality->latitude = Input::get('latitude');
     $locality->longitude = Input::get('longitude');
     $locality->code = Input::get('code');
     $locality->save();
     if (Input::hasFile('flag')) {
         $f = Input::file('flag');
         //Change the image name: s<number_of_service>-<filename>.
         $filename = 'locality-' . $locality->id . '-flag-' . $f->getClientOriginalName();
         //Move it to our public folder
         $f->move(public_path() . '/upload/', $filename);
         //This is the path to show it on the web
         $complete_path = '/upload/' . $filename;
         //create the gallery
         $image = array('path' => $complete_path, 'locality_id' => $locality->id, 'beer_id' => NULL);
         if ($locality->flag()) {
             $locality->flag()->fill($image)->save();
         } else {
             Image::create($image);
         }
     }
     return Redirect::back()->withMessage('Locality created correctly');
 }
 /**
  * Upload & store new images
  *
  * @param int $categoryId
  * @param int $albumId
  *
  * @return \Illuminate\View\View | \Illuminate\Http\Response | \Illuminate\Http\JsonResponse
  */
 public function create($categoryId, $albumId)
 {
     $category = Category::findOrFail($categoryId);
     $album = Album::findOrFail($albumId);
     if (Request::isMethod('GET')) {
         return View::make('image.create', compact('category', 'album'));
     } elseif (Request::isMethod('POST')) {
         $validator = Validator::make(Input::all(), Image::$rules);
         if ($validator->fails()) {
             return Response::make($validator->errors()->first(), 403);
         }
         $image = new Image();
         $uploadedFileName = $image->upload(Input::file('file'));
         if ($uploadedFileName) {
             Image::create(['album_id' => $albumId, 'name' => $uploadedFileName]);
             return Response::json('OK', 200);
         } else {
             return Response::json('Internal Server Error', 500);
         }
     }
 }
 /**
  * Fetch and update the media thumbnail
  */
 public function updateOEmbedThumbnail()
 {
     $oembed = $this->Media();
     if ($oembed && $oembed->thumbnail_url) {
         $fileName = preg_replace('/[^A-z0-9\\._-]/', '', $oembed->thumbnail_url);
         if ($existing = File::find($fileName)) {
             $this->MediaThumbID = $existing->ID;
         } else {
             $contents = @file_get_contents($oembed->thumbnail_url);
             if ($contents) {
                 $folder = Folder::find_or_make('downloaded');
                 file_put_contents($folder->getFullPath() . $fileName, $contents);
                 $file = Image::create();
                 $file->setFilename($folder->getFilename() . $fileName);
                 $file->ParentID = $folder->ID;
                 $this->MediaThumbID = $file->write();
             }
         }
     } else {
         $this->MediaThumbID = 0;
     }
 }
 public function store($projectId)
 {
     $destinationPath = public_path() . '/uploads/images';
     $detials = Input::all();
     $details['project_id'] = $projectId;
     if (Input::hasFile('image')) {
         $file = Input::file('image');
         $extension = $file->getClientOriginalExtension();
         $fileName = $projectId . '_' . str_random(16) . '.' . $extension;
         $details['path'] = $fileName;
         if ($file->move($destinationPath, $fileName)) {
             if (Image::create($details)) {
                 return Response::json(['alert' => Messages::$createSuccess . 'image']);
             } else {
                 File::delete($destinationPath . $fileName);
                 return Response::json(['alert' => Messages::$createFail . 'image'], 400);
             }
         } else {
             return Response::json(['alert' => Messages::$uploadFail . 'image'], 400);
         }
     } else {
         return Response::json(['alert' => 'Image' . Messages::$notFound], 404);
     }
 }
 /**
  * Method to render pie charts
  *
  * @param   img.chart.PieChart bc
  * @return  img.Image
  */
 public function renderPieChart($pc)
 {
     // Create local variables for faster access
     $border = 50;
     $sum = $pc->sum();
     $innerHeight = $this->height - $border * 2;
     $innerWidth = $this->width - $border * 2;
     $middleX = $this->width / 2;
     $middleY = $this->height / 2;
     $count = $pc->count();
     $font = 2;
     $fontw = imagefontwidth($font);
     $fonth = imagefontheight($font);
     // Create image
     with($img = Image::create($this->width, $this->height));
     $colors = $this->_colors($img, $pc->getColor('sample'));
     $axisColor = $img->allocate($pc->getColor('axis'));
     // Flood fill with background color
     $img->fill($img->allocate($pc->getColor('chartback')), $leftBorder + 1, $topBorder + 1);
     $pc->getDisplayLegend() && $this->_renderLegend(array('labels' => $pc->getLabels(), 'font' => $font, 'fontWidth' => $fontw, 'fontHeight' => $fonth, 'rightBorder' => $border / 5, 'topBorder' => $border / 5, 'margin' => 5, 'legendColor' => $img->allocate($pc->getColor('legend')), 'legendbackColor' => $img->allocate($pc->getColor('legendback')), 'sampleColor' => $colors), $img);
     $start = $end = 0;
     for ($i = 0; $i < $count; $i++) {
         $end += $pc->series[0]->values[$i];
         $angle = deg2rad(90 - ($start + ($end - $start) / 2) / $sum * 360);
         $insetX = sin($angle) * $pc->getValueInset($i);
         $insetY = cos($angle) * $pc->getvalueInset($i);
         imagefilledarc($img->handle, $middleX + $insetX, $middleY + $insetY, $innerWidth, $innerHeight, $start / $sum * 360, $end / $sum * 360, $colors[$i % sizeof($colors)]->handle, IMG_ARC_PIE);
         if ($pc->getDisplayValues()) {
             imagestring($img->handle, $font, $middleX + $insetX + sin($angle) * $innerWidth / 3 - strlen($pc->series[0]->values[$i]) * $fontw / 2, $middleY + $insetY + cos($angle) * $innerHeight / 3 - $fonth / 2, $pc->series[0]->values[$i], $axisColor->handle);
         }
         $start = $end;
     }
     return $img;
 }
Example #28
0
 /**
  * Replace insert tags with their values
  *
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If false, non-cacheable tags will be replaced
  *
  * @return string The text with the replaced tags
  */
 protected function doReplace($strBuffer, $blnCache)
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/{{([^{}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     if (count($tags) < 2) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         $flags = explode('|', $strTag);
         $tag = array_shift($flags);
         $elements = explode('::', $tag);
         // Load the value from cache
         if (isset($arrCache[$strTag]) && !in_array('refresh', $flags)) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'post' || $elements[0] == 'file' || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 $strBuffer .= '{{' . $strTag . '}}';
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('dateFormat'));
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . $elements[1] . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br>';
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \StringUtil::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" title="' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $file = $keys[0];
                 // Map the key (see #7217)
                 switch ($file) {
                     case 'CNT':
                         $file = 'countries';
                         break;
                     case 'LNG':
                         $file = 'languages';
                         break;
                     case 'MOD':
                     case 'FMD':
                         $file = 'modules';
                         break;
                     case 'FFL':
                         $file = 'tl_form_field';
                         break;
                     case 'CACHE':
                         $file = 'tl_page';
                         break;
                     case 'XPL':
                         $file = 'explain';
                         break;
                     case 'XPT':
                         $file = 'exception';
                         break;
                     case 'MSC':
                     case 'ERR':
                     case 'CTE':
                     case 'PTY':
                     case 'FOP':
                     case 'CHMOD':
                     case 'DAYS':
                     case 'MONTHS':
                     case 'UNITS':
                     case 'CONFIRM':
                     case 'DP':
                     case 'COLS':
                         $file = 'default';
                         break;
                 }
                 \System::loadLanguageFile($file);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements[1]};
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = \StringUtil::deserialize($value);
                     // Decrypt the value
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['encrypt']) {
                         $value = \Encryption::decrypt($value);
                     }
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('dateFormat'), $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('timeFormat'), $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('datimFormat'), $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = \StringUtil::specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
             case 'link_target':
             case 'link_name':
                 $strTarget = null;
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \StringUtil::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext instanceof PageModel) {
                                 $strUrl = $objNext->getFrontendUrl();
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strUrl = $objNextPage->getFrontendUrl();
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget, $strName);
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = $strName;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
             case 'email_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = ltrim($strOutput);
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->getContentElement($elements[1]);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->getFrontendModule($elements[1]);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->getForm($elements[1]);
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 if (($objArticle = \ArticleModel::findByIdOrAlias($elements[1])) === null || !($objPid = $objArticle->getRelated('pid')) instanceof PageModel) {
                     break;
                 }
                 /** @var PageModel $objPid */
                 $strUrl = $objPid->getFrontendUrl('/articles/' . ($objArticle->alias ?: $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, \StringUtil::specialchars($objArticle->title), $objArticle->title);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, \StringUtil::specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     $arrCache[$strTag] = \StringUtil::toHtml5($objTeaser->teaser);
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 $bundles = \System::getContainer()->getParameter('kernel.bundles');
                 if (isset($bundles['ContaoNewsBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (isset($bundles['ContaoCalendarBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_calendar_events) AS te";
                 }
                 $strQuery .= " FROM tl_content";
                 $objUpdate = \Database::getInstance()->query($strQuery);
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('datimFormat'), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // POST data
             // POST data
             case 'post':
                 $arrCache[$strTag] = \Input::post($elements[1]);
                 break;
                 // Mobile/desktop toggle (see #6469)
             // Mobile/desktop toggle (see #6469)
             case 'toggle_view':
                 $strUrl = ampersand(\Environment::get('request'));
                 $strGlue = strpos($strUrl, '?') === false ? '?' : '&amp;';
                 if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=desktop" class="toggle_desktop" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleDesktop'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleDesktop'][0] . '</a>';
                 } else {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=mobile" class="toggle_mobile" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleMobile'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleMobile'][0] . '</a>';
                 }
                 break;
                 // Conditional tags (if)
             // Conditional tags (if)
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for (; $_rit < $_cnt; $_rit += 2) {
                         if ($tags[$_rit + 1] == 'iflng' || $tags[$_rit + 1] == 'iflng::' . $objPage->language) {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Conditional tags (if not)
             // Conditional tags (if not)
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = \StringUtil::trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 2) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('host'));
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('httpHost'));
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('url'));
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('base'));
                         break;
                     case 'request':
                         $arrCache[$strTag] = \Environment::get('indexFreeRequest');
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'assets_url':
                     case 'plugins_url':
                     case 'script_url':
                         $arrCache[$strTag] = TL_ASSETS_URL;
                         break;
                     case 'base_url':
                         $arrCache[$strTag] = \System::getContainer()->get('request_stack')->getCurrentRequest()->getBaseUrl();
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 // Do not use \StringUtil::specialchars() here (see #4687)
                 $arrCache[$strTag] = $objPage->{$elements[1]};
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Abbreviations
             // Abbreviations
             case 'abbr':
             case 'acronym':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
             case 'picture':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 $size = null;
                 $strTemplate = 'picture_default';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = \StringUtil::specialchars($value);
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                             case 'size':
                                 $size = (int) $value;
                                 break;
                             case 'template':
                                 $strTemplate = preg_replace('/[^a-z0-9_]/i', '', $value);
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 if (\Validator::isUuid($strFile)) {
                     // Handle UUIDs
                     $objFile = \FilesModel::findByUuid($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } elseif (is_numeric($strFile)) {
                     // Handle numeric IDs (see #4805)
                     $objFile = \FilesModel::findByPk($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } else {
                     // Check the path
                     if (\Validator::isInsecurePath($strFile)) {
                         throw new \RuntimeException('Invalid path ' . $strFile);
                     }
                 }
                 // Check the maximum image width
                 if (\Config::get('maxImageWidth') > 0 && $width > \Config::get('maxImageWidth')) {
                     $width = \Config::get('maxImageWidth');
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     // Image
                     if (strtolower($elements[0]) == 'image') {
                         $dimensions = '';
                         $imageObj = \Image::create($strFile, array($width, $height, $mode));
                         $src = $imageObj->executeResize()->getResizedPath();
                         $objFile = new \File(rawurldecode($src));
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . $imgSize[0] . '" height="' . $imgSize[1] . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . '>';
                     } else {
                         $picture = \Picture::create($strFile, array(0, 0, $size))->getTemplateData();
                         $picture['alt'] = $alt;
                         $picture['class'] = $class;
                         $pictureTemplate = new \FrontendTemplate($strTemplate);
                         $pictureTemplate->setData($picture);
                         $arrCache[$strTag] = $pictureTemplate->parse();
                     }
                     // Add a lightbox link
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0) {
                             $attribute = ' rel="' . $rel . '"';
                         } else {
                             $attribute = ' data-lightbox="' . substr($rel, 8) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . $alt . '"' : '') . $attribute . '>' . $arrCache[$strTag] . '</a>';
                     }
                 } catch (\Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files (UUID or template path)
             // Files (UUID or template path)
             case 'file':
                 if (\Validator::isUuid($elements[1])) {
                     $objFile = \FilesModel::findByUuid($elements[1]);
                     if ($objFile !== null) {
                         $arrCache[$strTag] = $objFile->path;
                         break;
                     }
                 }
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Check the path
                 if (\Validator::isInsecurePath($strFile)) {
                     throw new \RuntimeException('Invalid path ' . $strFile);
                 }
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($tag, $blnCache, $arrCache[$strTag], $flags, $tags, $arrCache, $_rit, $_cnt);
                         // see #6672
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 if (\Config::get('debugMode')) {
                     $GLOBALS['TL_DEBUG']['unknown_insert_tags'][] = $strTag;
                 }
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'stripslashes':
                     case 'standardize':
                     case 'ampersand':
                     case 'specialchars':
                     case 'nl2br':
                     case 'nl2br_pre':
                     case 'strtolower':
                     case 'utf8_strtolower':
                     case 'strtoupper':
                     case 'utf8_strtoupper':
                     case 'ucfirst':
                     case 'lcfirst':
                     case 'ucwords':
                     case 'trim':
                     case 'rtrim':
                     case 'ltrim':
                     case 'utf8_romanize':
                     case 'strrev':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                     case 'decodeEntities':
                         $arrCache[$strTag] = \StringUtil::$flag($arrCache[$strTag]);
                         break;
                     case 'number_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 0);
                         break;
                     case 'currency_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 2);
                         break;
                     case 'readable_size':
                         $arrCache[$strTag] = \System::getReadableSize($arrCache[$strTag]);
                         break;
                     case 'flatten':
                         if (!is_array($arrCache[$strTag])) {
                             break;
                         }
                         $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arrCache[$strTag]));
                         $result = array();
                         foreach ($it as $leafValue) {
                             $keys = array();
                             foreach (range(0, $it->getDepth()) as $depth) {
                                 $keys[] = $it->getSubIterator($depth)->key();
                             }
                             $result[] = implode('.', $keys) . ': ' . $leafValue;
                         }
                         $arrCache[$strTag] = implode(', ', $result);
                         break;
                         // HOOK: pass unknown flags to callback functions
                     // HOOK: pass unknown flags to callback functions
                     default:
                         if (isset($GLOBALS['TL_HOOKS']['insertTagFlags']) && is_array($GLOBALS['TL_HOOKS']['insertTagFlags'])) {
                             foreach ($GLOBALS['TL_HOOKS']['insertTagFlags'] as $callback) {
                                 $this->import($callback[0]);
                                 $varValue = $this->{$callback[0]}->{$callback[1]}($flag, $tag, $arrCache[$strTag], $flags, $blnCache, $tags, $arrCache, $_rit, $_cnt);
                                 // see #5806
                                 // Replace the tag and stop the loop
                                 if ($varValue !== false) {
                                     $arrCache[$strTag] = $varValue;
                                     break;
                                 }
                             }
                         }
                         if (\Config::get('debugMode')) {
                             $GLOBALS['TL_DEBUG']['unknown_insert_tag_flags'][] = $flag;
                         }
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \StringUtil::restoreBasicEntities($strBuffer);
 }
Example #29
0
	/**
	 * Download the remote file and save it to disk, create a thumbnail for it,
	 * and create a database entry for the file.
	 *
	 * @param string $p_url
	 *		The remote location of the file. ("http://...");
	 *
	 * @param array $p_attributes
	 *		Optional attributes which are stored in the database.
	 *		Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date'
	 *
	 * @param int $p_userId
	 *		The user ID of the user who uploaded the image.
	 *
	 * @param int $p_id
	 *		If you are updating an image, specify its ID here.
	 *
	 * @return mixed
	 * 		Return an Image object on success, return a PEAR_Error otherwise.
	 */
	public static function OnAddRemoteImage($p_url, $p_attributes,
	                                        $p_userId = null, $p_id = null)
	{
		global $Campsite;
		if (function_exists("camp_load_translation_strings")) {
			camp_load_translation_strings("api");
		}

		// Check if thumbnail directory is writable.
		$imageDir = $Campsite['IMAGE_DIRECTORY'];
		$thumbDir = $Campsite['THUMBNAIL_DIRECTORY'];
		if (!file_exists($imageDir) || !is_writable($imageDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR);
		}
		if (!file_exists($thumbDir) || !is_writable($thumbDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR);
		}

		$client = new HTTP_Client();
	    $client->get($p_url);
	    $response = $client->currentResponse();
	    if ($response['code'] != 200) {
	    	return new PEAR_Error(getGS("Unable to fetch image from remote server."));
	    }
	    foreach ($response['headers'] as $headerName => $value) {
	    	if (strtolower($headerName) == "content-type") {
	    		$ContentType = $value;
	    		break;
	    	}
	    }

        // Check content type
        if (!preg_match('/image/', $ContentType)) {
            // wrong URL
            return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
        }

    	// Save the file
        $tmpname = $Campsite['TMP_DIRECTORY'].'img'.md5(rand());
        if (is_writable($Campsite['TMP_DIRECTORY'])) {
	        if ($tmphandle = fopen($tmpname, 'w')) {
	            fwrite($tmphandle, $response['body']);
	            fclose($tmphandle);
	        }
        } else {
	    	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
	    }

        // Check if it is really an image file
        $imageInfo = getimagesize($tmpname);
        if ($imageInfo === false) {
        	unlink($tmpname);
            return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
        }

        // content-type = image
        if (!is_null($p_id)) {
        	// Updating the image
        	$image = new Image($p_id);
        	$image->update($p_attributes);
	    	// Remove the old image & thumbnail because
	    	// the new file might have a different file extension.
	    	if (file_exists($image->getImageStorageLocation())) {
				if (is_writable(dirname($image->getImageStorageLocation()))) {
		    		unlink($image->getImageStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
	    	if (file_exists($image->getThumbnailStorageLocation())) {
				if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
		    		unlink($image->getThumbnailStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
        } else {
        	// Creating the image
        	$image = new Image();
        	$image->create($p_attributes);
        	$image->setProperty('TimeCreated', 'NULL', true, true);
        	$image->setProperty('LastModified', 'NULL', true, true);
        }
        if (!isset($p_attributes['Date'])) {
        	$image->setProperty('Date', 'NOW()', true, true);
        }
        $image->setProperty('Location', 'remote', false);
        $image->setProperty('URL', $p_url, false);
	    if (isset($imageInfo['mime'])) {
	    	$image->setProperty('ContentType', $imageInfo['mime'], false);
	    }

        // Remember who uploaded the image
        if (!is_null($p_userId)) {
			$image->setProperty('UploadedByUser', $p_userId, false);
        }

        if ($Campsite['IMAGEMAGICK_INSTALLED']) {
		    // Set thumbnail file name
		    $extension = Image::__ImageTypeToExtension($imageInfo[2]);
		    $thumbnail = $image->generateThumbnailStorageLocation($extension);
		    $image->setProperty('ThumbnailFileName', basename($thumbnail), false);

		    if (!is_writable(dirname($image->getThumbnailStorageLocation()))) {
            	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
		    }

		    // Create the thumbnail
            $cmd = $Campsite['THUMBNAIL_COMMAND'].' '
            	. $tmpname . ' ' . $image->getThumbnailStorageLocation();
            system($cmd);
            if (file_exists($image->getThumbnailStorageLocation())) {
            	chmod($image->getThumbnailStorageLocation(), 0644);
            }
        }
        unlink($tmpname);
        $image->commit();

		$logtext = getGS('The image $1 has been added.',
						$image->m_data['Description']." (".$image->m_data['Id'].")");
		Log::Message($logtext, null, 41);

	    return $image;
	} // fn OnAddRemoteImage
Example #30
0
		sendResponse(400, json_encode($response));
		return false; 	 
	}

	//Insert image into bucket
	$result = $client->putObject(array(
		'Bucket'     => $cdimageBucket['Name'],
		'Key'        => "/img/".$newFileNameWithExt,
		'SourceFile' => $_FILES['file']['tmp_name']
	));
 
	// We can poll the object until it is accessible
	$client->waitUntil('ObjectExists', array(
		'Bucket' => $cdimageBucket['Name'],
		'Key'    => "/img/".$newFileNameWithExt
	));

	$Image->create($newFileNameWithExt);
	 
		//Update the user's image
		$User->deleteImage();
		$User->setImage($Image->ID);

	//Set the status to 1 (success)
	$response['meta']['status'] = 1;
	$response['data']['imageURL'] = $signedURL;

	//Send the response
	sendResponse(200, json_encode($response));
	return true;
?>