How to update youtube annalytics to all previously registered youtube channels - api

I have a web app in which the users can register and connect their youtube channels. Next in the registration process I collect all the information I can get from youtube data api and youtube analytics and reporting api (with scopes and access tokens) and store it in the database. I show that info on their dashboards. I also display that info in the admin panel for the administrators to see.
The problem is, how can I refresh that info, lets say, once a day? I've tried with the access token but i get error 403 Forbidden message. I want to update the info to all of the registered youtube accounts, this is the function I use to update all but its not working
(In the bellow script, i send $code as a variable and the function is called on the redirect URI)
$youtube_channels = YouTubeChannels::get();
$key = env('NEW_YOUTUBE_API_KEY');
foreach($youtube_channels as $youtube_channel) {
$yt_channel_statistics = Http::get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'statistics,snippet',
'id' => $youtube_channel->youtube_channel_id,
'key' => $key
]);
$yt_channel_statistics_json = $yt_channel_statistics->json();
$update_yt = YouTubeChannels::where('youtube_channel_id', $youtube_channel->youtube_channel_id)->first();
if($update_yt != null) {
$update_yt->channel_name = $yt_channel_statistics_json['items'][0]['snippet']['title'];
$update_yt->channel_subscribers = $yt_channel_statistics_json['items'][0]['statistics']['subscriberCount'];
$update_yt->channel_total_views = $yt_channel_statistics_json['items'][0]['statistics']['viewCount'];
$update_yt->channel_videos_count = $yt_channel_statistics_json['items'][0]['statistics']['videoCount'];
$update_yt->save();
}
//test
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
$apiKey = env('NEW_YOUTUBE_API_KEY');
$channelId = $youtube_channel->youtube_channel_id;
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
$video_ids_string = collect($videos)->implode(',');
//
//endtest
//new test
//
$params = [
'part'=> 'snippet,contentDetails,statistics,status',
'id' => $video_ids_string,
'key'=> $apiKey
];
$url = $baseUrl . 'videos?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos_infos = $json;
//
YouTubeVideos::where('youtube_channel_id', $youtube_channel->id)->delete();
foreach ($videos as $video){
foreach($videos_infos['items'] as $info){
if ($info['id'] == $video) {
if($info['status']['privacyStatus'] == 'public') {
$youtube_video = new YouTubeVideos();
// if (!$live_error) {
// foreach ($live_videos as $live) {
// if ($live->youtube_id == $video) {
// $youtube_video->was_live = true;
// }
// }
// }
// dd($video);
$youtube_video->youtube_channel_id = $youtube_channel->id;
$youtube_video->yt_video_id = $video;
$youtube_video->yt_video_title = $info['snippet']['title'];
$youtube_video->yt_video_description = $info['snippet']['description'];
$youtube_video->yt_video_published_at = Carbon::parse($info['snippet']['publishedAt']);
if(isset($info['snippet']['defaultAudioLanguage'])) {
$youtube_video->yt_video_default_audio_language = $info['snippet']['defaultAudioLanguage'];
} else {
$youtube_video->yt_video_default_audio_language = '';
}
if (strcmp($info['contentDetails']['caption'], 'true') == 0) {
$youtube_video->is_video_captioned = true;
} else {
$youtube_video->is_video_captioned = false;
}
$youtube_video->yt_video_definition = $info['contentDetails']['definition'];
$youtube_video->yt_video_dislike_count = 0;
$youtube_video->yt_video_like_count = $info['statistics']['likeCount'];
$youtube_video->yt_video_views_count = $info['statistics']['viewCount'];
//proba type of views
//
$client = new Google_Client();
try{
$client->setAuthConfig(storage_path('app'.DIRECTORY_SEPARATOR. 'json'. DIRECTORY_SEPARATOR.'client_secret.json'));
}catch (\Google\Exception $e){
dd($e->getMessage());
}
// $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly']);
$client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL,GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, GOOGLE_SERVICE_YOUTUBE::YOUTUBEPARTNER,'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']);
$client->setRedirectUri(env('APP_URL') . '/get_access_token_yt_test');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt("consent");
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true); // incremental auth
if (!isset($code)){
$auth_url = $client->createAuthUrl();
return redirect()->away($auth_url)->send();
}else{
if($code != null) {
$client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($client->getAccessToken());
session()->push('refresh_token_youtube', $client->getRefreshToken());
session()->save();
}
}
$service = new Google_Service_YouTube($client);
$analytics = new Google_Service_YouTubeAnalytics($client);
$typeOfViews = $analytics->reports->query([
'ids' => 'channel==' . $youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'views',
'dimensions' => 'liveOrOnDemand',
'filters' => 'video=='.$video
]);
foreach ($typeOfViews as $viewType) {
if ($viewType[0] == 'ON_DEMAND') {
$youtube_video->yt_video_on_demand_views_count = $viewType[1];
} else if ($viewType[0] == 'LIVE') {
$youtube_video->yt_video_live_views_count = $viewType[1];
}
}
$watch_times = $analytics->reports->query([
'ids' => 'channel=='.$youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'estimatedMinutesWatched',
'dimensions' => 'day',
'filters' => 'video=='.$video
]);
// //update quotas
// // self::update_quotas(1);
$total = 0;
foreach ($watch_times as $watch_time){
$total += $watch_time[1];
}
$youtube_video->estimated_minutes_watch_time = $total;
$youtube_video->save();
//zacuvuva captions
$xmlString = file_get_contents("https://video.google.com/timedtext?type=list&v=" . $video);
$xmlObject = simplexml_load_string($xmlString);
$json = json_encode($xmlObject);
$phpArray = json_decode($json, true);
if (isset($phpArray['track'])) {
foreach ($phpArray['track'] as $array) {
$yt_video_captions = new YouTubeVideosCaptions();
$yt_video_captions->youtube_video_id = $youtube_video->id;
$yt_video_captions->language = $array['lang_code'];
$yt_video_captions->save();
}
}
//zacuvuva tags
if(isset($info['snippet']['tags'])) {
if ($info['snippet']['tags'] != null) {
foreach ($info['snippet']['tags'] as $tag) {
$youtube_video_tags = new YouTubeVideosTags();
$youtube_video_tags->youtube_video_id = $youtube_video->id;
$youtube_video_tags->tag = $tag;
$youtube_video_tags->save();
}
}
}
if ($youtube_video->is_video_captioned) {
$captions = YouTubeVideosCaptions::where('youtube_video_id', $youtube_video->id)->get();
foreach ($captions as $caption) {
$video_id = YouTubeVideos::where('id', $caption->youtube_video_id)->first();
$client->authorize();
$fp = fopen('../storage/app/captions/' . $caption->id . '.xml', 'w');
$xmlString = file_get_contents("http://video.google.com/timedtext?type=track&v=" . $video_id['yt_video_id'] . "&id=0&lang=" . $caption['language']);
fwrite($fp, $xmlString);
fclose($fp);
}
}
echo 'done';
}
}
}
}
// Command::line('Youtube videos updated');
//
//
//end new test
}
}

