I've installed ZendSearch with composer using these commands:
$ cd /var/www/CommunicationApp/vendor/
$ git clone https://github.com/zendframework/ZendSearch.git
ZendSearch
$ cd ZendSearch/
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar install
And I've installed Zendskeleton according to GITHUB
So, I don't know What I'm missing here.
Than, in the same book, it teaches how to use ZendSearch, but I'm not getting the same results, instead I'm getting a Fatal error: Fatal error: Class 'ZendSearch\Lucene\Lucene' not found in /var/www/CommunicationApp/module/Users/src/Users/Controller/SearchController.php on line 107
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Headers;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
use Users\Model\User;
use Users\Model\UserTable;
use Users\Model\Upload;
use Users\Model\ImageUpload;
use Users\Model\ImageUploadTable;
use ZendSearch\Lucene;
use ZendSearch\Lucene\Document;
use ZendSearch\Lucene\Index;
class SearchController extends AbstractActionController
{
protected $storage;
protected $authservice;
public function getAuthService()
{
if (! $this->authservice) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
public function getIndexLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['search_index'])) {
return $config['module_config']['search_index'];
} else {
return FALSE;
}
}
public function getFileUploadLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['upload_location'])) {
return $config['module_config']['upload_location'];
} else {
return FALSE;
}
}
public function indexAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$queryText = $request->getPost()->get('query');
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::open($searchIndexLocation);
$searchResults = $index->find($queryText);
}
// prepare search form
$form = new \Zend\Form\Form();
$form->add(array(
'name' => 'query',
'attributes' => array(
'type' => 'text',
'id' => 'queryText',
'required' => 'required'
),
'options' => array(
'label' => 'Search String',
),
));
$form->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Search',
'style' => "margin-bottom: 8px; height: 27px;"
),
));
$viewModel = new ViewModel(array('form' => $form, 'searchResults' => $searchResults));
return $viewModel;
}
public function generateIndexAction()
{
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::create($searchIndexLocation);
$userTable = $this->getServiceLocator()->get('UserTable');
$uploadTable = $this->getServiceLocator()->get('UploadTable');
$allUploads = $uploadTable->fetchAll();
foreach($allUploads as $fileUpload) {
//
$uploadOwner = $userTable->getUser($fileUpload->user_id);
// id field
$fileUploadId= Document\Field::unIndexed('upload_id', $fileUpload->id);
// label field
$label = Document\Field::Text('label', $fileUpload->label);
// owner field
$owner = Document\Field::Text('owner', $uploadOwner->name);
if (substr_compare($fileUpload->filename, ".xlsx", strlen($fileUpload->filename)-strlen(".xlsx"), strlen(".xlsx")) === 0) {
// index excel sheet
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Xlsx::loadXlsxFile($uploadPath ."/" . $fileUpload->filename);
} else if (substr_compare($fileUpload->filename, ".docx", strlen($fileUpload->filename)-strlen(".docx"), strlen(".docx")) === 0) {
// index word doc
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Docx::loadDocxFile($uploadPath ."/" . $fileUpload->filename);
} else {
$indexDoc = new Lucene\Document();
}
$indexDoc->addField($label);
$indexDoc->addField($owner);
$indexDoc->addField($fileUploadId);
$index->addDocument($indexDoc);
}
$index->commit();
}
}
The book is giving you weird instructions because it says Zend Search cannot be installed via. Composer, but this is no longer the case not quite true. To fix:
Delete your vendor folder
Edit your composer.json and add zendframework/zendsearch to the require section
Run php composer.phar install to install all packages (including Zend Search)
Then everything should be working.
Edit: okay, for some reason this package isn't listed on packagist. You'll also need to add the repo URL to your composer.json:
"repositories": [
{
"type": "vcs",
"url": "https://github.com/zendframework/ZendSearch"
}
],
then give it another try.
You should put zendsearch in zendframework in vendor folder and after installing it as the book said, you should insert this line at the end of vendor/composer/autoload_namespaces.php:
'ZendSearch' => array($vendorDir . '/zendframework/zendsearch/library')
Related
I'm migrating from zend framework 1 to 3 , and I have a function that returns twig template but I don't know what should I use to render view twig template on zf3
How to:
use class of viewer
set my template path
set array to render it in template
return template
code:
protected function convertItemList($aItemList)
{
$aSet = [];
//$config['template_paths'] = [APPLICATION_PATH . '/../library/Core/Backend/SRO/Views/'];
//$oView = new Core_Twig_View($config);
if (!$aItemList) {
return [];
}
foreach ($aItemList as $iKey => $aCurItem) {
$aSpecialInfo = [];
$aInfo = $aCurItem;
$aInfo['info'] = $this->getItemInfo($aCurItem);
$aInfo['blues'] = $this->getBluesStats($aCurItem, $aSpecialInfo);
$aInfo['whitestats'] = $this->getWhiteStats($aCurItem, $aSpecialInfo);
//$oView->assign('aItem', $aInfo);
$i = isset($aCurItem['Slot']) ? $aCurItem['Slot'] : $aCurItem['ID64'];
if ($aCurItem['MaxStack'] > 1) {
$aSet[$i]['amount'] = $aCurItem['Data'];
}
$aSet[$i]['TypeID2'] = $aInfo['TypeID2'];
$aSet[$i]['OptLevel'] = $aInfo['OptLevel'];
$aSet[$i]['RefItemID'] = !isset($aCurItem['RefItemID']) ? 0 : $aCurItem['RefItemID'];
$aSet[$i]['special'] = isset($aInfo['info']['sox']) && $aInfo['info']['sox'] ? true : false;
$aSet[$i]['ItemID'] = $aCurItem['ID64'];
$aSet[$i]['ItemName'] = $aInfo['info']['WebName'];
$aSet[$i]['imgpath'] = $this->getItemIcon($aCurItem['AssocFileIcon128']);
//$aSet[$i]['data'] = $oView->render('itemData.twig');
}
return $aSet;
}
I use this module https://github.com/OxCom/zf3-twig.
You can install it by github instructions and add this parameter to zf3 configuration array:
'service_manager' => array(
'factories' => array(
...
'TwigStrategy' => \ZendTwig\Service\TwigStrategyFactory::class,
...
),
)
1) After this you can use Twig in some action of some controller by this code:
function someAction(){
...
$viewModel = new ZendTwig\View\TwigModel(['foo'=>'bar']);
return $viewModel;
}
2) To set other template:
function someAction(){
$viewModel = new ZendTwig\View\TwigModel(['foo'=>'bar']);
$viewModel->setTemplate('application/controller/name'); //set path here
return $viewModel;
}
3) You can to set array variables by TwigModel "__construct" parameter:
function someAction(){
$viewModel = new ZendTwig\View\TwigModel($someVariablesArray);
$viewModel->setTemplate('application/controller/name'); //set path here
return $viewModel;
}
4) If you need to return html code, you need to do something:
Add in services config one more param:
'service_manager' => array(
'factories' => array(
...
'TwigStrategy' => \ZendTwig\Service\TwigStrategyFactory::class,
'TwigRenderer' => \ZendTwig\Service\TwigRendererFactory::class,
...
),
)
Add TwigRenderer service in your controller factory:
class YourControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new YourController($twigRenderer);
}
}
and get twigRenderer in your Controller:
private $twigRenderer;
public function __construct($twigRenderer)
{
$this->twigRenderer = $twigRenderer;
}
After this get html:
function someAction(){
$viewModel = new ZendTwig\View\TwigModel(['foo'=>'bar']);
$viewModel->setTemplate('mails/order/order_in_process');
$html = $this->twigRenderer->render($viewModel);
return $html;
}
Sorry for my english!
I am facing a strange error. I got a fairly simple piece of code yet it is constantly giving me error that class not found.
The error i am getting is
Fatal error: Class 'pipedriveintegrationConfig' not found in /home/preston/public_html/fullslate-pipedrive/index.php on line 4
Here is index.php
require_once 'config.php';
require_once pipedriveintegrationConfig::PHP_LIB;
require_once 'fullslate.php';
require_once 'pipedrive.php';
require_once 'fullslate-pipedrive.php';
pipedriveintegrationConfig::init();
if ($_SERVER['argc'] > 1) {
$action = $_SERVER['argv'][1];
} else
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
if ($action) {
switch($action) {
case 'sync-clients':
$client = new pipedriveintegrationFullslatePipedrive(pipedriveintegrationFullslateConfig::toArray(), pipedriveintegrationPipedriveConfig::toArray());
$client->syncClients();
break;
default:
throw new CustomException('Unknown command line action: ', $action);
break;
}
} else {
if (file_exists(__DIR__ . '/test.php')) {
require_once __DIR__ . '/test.php';
}
}
Code for config.php is
namespace pipedriveintegration;
class PipedriveConfig{
const URL = 'https://api.pipedrive.com/v1';
const API_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXX';
const STAGE_ID_NEW_PROSPECT = 1;
const STAGE_ID_CONSULTATION_SCHEDULED = 3;
public static
function toArray() {
return array('url' => self::URL, 'api_token' => self::API_TOKEN, 'stage_id_new_prospect' => self::STAGE_ID_NEW_PROSPECT, 'stage_id_consultation_scheduled' => self::STAGE_ID_CONSULTATION_SCHEDULED,);
}
}
class FullslateConfig{
const URL = 'https://slcguitar.fullslate.com/api';
const API_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXx';
public static
function toArray() {
return array('url' => self::URL, 'api_token' => self::API_TOKEN,);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class Config{
const PHP_LIB = 'PHPLib.php';
const USE_TIMESTAMP = false;
//'2014-12-15';
public static
function init() {
APP::init(array('mode' => 'development','log' => array('level' => Log::LEVEL_ALL, 'append' => true, 'limit' => 10,), 'curl' => array('log' => false, 'retry' => 3,),'temp' => array('path' => __DIR__, 'active' => true,),));
}
}
class PDEBUG{
const USE_FIDDLER = false;
}
Not sure wrong I am doing?
You need to change the require to:
require_once \pipedriveintegration\Config::PHP_LIB;
Your namespace is pipedriveintegration not pipedriveintegrationConfig. Also the constant is inside the class Config.
I don't know which PHP version are you using but I tested this in 5.6 and it works.
Please remove API tokens, and regenerate them in the application, by publishing API token you are giving access to your account to everyone.
I was following this book to install the ZendSearh on the application, I did exactly as it's written and I'm getting a Fatal error: Class 'ZendSearch\Lucene\Lucene' not found in /var/www/CommunicationApp/module/Users/src/Users/Controller/SearchController.php on line 107
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Headers;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
use Users\Model\User;
use Users\Model\UserTable;
use Users\Model\Upload;
use Users\Model\ImageUpload;
use Users\Model\ImageUploadTable;
use ZendSearch\Lucene;
use ZendSearch\Lucene\Document;
use ZendSearch\Lucene\Index;
class SearchController extends AbstractActionController
{
protected $storage;
protected $authservice;
public function getAuthService()
{
if (! $this->authservice) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
public function getIndexLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['search_index'])) {
return $config['module_config']['search_index'];
} else {
return FALSE;
}
}
public function getFileUploadLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['upload_location'])) {
return $config['module_config']['upload_location'];
} else {
return FALSE;
}
}
public function indexAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$queryText = $request->getPost()->get('query');
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::open($searchIndexLocation);
$searchResults = $index->find($queryText);
}
// prepare search form
$form = new \Zend\Form\Form();
$form->add(array(
'name' => 'query',
'attributes' => array(
'type' => 'text',
'id' => 'queryText',
'required' => 'required'
),
'options' => array(
'label' => 'Search String',
),
));
$form->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Search',
'style' => "margin-bottom: 8px; height: 27px;"
),
));
$viewModel = new ViewModel(array('form' => $form, 'searchResults' => $searchResults));
return $viewModel;
}
public function generateIndexAction()
{
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::create($searchIndexLocation); // line 107
$userTable = $this->getServiceLocator()->get('UserTable');
$uploadTable = $this->getServiceLocator()->get('UploadTable');
$allUploads = $uploadTable->fetchAll();
foreach($allUploads as $fileUpload) {
//
$uploadOwner = $userTable->getUser($fileUpload->user_id);
// id field
$fileUploadId= Document\Field::unIndexed('upload_id', $fileUpload->id);
// label field
$label = Document\Field::Text('label', $fileUpload->label);
// owner field
$owner = Document\Field::Text('owner', $uploadOwner->name);
if (substr_compare($fileUpload->filename, ".xlsx", strlen($fileUpload->filename)-strlen(".xlsx"), strlen(".xlsx")) === 0) {
// index excel sheet
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Xlsx::loadXlsxFile($uploadPath ."/" . $fileUpload->filename);
} else if (substr_compare($fileUpload->filename, ".docx", strlen($fileUpload->filename)-strlen(".docx"), strlen(".docx")) === 0) {
// index word doc
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Docx::loadDocxFile($uploadPath ."/" . $fileUpload->filename);
} else {
$indexDoc = new Lucene\Document();
}
$indexDoc->addField($label);
$indexDoc->addField($owner);
$indexDoc->addField($fileUploadId);
$index->addDocument($indexDoc);
}
$index->commit();
}
}
It has its own repository on github.
https://github.com/zendframework/ZendSearch
You have to load it via composer or just download and put it under vendor folder.
i'm trying Zend framework, i've got two folders in E:\Archivos de programa\Zend\ZendServer\share, une is ZendServer and the other one is ZendServer2
I can't recall if i ever install this two version but i dont think this is the problem
I'm using netbeans as ide ando i'm trying to make an ABM of users using BlockCipher
Here is my code
<?php
use Zend\Crypt\BlockCipher;
class Application_Model_DbTable_Usuarios extends Zend_Db_Table_Abstract
{
protected $_name = 'usuario';
public function getUsuario($usuario)
{
$usuario = (string)$usuario;
$row = $this->fetchRow('Usuario = ' . $usuario);
if (!$row) {
throw new Exception("Could not find row $usuario");
}
return $row->toArray();
}
public function addUsuario($usuario, $clave)
{
$blockCipher = Zend\Crypt\BlockCipher::factory('mcrypt',array('algo'=>'aes'));
$blockCipher->setKey('encryption key');
$result = $blockCipher->encrypt($clave);
echo "Encrypted text: $result \n";
exit;
$data = array(
'Usuario' => $usuario,
'Clave' => $blockCipher,
);
$this->insert($data);
}
public function updateUsuario($usuario, $clave)
{
$blockCipher = BlockCipher::factory($clave, array(
'algo' => 'blowfish',
'mode' => 'cfb',
'hash' => 'sha512'
));
$data = array(
'Clave' => $blockCipher,
);
$this->update($data, 'Usuario = ' . (string)$usuario);
}
public function deleteUsuario($usuario)
{
$this->delete('Usuario = ' . (string)$usuario);
}
}
and in my php.ini i've got
include_path=".;E:\Archivos de programa\Zend\ZendServer\share\ZendFramework2\library"
And i get this error
Fatal error: Class 'Zend\Crypt\BlockCipher' not found in E:\Documents and Settings\dvieira\Mis documentos\NetBeansProjects\justforgeeks\application\models\DbTable\Usuarios.php on line 21
I dont understand why.
Can you help me please?
Thanks in advance
You are using namespaces in your application, therefore you need to make sure that your autoloader can handle this. If it's a ZF1 app then not. Can you try using require to include the class file instead? You can ass well amend the autoloader to work with namespaces
Secondly when using namespaces, if you create an alias for a class
use Zend\Crypt\BlockCipher;
you then instantiate it
$blockCipher = BlockCipher::factory('mcrypt',array('algo'=>'aes'));
So far I have been unable to successfully implement ACLs (permissions) in SabreDAV.
I have implemented SabreDAV in Code Igniter with my own Auth, Principal and CalDAV backend. This the actual code from the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CalDAV extends CI_Controller {
public function _remap() {
$this->load->library('SabreDAV');
$authBackend = new SabreDAV_DAV_Auth_Backend_Tank_Auth;
$principalBackend = new Sabre_DAVACL_PrincipalBackend_Click4Time;
$calendarBackend = new Sabre_CalDAV_Backend_Click4Time;
// Directory tree
$tree = array(
new Sabre_DAVACL_PrincipalCollection($principalBackend),
new Sabre_CalDAV_CalendarRootNode($principalBackend, $calendarBackend)
);
// The object tree needs in turn to be passed to the server class
$server = new Sabre_DAV_Server($tree);
// You are highly encouraged to set your WebDAV server base url. Without it,
// SabreDAV will guess, but the guess is not always correct. Putting the
// server on the root of the domain will improve compatibility.
$server->setBaseUri('/caldav/');
// Authentication plugin
$authPlugin = new Sabre_DAV_Auth_Plugin($authBackend, 'SabreDAV');
$server->addPlugin($authPlugin);
// CalDAV plugin
$caldavPlugin = new Sabre_CalDAV_Plugin();
$server->addPlugin($caldavPlugin);
// ACL plugin
$aclPlugin = new Sabre_DAVACL_Custom;
$server->addPlugin($aclPlugin);
// Support for html frontend
$browser = new Sabre_DAV_Browser_Plugin();
$server->addPlugin($browser);
$server->exec();
}
}
My current attempt at implementing permissions has been through my custom ACL Plugin:
<?php
class Sabre_DAVACL_Custom extends Sabre_DAVACL_Plugin {
public $allowAccessToNodesWithoutACL = false;
private function _getCurrentUserName() {
$authPlugin = $this->server->getPlugin('auth');
if (is_null($authPlugin)) return null;
return $authPlugin->getCurrentUser();
}
public function getACL($node) {
$user = $this->_getCurrentUserName();
$path = $node->getName();
if ($path == 'calendars' || $path == 'principals' || $path == 'root') {
return array(
array(
'privilege' => '{DAV:}read',
'principal' => 'principals/' . $user,
'protected' => true,
)
);
}
else if ($path == 'calendars/' . $user) {
return array(
array(
'privilege' => '{DAV:}read',
'principal' => 'principals/' . $user,
'protected' => true,
)
);
}
return array();
}
}
This code pretty much works except the second check which should authorize the user to see his or her own calendar(s). I am unable to get the full path name for $node.
This may be the wrong way to implement but I have been unable to find any documentation to confirm that this is the way to implement ACLs.
i'm using a different attempt, i extended the plugin, just like you did but then i replaced getSupportedPrivilegeSet($node) instead.
in sabredav 1.8.6 it looks like this:
public function getSupportedPrivilegeSet($node) {
if (is_string($node)) {
$node = $this->server->tree->getNodeForPath($node);
}
if ($node instanceof IACL) {
$result = $node->getSupportedPrivilegeSet();
if ($result)
return $result;
}
return self::getDefaultSupportedPrivilegeSet();
}
now you can use the classes instead of the path which i found more usefull, i.e.:
class DavCalAcl extends \Sabre\DAVACL\Plugin {
public function getSupportedPrivilegeSet($node) {
if (is_string($node)) {
$node = $this->server->tree->getNodeForPath($node);
}
if($node instanceof \Sabre\CalDAV\Calendar || $node instanceof \Sabre\CalDAV\CalendarObject) {
return array(
array(
'privilege' => '{DAV:}read',
'aggregates' => array(
array(
'privilege' => '{DAV:}read-acl',
'abstract' => true,
),
array(
'privilege' => '{DAV:}read-current-user-privilege-set',
'abstract' => true,
),
),
)
);
}
if ($node instanceof \Sabre\DAVACL\IACL) {
$result = $node->getSupportedPrivilegeSet();
if ($result)
return $result;
}
return self::getDefaultSupportedPrivilegeSet();
}
}
this is my current attempt to get iCal to recognize a calendar as read-only... i'm not quite there yet but maybe this will help you in better identifying the objects
if you want the absolute path of a node i guess you could always go to the root search it for your current node and by doing so recording the path which took you there. as far as i checked the nodes in sabredav do not support a parent or a root property.
[UPDATE]
the best way seems to be to override getACL in the plugin. here you can test for the node's class and return what you really want on instead of the stuff which is returned by the default objects (for instance look at UserCalendars->getACL().
here's my working solution for read-only enforcement based on the object types:
class DavCalAcl extends \Sabre\DAVACL\Plugin {
/**
* Returns the full ACL list.
*
* Either a uri or a DAV\INode may be passed.
*
* null will be returned if the node doesn't support ACLs.
*
* #param string|DAV\INode $node
* #return array
*/
public function getACL($node) {
if (is_string($node)) {
$node = $this->server->tree->getNodeForPath($node);
}
if (!$node instanceof \Sabre\DAVACL\IACL) {
return null;
}
if( $node instanceof \Sabre\CalDAV\Calendar ||
$node instanceof \Sabre\CalDAV\CalendarObject ||
$node instanceof \Sabre\CalDAV\UserCalendars
) {
$acl = array(
array(
'privilege' => '{DAV:}read',
'principal' => $node->getOwner(),
'protected' => true,
),
);
} else {
$acl = $node->getACL();
}
foreach($this->adminPrincipals as $adminPrincipal) {
$acl[] = array(
'principal' => $adminPrincipal,
'privilege' => '{DAV:}all',
'protected' => true,
);
}
return $acl;
}
}