Symfony getRootDir() + /../folder/file.ext (file_get_contents) not found - symfony

I am virtually at a brick wall with Symfony, I have a folder at /../compiled/ with some minified files, and the controller is configured to get files from getRootDir() + /../compiled/file.min.css
However, it just throws out an exception 'file not found' when call file_get_contents(file) even when the file actually exists.
I just don't know what is wrong, it is such a cryptic problem.
Code as requested:
public function atpInitAction(Request $request) // Validates the origin.
{
$content = null; $_file = $request->query->get('file');
if ($_SERVER["SERVER_NAME"] == atpHandler::getDomain())
{
// I AM FROM THE ORIGIN...
$webfolder = $this->get('kernel')->getRootDir() . '/../compiled';
$_file = $webfolder."/".$_file;
}
// What's my mime?
$_mime = 'text/plain';
if ($_file[strlen($_file)-2] == 'j') { $_mime = 'text/javascript'; }
else { $_mime = 'text/css'; }
$response = new Response();
$response->headers->set('Content-Type', $_mime);
$response->headers->set('Content-Disposition', 'filename="'.basename($_file) . '";');
$response->headers->set('Content-Length', filesize($_file));
$response->setContent(file_get_contents($_file));
$response->sendHeaders();
return $response;
}

Related

Ajax and hook_form_alter

I'm getting a "The value you selected is not a valid choice." error for an Ajax modified field when I submit a custom altered node/add form. An "Illegal choice error is also written to the log. This a Drupal 9 version of an app that I developed using Drupal 7 which worked. The Ajax functionality is working. Why? How do I fix it?
I believe the error is coming from some Symfony code. I'm dynamically modifying two "select" form elements. The first doesn't appear to have the problem. I'm doing the same thing for both form elements.
function bncreports_form_node_bnc_message_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
$form['actions']['submit']['#submit'][] = 'bncreports_node_bnc_message_form_submit';
$form['#title'] = t('Create Contact Us');
$user = User::load(\Drupal::currentUser()->id());
$district_id = $user->get('field_district')->value;
$form['field_first_name']['widget'][0]['value']['#default_value'] = $user->get('field_first_name')->value;
$form['field_last_name']['widget'][0]['value']['#default_value'] = $user->get('field_last_name')->value;
$form['field_email']['widget'][0]['value']['#default_value'] = $user->getEmail();
$form['field_email']['widget'][0]['value']['#attributes'] = ['onblur' => 'this.value=this.value.toLowerCase();'];
$form['field_phone']['widget'][0]['value']['#default_value'] = $user->get('field_phone')->value;
$form['field_district']['widget'][0]['value']['#default_value'] = $district_id;
if (isset($form['field_district']['widget']['#default_value']))
$form['field_district']['widget']['#default_value'] = $district_id; // wtf?
if ($user->hasRole('administrator') || $user->hasRole('bnc_operator') || $user->hasRole('ao_user')) {
$form['field_office']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_district']['widget']['#ajax'] = [
'event' => 'change',
'callback' => 'bncreports_ajax_offices_and_user',
'wrapper' => ['ajax-wrapper-field-offices', 'ajax-wrapper-field-user'],
];
$form['field_offices']['#prefix'] = '<div id="ajax-wrapper-field-offices">';
$form['field_offices']['#suffix'] = '</div>';
$form['field_user']['#prefix'] = '<div id="ajax-wrapper-field-user">';
$form['field_user']['#suffix'] = '</div>';
$district_id = $form_state->hasValue('field_district')
? $form_state->getValue('field_district')[0]['value']
: false;
$form['field_offices']['widget']['#options'] = $district_id
? Functions::officeNames($district_id)
: [];
$form['field_user']['widget']['#options'] = $district_id
? ['_none' => '- Select a value -'] + Functions::districtUserLastandFirstNames($district_id)
: ['_none' => '- Select a value -'];
} else { // Alterations for court users only
$form['bnc_prefix']['#markup'] =
'<p>BNC User Support: ' . Constants::BNC_PHONE_NO
. ' ' . Constants::BNC_EMAIL . '</p>'
. '<p>AO Program and CM/ECF Contacts</p>'
. '<h4>Unable to find what you need? Send us a message.</h4>';
$form['bnc_prefix']['#weight'] = -1;
$form['field_offices']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_user']['#access'] = false;
$form['field_non_user_name']['#access'] = false;
$form['field_non_user_phone']['#access'] = false;
$form['field_assigned_to']['#access'] = false;
$form['revision_information']['#access'] = false;
$office = $user->get('field_office')->value;
$form['field_district']['widget']['#default_value'] = $district_id;
$form['field_office']['widget']['#options'] = Functions::officeNames($district_id);
$form['field_office']['widget']['#default_value'] = $office;
$form['field_office_name']['widget'][0]['value']['#default_value'] = Functions::officeName($district_id, $office);
$form['#attached']['library'][] = 'bncreports/restricted_contact_log';
}
}
function bncreports_ajax_offices_and_user(array $form, FormStateInterface $form_state): AjaxResponse
{
$response = new AjaxResponse();
// Issue a command that replaces the elements 'field_offices' and 'field_user'
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-office', $form['field_offices']));
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-user', $form['field_user']));
return $response;
}
Problem is there are no allowed values for the field_user list. Solution is to use an allowed values function callback. This is done in Configuration synchronization for Field Storage. Set the allowed value function property and import. Need to provide uuid to override existing config.
In my hook_form_alter:
$_SESSION['selected_district_id'] = $district_id;
In my xxx.module:
function bncreports_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable): array
{
// NOTE: This is defined in Configuation synchronization for Field Storage (see node.field_user)
if ($entity->bundle() == 'bnc_message') { // Add a custom field_user options for BNC Message nodes.
$district_id = $_SESSION['selected_district_id'] ?? null;
return Functions::districtUserLastandFirstNames($district_id);
}
throw new Exception("Allowed values function for {$entity->bundle()} is not allowed.");
}

