PHP code example of 3xw / attachment

1. Go to this page and download the library: Download 3xw/attachment library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

3xw / attachment example snippets


$this->addPlugin(\ Attachment\Plugin::class, ['bootstrap' => true, 'routes' => true]);

Configure::write('Attachment.config', ['attachment']);
$this->addPlugin(\ Attachment\Plugin::class, ['bootstrap' => true, 'routes' => true]);

<head>
	...
	<!-- CSS -->
	<?= $this->Html->css([
	    'bootstrap.min.css',
	    'app.css'
  	]) 

return [
  'Attachment' => [

    // set profiles
    'profiles' => [
      's3' => [
		'replace' => false,
		'afterReplace' => null // null | callback fct($entity),
		'delete' => true,
		'adapter' => 'League\Flysystem\AwsS3v3\AwsS3Adapter',
		'client' => new League\Flysystem\AwsS3v3\AwsS3Adapter(Aws\S3\S3Client::factory([
			'credentials' => [
				'key'    => '***',
				'secret' => '***',
			],
			'region' => 'eu-central-1',
			'version' => 'latest',
		]),'s3.example.com',''),
		'baseUrl' =>  's3.example.com'
      ],
    ],

    // lsiteners
    lsiteners => [],

    // upload settings
    'upload' => [
      'maxsize' => 30, // 30MB
      'types' =>['image/jpeg','image/png','image/gif'],
      'atags' => [],
      'atagsDisplay' => false, // false | 'select' | 'input'
      'profile' => 's3',

      // pagination setting in browse views
      'pagination' => [
        'offset' => 9, // = 10 pages
        'start' => true,
        'end' => true,
      ],
    ],

    // thumbnails settings
    'thumbnails' => [
      'driver' => 'Imagick', // or Imagick if installed,
      'compression' => [
     		'jpegoptim' => '/usr/local/bin/jpegoptim', // path or false ( default /usr/local/bin/jpegoptim )
    		'pngquant' => '/usr/local/bin/pngquant', // path or false ( default /usr/local/bin/pngquant )
    		'quality' => 25 // encoding quality level from 0 to 100 ( default 25 )
  		],
  		'breakpoints' => [
	        'lg' => '(min-width: 1200px)',
	        'md' => '(max-width: 1199px)',
	        'sm' => '(max-width: 991px)',
	        'xs' => '(max-width: 767px)',
      ],
      'widths' => ['678','1200'],
      'heights' => false,
      'aligns' => false, // or some of following [0,1,2,3,4,5,6,7,8] with 0 center, 1 top, 4 left, 5 right top corner, 8 left top corner ....
      'crops' => ['16:9','4:3','1:1']
    ]
]];

'default' => [
	'adapter' => 'League\Flysystem\Adapter\Local',
	'client' => new League\Flysystem\Adapter\Local('files'),
	'baseUrl' =>  '/files/'
],

'upload' => [
  'maxsize' => 30, // 30MB
  'types' =>['image/jpeg','embed/soundcloud',...], // mime types and embed/:service for embed stuff
  'atags' => [], // atags are use to store attachemnts with
  'relation' => 'belongsToMany', // model relation
  'profile' => 'default', // profile to use (where you store files)
  'visibility' => 'public', // public or private
  'speech' => false, // french goody
  'restrictions' => [] // or Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED
],

AttachmentHelper::TAG_RESTRICTED // enforce attachments to associted with given tags in save and retieve with a AND strategy
AttachmentHelper::TAG_OR_RESTRICTED // enforce attachments to associted with given tags in save and retieve with a OR strategy
AttachmentHelper::types_restricted // enforce attachments to saved and retrieve with a OR strategy according given mime types

'listeners' => [
  'beforePaginate' => [
    'App\Listener\MyListener',
    'App\Listener\MayOtherListener' => [
      'momo' => 'toto'
    ]
  ],
]

namespace App\Listener;

use Attachment\Listener\BaseListener;
use Cake\Event\Event;

class ExtranetMoveFileListener extends BaseListener
{
  // $event->getSubject() returns an object with minimum a request variable
  // all model events are wrapped on top of:
  // https://crud.readthedocs.io/en/latest/events.html#crud-beforesave
  public function respond(Event $event)  
  {

  }
}

'thumbnails' => [
  'driver' => 'Imagick', // or Imagick if installed,
  'widths' => [600, 1200],
  'heights' => [],
  'aligns' => [], // or some of following [0,1,2,3,4,5,6,7,8] with 0 center, 1 top, 4 left, 5 right top corner, 8 left top corner ....
  'crops' => ['4:3','16:9']
]

public function index()
{
	$this->paginate = [
	  'contain' => ['Attachments' /* => ['sort' => 'order'] */ ] // if HABTM with an order field
	];
	$posts = $this->paginate($this->Posts);
	$this->set(compact('posts'));
	$this->set('_serialize', ['posts']);
}

public function initialize()
{
	$this->loadHelper('Attachment.Attachment');
}

