Phalcon Paginator error: Syntax error, unexpected EOF - frameworks

my problem is, every time I click in the paginator link in the view, the controller returns me this error:
Syntax error, unexpected EOF
What is this? EOF?
My controller:
$domicilios = Domicilios::find();
$paginator = new \Phalcon\Paginator\Adapter\Model(
array(
"data" => $domicilios,
"limit"=> 5,
"page" => $currentPage
)
);
$pagina = $paginator->getPaginate();
$this->view->setVar("estado", $estado);
$this->view->setVar("pagina", $pagina);
The content in the model Domicilios is returning right, but why the paginator keeps returning this error?
Thanks in advance!

EOF is end of file. there might be several issues. 1stly if you upload this file to server, there might be problems with upload process and file is not fully uploaded and you have broken end of file (EOF).
try converting your php file to utf8. you can do it with notepad++ and many other programs.
here are my working pagination:
$page = $this->request->get('page', 'int', 1);
$this->view->page = $page;
if ($page < 1) {
$page = 1;
}
$user = $this->session->get('auth');
$questions = Model_UserQuestion::find(array(
'user_id=:user_id:',
'bind' => array('user_id' => $user['id']),
"order" => "id DESC",
));
// Create a Model paginator, show 10 rows by page starting from $currentPage
$paginator = new \Phalcon\Paginator\Adapter\Model(
array(
"data" => $questions,
"limit" => $this->config->application->itemsPerPage,
"page" => $page
)
);
$page = $paginator->getPaginate();
$this->view->questions = $page->items;
notice that to get items you have to use this:
$page->items

Related

Is there a way to fix a date error using Symfony 4?

I'm working on a project as a back-end developer using PHP 7.2.11 and Symfony 4.2.3
My goal is to showcase events (concerts, festivals...) from data I grab from an API on an interactive map.
This is the result I get:
https://imgur.com/HmpBK5B.png
To import the data from the API, I use a for loop going from 1 to 7 (corresponding to days) and adding days to the today's date.
This date will be used as a parameter to grab the events occuring from today to the next 7 days.
Problem is: I get the following error running my custom symfony command
php bin/console import:mapado :
2019-03-26T12:08:34+01:00 [error] Error thrown while running command "import:mapado". Message: "Notice: Undefined index: address"
The error is due to a date not existing and then refering to an inexistant address.
I tried to change the parameters in my first for loop, with days going either to 8 or to 6 but it didn't change the output error.
I change the custom date parameter (from my loop) from the API url to the default parameter and everything is working with default (but it only gets the events for the 3 next days).
Here is the parameter I use:
https://imgur.com/tx1OyrM.png
From: https://api.mapado.net/v2/docs#operation/getActivityCollection
And how an element from the API looks like:
https://imgur.com/l1nTOCC.png
This is the code I've written:
protected function execute(InputInterface $input, OutputInterface $output) {
for ($jour = 0; $jour <= 7; $jour++) {
// problem is here
$futureDay = date('Y-m-d', strtotime('+'.$jour.' days'));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.mapado.net/v2/activities?fields=#id,title,shortDate,nextDate,activityType,locale,description,address&itemsPerPage=1000&when=".$futureDay."&periodOfDay=evening",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer MTMwZWJiODFiZjA4YTcyOGY2ZmMzMGYwOTQyYWM2NDZjODVlNDg1MzU0MzE3M2I4MTdiMDQyZjU5MDVkZjFjZA",
"Cache-Control: no-cache",
"Conent-Type: application/json",
"Content-Type: application/x-www-form-urlencoded",
"Postman-Token: 55672a19-0ffc-4fe6-a866-3e15c3df9dae"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$mapado_events = json_decode($response, JSON_PRETTY_PRINT);
for ($i = 0; $i < count($mapado_events['hydra:member']); $i++) {
if ($mapado_events['hydra:member'][$i]['locale'] == 'fr') {
$mapado_id = $mapado_events['hydra:member'][$i]['#id'];
$mapado_date = \date('Y-m-d', strtotime($mapado_events['hydra:member'][$i]['nextDate']));
$result = $this->getContainer()
->get('doctrine')
->getRepository(MapadoIDs::class)
->findOneBy(['mapado_id' => $mapado_id]);
if ($result == null) {
echo 'event existe pas, ajout en bdd'.PHP_EOL;
$MapadoIDs = new MapadoIDs();
$MapadoIDs->setMapadoId($mapado_id);
$this->em->persist($MapadoIDs);
$mapado = json_decode($response, JSON_PRETTY_PRINT);
$event = new Event();
$event->setLongitude($mapado['hydra:member'][$i]['address']['longitude']);
$event->setLatitude($mapado['hydra:member'][$i]['address']['latitude']);
$event->setTitle($mapado['hydra:member'][$i]['title']);
$event->setDate($mapado_date);
$event->setFormattedAddress($mapado['hydra:member'][$i]['address']['formattedAddress']);
$event->setCity($mapado['hydra:member'][$i]['address']['city']);
$event->setLocale($mapado['hydra:member'][$i]['locale']);
$event->setActivityType($mapado['hydra:member'][$i]['activityType']);
$event->setDescription($mapado['hydra:member'][$i]['description']);
$this->em->persist($event);
}
}
}
}
$this->em->flush();
curl_close($curl);
if ($err) {
echo "cURL Error #: " . $err;
} else {
echo $response;
}
}
}
for better readability:
https://pastebin.com/CTu5gb8t
Expected result is a json output in my console.
Actual result is an error thrown preventing me from inserting results into my database.
Could you tell me if I'm missing something that could result in this error ?
It's a long and detailed post so that you can understand better my problem.
Well I solved my problem and it was not a date problem.
The problem was with the itemsPerPage query parameter requesting too much data and then throwing an error.
I set it up to 400 and everything is working as expected.