Related

Symfony 5 - A problem with package HTTP-Client (NativeHttpClient)

I have an error that I don't understand.
I'm trying to validate the creation of a MangoPay account and I'm using the Http-Client package for the APIs (I've also installed mangopay's package).
When I try to create one, this error shows up:
Unsupported option "0" passed to "Symfony\Component\HttpClient\NativeHttpClient", did you mean "auth_basic", "auth_bearer", "query", "headers", "body", "json", "user_data", "max_redirects", "http_version", "base_uri", "buffer", "on_progress", "resolve", "proxy", "no_proxy", "timeout", "max_duration", "bindto", "verify_peer", "verify_host", "cafile", "capath", "local_cert", "local_pk", "passphrase", "ciphers", "peer_fingerprint", "capture_peer_cert_chain", "extra"?
That's the file I'm working on:
<?php
namespace App\Service;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use MangoPay;
use App\Service\MockStorage;
class CallApiService
{
private $mangoPayApi;
private $client;
public function __construct(HttpClientInterface $httpClient)
{
$this->client = $httpClient;
$this->mangoPayApi = new MangoPay\MangoPayApi();
$this->mangoPayApi->Config->ClientId = $_ENV['CLIENT_ID'];
$this->mangoPayApi->Config->ClientPassword = $_ENV['API_KEY'];
// $this->mangoPayApi->Config->TemporaryFolder = 'mangotemp';
$this->mangoPayApi->OAuthTokenManager->RegisterCustomStorageStrategy(new MockStorage());
}
public function createProfilMango($form)
{
$date = date_format($form['birthday']->getData(), "Ymd");
$userMango = $this->client->request(
'POST',
$_ENV['SERVER_URL'] . '/' . $_ENV['VERSION'] . '/' . $_ENV['CLIENT_ID'] .'/users/natural',
[
$UserNatural = new MangoPay\UserNatural(),
$UserNatural->FirstName = $form['firstname']->getData(),
$UserNatural->LastName = $form['lastname']->getData(),
$UserNatural->Email = $form['email']->getData(),
$UserNatural->Address = new MangoPay\Address(),
$UserNatural->Address->AddressLine1 = $form['streetNumber']->getData() . " " . $form['address']->getData(),
$UserNatural->Address->AddressLine2 = "",
$UserNatural->Address->City = $form['city']->getData(),
$UserNatural->Address->Region = "",
$UserNatural->Address->PostalCode = $form['zipCode']->getData(),
$UserNatural->Address->Country = "FR",
$UserNatural->Birthday = intval($date),
$UserNatural->Nationality = $form['nationality']->getData(),
$UserNatural->CountryOfResidence = "FR",
$UserNatural->Capacity = "NORMAL",
$Result = $this->mangoPayApi->Users->Create($UserNatural),
]
);
return $userMango;
}
}
The CallApiService.php is called upon the signup controller of my website:
// RegistrationController.php
[...]
public function register(CallApiService $callApiService, User $user = null, Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, AppCustomAuthenticator $authenticator, EntityManagerInterface $entityManager): Response
{
if(!$user){
$user = new User();
}
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$callApiService->createProfilMango($form);
// $entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
// return $userAuthenticator->authenticateUser(
// $user,
// $authenticator,
// $request,
// // 'main' // firewall name in security.yaml
// );
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
'editMode'=> $user-> getId() !== null,
]);
}
I've tried to change the $client value with new NativeHttpClient() and new CurlHttpClient() but the error doesn't change.
What's the error? How can I fix it?