<!-- Attachment -->
<?= $this->Attachment->input('Attachments', // if Attachments => HABTM else if !Attachments => belongsTo
  	[
	  	'label' => 'Image',
	  	'types' =>['image/jpeg','image/png'],
	  	'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
	  	'profile' => 's3', // optional as it was set in config/attachment.php
	  	'cols' => 'col-xs-6 col-md-6 col-lg-4', // optional as it was set in config/attachment.php,
	  	'maxquantity' => -1,
	  	'restrictions' => [
	    	Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
	    	Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
	  	],
	  	'attachments' => [] // array of exisiting Attachment entities ( HABTM ) or [entity] ( belongsTo )
	]
) 

<!-- Attachment -->
<?= $this->Attachment->input('Attachments', // if Attachments => HABTM else if !Attachments => belongsTo
  	[
	  	'label' => 'Image',
	  	'types' =>['image/jpeg','image/png'],
	  	'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
	  	'profile' => 's3', // optional as it was set in config/attachment.php
	  	'cols' => 'col-xs-6 col-md-6 col-lg-4', // optional as it was set in config/attachment.php,
	  	'maxquantity' => -1,
	  	'restrictions' => [
	    	Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
	    	Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
	  	],
	  	'attachments' => $posts->attachments // array of exisiting Attachment entities ( HABTM ) or entity ( belongsTo )
	]
) 

<!-- Attachments element -->
<?= $this->Attachment->buildIndex([
  'actions' => ['add','edit','delete','view','download'],
  'types' =>['image/jpeg','image/png','embed/youtube','embed/vimeo'],
  'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
		'listStyle' => true,
		'profile' => 's3', // optional as it was set in config/attachment.php
  'restrictions' => [
    Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
    Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
  ]
]) 

echo $this->element('Trois/Tinymce.tinymce',[
  'field' => 'content',
  'value' => $post->content,
  'init' => [
    'external_plugins' => [
      'attachment' => $this->Url->build('/attachment/js/Plugins/tinymce/plugin.min.js', true),
    ],
    'attachment_settings' => $this->Attachment->jsSetup('content',[

      // overrides config/attachment.php settings
      'types' => [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/jpeg',
        'image/png',
        'embed/youtube',
        'embed/vimeo'
      ],
			'thumbBaseUrl' => '', //IF NOT $this->Url->build('/')
      'atags' => [],
      'restrictions' => [
        Attachment\View\Helper\AttachmentHelper::TAG_OR_RESTRICTED,
        Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
      ],
    ])
  ]
]);

$this->element('locale',['fields' => ['meta',
	'header' => [
		'Trois/Tinymce.tinymce' => [
			'value' => $post,
			'init' => []
		]
	],
	'body' => [
		'Trois/Tinymce.tinymce' => [
			'value' => $post,
			'init' => [
				'external_plugins' => [
					'attachment' => $this->Url->build('/attachment/js/Plugins/tinymce/plugin.min.js', true),
				],
				'attachment_settings' => [
					'types' => [
						'application/pdf',
						'application/msword',
						'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
						'application/vnd.ms-excel',
						'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
						'image/jpeg',
						'image/png',
						'embed/youtube',
						'embed/vimeo'
					],
					'atags' => [],
					'restrictions' => [
						Attachment\View\Helper\AttachmentHelper::TAG_OR_RESTRICTED,
						Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
					],
				]
			]
		]
	]
], 'labels' => ['meta (description google, facebook)', 'lead', 'text']]);

<!-- Display a 16:9 croped image  -->
<?= $this->Attachment->image([
	'image' => $post->attachments[0]->path,
	'profile' => $post->attachments[0]->profile,
	'width' => '600',
	'cropratio' => '16:9,
	'quality' => 50, // from 0 to 100 ( default 25 in plugin's config file attachment.php )
	'srcset' => [
      'lg' => [360,720],
      'md' => [293, 586],
      'sm' => [283, 566],
      'xs' => [767,1534],
    ]
],['class' => 'img-responsive']) 

<?= $this->Attachment->thumbSrc([
	'image' => $post->attachments[0]->path,
	'profile' => $post->attachments[0]->profile,
	'width' => '600',
	'cropratio' => '16:9,
	'quality' => 50, // from 0 to 100 ( default 25 in plugin's config file attachment.php )
	'srcset' => [
      'lg' => [360,720],
      'md' => [293, 586],
      'sm' => [283, 566],
      'xs' => [767,1534],
    ]
]) 

echo $this->Attachment->downloadLink($attachment ); // Attachment $attachment
// return the full download url for THIS SESSION ONLY
bash
$this->belongsToMany('Attachments', [
  'foreignKey' => 'post_id',
  'targetForeignKey' => 'attachment_id',
  'joinTable' => 'attachments_posts'
]);

// OR

$this->belongsTo('Attachments', [
  'foreignKey' => 'attachment_id',
  'joinType' => 'INNER' // OR LEFT ...
]);