magento 1.9.2.2 add to cart with custom option image not working

I have a script which adds a product in cart with custom option image and it was working perfect till CE 1.9.2.1 but after up gradation to latest version it troughs exception that Please specify the product's required option(s).
Below is code, please guide me if something has to change for newer version .
<?php
$productId = xxx;
$image = 'path to image(tested image exists)';
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
'product' => $productId,
'qty' => 1,
'options' => array(
$optionId3inmycase => array(
'type' => 'image/tiff',
'title' => $image,
'quote_path' => '/media/custom/' . $image,
'order_path' => '/media/custom/' . $image,
'fullpath' => Mage::getBaseDir() . '/media/custom/' . $image,
'secret_key' => substr(md5(file_get_contents(Mage::getBaseDir() . '/media/custom/' . $image)), 0, 20)),
)
);
$request = new Varien_Object();
$request->setData($params);
$cart->addProduct($product, $request);
$cart->save();
if ($itemId > 0) {
$cartHelper = Mage::helper('checkout/cart');
$cartHelper->getCart()->removeItem($itemId)->save();
}
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->_redirect('checkout/cart/');
?>
One quick solution is to rewrite Mage_Catalog_Model_Product_Option_Type_File class and change validateUserValue() function.
around line 129, replace
$fileInfo = $this->_getCurrentConfigFileInfo();
with
$fileInfo = null;
if (isset($values[$option->getId()]) && is_array($values[$option->getId()])) {
// Legacy style, file info comes in array with option id index
$fileInfo = $values[$option->getId()];
} else {
/*
* New recommended style - file info comes in request processing parameters and we
* sure that this file info originates from Magento, not from manually formed POST request
*/
$fileInfo = $this->_getCurrentConfigFileInfo();
}
but its old code and will have APPSEC-1079 security issue.
and to download image this uploaded image in order detail etc. add this function in same model class.
/**
* changed the image save address as we are saving image in custom
* Main Destination directory
*
* #param boolean $relative If true - returns relative path to the webroot
* #return string
*/
public function getTargetDir($relative = false)
{
$fullPath = Mage::getBaseDir('media') . DS . 'custom';
return $relative ? str_replace(Mage::getBaseDir(), '', $fullPath) : $fullPath;
}

Form bindAndSave method doesn't save files

Parsing an XML feed and save it this way:
$action = new CouponActionForm();
$values = array(
'name' => $offer->name,
'link' => $offer->url,
'description' => $offer->description,
'discount' => $offer->discount,
'price' => $offer->price
);
$files = $this->getImages($offer->picture);
if(!$action->bindAndSave($values, $files)){
echo $action->renderGlobalErrors();
die('BAD THING');
}
Here is the getImages method:
private function getImages($url){
$ret = array('error' => 0);
$tmp_dir = sys_get_temp_dir();
$tmp_file = tempnam($tmp_dir, 'kupon');
if(copy($url, $tmp_file)){
$ret['tmp_name'] = $tmp_file;
$ret['name'] = basename($url);
$ret['size'] = filesize($tmp_file);
$ret['type'] = 'image/jpeg';
return array('filename' => $ret);
}else{
die('HELP');
}
}
Why do I use form saving instead of object saving with ->fromArray method ? Well, I already made the form and all validation, so I don't want to implement the same thing twice (DRY), but as important, I actually don't know how to use validators in doctrine model.
So the problem is that the form doesn't save files in specific directory specified by the path property of sfValidatorFile validator, but it exists in tmp directory.

silverstripe dataobject searchable