How to get the Gross Sales from the Square Order API?

Qn1) I have tried getting the gross sales from the Order API. However, I could only be able to get each lineitem gross value concatenating with one and another ...
Gross value that is concatenating
Qn2) I tried to echo all the item name, qty and etc to insert it into my database although it works but I am getting an error message shown below
Error message
Here is my code: (Have replaced the access token and the location_id to 'XXXX')
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
echo (array_sum($grossSales)/100); //Qn1
echo($orderid. " ". $lineItemsID ." ".$catalogObjID." ".$itemName ." ".$itemQty." <br/>"); //Qn2
}
}
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
$grossSales = array();
if (is_array($orders) || is_object($orders)) {
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
if (is_array($lineItems) || is_object($lineItems)){
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
}
}
}
}
$sum = 0;
foreach($grossSales as $key=>$value)
{
$sum+= $value;
}
echo ($sum/100);
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>

Yii2-How to access a variable from model to a controller?

I am working on yii2. I have came across a point in which I have to send an email to a person when a meter is installed and it's images are uploaded to the server. Fro this I have already configured the swift mailer.
There is a model named Installations which have a function which saves all the installation data.
public static function saveAll($inputs){
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new Installations;
foreach ((array)$input as $key => $value) {
if($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (Installations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:sā€Šā€Š');
if($s->save()){
if ($s->istallation_status == 'Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[4]);
}
else if ($s->istallation_status != 'Installed' && $s->comm_status =='Failed')
{
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[5]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->doc_images_name)) {
foreach ($input->doc_images_name as $img) {
$image = new InstallationImages;
$image->image_name = $img->image_name;
$image->installation_id = $s->id;
$image->save();
}
}
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img2) {
$image2 = new InstallationImagesSite;
$image2->image_name = $img2->image_name;
$image2->installation_id = $s->id;
$image2->save();
}
}
}else{
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
$status = $s->istallation_status;
$msn = $s->meter_msn;
$com = $s->comm_status;
// want to pass these variables to the controller function
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Now There Is a Controller name InstallationController. This controller contains all the APIs for my mobile application. Below are two main functions in it
public function actionAddnew()
{
$fp = fopen('debugeeeeeee.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return Installations::saveAll($inputs);
}
public function actionSavephoto()
{
try {
$count = 0;
foreach ($_FILES as $f) {
$dd = pathinfo($f['name']);
if (!isset($dd['extension']) || !in_array($dd['extension'], array('jpg', 'png', 'gif'))) {
return ['status' => 'ERROR', 'uploaded_files' => $count, 'message' => 'Invalid File'];
break;
}
if (move_uploaded_file($f['tmp_name'], Installations::UPLOAD_FOLDER . $f['name'])) {
$count++;
return ['status' => 'OK', 'uploaded_files' => $count];
break;
} else {
return ['status' => 'ERROR', 'uploaded_files' => $count];
break;
}
}
} catch (Exception $x) {
return ['status' => 'ERROR', 'message' => $x->getMessage()];
}
}
The mobile application will call the Addnew() api and after that it will call the savephoto. Now I want to pass $msn,$status and $com values from the Model to the controller function Savephoto.
For this I have tried to use session variables but still I am unable to get by desired result(s).
I have also checked the question Yii, how to pass variables to model from controller?
but it didn't worked for me.
How can I achieve it?
Any help would be highly appreciated.
The only way to get those values out of saveAll() is to return them. Presently, they are defined on an object in $s that is overwritten each loop. The best way to do that seems to be creating an array outside of your foreach ($inputs... loop and appending each created Installations object.
Return that at the end, and pass it (or just the relevant element from it) into actionSavephoto() as a parameter. Then, those values will be accessible of properties of that passed object. This handling will occur in the code that is not pictured which calls actionAddNew() and then actionSavephoto()

How to resize a image while uploading in ZF2

I'm new to Zend Frame work and I need to implement image resize while uploading in zend framework 2. I try to use the method in image resize zf2 but it didnot work for me.
please help?
public function addAction(){
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$width = $this->params('width', 30); // #todo: apply validation!
$height = $this->params('height', 30); // #todo: apply validation!
$imagine = $this->getServiceLocator()->get('my_image_service');
$image = $imagine->open($File['tmp_name']);
$transformation = new \Imagine\Filter\Transformation();
$transformation->thumbnail(new \Imagine\Image\Box($width, $height));
$transformation->apply($image);
$response = $this->getResponse();
$response->setContent($image->get('png'));
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('./data/tmpuploads/');
if ($adapter->receive($File['name'])) { //identify the uploaded errors
$profile->exchangeArray($form->getData());
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
}
}
}
}
return array('form' => $form);
}
Related to :-image resize zf2
I get answer for this question by adding external library to zend module.It is a easy way for me. i used http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ class as external library.this is my controller class.
class ProfileController extends AbstractActionController{
public function addAction()
{
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
//set data post and file ...
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('//destination for upload the file');
if ($adapter->receive($File['name'])) {
$profile->exchangeArray($form->getData());
//print_r($profile);
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
$image = new SimpleImage();
$image->load('//destination of the uploaded file');
$image->resizeToHeight(500);
$image->save('//destination for where the resized file to be uploaded');
}
}
}
}
return array('form' => $form);
}
}
Related:-Zend Framework 2 - How to use an external library
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