404 cehck status for current page

i want to check current page's 404 status in a plugin file
i tried this but page only spinning and never finish loading
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
$ch = curl_init($my_url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($retcode != 200) {
$result=true;
return $result;
}
else {
// echo "Specified URL exists";
}
curl_close($ch);
}
i have also tried this but it gives error
is_404 was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.)
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
if(is_404())
{
$result=true;
return $result;
}
}
I am new to wordpress, can someone please help me to solve this??
is_404() conditional is set in the WP_Query class and checks is the query returns a 404 (returns no results)
So, you can try to modify your function like that
public static function check_404_status()
{
global $wp_query;
if (isset($wp_query)) {
return $wp_query->is_404();
}
return false;
}

How to test service function without connecting on database

I'm turning again on you guys, because I spend my fair share of hours on this "task" and I still can't figure out how to test my service method, without my function connection on database (I have to mock repository functions)
This is my service function
public function getInfo($history, $name)
{
$requestRepository = $this->em->getRepository(Request::class);
if ($history) {
$requests = [];
foreach ($requestRepository->getRequestsByName($name) as $request) {
$requests[] = $requestRepository->transform($request);
}
return $requests;
} else {
$request = $requestRepository->getCompletedRequestByName($name);
if (!is_null($request)) {
return $requestRepository->transform($request);
} else {
return null;
}
}
}
And this is my test
public function testGetInfo()
{
/* This returns errors, because it tries to connect to DATABASE, but I don't wan't that, that's why I figure out I need to mock this
$requestManager = new RequestManager($this->entityManager);
$test = $requestManager->getInfo('histroy', 'antrax.com');
*/
$requestManager = $this->getMockBuilder(RequestManager::class)->disableOriginalConstructor()->setMethods(['getInfo'])
->getMock();
// And rest of this are just my FAILED attempts to figure out, how to test my methods
$queryBuilder = $this->getMockBuilder(RequestRepository::class)->disableOriginalConstructor()
->setMethods(['getInfo'])->getMock();
$test = $queryBuilder->method('getInfo')->willReturnSelf();
$queryBuilder->method('getInfo')->willReturnCallback(function ($field, $value) use ($queryBuilder, $test){
if ($field == 'newStatus') {
$this->assertSame('EXPIRED', $value);
}
return $queryBuilder;
});
}
Can some one please help me how to write a test for my method getInfo so it will have 100% cover. If you need any additional informations, please let me know and I will provide. Thank you!
This is an answer to my problem
public function testGetInfo()
{
$mockEntity = $this->mockEntityManager;
$name = 'antrax.com';
$requestMock = new RequestEntity();
$transformedRequest = [
'id' => 1
];
$requestRepo = $this->getMockBuilder(RequestRepository::class)->disableOriginalConstructor()
->setMethods(['getRequestsByName', 'transform', 'getCompletedRequestByName'])->getMock();
$requestRepo->method('getRequestsByName')->willReturnCallback(function ($passedName) use ($name, $requestMock) {
$this->assertSame($name, $passedName);
return [$requestMock, $requestMock];
});
$requestRepo->method('transform')->willReturnCallback(function ($request) use ($requestMock, $transformedRequest) {
$this->assertSame($requestMock, $request);
return $transformedRequest;
});
$i = 0;
$requestRepo->method('getCompletedRequestByName')->willReturnCallback(function ($passedName) use ($name, $requestMock, &$i) {
$this->assertSame($name, $passedName);
if ($i == 0) {
$i+=1;
return null;
} else {
return $requestMock;
}
});
$mockEntity->method('getRepository')->willReturnCallback(function ($requestClass) use ($requestRepo) {
$this->assertSame(RequestEntity::class, $requestClass);
return $requestRepo;
});
$requestManager = new RequestManager($mockEntity);
$this->assertSame([$transformedRequest, $transformedRequest], $requestManager->getInfo(true, $name));
$this->assertNull($requestManager->getInfo(false, $name));
$this->assertSame($transformedRequest, $requestManager->getInfo(false, $name));
}