I´m trying to have certain DataObjects (News) displayed in the default SearchResult Page. So the result should display normal Pages and News.
Is there an easy way to accomplish that in Silverstripe 3?
Or is it recommended to code it completely custom - I mean a custom controller/action which handles the search request and creates a result list, which I display then in a custom template?
I found this, but obviously search is disabled right now:
https://github.com/arambalakjian/DataObjects-as-Pages
Thx and regards,
Florian
I usually but together a custom search function after enabling FulltextSearchable. So in _config.php I would have
FulltextSearchable::enable();
Object::add_extension('NewsStory', "FulltextSearchable('Name,Content')");
replacing Name and Content with whatever DBField you want to be searchable. And each searchable DataObject have this in their class to enable search indexes (pretty sure this needs to be added and run dev/build before enabling the extension, and only works on MySQL DB).
static $create_table_options = array(
'MySQLDatabase' => 'ENGINE=MyISAM'
);
then in my PageController I have my custom searchForm and results functions.
Here is the search function that returns the search form, called with $search in the template:
public function search()
{
if($this->request && $this->request->requestVar('Search')) {
$searchText = $this->request->requestVar('Search');
}else{
$searchText = 'Search';
}
$f = new TextField('Search', false, $searchText);
$fields = new FieldList(
$f
);
$actions = new FieldList(
new FormAction('results', 'Go')
);
$form = new Form(
$this,
'search',
$fields,
$actions
);
//$form->disableSecurityToken();
$form->setFormMethod('GET');
$form->setTemplate('SearchForm');
return $form;
}
and here the custom results function to handle the queries...
function results($data, $form, $request)
{
$keyword = trim($request->requestVar('Search'));
$keyword = Convert::raw2sql($keyword);
$keywordHTML = htmlentities($keyword, ENT_NOQUOTES, 'UTF-8');
$pages = new ArrayList();
$news = new ArrayList();
$mode = ' IN BOOLEAN MODE';
//$mode = ' WITH QUERY EXPANSION';
//$mode = '';
$siteTreeClasses = array('Page');
$siteTreeMatch = "MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keyword'$mode)
+ MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keywordHTML'$mode)";
$newsItemMatch = "MATCH( Name, Content ) AGAINST ('$keyword'$mode)
+ MATCH( Name, Content ) AGAINST ('$keywordHTML'$mode)";
//Standard pages
foreach ( $siteTreeClasses as $c )
{
$query = DataList::create($c)
->where($siteTreeMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $siteTreeMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record )
{
if ( in_array($record['ClassName'], $siteTreeClasses) )
$objects[] = new $record['ClassName']($record);
}
$pages->merge($objects);
}
//news
$query = DataList::create('NewsStory')->where($newsItemMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $newsItemMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record ) $objects[] = new $record['ClassName']($record);
$news->merge($objects);
//sorting results
$pages->sort(array(
'Relevance' => 'DESC',
'Title' => 'ASC'
));
$news->sort(array(
'Relevance' => 'DESC',
'Date' => 'DESC'
));
//output
$data = array(
'Pages' => $pages,
'News' => $news,
'Query' => $keyword
);
return $this->customise($data)->renderWith(array('Search','Page'));
}
I add all the Page classes I want to be searched and that extend SiteTree in the $siteTreeClasses array, and the News parts can be pretty much copied for any other DataObjectI need searchable.
I am not saying this is the best solution and this can definitely be improved on, but it works for me and this might be a good stating point.
I have adapted #colymba's solution into a silverstripe module: https://github.com/burnbright/silverstripe-pagesearch
It allows setting the pagetype in the url.
You'll need to substantially overwrite SearchForm->getResults().
It uses Database->searchEngine(), but those are tailored towards SiteTree and Page classes.
The "proper" solution is to feed the data into a search engine like Solr or Sphinx.
We have the SS3-compatible "fulltextsearch" module for this purpose:
https://github.com/silverstripe-labs/silverstripe-fulltextsearch
It's going to take some upfront setup, and is only feasible if you can either host Solr yourself, or are prepared to pay for a SaaS provider. Once you've got it running though, the possibilities are endless, its a great tool!

Drupal - Include more than one user_profile_form on a page

