I am trying to create a buddypress through a custom plugin with the following code
if(isset($_POST['update-groups'])){
global $wpdb;
require_once("https://dev.technologyforthefuture.org/wp-load.php");
$csv_us_city_map = array_map('str_getcsv',file("https://dev.technologyforthefuture.org/wp-content/plugins/t4tf/Data_Files/uscountiesv1.0.0.csv"));
/*$groups = BP_Groups_Group::get(array(
'type'=>'alphabetical',
'per_page'=> -1
));*/
for($i =0; $i < count($csv_us_city_map); $i++){
$countyName = $csv_us_city_map[$i][0];
$stateName = $csv_us_city_map[$i][2];
$fullGroupName = $countyName . ", " . $stateName;
$groupSlug = strtolower($countyName) . "-" . strtolower($stateName);
$groupDescription = "<span style=\"font-family: Roboto, sans-serif;font-size: 13px;text-align: center\">Together we OPEN Doors to a brighter future for the students in $fullGroupName, $stateName.</span>";
//$groups = $wpdb->get_results("SELECT * FROM wp_bp_groups");
//$newGroup = $wpdb->insert("wp_bp_groups",array('creator_id' => 1, 'name' => $fullGroupName, 'slug' => $groupSlug, 'description' => $groupDescription, 'status' => 'public'));
$args = array(
'group_id' => 0,
'creator_id' => 1,
'name' => $fullGroupName,
'description' => $groupDescription,
'slug' => $groupSlug,
'status' => 'public',
'parent_id' => 0,
'enable_forum' => 0
);
$newGroup = groups_create_group($args);
}
}
I am getting this error when running this code
Fatal error: Uncaught Error: Call to undefined function groups_create_group()
I have tried as you can see to include the wp-load.php file and I have even required the file containing the function groups_create_group but it always shows this same error and I do not know why the function is undefined
SO How do I fix this error?
The path to the file that im working on is wp-content/plugins/t4tf/t4tf.php
Do not use http urls to include php files.
require_once("https://dev.technologyforthefuture.org/wp-load.php");
is plain wrong on so many levels.
Use relative or absolute file system path.
It is not clear where your code is used exactly, so I can't just give you a working code, but something like the following line should work:
require_once(__DIR__ . '/../wp-load.php');
Related
I'm trying to create an Admin Controller with a csv file uploader to process it like an array.
I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.
Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.
I need to create multiple object of different classes that I made, thanks to the csv file.
Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)
Waiting for your help guys !
Update :
Update :
Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?
Here is my code :
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_BULB_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_BULB_DATA'
),
),
'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
),
);
if(isset($_FILES['DB_BULB_DATA'])){
$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
print_r($headers);
}
}
There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.
Just find out how to do it, I feel dummy 😅
I just needed to save my tmp file as a csv to be able to use it then.
Here is the full code :
<?php
class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_<YourThings>_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_<YourThings>_DATA'
),
),
'submit' => array('title' => $this->l('Save')),
),
);
}
public function initContent()
{
parent::initContent();
unset($_FILES);
}
public function postProcess()
{
$fileName = '<YourThings>Db.csv';
if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
if (isset($_FILES['DB_<YourThings>_DATA'])) {
$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
} else {
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
unset($_FILES['DB_<YourThings>_DATA']);
}
}
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require "vendor/autoload.php";
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\PurchaseOrder;
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth1',
'consumerKey' => " ",
'consumerSecret' => " ",
'accessTokenKey' => " ",
'accessTokenSecret' => " ",
'QBORealmID' => "",
'baseUrl' => "https://quickbooks.api.intuit.com/"
));
for($i = 1; $i<= 3; $i ++){
$LineObj = Line::create([
"Id" => $i,
"LineNum" => $i,
"Description" => "Pest Control Services",
"Amount" => 35.0,
"DetailType" => "SalesItemLineDetail",
"SalesItemLineDetail" => [
"ItemRef" => [
"value" => "1",
"name" => "Pest Control"
],
"UnitPrice" => 35,
"Qty" => 1,
"TaxCodeRef" => [
"value" => "NON"
]
]
]);
$lineArray[] = $LineObj;
}
//Add a new Invoice
$theResourceObj = PurchaseOrder::create([
"Line" => $lineArray,
"CustomerRef"=> [
"value"=> "1"
],
"BillEmail" => [
"Address" => "Familiystore#intuit.com"
],
"BillEmailCc" => [
"Address" => "a#intuit.com"
],
"BillEmailBcc" => [
"Address" => "v#intuit.com"
]
]);
?>
Fatal error: Uncaught Error: Class 'Line' not found in /var/www/html/QuickBooks-V3-PHP-SDK-master/Test2.php:24
purchaseOrder.php:
<?php
//require "vendor/autoload.php";
include('src/config.php');
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\PurchaseOrder;
// OBOT Data service
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth1',
'consumerKey' => " ",
'consumerSecret' => " ",
'accessTokenKey' => " ",
'accessTokenSecret' => " ",
'QBORealmID' => " ",
'baseUrl' => "https://quickbooks.api.intuit.com/"
));
$linedet = new IPPPurchaseOrderItemLineDetail();
$linedet->CustomerRef = 86;
$line = new IPPLine();
$line->Id = 0;
$line->Description = 'test purchase order';
$line->Amount = 2.00;
$line->DetailType= 'ItemBasedExpenseLineDetail ';
$line->ItemBasedExpenseLineDetail = $linedet;
$line->BillableStatus = 'Notbillable';
$line->ItemRef = '19';
$line->UnitPrice = '25';
$line->Qty = '1';
$purchaseOrder = new IPPPurchaseOrder();
$purchaseOrder->Line = $line;
$purchaseOrder->VendorRef = 85;
$purchaseOrder->APAccountRef = 1;
$purchaseOrder->TotalAmt = 200.00;
$result = $dataService->Add($purchaseOrder); //add purchase order
?>
PHP Fatal error: Uncaught Error: Class 'IPPPurchaseOrderItemLineDetail' not found in /var/www/html/QuickBooks-V3-PHP-SDK-master/purchaseOrder.php:20
Why am I getting these errors? is the autoload not working? should I just directly include the class files that I need?
In regards your first error below:
Fatal error: Uncaught Error: Class 'Line' not found in /var/www/html/QuickBooks-V3-PHP-SDK-master/Test2.php:24
I don't see you including the Line class anywhere, from the GitHub page here I have truncated their advice:
Connecting to the QuickBooks Online API
Currently the below API entity Endpoints support creating Objects from Array:
Estimate
Line
Invoice
Item
For create/update above entity endpoints, you are going to import corresponding facade class:
use QuickBooksOnline\API\Facades\{Facade_Class_Name};
As such you need to update your first script to include this Facade, which should be as simple as:
<?php
require "vendor/autoload.php";
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\PurchaseOrder;
use QuickBooksOnline\API\Facades\Line; // <-- You are missing this line
In regards the second error below:
PHP Fatal error: Uncaught Error: Class 'IPPPurchaseOrderItemLineDetail' not found in /var/www/html/QuickBooks-V3-PHP-SDK-master/purchaseOrder.php:20
From searching the GitHub codebase again I can see this class is declared here. Therefore it should be as simple as declaring this again in your use statements at the top of the file that is using this, such as below:
<?php
//require "vendor/autoload.php";
include('src/config.php');
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\PurchaseOrder;
use QuickBooksOnline\API\Data\IPPPurchaseOrderItemLineDetail; // <-- You are missing this line
Looking at the rest of your code there seems to be a lot of classes that you are not declaring through use statements such as PurchaseOrder, IPPLine and IPPPurchaseOrder which you will also need to include.
I am receiving an error that indicates that:
array_merge(): Argument #2 is not an array
I'm trying to resolve it but I'm not sure what else to try. Here is the code that I an executing:
$config = array();
$config['base_url'] = Application::getInstance()->request->getRootUri();
$config['public_url'] = $config['base_url'] . '/public';
$config['bower_components_url'] = $config['public_url'] . '/bower_components';
$app_config = array();
$app_config = require_once 'app/config/application.php';
$full_config = array_merge($config, $app_config, $data);
Argument app config requires this file:
return array (
'debug' => true,
'app_name' => 'Name',
'app_author' => 'Author',
'app_url' => '',
'session_prefix' => '',
'session_secret' => '',
);
Can someone help me to understand why I am receiving this error?
You need to put php opening tag at the beginning of this config file:
<?php
return array (
'debug' => true,
'app_name' => 'Name',
'app_author' => 'Author',
'app_url' => '',
'session_prefix' => '',
'session_secret' => '',
);
Enable error reporting and check if your path is correct.
The problem is you are defining $app_config as array then redefining it as a variable. Try this
$app_config = array();
$app_config[] = require_once 'app/config/application.php';
Doing this: $app_config = require_once 'app/config/application.php'; will return an object (not an array for sure). I think.
I think this method is more customizable.
app/config/functions.php
//this will be inside functions.php
function appConfig() {
return array (
'debug' => true,
'app_name' => 'Name',
'app_author' => 'Author',
'app_url' => '',
'session_prefix' => '',
'session_secret' => '',
);
}
Your main php file
require_once 'app/config/functions.php';
// your other code
$app_config = appConfig();
$full_config = array_merge($config, $app_config, $data);
I have created a class using migrate module but I am unable to migrate entities. my class codes are below please check it and tell me whats the problem with it??
<?php
class ItemOrderXMLMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('OrderFeed'));
$this->description = t('Migrate entity from XML file');
//$this->softDependencies = array('WineFileCopy');
$fields = array(
'Number' => t('Number'),
'Date' => t('Date'),
'SubTotal' => t('Sub Total'),
'Discount' => t('Discount'),
'ShippingCharges' => t('Shipping Charges'),
'ShippingChargesDiscount' => t('Shipping Charges Discount'),
'NumItems' => t('NumItems'),
'VATPercentage' => t('VAT Percentage'),
'CurrencyCode' => t('Currency Code'),
'PaymentTypeDesc' => t('Payment Type Desc'),
'OrderState' => t('Order State'),
);
$this->map = new MigrateSQLMap($this->machineName,
array(
'Number' => array(
'type' => 'varchar',
'length' => 225,
'not null' => TRUE,
)
),
MigrateDestinationEntityAPI::getKeySchema('entity_example_basic','first_example_bundle')
);
$xml_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'products_import') . '/xml/';
$items_url = $xml_folder . 'OrderFeed.xml';
$item_xpath = '/Orders/Item'; // relative to document
$item_ID_xpath = 'Number'; // relative to item_xpath and gets assembled
// into full path /producers/producer/sourceid
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_ID_xpath);
$this->source = new MigrateSourceMultiItems($items_class, $fields);
$this->destination = new MigrateDestinationEntityAPI('entity_example_basic','first_example_bundle');
$this->addFieldMapping('field_number', 'Number')
->xpath('Number');
$this->addFieldMapping('field_subtotal', 'SubTotal')
->xpath('SubTotal');
$this->addFieldMapping('field_discount', 'Discount')
->xpath('Discount');
//$this->addUnmigratedDestinations(array('weight'));
}
}
?>
When I import it I got the save error message for all entities: Creating default object from empty value File /var/www/mig/migration/sites/all/modules/migrate_extras/entity_api.inc, line 227
Try the latest or updated migrate module https://www.drupal.org/project/migrate. I think you were using old one which were having some issues to migrate entities.
Why don't you try with a feed importer (Feeds module) using XPath parser module?. It's really easy, and you can use both an uploaded file or a source URL.
I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.
I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.
I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}