SQL showing in place of web page

I've copied a codeigniter website from my old computer to my new one, and copied the database. When I navigate to the site in my localhost however, I just get SQL printed out
db->where($cell_name, $id); $this->db->delete($table_name); if (!is_array($tags)) { $tmp = array(); $tmp[] = $tags; $tags = $tmp; } if (!empty($tags)) { foreach($tags as $tag) { switch(gettype($tag)) { case 'integer': $this->db->set($cell_name, $id); $this->db->set('tag_id', $tag); $this->db->insert($table_name); break; case 'string': $tag = strtolower($tag); $results = $this->db->query('SELECT id FROM tag WHERE tag = \''.$tag.'\' LIMIT 1'); if ($results->num_rows() == 1) { $tag_id = $results->first_row()->id; } else { $this->db->set('tag', $tag); $this->db->set('permalink', url_title($tag, 'dash')); $this->db->insert('tag'); $tag_id = $this->db->insert_id(); } $this->db->set($cell_name, $id); $this->db->set('tag_id', $tag_id); $this->db->insert($table_name); break; } } } } function get_active($type, $id, $return_ids = true) { $ret = array(); switch($type) { case 'media': $table_name = 'media_tag'; $cell_name = 'media_id'; break; case 'post': $table_name = 'post_tag'; $cell_name = 'post_id'; break; } if (!$id) { $results = $this->db->query('SELECT tag.id, tag.tag, tag.permalink FROM '.$table_name.', tag WHERE tag_id = tag.id GROUP BY tag.id ORDER BY tag.tag'); if ($results->num_rows() > 0) { foreach($results->result() as $data) { if ($return_ids) $ret[] = $data->id; else $ret[] = (object) array('id' => $data->id, 'tag' => $data->tag, 'permalink' => $data->permalink); } } } else { $results = $this->db->query('SELECT tag.id, tag.tag, tag.permalink FROM '.$table_name.', tag WHERE '.$cell_name.' = '.$id.' AND tag_id = tag.id ORDER BY tag.tag'); if ($results->num_rows() > 0) { foreach($results->result() as $data) { if ($return_ids) $ret[] = $data->id; else $ret[] = (object) array('id' => $data->id, 'tag' => $data->tag, 'permalink' => $data->permalink); } } } return $ret; } }
Does anyone know if there's a simple reason for this - some setting I need to turn on in wamp for example, I'm completely at a loss, the files and database are identical on my old and new computers
It turns out I had simply not allowed "short open tags" from the WAMP PHP settings