Edit:
I think it is because the action is the same or something. I tried to modify the action using this:
function mytheme_user_profile_form($form) {
global $user;
$uid = $user->uid;
//print '<pre>'; print_r($form); print '</pre>';
$category = $form['_category']['#value'];
switch($category) {
case 'account':
$form['#action'] = '/user/'.$uid.'/edit?destination=user/'.$uid;
break;
case 'education':
$form['#action'] = '/user/'.$uid.'/edit/education?destination=user/'.$uid;
break;
case 'experience':
$form['#action'] = '/user/'.$uid.'/edit/experience?destination=user/'.$uid;
break;
case 'publications':
$form['#action'] = '/user/'.$uid.'/edit/publications?destination=user/'.$uid;
break;
case 'conflicts':
$form['#action'] = '/user/'.$uid.'/edit/conflicts?destination=user/'.$uid;
break;
}
//print '<pre>'; print_r($form); print '</pre>';
//print $form['#action'];
$output .= drupal_render($form);
return $output;
}
But, the form action, when the form is actually rendered is unchanged. They're all /user/%uid
Can I modify the form action?
I am including several different "categories" of the user profile form on one page, and the code will correctly output the forms I'm specifying. Each form is in a separate collapsible div.
My problem is twofold.
(1) The existing values for the fields aren't pre-populated and
(2) Clicking on "Save" for one section will result in a warning: Email field is required, regardless of which form you're actually saving
I am pretty sure that for problem #2, it is because the name of the button is the same in all cases, as is the form id.
print '<h3>– Account Settings</h3>';
print '<div class="expand">';
print(drupal_get_form('user_profile_form', $user, 'account'));
print '</div>';
print '<h3>– My Info</h3>';
print '<div class="expand">';
print(drupal_get_form('user_profile_form', $user, 'Personal'));
print '</div>';
print '<h3>– Experience</h3>';
print '<div class="expand">';
print(drupal_get_form('user_profile_form', $user, 'experience'));
print '</div>';
print '<h3>– Education</h3>';
print '<div class="expand">';
print(drupal_get_form('user_profile_form', $user, 'education'));
print '</div>';
Problem #1: ? Could you post the html source?
For problem #2:
OK, I'll step through the code here:
The validation handler for the user profile form (user_profile_form_validate()) calls
user_module_invoke('validate', $form_state['values'], $form_state['values']['_account'], $form_state['values']['_category']);
Which looks like
<?php
/**
* Invokes hook_user() in every module.
*
* We cannot use module_invoke() for this, because the arguments need to
* be passed by reference.
*/
function user_module_invoke($type, &$array, &$user, $category = NULL) {
foreach (module_list() as $module) {
$function = $module .'_user';
if (function_exists($function)) {
$function($type, $array, $user, $category);
}
}
}
?>
So, the validation handler for this form is going through every module looking for user hook functions and calling them with $type = 'validate'. (Note that 'category' param is optional here - contrib modules are not required to use it)
Let's look at user.module's user hook as an example to see what happens:
function user_user($type, &$edit, &$account, $category = NULL) {
if ($type == 'view') {
$account->content['user_picture'] = array(
'#value' => theme('user_picture', $account),
'#weight' => -10,
);
if (!isset($account->content['summary'])) {
$account->content['summary'] = array();
}
$account->content['summary'] += array(
'#type' => 'user_profile_category',
'#attributes' => array('class' => 'user-member'),
'#weight' => 5,
'#title' => t('History'),
);
$account->content['summary']['member_for'] = array(
'#type' => 'user_profile_item',
'#title' => t('Member for'),
'#value' => format_interval(time() - $account->created),
);
}
if ($type == 'form' && $category == 'account') {
$form_state = array();
return user_edit_form($form_state, (isset($account->uid) ? $account->uid : FALSE), $edit);
}
//<-- LOOK HERE -->
if ($type == 'validate' && $category == 'account') {
return _user_edit_validate((isset($account->uid) ? $account->uid : FALSE), $edit);
}
if ($type == 'submit' && $category == 'account') {
return _user_edit_submit((isset($account->uid) ? $account->uid : FALSE), $edit);
}
if ($type == 'categories') {
return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
}
}
So, it is only supposed to validate if the category == 'account'
In the function _use_edit_validate, we find:
// Validate the e-mail address:
if ($error = user_validate_mail($edit['mail'])) {
form_set_error('mail', $error);
}
There's your error message.
Since that form is only supposed to validate when the category == 'account', and your problem (#2) seems to be that it always validates regardless of the category, maybe your forms are not being rendered as unique form instances? Drupal might be rendering a complete form each time, and just setting a hidden form value to whatever the category is (like in this form's definition function in user_pages.inc $form['_category'] = array('#type' => 'value', '#value' => $category);)
It would be helpful to see the actual html source output.
==EDIT 10-15-09 in response to updated question===
OK, it looks like your method (editing $form['#action'] manually in the theme layer) may not be possible (see this post for reference). If you want to alter the form action you need to write a custom module that implements hook_form_alter() (it won't work in a theme template file). This function allows you to modify how a form is rendered, in your case the user modification form. There are more details on form modification here.
I am not 100% sure that's what you want to do though; (since it looks like you already must create a module) perhaps you want to hook into hook_user() instead; this function "... allows modules to react when operations are performed on user accounts.". You may be able to react to the category in this function and block/allow whichever user changes you like.
However, if it's just email address validation that is the problem, and if you are dealing with existing users, why don't you just make sure the email address is set before you save?