phpexcel error when use include_once, require_once?

I use phpexcel in my project, if i call my class by my function, excel file cannot open
I call my class:
$Model = loadModel('cpm','cpm',$this->registry);
My function:
function loadModel($com='',$class_name='',$registry=null) {
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}
return $model;
}
When i change to
/*require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}*/
$model=true;
return $model;
it work. In my project, I use autoload:
function __autoload($class_name) {
/*** get the component from the url ***/
$com = (empty($_GET['com'])) ? '' : $_GET['com'];
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
requine_once ($file);
}
I am not sure it is reason.
I don't found any error in log.
Any help, thank.
I found that if I require(once) or include(once) file in controler, excel file will be can not open.
class excelController extends baseController {
public function index(){
require('abc.class.php');
$this->registry->template->show('excel', false);
}
}
It's probable that your autoloader is clashing with PHPExcel's autoloader. See section 3.2 of the developer documentation (entitled "Lazy Loader") for advice on registering your own autoloader with spl_autoload_register() so that the two can co-exist

Opencart session info in Wordpress

I have a site that is using both WordPress and Opencart. The main site is built off of WP and then there is an OC site in a sub-directory.
I would like to bring the session data from OC into the wordpress site so I can have the Wishlist, Shopping Cart, Checkout, Login status and My Account info throughout the site.
Does anyone know what code I can add to WP to bring in this info?
Thanks again in advance,
Matt
There are already many articles regarding module development and export and session building in OpenCart.
Given your existing pages:
yoursite.com/wordpress
yoursite.com/wordpress/page.php (i.e. your page outside the shop),
yoursite.com/products/catalog/controller/common/header.php -and-
yoursite/products/catalog/view/theme/default/template/common/header.tpl
1. Create file headerXYZ.php using the following code and save it to the root directory of your main site (or other location of your choosing outside your OC shop).
<?php
// Config
require_once('shop/config.php');
// VirtualQMOD
require_once('shop/vqmod/vqmod.php');
$vqmod = new VQMod();
// VQMODDED Startup
require_once($vqmod->modCheck(DIR_SYSTEM . 'startup.php'));
// Application Classes
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/customer.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/affiliate.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/currency.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/tax.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/weight.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/length.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/cart.php'));
$myVar = array();
$myVar = array();
// Registry
$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') :
$config->get('config_url'));
$registry->set('url', $url);
// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);
function error_handler($errno, $errstr, $errfile, $errline) {
global $log, $config;
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$error = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
break;
default:
$error = 'Unknown';
break;
}
if ($config->get('config_error_display')) {
echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
}
if ($config->get('config_error_log')) {
$log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
}
return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new Request();
$registry->set('request', $request);
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Cache
$cache = new Cache();
$registry->set('cache', $cache);
// Session
$session = new Session();
$registry->set('session', $session);
// Language Detection
$languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) {
$languages[$result['code']] = $result;
}
$detect = '';
if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
foreach ($browser_languages as $browser_language) {
foreach ($languages as $key => $value) {
if ($value['status']) {
$locale = explode(',', $value['locale']);
if (in_array($browser_language, $locale)) {
$detect = $key;
}
}
}
}
}
if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) &&
$languages[$request->get['language']]['status']) {
$code = $request->get['language'];
} elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages)) {
$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages)) {
$code = $request->cookie['language'];
} elseif ($detect) {
$code = $detect;
} else {
$code = $config->get('config_language');
}
if (!isset($session->data['language']) || $session->data['language'] != $code) {
$session->data['language'] = $code;
}
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
$config->set('config_language_id', $languages[$code]['language_id']);
$config->set('config_language', $languages[$code]['code']);
// Language
$language = new Language($languages[$code]['directory']);
$language->load($languages[$code]['filename']);
$registry->set('language', $language);
// Document
$document = new Document();
$registry->set('document', $document);
// Customer
$registry->set('customer', new Customer($registry));
// Affiliate
$affiliate = new Affiliate($registry);
$registry->set('affiliate', $affiliate);
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Tax
$tax = new Tax($registry);
$registry->set('tax', $tax);
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// Cart
$registry->set('cart', new Cart($registry));
// Front Controller
$controller = new Front($registry);
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
// Router
if (isset($request->get['route'])) {
$action = new Action($request->get['route']);
} else {
$action = new Action('common/home');
}
// Dispatch
$controller->dispatch($action, new Action('error/not_found'));
2. Now, include headerXYZ.php in page.php i.e. Place the statement below on line 1 at the very top of page.php
<?php require_once ('headerXYZ.php');?>
3. Finally, right after the opening body tag of your external page.php page add the following list of statements
<?php
require_once('shop/catalog/model/total/sub_total.php');
require_once('shop/catalog/language/english/total/sub_total.php');
require_once('shop/catalog/model/total/reward.php');
require_once('shop/catalog/model/total/shipping.php');
require_once('shop/catalog/model/total/coupon.php');
require_once('shop/catalog/model/total/tax.php');
require_once('shop/catalog/model/total/credit.php');
require_once('shop/catalog/language/english/total/credit.php');
require_once('shop/catalog/model/total/voucher.php');
require_once('shop/catalog/model/total/total.php');
require_once('shop/catalog/language/english/total/total.php');
foreach($myVar as $key=>$value)
{
$$key = $value;
}
require_once('shop/catalog/controller/common/header.php');
require_once('shop/catalog/view/theme/default/template/common/header.tpl');
?>
That's it... You're done! You should now have a fully functional header (with working cart, login, etc.) in your page located outside of your Opencart shop.
SIDE NOTE: You could also just plug the entire code (including the content of headerXYZ.php and the 13 require_once statements) directly into the your external page.
I was looking for something similar, what I did was to write same html/css for footer and header in both systems, after that, I wrote an additional Wordpress plugin to show user and cart info when user is logged in opencart.
https://github.com/saRca/op2wp

Resources