Xtreme_Livrarionline - Version 1.0.1

Version Notes

Release 1.0.1

Download this release

Release Info

Developer Michael Mussulis
Extension Xtreme_Livrarionline
Version 1.0.1
Comparing to
See all releases


Version 1.0.1

Files changed (81) hide show
  1. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Awb.php +13 -0
  2. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline.php +12 -0
  3. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit.php +45 -0
  4. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Form.php +19 -0
  5. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Tab/Form.php +58 -0
  6. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Tabs.php +24 -0
  7. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Grid.php +116 -0
  8. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb.php +12 -0
  9. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit.php +45 -0
  10. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Form.php +19 -0
  11. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Tab/Form.php +173 -0
  12. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Tabs.php +24 -0
  13. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Grid.php +161 -0
  14. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers.php +12 -0
  15. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit.php +45 -0
  16. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Form.php +19 -0
  17. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Tab/Form.php +72 -0
  18. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Tabs.php +24 -0
  19. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Grid.php +129 -0
  20. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores.php +12 -0
  21. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit.php +45 -0
  22. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Form.php +19 -0
  23. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Tab/Form.php +198 -0
  24. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Tabs.php +24 -0
  25. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Grid.php +171 -0
  26. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Sales/Order/View.php +35 -0
  27. app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Sales/Order/View/Tab/Loawb.php +55 -0
  28. app/code/local/Xtreme/Livrarionline/Block/Livrarionline.php +17 -0
  29. app/code/local/Xtreme/Livrarionline/Helper/Data.php +377 -0
  30. app/code/local/Xtreme/Livrarionline/Model/Awb.php +49 -0
  31. app/code/local/Xtreme/Livrarionline/Model/Awb/Parcels.php +11 -0
  32. app/code/local/Xtreme/Livrarionline/Model/Carrier/Livrarionline.php +235 -0
  33. app/code/local/Xtreme/Livrarionline/Model/Carriers.php +20 -0
  34. app/code/local/Xtreme/Livrarionline/Model/Livrarionline.php +10 -0
  35. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb.php +10 -0
  36. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Collection.php +10 -0
  37. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Parcels.php +10 -0
  38. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Parcels/Collection.php +10 -0
  39. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Carriers.php +10 -0
  40. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Carriers/Collection.php +10 -0
  41. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Livrarionline.php +10 -0
  42. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Livrarionline/Collection.php +10 -0
  43. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Stores.php +10 -0
  44. app/code/local/Xtreme/Livrarionline/Model/Mysql4/Stores/Collection.php +10 -0
  45. app/code/local/Xtreme/Livrarionline/Model/Payee.php +17 -0
  46. app/code/local/Xtreme/Livrarionline/Model/Status.php +15 -0
  47. app/code/local/Xtreme/Livrarionline/Model/Stores.php +29 -0
  48. app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/AwbController.php +230 -0
  49. app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/LivrarionlineController.php +218 -0
  50. app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManageawbController.php +292 -0
  51. app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManagecarriersController.php +215 -0
  52. app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManagestoresController.php +208 -0
  53. app/code/local/Xtreme/Livrarionline/controllers/IndexController.php +47 -0
  54. app/code/local/Xtreme/Livrarionline/etc/config.xml +189 -0
  55. app/code/local/Xtreme/Livrarionline/etc/system.xml +127 -0
  56. app/code/local/Xtreme/Livrarionline/sql/livrarionline_setup/mysql4-install-0.1.0.php +116 -0
  57. app/design/adminhtml/default/default/layout/livrarionline.xml +49 -0
  58. app/design/adminhtml/default/default/template/livrarionline/awb.phtml +230 -0
  59. app/design/adminhtml/default/default/template/livrarionline/order/view/tab/info.phtml +136 -0
  60. app/design/adminhtml/default/default/template/livrarionline/sales/order/view/loawb.phtml +1 -0
  61. app/etc/modules/Xtreme_Livrarionline.xml +17 -0
  62. js/livrarionline/jquery-1.11.1.min.js +4 -0
  63. js/livrarionline/jquery.noconflict.js +1 -0
  64. lib/LivrariOnline/AES.php +184 -0
  65. lib/LivrariOnline/AES_Encryption.php +188 -0
  66. lib/LivrariOnline/Base.php +1989 -0
  67. lib/LivrariOnline/BigInteger.php +3651 -0
  68. lib/LivrariOnline/Blowfish.php +673 -0
  69. lib/LivrariOnline/DES.php +1534 -0
  70. lib/LivrariOnline/Hash.php +823 -0
  71. lib/LivrariOnline/RC2.php +652 -0
  72. lib/LivrariOnline/RC4.php +333 -0
  73. lib/LivrariOnline/RSA.php +2661 -0
  74. lib/LivrariOnline/Random.php +249 -0
  75. lib/LivrariOnline/Rijndael.php +1370 -0
  76. lib/LivrariOnline/TripleDES.php +418 -0
  77. lib/LivrariOnline/Twofish.php +920 -0
  78. lib/LivrariOnline/curl.php +89 -0
  79. lib/LivrariOnline/lo.php +168 -0
  80. lib/LivrariOnline/padCrypt.php +110 -0
  81. package.xml +18 -0
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Awb.php ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Adminhtml_Awb extends Mage_Adminhtml_Block_Widget_Grid_Container
3
+ {
4
+ public function __construct()
5
+ {
6
+ $this->_controller = 'adminhtml_awb';
7
+ $this->_blockGroup = 'livrarionline';
8
+ $this->_headerText = Mage::helper('livrarionline')->__('LO Create AWB');
9
+ $this->_addButtonLabel = Mage::helper('livrarionline')->__('Create AWB');
10
+ //$this->setOrderId(22);
11
+ parent::__construct();
12
+ }
13
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline.php ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline extends Mage_Adminhtml_Block_Widget_Grid_Container
3
+ {
4
+ public function __construct()
5
+ {
6
+ $this->_controller = 'adminhtml_livrarionline';
7
+ $this->_blockGroup = 'livrarionline';
8
+ $this->_headerText = Mage::helper('livrarionline')->__('Item Manager');
9
+ $this->_addButtonLabel = Mage::helper('livrarionline')->__('Add Item');
10
+ parent::__construct();
11
+ }
12
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+
9
+ $this->_objectId = 'id';
10
+ $this->_blockGroup = 'livrarionline';
11
+ $this->_controller = 'adminhtml_livrarionline';
12
+
13
+ $this->_updateButton('save', 'label', Mage::helper('livrarionline')->__('Save Item'));
14
+ $this->_updateButton('delete', 'label', Mage::helper('livrarionline')->__('Delete Item'));
15
+
16
+ $this->_addButton('saveandcontinue', array(
17
+ 'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
18
+ 'onclick' => 'saveAndContinueEdit()',
19
+ 'class' => 'save',
20
+ ), -100);
21
+
22
+ $this->_formScripts[] = "
23
+ function toggleEditor() {
24
+ if (tinyMCE.getInstanceById('livrarionline_content') == null) {
25
+ tinyMCE.execCommand('mceAddControl', false, 'livrarionline_content');
26
+ } else {
27
+ tinyMCE.execCommand('mceRemoveControl', false, 'livrarionline_content');
28
+ }
29
+ }
30
+
31
+ function saveAndContinueEdit(){
32
+ editForm.submit($('edit_form').action+'back/edit/');
33
+ }
34
+ ";
35
+ }
36
+
37
+ public function getHeaderText()
38
+ {
39
+ if( Mage::registry('livrarionline_data') && Mage::registry('livrarionline_data')->getId() ) {
40
+ return Mage::helper('livrarionline')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('livrarionline_data')->getTitle()));
41
+ } else {
42
+ return Mage::helper('livrarionline')->__('Add Item');
43
+ }
44
+ }
45
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Form.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form(array(
8
+ 'id' => 'edit_form',
9
+ 'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
10
+ 'method' => 'post',
11
+ 'enctype' => 'multipart/form-data'
12
+ )
13
+ );
14
+
15
+ $form->setUseContainer(true);
16
+ $this->setForm($form);
17
+ return parent::_prepareForm();
18
+ }
19
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Tab/Form.php ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form();
8
+ $this->setForm($form);
9
+ $fieldset = $form->addFieldset('livrarionline_form', array('legend'=>Mage::helper('livrarionline')->__('Item information')));
10
+
11
+ $fieldset->addField('title', 'text', array(
12
+ 'label' => Mage::helper('livrarionline')->__('Title'),
13
+ 'class' => 'required-entry',
14
+ 'required' => true,
15
+ 'name' => 'title',
16
+ ));
17
+
18
+ $fieldset->addField('filename', 'file', array(
19
+ 'label' => Mage::helper('livrarionline')->__('File'),
20
+ 'required' => false,
21
+ 'name' => 'filename',
22
+ ));
23
+
24
+ $fieldset->addField('status', 'select', array(
25
+ 'label' => Mage::helper('livrarionline')->__('Status'),
26
+ 'name' => 'status',
27
+ 'values' => array(
28
+ array(
29
+ 'value' => 1,
30
+ 'label' => Mage::helper('livrarionline')->__('Enabled'),
31
+ ),
32
+
33
+ array(
34
+ 'value' => 2,
35
+ 'label' => Mage::helper('livrarionline')->__('Disabled'),
36
+ ),
37
+ ),
38
+ ));
39
+
40
+ $fieldset->addField('content', 'editor', array(
41
+ 'name' => 'content',
42
+ 'label' => Mage::helper('livrarionline')->__('Content'),
43
+ 'title' => Mage::helper('livrarionline')->__('Content'),
44
+ 'style' => 'width:700px; height:500px;',
45
+ 'wysiwyg' => false,
46
+ 'required' => true,
47
+ ));
48
+
49
+ if ( Mage::getSingleton('adminhtml/session')->getLivrarionlineData() )
50
+ {
51
+ $form->setValues(Mage::getSingleton('adminhtml/session')->getLivrarionlineData());
52
+ Mage::getSingleton('adminhtml/session')->setLivrarionlineData(null);
53
+ } elseif ( Mage::registry('livrarionline_data') ) {
54
+ $form->setValues(Mage::registry('livrarionline_data')->getData());
55
+ }
56
+ return parent::_prepareForm();
57
+ }
58
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Edit/Tabs.php ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
4
+ {
5
+
6
+ public function __construct()
7
+ {
8
+ parent::__construct();
9
+ $this->setId('livrarionline_tabs');
10
+ $this->setDestElementId('edit_form');
11
+ $this->setTitle(Mage::helper('livrarionline')->__('Item Information'));
12
+ }
13
+
14
+ protected function _beforeToHtml()
15
+ {
16
+ $this->addTab('form_section', array(
17
+ 'label' => Mage::helper('livrarionline')->__('Item Information'),
18
+ 'title' => Mage::helper('livrarionline')->__('Item Information'),
19
+ 'content' => $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_edit_tab_form')->toHtml(),
20
+ ));
21
+
22
+ return parent::_beforeToHtml();
23
+ }
24
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Livrarionline/Grid.php ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Livrarionline_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->setId('livrarionlineGrid');
9
+ $this->setDefaultSort('livrarionline_id');
10
+ $this->setDefaultDir('ASC');
11
+ $this->setSaveParametersInSession(true);
12
+ }
13
+
14
+ protected function _prepareCollection()
15
+ {
16
+ $collection = Mage::getModel('livrarionline/livrarionline')->getCollection();
17
+ $this->setCollection($collection);
18
+ return parent::_prepareCollection();
19
+ }
20
+
21
+ protected function _prepareColumns()
22
+ {
23
+ $this->addColumn('livrarionline_id', array(
24
+ 'header' => Mage::helper('livrarionline')->__('ID'),
25
+ 'align' =>'right',
26
+ 'width' => '50px',
27
+ 'index' => 'livrarionline_id',
28
+ ));
29
+
30
+ $this->addColumn('title', array(
31
+ 'header' => Mage::helper('livrarionline')->__('Title'),
32
+ 'align' =>'left',
33
+ 'index' => 'title',
34
+ ));
35
+
36
+ /*
37
+ $this->addColumn('content', array(
38
+ 'header' => Mage::helper('livrarionline')->__('Item Content'),
39
+ 'width' => '150px',
40
+ 'index' => 'content',
41
+ ));
42
+ */
43
+
44
+ $this->addColumn('status', array(
45
+ 'header' => Mage::helper('livrarionline')->__('Status'),
46
+ 'align' => 'left',
47
+ 'width' => '80px',
48
+ 'index' => 'status',
49
+ 'type' => 'options',
50
+ 'options' => array(
51
+ 1 => 'Enabled',
52
+ 2 => 'Disabled',
53
+ ),
54
+ ));
55
+
56
+ $this->addColumn('action',
57
+ array(
58
+ 'header' => Mage::helper('livrarionline')->__('Action'),
59
+ 'width' => '100',
60
+ 'type' => 'action',
61
+ 'getter' => 'getId',
62
+ 'actions' => array(
63
+ array(
64
+ 'caption' => Mage::helper('livrarionline')->__('Edit'),
65
+ 'url' => array('base'=> '*/*/edit'),
66
+ 'field' => 'id'
67
+ )
68
+ ),
69
+ 'filter' => false,
70
+ 'sortable' => false,
71
+ 'index' => 'stores',
72
+ 'is_system' => true,
73
+ ));
74
+
75
+ $this->addExportType('*/*/exportCsv', Mage::helper('livrarionline')->__('CSV'));
76
+ $this->addExportType('*/*/exportXml', Mage::helper('livrarionline')->__('XML'));
77
+
78
+ return parent::_prepareColumns();
79
+ }
80
+
81
+ protected function _prepareMassaction()
82
+ {
83
+ $this->setMassactionIdField('livrarionline_id');
84
+ $this->getMassactionBlock()->setFormFieldName('livrarionline');
85
+
86
+ $this->getMassactionBlock()->addItem('delete', array(
87
+ 'label' => Mage::helper('livrarionline')->__('Delete'),
88
+ 'url' => $this->getUrl('*/*/massDelete'),
89
+ 'confirm' => Mage::helper('livrarionline')->__('Are you sure?')
90
+ ));
91
+
92
+ $statuses = Mage::getSingleton('livrarionline/status')->getOptionArray();
93
+
94
+ array_unshift($statuses, array('label'=>'', 'value'=>''));
95
+ $this->getMassactionBlock()->addItem('status', array(
96
+ 'label'=> Mage::helper('livrarionline')->__('Change status'),
97
+ 'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
98
+ 'additional' => array(
99
+ 'visibility' => array(
100
+ 'name' => 'status',
101
+ 'type' => 'select',
102
+ 'class' => 'required-entry',
103
+ 'label' => Mage::helper('livrarionline')->__('Status'),
104
+ 'values' => $statuses
105
+ )
106
+ )
107
+ ));
108
+ return $this;
109
+ }
110
+
111
+ public function getRowUrl($row)
112
+ {
113
+ return $this->getUrl('*/*/edit', array('id' => $row->getId()));
114
+ }
115
+
116
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb.php ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb extends Mage_Adminhtml_Block_Widget_Grid_Container
3
+ {
4
+ public function __construct()
5
+ {
6
+ $this->_controller = 'adminhtml_manageawb';
7
+ $this->_blockGroup = 'livrarionline';
8
+ $this->_headerText = Mage::helper('livrarionline')->__('AWB Manager');
9
+ parent::__construct();
10
+ $this->_removeButton('add');
11
+ }
12
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+
9
+ $this->_objectId = 'id';
10
+ $this->_blockGroup = 'livrarionline';
11
+ $this->_controller = 'adminhtml_manageawb';
12
+
13
+ $this->_updateButton('save', 'label', Mage::helper('livrarionline')->__('Save AWB'));
14
+ $this->_updateButton('delete', 'label', Mage::helper('livrarionline')->__('Delete AWB'));
15
+
16
+ $this->_addButton('saveandcontinue', array(
17
+ 'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
18
+ 'onclick' => 'saveAndContinueEdit()',
19
+ 'class' => 'save',
20
+ ), -100);
21
+
22
+ $this->_formScripts[] = "
23
+ function toggleEditor() {
24
+ if (tinyMCE.getInstanceById('livrarionline_content') == null) {
25
+ tinyMCE.execCommand('mceAddControl', false, 'livrarionline_content');
26
+ } else {
27
+ tinyMCE.execCommand('mceRemoveControl', false, 'livrarionline_content');
28
+ }
29
+ }
30
+
31
+ function saveAndContinueEdit(){
32
+ editForm.submit($('edit_form').action+'back/edit/');
33
+ }
34
+ ";
35
+ }
36
+
37
+ public function getHeaderText()
38
+ {
39
+ if( Mage::registry('awb_data') && Mage::registry('awb_data')->getId() ) {
40
+ return Mage::helper('livrarionline')->__("Edit AWB '%s'", $this->htmlEscape(Mage::registry('awb_data')->getId()));
41
+ } else {
42
+ return Mage::helper('livrarionline')->__('Add AWB');
43
+ }
44
+ }
45
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Form.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form(array(
8
+ 'id' => 'edit_form',
9
+ 'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
10
+ 'method' => 'post',
11
+ 'enctype' => 'multipart/form-data'
12
+ )
13
+ );
14
+
15
+ $form->setUseContainer(true);
16
+ $this->setForm($form);
17
+ return parent::_prepareForm();
18
+ }
19
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Tab/Form.php ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form();
8
+ $this->setForm($form);
9
+ $fieldset = $form->addFieldset('livrarionline_form', array('legend'=>Mage::helper('livrarionline')->__('AWB Information')));
10
+ $fieldset2 = $form->addFieldset('livrarionline_form2', array('legend'=>Mage::helper('livrarionline')->__('AWB Parcels')));
11
+
12
+ $fieldset->addField('name', 'text', array(
13
+ 'label' => Mage::helper('livrarionline')->__('Name'),
14
+ 'class' => 'required-entry',
15
+ 'required' => true,
16
+ 'name' => 'name',
17
+ ));
18
+
19
+ $fieldset->addField('address1', 'text', array(
20
+ 'label' => Mage::helper('livrarionline')->__('Address (line 1)'),
21
+ 'class' => 'required-entry',
22
+ 'required' => true,
23
+ 'name' => 'address1',
24
+ ));
25
+
26
+ $fieldset->addField('address2', 'text', array(
27
+ 'label' => Mage::helper('livrarionline')->__('Address (line 2)'),
28
+ //'class' => 'required-entry',
29
+ 'required' => false,
30
+ 'name' => 'address2',
31
+ ));
32
+
33
+ $fieldset->addField('zipcode', 'text', array(
34
+ 'label' => Mage::helper('livrarionline')->__('Zipcode'),
35
+ //'class' => 'required-entry',
36
+ 'required' => false,
37
+ 'name' => 'zipcode',
38
+ ));
39
+
40
+ $country = $fieldset->addField('country', 'select', array(
41
+ 'label' => Mage::helper('livrarionline')->__('Country'),
42
+ 'class' => 'required-entry',
43
+ 'required' => true,
44
+ 'name' => 'country',
45
+ 'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
46
+ 'onchange' => 'getstate(this)',
47
+ //'value' => 'RO'
48
+ ));
49
+
50
+ /*
51
+ * Add Ajax to the Country select box html output
52
+ */
53
+ $country->setAfterElementHtml("<script type=\"text/javascript\">
54
+ function getstate(selectElement){
55
+ var reloadurl = '". $this->getUrl('livrarionline/adminhtml_managestores/state') . "country/' + selectElement.value;
56
+ new Ajax.Request(reloadurl, {
57
+ method: 'get',
58
+ onComplete: function(transport){
59
+ var response = transport.responseText;
60
+ $('state').update(response);
61
+ }
62
+ });
63
+ }
64
+ </script>");
65
+ if(Mage::registry('store_data'))
66
+ {
67
+ $countrycode = Mage::registry('store_data')->getData('country');
68
+ $states = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter($countrycode)->load();
69
+ foreach($states as $st)
70
+ {
71
+ $statearray[] = array(
72
+ 'value' => $st->getCode(),
73
+ 'label' => $st->getDefaultName(),
74
+ );
75
+ }
76
+ }
77
+ else
78
+ {
79
+ $statearray = array('' => '--Please Select State--');
80
+ }
81
+ $fieldset->addField('state', 'select', array(
82
+ 'label' => Mage::helper('livrarionline')->__('State'),
83
+ 'class' => 'required-entry',
84
+ 'required' => true,
85
+ 'name' => 'state',
86
+ //'values' => Mage::getModel('modulename/modulename')->getstate('AU'),
87
+ 'values' => $statearray,
88
+ ));
89
+
90
+ $fieldset->addField('city', 'text', array(
91
+ 'label' => Mage::helper('livrarionline')->__('City'),
92
+ 'class' => 'required-entry',
93
+ 'required' => true,
94
+ 'name' => 'city',
95
+ ));
96
+
97
+ $fieldset->addField('latitude', 'text', array(
98
+ 'label' => Mage::helper('livrarionline')->__('Latitude'),
99
+ //'class' => 'required-entry',
100
+ 'required' => false,
101
+ 'name' => 'latitude',
102
+ ));
103
+
104
+ $fieldset->addField('longtitude', 'text', array(
105
+ 'label' => Mage::helper('livrarionline')->__('Longtitude'),
106
+ //'class' => 'required-entry',
107
+ 'required' => false,
108
+ 'name' => 'longtitude',
109
+ ));
110
+
111
+ $fieldset->addField('phone', 'text', array(
112
+ 'label' => Mage::helper('livrarionline')->__('Phone'),
113
+ //'class' => 'required-entry',
114
+ 'required' => false,
115
+ 'name' => 'phone',
116
+ ));
117
+
118
+ $fieldset->addField('fax', 'text', array(
119
+ 'label' => Mage::helper('livrarionline')->__('Fax'),
120
+ //'class' => 'required-entry',
121
+ 'required' => false,
122
+ 'name' => 'fax',
123
+ ));
124
+
125
+ $fieldset->addField('email', 'text', array(
126
+ 'label' => Mage::helper('livrarionline')->__('Email'),
127
+ //'class' => 'required-entry',
128
+ 'required' => false,
129
+ 'name' => 'email',
130
+ ));
131
+
132
+ /*$fieldset->addField('filename', 'file', array(
133
+ 'label' => Mage::helper('livrarionline')->__('File'),
134
+ 'required' => false,
135
+ 'name' => 'filename',
136
+ ));*/
137
+
138
+ $fieldset->addField('comment', 'editor', array(
139
+ 'name' => 'comment',
140
+ 'label' => Mage::helper('livrarionline')->__('Comment'),
141
+ 'title' => Mage::helper('livrarionline')->__('Comment'),
142
+ 'style' => 'width:300px; height:100px;',
143
+ 'wysiwyg' => true,
144
+ 'required' => false,
145
+ ));
146
+
147
+ $fieldset->addField('status', 'select', array(
148
+ 'label' => Mage::helper('livrarionline')->__('Status'),
149
+ 'name' => 'status',
150
+ 'values' => array(
151
+ array(
152
+ 'value' => 1,
153
+ 'label' => Mage::helper('livrarionline')->__('Enabled'),
154
+ ),
155
+
156
+ array(
157
+ 'value' => 2,
158
+ 'label' => Mage::helper('livrarionline')->__('Disabled'),
159
+ ),
160
+ ),
161
+ ));
162
+
163
+ if ( Mage::getSingleton('adminhtml/session')->getStoreData() )
164
+ {
165
+ $form->setValues(Mage::getSingleton('adminhtml/session')->getStoreData());
166
+ Mage::getSingleton('adminhtml/session')->setStoreData(null);
167
+ } elseif ( Mage::registry('store_data') ) {
168
+ $form->setValues(Mage::registry('store_data')->getData());
169
+ //print_r(Mage::registry('store_data')->getData());
170
+ }
171
+ return parent::_prepareForm();
172
+ }
173
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Edit/Tabs.php ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
4
+ {
5
+
6
+ public function __construct()
7
+ {
8
+ parent::__construct();
9
+ $this->setId('livrarionline_tabs');
10
+ $this->setDestElementId('edit_form');
11
+ $this->setTitle(Mage::helper('livrarionline')->__('AWB Information'));
12
+ }
13
+
14
+ protected function _beforeToHtml()
15
+ {
16
+ $this->addTab('form_section', array(
17
+ 'label' => Mage::helper('livrarionline')->__('AWB Information'),
18
+ 'title' => Mage::helper('livrarionline')->__('AWB Information'),
19
+ 'content' => $this->getLayout()->createBlock('livrarionline/adminhtml_manageawb_edit_tab_form')->toHtml(),
20
+ ));
21
+
22
+ return parent::_beforeToHtml();
23
+ }
24
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Manageawb/Grid.php ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Manageawb_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->setId('livrarionlineGrid');
9
+ $this->setDefaultSort('awb_id');
10
+ $this->setDefaultDir('DESC');
11
+ $this->setSaveParametersInSession(true);
12
+ }
13
+
14
+ protected function _prepareCollection()
15
+ {
16
+ $collection = Mage::getModel('livrarionline/awb')->getCollection();
17
+ $collection->getSelect()->join( array('tb_orders'=>Mage::getSingleton('core/resource')->getTableName('sales/order')), 'main_table.order_id = tb_orders.entity_id', array('tb_orders.increment_id'));
18
+
19
+ $this->setCollection($collection);
20
+ return parent::_prepareCollection();
21
+ }
22
+
23
+ protected function _prepareColumns()
24
+ {
25
+ $this->addColumn('awb_id', array(
26
+ 'header' => Mage::helper('livrarionline')->__('ID'),
27
+ 'align' =>'right',
28
+ 'width' => '50px',
29
+ 'index' => 'awb_id',
30
+ ));
31
+
32
+ $this->addColumn('increment_id', array(
33
+ 'header' => Mage::helper('livrarionline')->__('Order'),
34
+ 'align' =>'center',
35
+ 'index' => 'increment_id',
36
+ 'width' => '90px',
37
+ ));
38
+
39
+ $this->addColumn('awb_no', array(
40
+ 'header' => Mage::helper('livrarionline')->__('AWB No'),
41
+ 'align' =>'left',
42
+ 'index' => 'awb_no',
43
+ 'width' => '90px',
44
+ ));
45
+
46
+ $this->addColumn('description', array(
47
+ 'header' => Mage::helper('livrarionline')->__('Description'),
48
+ 'align' =>'left',
49
+ 'index' => 'description',
50
+ ));
51
+
52
+ $this->addColumn('reference', array(
53
+ 'header' => Mage::helper('livrarionline')->__('Reference'),
54
+ 'align' =>'left',
55
+ 'index' => 'reference',
56
+ ));
57
+
58
+
59
+ $this->addColumn('created_time', array(
60
+ 'header' => Mage::helper('livrarionline')->__('Created'),
61
+ 'width' => '150px',
62
+ 'type' => 'datetime',
63
+ 'index' => 'created_time',
64
+ ));
65
+
66
+ /*$this->addColumn('updated_time', array(
67
+ 'header' => Mage::helper('livrarionline')->__('Updated'),
68
+ 'width' => '150px',
69
+ 'type' => 'datetime',
70
+ 'index' => 'updated_time',
71
+ ));*/
72
+
73
+
74
+ $this->addColumn('status', array(
75
+ 'header' => Mage::helper('livrarionline')->__('Status'),
76
+ 'align' => 'left',
77
+ 'width' => '80px',
78
+ 'index' => 'status',
79
+ 'type' => 'options',
80
+ 'options' => Xtreme_Livrarionline_Model_Awb::getStatusOptionArray()
81
+ ));
82
+
83
+ $this->addColumn('action',
84
+ array(
85
+ 'header' => Mage::helper('livrarionline')->__('Action'),
86
+ 'width' => '100',
87
+ 'type' => 'action',
88
+ 'getter' => 'getId',
89
+ 'actions' => array(
90
+ //array(
91
+ // 'caption' => Mage::helper('livrarionline')->__('Edit'),
92
+ // 'url' => array('base'=> '*/*/edit'),
93
+ // 'field' => 'id'
94
+ //),
95
+ array(
96
+ 'caption' => Mage::helper('livrarionline')->__('Cancel'),
97
+ 'url' => array('base'=> '*/*/cancel'),
98
+ 'field' => 'id',
99
+ 'confirm' => Mage::helper('livrarionline')->__('Are you sure?'),
100
+ ),
101
+ array(
102
+ 'caption' => Mage::helper('livrarionline')->__('Print'),
103
+ 'url' => array('base'=> '*/*/print'),
104
+ 'field' => 'id',
105
+ 'popup' => true,
106
+ ),
107
+ //array(
108
+ // 'caption' => Mage::helper('livrarionline')->__('Delete'),
109
+ // 'url' => array('base'=> '*/*/delete'),
110
+ // 'field' => 'id',
111
+ // 'confirm' => Mage::helper('livrarionline')->__('Are you sure?'),
112
+ //),
113
+ ),
114
+ 'filter' => false,
115
+ 'sortable' => false,
116
+ 'index' => 'awb',
117
+ 'is_system' => true,
118
+ ));
119
+
120
+ $this->addExportType('*/*/exportCsv', Mage::helper('livrarionline')->__('CSV'));
121
+ $this->addExportType('*/*/exportXml', Mage::helper('livrarionline')->__('XML'));
122
+
123
+ return parent::_prepareColumns();
124
+ }
125
+
126
+ protected function _prepareMassaction()
127
+ {
128
+ $this->setMassactionIdField('awb_id');
129
+ $this->getMassactionBlock()->setFormFieldName('awb');
130
+
131
+ $this->getMassactionBlock()->addItem('delete', array(
132
+ 'label' => Mage::helper('livrarionline')->__('Delete'),
133
+ 'url' => $this->getUrl('*/*/massDelete'),
134
+ 'confirm' => Mage::helper('livrarionline')->__('Are you sure?')
135
+ ));
136
+
137
+ $statuses = Mage::getSingleton('livrarionline/status')->getOptionArray();
138
+
139
+ array_unshift($statuses, array('label'=>'', 'value'=>''));
140
+ $this->getMassactionBlock()->addItem('status', array(
141
+ 'label'=> Mage::helper('livrarionline')->__('Change status'),
142
+ 'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
143
+ 'additional' => array(
144
+ 'visibility' => array(
145
+ 'name' => 'status',
146
+ 'type' => 'select',
147
+ 'class' => 'required-entry',
148
+ 'label' => Mage::helper('livrarionline')->__('Status'),
149
+ 'values' => $statuses
150
+ )
151
+ )
152
+ ));
153
+ return $this;
154
+ }
155
+
156
+ public function getRowUrl($row)
157
+ {
158
+ //return $this->getUrl('*/*/edit', array('id' => $row->getId()));
159
+ }
160
+
161
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers.php ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers extends Mage_Adminhtml_Block_Widget_Grid_Container
3
+ {
4
+ public function __construct()
5
+ {
6
+ $this->_controller = 'adminhtml_managecarriers';
7
+ $this->_blockGroup = 'livrarionline';
8
+ $this->_headerText = Mage::helper('livrarionline')->__('Carriers Manager');
9
+ $this->_addButtonLabel = Mage::helper('livrarionline')->__('Add Carrier');
10
+ parent::__construct();
11
+ }
12
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+
9
+ $this->_objectId = 'id';
10
+ $this->_blockGroup = 'livrarionline';
11
+ $this->_controller = 'adminhtml_managecarriers';
12
+
13
+ $this->_updateButton('save', 'label', Mage::helper('livrarionline')->__('Save Carrier'));
14
+ $this->_updateButton('delete', 'label', Mage::helper('livrarionline')->__('Delete Carrier'));
15
+
16
+ $this->_addButton('saveandcontinue', array(
17
+ 'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
18
+ 'onclick' => 'saveAndContinueEdit()',
19
+ 'class' => 'save',
20
+ ), -100);
21
+
22
+ $this->_formScripts[] = "
23
+ function toggleEditor() {
24
+ if (tinyMCE.getInstanceById('livrarionline_content') == null) {
25
+ tinyMCE.execCommand('mceAddControl', false, 'livrarionline_content');
26
+ } else {
27
+ tinyMCE.execCommand('mceRemoveControl', false, 'livrarionline_content');
28
+ }
29
+ }
30
+
31
+ function saveAndContinueEdit(){
32
+ editForm.submit($('edit_form').action+'back/edit/');
33
+ }
34
+ ";
35
+ }
36
+
37
+ public function getHeaderText()
38
+ {
39
+ if( Mage::registry('carrier_data') && Mage::registry('carrier_data')->getId() ) {
40
+ return Mage::helper('livrarionline')->__("Edit Carrier '%s'", $this->htmlEscape(Mage::registry('carrier_data')->getId()));
41
+ } else {
42
+ return Mage::helper('livrarionline')->__('Add Carrier');
43
+ }
44
+ }
45
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Form.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form(array(
8
+ 'id' => 'edit_form',
9
+ 'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
10
+ 'method' => 'post',
11
+ 'enctype' => 'multipart/form-data'
12
+ )
13
+ );
14
+
15
+ $form->setUseContainer(true);
16
+ $this->setForm($form);
17
+ return parent::_prepareForm();
18
+ }
19
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Tab/Form.php ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form();
8
+ $this->setForm($form);
9
+ $fieldset = $form->addFieldset('livrarionline_form', array('legend'=>Mage::helper('livrarionline')->__('Carrier information')));
10
+
11
+ $fieldset->addField('name', 'text', array(
12
+ 'label' => Mage::helper('livrarionline')->__('Name'),
13
+ 'class' => 'required-entry',
14
+ 'required' => true,
15
+ 'name' => 'name',
16
+ ));
17
+
18
+ $fieldset->addField('service_id', 'text', array(
19
+ 'label' => Mage::helper('livrarionline')->__('Service ID'),
20
+ 'class' => 'required-entry',
21
+ 'required' => true,
22
+ 'name' => 'service_id',
23
+ ));
24
+
25
+ $fieldset->addField('shipping_company_id', 'text', array(
26
+ 'label' => Mage::helper('livrarionline')->__('Shipping Company ID'),
27
+ 'class' => 'required-entry',
28
+ 'required' => true,
29
+ 'name' => 'shipping_company_id',
30
+ ));
31
+
32
+ /*$fieldset->addField('filename', 'file', array(
33
+ 'label' => Mage::helper('livrarionline')->__('File'),
34
+ 'required' => false,
35
+ 'name' => 'filename',
36
+ ));*/
37
+ $fieldset->addField('status', 'select', array(
38
+ 'label' => Mage::helper('livrarionline')->__('Status'),
39
+ 'name' => 'status',
40
+ 'values' => array(
41
+ array(
42
+ 'value' => 1,
43
+ 'label' => Mage::helper('livrarionline')->__('Enabled'),
44
+ ),
45
+
46
+ array(
47
+ 'value' => 2,
48
+ 'label' => Mage::helper('livrarionline')->__('Disabled'),
49
+ ),
50
+ ),
51
+ ));
52
+
53
+ /*$fieldset->addField('description', 'editor', array(
54
+ 'name' => 'description',
55
+ 'label' => Mage::helper('livrarionline')->__('Description'),
56
+ 'title' => Mage::helper('livrarionline')->__('Description'),
57
+ 'style' => 'width:300px; height:100px;',
58
+ 'wysiwyg' => false,
59
+ 'required' => true,
60
+ ));*/
61
+
62
+
63
+ if ( Mage::getSingleton('adminhtml/session')->getCarrierData() )
64
+ {
65
+ $form->setValues(Mage::getSingleton('adminhtml/session')->getCarrierData());
66
+ Mage::getSingleton('adminhtml/session')->setCarrierData(null);
67
+ } elseif ( Mage::registry('carrier_data') ) {
68
+ $form->setValues(Mage::registry('carrier_data')->getData());
69
+ }
70
+ return parent::_prepareForm();
71
+ }
72
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Edit/Tabs.php ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
4
+ {
5
+
6
+ public function __construct()
7
+ {
8
+ parent::__construct();
9
+ $this->setId('livrarionline_tabs');
10
+ $this->setDestElementId('edit_form');
11
+ $this->setTitle(Mage::helper('livrarionline')->__('Carrier Information'));
12
+ }
13
+
14
+ protected function _beforeToHtml()
15
+ {
16
+ $this->addTab('form_section', array(
17
+ 'label' => Mage::helper('livrarionline')->__('Carrier Information'),
18
+ 'title' => Mage::helper('livrarionline')->__('Carrier Information'),
19
+ 'content' => $this->getLayout()->createBlock('livrarionline/adminhtml_managecarriers_edit_tab_form')->toHtml(),
20
+ ));
21
+
22
+ return parent::_beforeToHtml();
23
+ }
24
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managecarriers/Grid.php ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managecarriers_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->setId('livrarionlineGrid');
9
+ $this->setDefaultSort('livrarionline_id');
10
+ $this->setDefaultDir('ASC');
11
+ $this->setSaveParametersInSession(true);
12
+ }
13
+
14
+ protected function _prepareCollection()
15
+ {
16
+ $collection = Mage::getModel('livrarionline/carriers')->getCollection();
17
+ $this->setCollection($collection);
18
+ return parent::_prepareCollection();
19
+ }
20
+
21
+ protected function _prepareColumns()
22
+ {
23
+ $this->addColumn('carrier_id', array(
24
+ 'header' => Mage::helper('livrarionline')->__('ID'),
25
+ 'align' =>'right',
26
+ 'width' => '50px',
27
+ 'index' => 'carrier_id',
28
+ ));
29
+
30
+ $this->addColumn('name', array(
31
+ 'header' => Mage::helper('livrarionline')->__('Name'),
32
+ 'align' =>'left',
33
+ 'index' => 'name',
34
+ ));
35
+
36
+
37
+ $this->addColumn('created_time', array(
38
+ 'header' => Mage::helper('livrarionline')->__('Created'),
39
+ 'width' => '150px',
40
+ 'type' => 'datetime',
41
+ 'index' => 'created_time',
42
+ ));
43
+
44
+ $this->addColumn('updated_time', array(
45
+ 'header' => Mage::helper('livrarionline')->__('Updated'),
46
+ 'width' => '150px',
47
+ 'type' => 'datetime',
48
+ 'index' => 'updated_time',
49
+ ));
50
+
51
+
52
+ $this->addColumn('status', array(
53
+ 'header' => Mage::helper('livrarionline')->__('Status'),
54
+ 'align' => 'left',
55
+ 'width' => '80px',
56
+ 'index' => 'status',
57
+ 'type' => 'options',
58
+ 'options' => array(
59
+ 1 => 'Enabled',
60
+ 2 => 'Disabled',
61
+ ),
62
+ ));
63
+
64
+ $this->addColumn('action',
65
+ array(
66
+ 'header' => Mage::helper('livrarionline')->__('Action'),
67
+ 'width' => '100',
68
+ 'type' => 'action',
69
+ 'getter' => 'getId',
70
+ 'actions' => array(
71
+ array(
72
+ 'caption' => Mage::helper('livrarionline')->__('Edit'),
73
+ 'url' => array('base'=> '*/*/edit'),
74
+ 'field' => 'id'
75
+ ),
76
+ array(
77
+ 'caption' => Mage::helper('livrarionline')->__('Delete'),
78
+ 'url' => array('base'=> '*/*/delete'),
79
+ 'field' => 'id'
80
+ )
81
+ ),
82
+ 'filter' => false,
83
+ 'sortable' => false,
84
+ 'index' => 'stores',
85
+ 'is_system' => true,
86
+ ));
87
+
88
+ $this->addExportType('*/*/exportCsv', Mage::helper('livrarionline')->__('CSV'));
89
+ $this->addExportType('*/*/exportXml', Mage::helper('livrarionline')->__('XML'));
90
+
91
+ return parent::_prepareColumns();
92
+ }
93
+
94
+ protected function _prepareMassaction()
95
+ {
96
+ $this->setMassactionIdField('carrier_id');
97
+ $this->getMassactionBlock()->setFormFieldName('carriers');
98
+
99
+ $this->getMassactionBlock()->addItem('delete', array(
100
+ 'label' => Mage::helper('livrarionline')->__('Delete'),
101
+ 'url' => $this->getUrl('*/*/massDelete'),
102
+ 'confirm' => Mage::helper('livrarionline')->__('Are you sure?')
103
+ ));
104
+
105
+ $statuses = Mage::getSingleton('livrarionline/status')->getOptionArray();
106
+
107
+ array_unshift($statuses, array('label'=>'', 'value'=>''));
108
+ $this->getMassactionBlock()->addItem('status', array(
109
+ 'label'=> Mage::helper('livrarionline')->__('Change status'),
110
+ 'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
111
+ 'additional' => array(
112
+ 'visibility' => array(
113
+ 'name' => 'status',
114
+ 'type' => 'select',
115
+ 'class' => 'required-entry',
116
+ 'label' => Mage::helper('livrarionline')->__('Status'),
117
+ 'values' => $statuses
118
+ )
119
+ )
120
+ ));
121
+ return $this;
122
+ }
123
+
124
+ public function getRowUrl($row)
125
+ {
126
+ return $this->getUrl('*/*/edit', array('id' => $row->getId()));
127
+ }
128
+
129
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores.php ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores extends Mage_Adminhtml_Block_Widget_Grid_Container
3
+ {
4
+ public function __construct()
5
+ {
6
+ $this->_controller = 'adminhtml_managestores';
7
+ $this->_blockGroup = 'livrarionline';
8
+ $this->_headerText = Mage::helper('livrarionline')->__('Stores Manager');
9
+ $this->_addButtonLabel = Mage::helper('livrarionline')->__('Add Store');
10
+ parent::__construct();
11
+ }
12
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+
9
+ $this->_objectId = 'id';
10
+ $this->_blockGroup = 'livrarionline';
11
+ $this->_controller = 'adminhtml_managestores';
12
+
13
+ $this->_updateButton('save', 'label', Mage::helper('livrarionline')->__('Save Store'));
14
+ $this->_updateButton('delete', 'label', Mage::helper('livrarionline')->__('Delete Store'));
15
+
16
+ $this->_addButton('saveandcontinue', array(
17
+ 'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
18
+ 'onclick' => 'saveAndContinueEdit()',
19
+ 'class' => 'save',
20
+ ), -100);
21
+
22
+ $this->_formScripts[] = "
23
+ function toggleEditor() {
24
+ if (tinyMCE.getInstanceById('livrarionline_content') == null) {
25
+ tinyMCE.execCommand('mceAddControl', false, 'livrarionline_content');
26
+ } else {
27
+ tinyMCE.execCommand('mceRemoveControl', false, 'livrarionline_content');
28
+ }
29
+ }
30
+
31
+ function saveAndContinueEdit(){
32
+ editForm.submit($('edit_form').action+'back/edit/');
33
+ }
34
+ ";
35
+ }
36
+
37
+ public function getHeaderText()
38
+ {
39
+ if( Mage::registry('store_data') && Mage::registry('store_data')->getId() ) {
40
+ return Mage::helper('livrarionline')->__("Edit Store '%s'", $this->htmlEscape(Mage::registry('store_data')->getId()));
41
+ } else {
42
+ return Mage::helper('livrarionline')->__('Add Store');
43
+ }
44
+ }
45
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Form.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $form = new Varien_Data_Form(array(
8
+ 'id' => 'edit_form',
9
+ 'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
10
+ 'method' => 'post',
11
+ 'enctype' => 'multipart/form-data'
12
+ )
13
+ );
14
+
15
+ $form->setUseContainer(true);
16
+ $this->setForm($form);
17
+ return parent::_prepareForm();
18
+ }
19
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Tab/Form.php ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ $formData = Mage::registry('store_data')->getData();
8
+
9
+ $form = new Varien_Data_Form();
10
+ $this->setForm($form);
11
+ $fieldset = $form->addFieldset('livrarionline_form', array('legend'=>Mage::helper('livrarionline')->__('Stores information')));
12
+
13
+ $fieldset->addField('name', 'text', array(
14
+ 'label' => Mage::helper('livrarionline')->__('Name'),
15
+ 'class' => 'required-entry',
16
+ 'required' => true,
17
+ 'name' => 'name',
18
+ ));
19
+
20
+ $fieldset->addField('address1', 'text', array(
21
+ 'label' => Mage::helper('livrarionline')->__('Address (line 1)'),
22
+ 'class' => 'required-entry',
23
+ 'required' => true,
24
+ 'name' => 'address1',
25
+ ));
26
+
27
+ $fieldset->addField('address2', 'text', array(
28
+ 'label' => Mage::helper('livrarionline')->__('Address (line 2)'),
29
+ //'class' => 'required-entry',
30
+ 'required' => false,
31
+ 'name' => 'address2',
32
+ ));
33
+
34
+ $fieldset->addField('zipcode', 'text', array(
35
+ 'label' => Mage::helper('livrarionline')->__('Zipcode'),
36
+ //'class' => 'required-entry',
37
+ 'required' => false,
38
+ 'name' => 'zipcode',
39
+ ));
40
+
41
+ $country = $fieldset->addField('country', 'select', array(
42
+ 'label' => Mage::helper('livrarionline')->__('Country'),
43
+ 'class' => 'required-entry',
44
+ 'required' => true,
45
+ 'name' => 'country',
46
+ 'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
47
+ 'onchange' => 'getstate(this)',
48
+ //'value' => 'RO'
49
+ ));
50
+
51
+ /*
52
+ * Add Ajax to the Country select box html output
53
+ */
54
+ $country->setAfterElementHtml("<script type=\"text/javascript\">
55
+ function getstate(selectElement){
56
+ var reloadurl = '". $this->getUrl('livrarionline/adminhtml_managestores/state') . "country/' + selectElement.value;
57
+ new Ajax.Request(reloadurl, {
58
+ method: 'get',
59
+ onComplete: function(transport){
60
+ var response = transport.responseText;
61
+ $('state').update(response);
62
+ }
63
+ });
64
+ }
65
+ </script>");
66
+ if(Mage::registry('store_data'))
67
+ {
68
+ $countrycode = Mage::registry('store_data')->getData('country');
69
+ $states = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter($countrycode)->load();
70
+ foreach($states as $st)
71
+ {
72
+ $statearray[] = array(
73
+ 'value' => $st->getCode(),
74
+ 'label' => $st->getDefaultName(),
75
+ );
76
+ }
77
+ }
78
+ else
79
+ {
80
+ $statearray = array('' => '--Please Select State--');
81
+ }
82
+ $fieldset->addField('state', 'select', array(
83
+ 'label' => Mage::helper('livrarionline')->__('State'),
84
+ 'class' => 'required-entry',
85
+ 'required' => true,
86
+ 'name' => 'state',
87
+ //'values' => Mage::getModel('modulename/modulename')->getstate('AU'),
88
+ 'values' => $statearray,
89
+ ));
90
+
91
+ $fieldset->addField('city', 'text', array(
92
+ 'label' => Mage::helper('livrarionline')->__('City'),
93
+ 'class' => 'required-entry',
94
+ 'required' => true,
95
+ 'name' => 'city',
96
+ ));
97
+
98
+ $fieldset->addField('latitude', 'text', array(
99
+ 'label' => Mage::helper('livrarionline')->__('Latitude'),
100
+ //'class' => 'required-entry',
101
+ 'required' => false,
102
+ 'name' => 'latitude',
103
+ ));
104
+
105
+ $fieldset->addField('longtitude', 'text', array(
106
+ 'label' => Mage::helper('livrarionline')->__('Longtitude'),
107
+ //'class' => 'required-entry',
108
+ 'required' => false,
109
+ 'name' => 'longtitude',
110
+ ));
111
+
112
+ $fieldset->addField('phone', 'text', array(
113
+ 'label' => Mage::helper('livrarionline')->__('Phone'),
114
+ //'class' => 'required-entry',
115
+ 'required' => false,
116
+ 'name' => 'phone',
117
+ ));
118
+
119
+ $fieldset->addField('fax', 'text', array(
120
+ 'label' => Mage::helper('livrarionline')->__('Fax'),
121
+ //'class' => 'required-entry',
122
+ 'required' => false,
123
+ 'name' => 'fax',
124
+ ));
125
+
126
+ $fieldset->addField('email', 'text', array(
127
+ 'label' => Mage::helper('livrarionline')->__('Email'),
128
+ 'class' => 'required-entry',
129
+ 'required' => true,
130
+ 'name' => 'email',
131
+ ));
132
+
133
+ $fieldset->addField('firstname', 'text', array(
134
+ 'label' => Mage::helper('livrarionline')->__('Firstname'),
135
+ 'class' => 'required-entry',
136
+ 'required' => true,
137
+ 'name' => 'firstname',
138
+ ));
139
+ $fieldset->addField('lastname', 'text', array(
140
+ 'label' => Mage::helper('livrarionline')->__('Lastname'),
141
+ 'class' => 'required-entry',
142
+ 'required' => true,
143
+ 'name' => 'lastname',
144
+ ));
145
+
146
+ $fieldset->addField('default', 'checkbox', array(
147
+ 'label' => Mage::helper('livrarionline')->__('Default Store'),
148
+ //'class' => 'required-entry',
149
+ 'required' => false,
150
+ 'name' => 'default',
151
+ 'onclick' => 'this.value = this.checked ? 1 : 0;',
152
+ 'disabled' => (!empty($formData['default']) && $formData['default']),
153
+ 'after_element_html' => (!empty($formData['default']) && $formData['default']) ? '<small>This is the default store, it can not be unchecked.</small>' : '',
154
+ ));
155
+
156
+ /*$fieldset->addField('filename', 'file', array(
157
+ 'label' => Mage::helper('livrarionline')->__('File'),
158
+ 'required' => false,
159
+ 'name' => 'filename',
160
+ ));*/
161
+
162
+ $fieldset->addField('comment', 'editor', array(
163
+ 'name' => 'comment',
164
+ 'label' => Mage::helper('livrarionline')->__('Comment'),
165
+ 'title' => Mage::helper('livrarionline')->__('Comment'),
166
+ 'style' => 'width:300px; height:100px;',
167
+ 'wysiwyg' => true,
168
+ 'required' => false,
169
+ ));
170
+
171
+ $fieldset->addField('status', 'select', array(
172
+ 'label' => Mage::helper('livrarionline')->__('Status'),
173
+ 'name' => 'status',
174
+ 'values' => array(
175
+ array(
176
+ 'value' => 1,
177
+ 'label' => Mage::helper('livrarionline')->__('Enabled'),
178
+ ),
179
+
180
+ array(
181
+ 'value' => 2,
182
+ 'label' => Mage::helper('livrarionline')->__('Disabled'),
183
+ ),
184
+ ),
185
+ ));
186
+
187
+ if ( Mage::getSingleton('adminhtml/session')->getStoreData() )
188
+ {
189
+ $form->setValues(Mage::getSingleton('adminhtml/session')->getStoreData());
190
+ Mage::getSingleton('adminhtml/session')->setStoreData(null);
191
+ } elseif ( Mage::registry('store_data') ) {
192
+ $form->setValues(Mage::registry('store_data')->getData());
193
+ $form->getElement('default')->setIsChecked(!empty($formData['default']));
194
+ //print_r(Mage::registry('store_data')->getData());
195
+ }
196
+ return parent::_prepareForm();
197
+ }
198
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Edit/Tabs.php ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
4
+ {
5
+
6
+ public function __construct()
7
+ {
8
+ parent::__construct();
9
+ $this->setId('livrarionline_tabs');
10
+ $this->setDestElementId('edit_form');
11
+ $this->setTitle(Mage::helper('livrarionline')->__('Store Information'));
12
+ }
13
+
14
+ protected function _beforeToHtml()
15
+ {
16
+ $this->addTab('form_section', array(
17
+ 'label' => Mage::helper('livrarionline')->__('Store Information'),
18
+ 'title' => Mage::helper('livrarionline')->__('Store Information'),
19
+ 'content' => $this->getLayout()->createBlock('livrarionline/adminhtml_managestores_edit_tab_form')->toHtml(),
20
+ ));
21
+
22
+ return parent::_beforeToHtml();
23
+ }
24
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Managestores/Grid.php ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Managestores_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->setId('livrarionlineGrid');
9
+ $this->setDefaultSort('store_id');
10
+ $this->setDefaultDir('DESC');
11
+ $this->setSaveParametersInSession(true);
12
+ }
13
+
14
+ protected function _prepareCollection()
15
+ {
16
+ $collection = Mage::getModel('livrarionline/stores')->getCollection();
17
+ $this->setCollection($collection);
18
+ return parent::_prepareCollection();
19
+ }
20
+
21
+ protected function _prepareColumns()
22
+ {
23
+ $this->addColumn('store_id', array(
24
+ 'header' => Mage::helper('livrarionline')->__('ID'),
25
+ 'align' =>'right',
26
+ 'width' => '50px',
27
+ 'index' => 'store_id',
28
+ ));
29
+
30
+ $this->addColumn('name', array(
31
+ 'header' => Mage::helper('livrarionline')->__('Store Name'),
32
+ 'align' =>'left',
33
+ 'index' => 'name',
34
+ ));
35
+
36
+ $this->addColumn('email', array(
37
+ 'header' => Mage::helper('livrarionline')->__('Email'),
38
+ 'align' =>'left',
39
+ 'index' => 'email',
40
+ ));
41
+
42
+ $this->addColumn('firstname', array(
43
+ 'header' => Mage::helper('livrarionline')->__('Firstname'),
44
+ 'align' =>'left',
45
+ 'index' => 'firstname',
46
+ ));
47
+
48
+ $this->addColumn('lastname', array(
49
+ 'header' => Mage::helper('livrarionline')->__('Lastname'),
50
+ 'align' =>'left',
51
+ 'index' => 'lastname',
52
+ ));
53
+
54
+ $this->addColumn('country', array(
55
+ 'header' => Mage::helper('livrarionline')->__('Country'),
56
+ 'align' =>'left',
57
+ 'index' => 'country',
58
+ ));
59
+
60
+ $this->addColumn('state', array(
61
+ 'header' => Mage::helper('livrarionline')->__('State'),
62
+ 'align' =>'left',
63
+ 'index' => 'state',
64
+ ));
65
+
66
+
67
+ $this->addColumn('created_time', array(
68
+ 'header' => Mage::helper('livrarionline')->__('Created'),
69
+ 'width' => '150px',
70
+ 'type' => 'datetime',
71
+ 'index' => 'created_time',
72
+ ));
73
+
74
+ $this->addColumn('updated_time', array(
75
+ 'header' => Mage::helper('livrarionline')->__('Updated'),
76
+ 'width' => '150px',
77
+ 'type' => 'datetime',
78
+ 'index' => 'updated_time',
79
+ ));
80
+
81
+
82
+ $this->addColumn('status', array(
83
+ 'header' => Mage::helper('livrarionline')->__('Status'),
84
+ 'align' => 'left',
85
+ 'width' => '80px',
86
+ 'index' => 'status',
87
+ 'type' => 'options',
88
+ 'options' => array(
89
+ 1 => 'Enabled',
90
+ 2 => 'Disabled',
91
+ ),
92
+ ));
93
+
94
+ $this->addColumn('default', array(
95
+ 'header' => Mage::helper('livrarionline')->__('Default'),
96
+ 'align' => 'center',
97
+ 'width' => '80px',
98
+ 'index' => 'default',
99
+ 'type' => 'options',
100
+ 'options' => array(
101
+ 0 => '',
102
+ 1 => 'Yes',
103
+ ),
104
+ ));
105
+
106
+ $this->addColumn('action',
107
+ array(
108
+ 'header' => Mage::helper('livrarionline')->__('Action'),
109
+ 'width' => '100',
110
+ 'type' => 'action',
111
+ 'getter' => 'getId',
112
+ 'actions' => array(
113
+ array(
114
+ 'caption' => Mage::helper('livrarionline')->__('Edit'),
115
+ 'url' => array('base'=> '*/*/edit'),
116
+ 'field' => 'id'
117
+ ),
118
+ array(
119
+ 'caption' => Mage::helper('livrarionline')->__('Delete'),
120
+ 'url' => array('base'=> '*/*/delete'),
121
+ 'field' => 'id'
122
+ )
123
+ ),
124
+ 'filter' => false,
125
+ 'sortable' => false,
126
+ 'index' => 'stores',
127
+ 'is_system' => true,
128
+ ));
129
+
130
+ $this->addExportType('*/*/exportCsv', Mage::helper('livrarionline')->__('CSV'));
131
+ $this->addExportType('*/*/exportXml', Mage::helper('livrarionline')->__('XML'));
132
+
133
+ return parent::_prepareColumns();
134
+ }
135
+
136
+ protected function _prepareMassaction()
137
+ {
138
+ $this->setMassactionIdField('store_id');
139
+ $this->getMassactionBlock()->setFormFieldName('stores');
140
+
141
+ $this->getMassactionBlock()->addItem('delete', array(
142
+ 'label' => Mage::helper('livrarionline')->__('Delete'),
143
+ 'url' => $this->getUrl('*/*/massDelete'),
144
+ 'confirm' => Mage::helper('livrarionline')->__('Are you sure?')
145
+ ));
146
+
147
+ $statuses = Mage::getSingleton('livrarionline/status')->getOptionArray();
148
+
149
+ array_unshift($statuses, array('label'=>'', 'value'=>''));
150
+ $this->getMassactionBlock()->addItem('status', array(
151
+ 'label'=> Mage::helper('livrarionline')->__('Change status'),
152
+ 'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
153
+ 'additional' => array(
154
+ 'visibility' => array(
155
+ 'name' => 'status',
156
+ 'type' => 'select',
157
+ 'class' => 'required-entry',
158
+ 'label' => Mage::helper('livrarionline')->__('Status'),
159
+ 'values' => $statuses
160
+ )
161
+ )
162
+ ));
163
+ return $this;
164
+ }
165
+
166
+ public function getRowUrl($row)
167
+ {
168
+ return $this->getUrl('*/*/edit', array('id' => $row->getId()));
169
+ }
170
+
171
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Sales/Order/View.php ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Sales_Order_View extends Mage_Adminhtml_Block_Sales_Order_View {
4
+ public function __construct() {
5
+
6
+ parent::__construct();
7
+
8
+ $hasShipping = count($this->getOrder()->getShipmentsCollection());
9
+ if($hasShipping)
10
+ {
11
+ $awb_col = Mage::getModel('livrarionline/awb')->getCollection()
12
+ ->addFieldToFilter('order_id', $this->getOrder()->getId())
13
+ ->addFieldToFilter('status', 1);
14
+ }
15
+
16
+ if(!$hasShipping) $title = Mage::helper('livrarionline')->__('Must create shipping first');
17
+ else if(count($awb_col) > 0) $title = "";
18
+ else $title = Mage::helper('livrarionline')->__('LO Create AWB');
19
+
20
+ $label = Mage::helper('livrarionline')->__('LO Create AWB');
21
+ if(count($awb_col) > 0) $label = Mage::helper('livrarionline')->__('AWB already created');
22
+ $this->_addButton('button_id', array(
23
+ 'label' => $label,
24
+ 'onclick' => ($hasShipping && count($awb_col) == 0) ? 'setLocation(\'' . $this->getLOAwbUrl() . '\')' : '',
25
+ 'class' => ($hasShipping && count($awb_col) == 0) ? 'go' : '',
26
+ 'disabled' => (!$hasShipping || count($awb_col) > 0) ? 'disabled' : '',
27
+ 'title' => $title,
28
+ ), 0, 100, 'header', 'header');
29
+ }
30
+
31
+ public function getLOAwbUrl()
32
+ {
33
+ return $this->getUrl('livrarionline/adminhtml_awb');
34
+ }
35
+ }
app/code/local/Xtreme/Livrarionline/Block/Adminhtml/Sales/Order/View/Tab/Loawb.php ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Block_Adminhtml_Sales_Order_View_Tab_Loawb extends Mage_Adminhtml_Block_Sales_Order_Abstract
4
+ implements Mage_Adminhtml_Block_Widget_Tab_Interface
5
+ {
6
+
7
+ protected function _construct()
8
+ {
9
+ parent::_construct();
10
+ $this->setTemplate('livrarionline/sales/order/view/loawb.phtml');
11
+
12
+ Mage::Log("LO AWB Tab Created");
13
+ }
14
+
15
+ /**
16
+ * Retrieve order model instance
17
+ *
18
+ * @return Mage_Sales_Model_Order
19
+ */
20
+ public function getOrder()
21
+ {
22
+ return Mage::registry('current_order');
23
+ }
24
+
25
+ /**
26
+ * Retrieve source model instance
27
+ *
28
+ * @return Mage_Sales_Model_Order
29
+ */
30
+ public function getSource()
31
+ {
32
+ return $this->getOrder();
33
+ }
34
+
35
+
36
+ public function getTabLabel()
37
+ {
38
+ return Mage::helper('sales')->__('LO AWB');
39
+ }
40
+
41
+ public function getTabTitle()
42
+ {
43
+ return Mage::helper('sales')->__('LivrariOnline Manage AWB');
44
+ }
45
+
46
+ public function canShowTab()
47
+ {
48
+ return true;
49
+ }
50
+
51
+ public function isHidden()
52
+ {
53
+ return false;
54
+ }
55
+ }
app/code/local/Xtreme/Livrarionline/Block/Livrarionline.php ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_Block_Livrarionline extends Mage_Core_Block_Template
3
+ {
4
+ public function _prepareLayout()
5
+ {
6
+ return parent::_prepareLayout();
7
+ }
8
+
9
+ public function getLivrarionline()
10
+ {
11
+ if (!$this->hasData('livrarionline')) {
12
+ $this->setData('livrarionline', Mage::registry('livrarionline'));
13
+ }
14
+ return $this->getData('livrarionline');
15
+
16
+ }
17
+ }
app/code/local/Xtreme/Livrarionline/Helper/Data.php ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ ini_set("memory_limit", "1G");
3
+ require_once('lib/LivrariOnline/lo.php');
4
+ class Xtreme_Livrarionline_Helper_Data extends Mage_Core_Helper_Abstract
5
+ {
6
+ protected $_code = 'livrarionline';
7
+
8
+ public function createAwbFromOrder($awb_id)
9
+ {
10
+ $awb = Mage::getModel('livrarionline/awb')->load($awb_id);
11
+ $parcels = Mage::getModel('livrarionline/awb_parcels')->getCollection();
12
+ $parcels->addFieldToFilter('awb_id', $awb_id);
13
+ $order = Mage::getModel('sales/order')->load($awb->getOrderId());
14
+ $carrier = Mage::getModel('livrarionline/carriers')->load($awb->getServiceId());
15
+
16
+ $billing = $order->getBillingAddress();
17
+ $shipping = $order->getShippingAddress();
18
+
19
+ $login_id = Mage::getStoreConfig('carriers/'.$this->_code.'/login_id');
20
+ $security_key = Mage::getStoreConfig('carriers/'.$this->_code.'/security_key');
21
+ $carrier_id = Mage::getStoreConfig('carriers/'.$this->_code.'/carrier_id');
22
+ $store = Mage::app()->getStore();
23
+ $name = $store->getName();
24
+
25
+ $price = 0;
26
+
27
+ $f_request_awb = array();
28
+ $f_request_awb['f_shipping_company_id'] = (int) $carrier->getShippingCompanyId(); // int obligatoriu
29
+ $f_request_awb['request_data_ridicare'] = '2013-11-28'; // date Y-m-d optional
30
+ $f_request_awb['request_ora_ridicare'] = '14:00:00'; // time without time zone H:i:s optional
31
+ $f_request_awb['request_ora_ridicare_end'] = '14:00:00'; // time without time zone optional
32
+ $f_request_awb['request_ora_livrare_sambata'] = '14:00:00'; // time without time zone optional
33
+ $f_request_awb['request_ora_livrare_end_sambata'] = '14:00:00'; // time without time zone optional
34
+ $f_request_awb['request_ora_livrare'] = '14:00:00'; // time without time zone optional
35
+ $f_request_awb['request_ora_livrare_end'] = '14:00:00'; // time without time zone optional
36
+ $f_request_awb['descriere_livrare'] = $awb->getDescription();
37
+ $f_request_awb['referinta_expeditor'] = $awb->getReference(); // varchar(255) Obligatoriu
38
+ $f_request_awb['valoare_declarata'] = $awb->getDeclaredValue(); // decimal(10,2) Obligatoriu
39
+ $f_request_awb['ramburs'] = $awb->getCod(); // decimal(10,2) Obligatoriu
40
+ $f_request_awb['asigurare_la_valoarea_declarata'] = (bool) $awb->getInsurance(); // Boolean Obligatoriu
41
+ $f_request_awb['retur_documente'] = (bool) $awb->getReturndocs(); // boolean optional
42
+ $f_request_awb['retur_documente_bancare'] = (bool) $awb->getReturndocsbank(); // boolean optional
43
+ $f_request_awb['confirmare_livrare'] = (bool) $awb->getDeliveryconf(); // boolean optional
44
+ $f_request_awb['livrare_sambata'] = (bool) $awb->getDeliverysat(); // Boolean optional
45
+ $f_request_awb['currency'] = ($awb->getDeclaredValue() > 0) ? $awb->getCurrency() : ''; // char(3) Obligatoriu cand "valoare_declarata" > 0
46
+ $f_request_awb['currency_ramburs'] = ($awb->getCod() > 0) ? $awb->getCod() : ''; // char(3) Obligatoriu cand "ramburs" > 0
47
+ $f_request_awb['notificare_email']= (bool) $awb->getEmailnotify(); // Boolean optional
48
+ $f_request_awb['notificare_sms'] = (bool) $awb->getSmsnotify(); // Boolean optional
49
+ $f_request_awb['cine_plateste'] = $awb->getPayee(); // 0 - merchant,2 - destinatar,1 - expeditor Obligatoriu
50
+ $f_request_awb['serviciuid']= (int) $carrier->getServiceId(); // int Obligatoriu
51
+ $f_request_awb['request_mpod'] = false; // Boolean optional
52
+
53
+ $colete = array();
54
+ foreach($parcels as $item)
55
+ {
56
+ $colete[] = array(
57
+ 'greutate'=> (float) (($item->getWeight() > 0) ? $item->getWeight() : 1), // decimal 10,2 kg
58
+ 'lungime'=> ($item->getLength() > 0) ? $item->getLength() : 1, // integer cm
59
+ 'latime'=> ($item->getWidth() > 0) ? $item->getWidth() : 1, // integer cm
60
+ 'inaltime'=> ($item->getHeight() > 0) ? $item->getHeight() : 1, // integer cm
61
+ 'continut'=> $item->getContent(), // int 1;"Acte" 2;"Tipizate" 3;"Fragile" 4;"Generale"
62
+ 'tipcolet'=> $item->getParcelType() // int 1;"Plic"2;"Colet"3;"Palet"11
63
+ );
64
+ }
65
+
66
+ $f_request_awb['colete'] = $colete;
67
+
68
+ $f_request_awb['destinatar'] = array(
69
+ 'first_name' => $billing->getFirstname(), //Obligatoriu
70
+ 'last_name'=> $billing->getLastname(), //Obligatoriu
71
+ 'email' => $billing->getEmail(), //Obligatoriu
72
+ 'phone' => $billing->getTelephone(), //phone sau mobile Obligatoriu
73
+ 'mobile' => '',
74
+ 'lang' => 'ro', //Obligatoriu ro/en
75
+ 'company_name' => ($billing->getCompany()) ? $billing->getCompany() : '', //optional
76
+ 'j' => '', //optional
77
+ 'bank_account' => '', //optional
78
+ 'bank_name' => '', //optional
79
+ 'cui' => ''//optional
80
+ );
81
+
82
+ //$region = Mage::getModel('directory/region')->load($shipping->getRegionId());
83
+ $country = Mage::getModel('directory/country')->loadByCode($shipping->getCountryId());
84
+ //$street = explode("\n", $shipping->getStreet());
85
+ $street = $shipping->getStreet();
86
+ $f_request_awb['shipTOaddress'] = array(
87
+ //Obligatoriu
88
+ 'address1' => $street[0],
89
+ 'address2' => (count($street) == 2) ? $street[1] : '',
90
+ 'city' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $shipping->getCity()),
91
+ //'state' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $region->getName()),
92
+ 'state' => "Bucuresti",
93
+ 'zip' => $shipping->getPostcode(),
94
+ 'country' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $country->getName()),
95
+ 'phone' => $shipping->getTelephone(),
96
+ 'observatii'=> 'Observatii de test'
97
+ );
98
+
99
+ //$region = Mage::getModel('directory/region')->load($request->getRegionId());
100
+ $lo_store = Mage::getModel('livrarionline/stores')->load($awb->getPickFrom());
101
+ $region = $country = '';
102
+ if($lo_store->getCountry())
103
+ {
104
+ $region = Mage::getModel('directory/region')->loadByCode($lo_store->getState(), $lo_store->getCountry())->getName();
105
+ $country = Mage::getModel('directory/country')->loadByCode($lo_store->getCountry());
106
+ $country = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $country->getName());
107
+ }
108
+ $f_request_awb['shipFROMaddress'] = array(
109
+ 'email' => $lo_store->getEmail(),
110
+ 'first_name' => $lo_store->getFirstname(),
111
+ 'last_name' => $lo_store->getLastname(),
112
+ 'mobile' => '',
113
+ 'main_address' => $lo_store->getAddress1(),
114
+ 'city' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $lo_store->getCity()),
115
+ 'state' => $region,
116
+ 'zip' => $lo_store->getZipcode(),
117
+ 'country' => $country,
118
+ 'phone' => $lo_store->getPhone(),
119
+ 'instructiuni' => ''
120
+ );
121
+
122
+ //print_r($f_request_awb);exit;
123
+
124
+ Mage::log(var_export($f_request_awb, true));
125
+
126
+ $lo = new LO ();
127
+
128
+ $lo->f_login = $login_id;
129
+ $lo->setRSAKey($security_key);
130
+
131
+ $response_awb = $lo->GenerateAwb($f_request_awb);
132
+ Mage::log($response_awb);
133
+
134
+ //raspuns generare AWB
135
+ if ((isset($response_awb->status) && $response_awb->status == 'error') || empty($response_awb))
136
+ {
137
+ Mage::log("Error livrarionline:");
138
+ throw new Exception("Error livrarionline (response + f_request_awb dump):<br/>"."<pre>".print_r($response_awb, true).print_r($f_request_awb, true)."</pre>");
139
+ return false;
140
+ }
141
+ else
142
+ return $response_awb->f_awb_collection[0]; //array de awb-uri (awb pe fiecare colet)
143
+ }
144
+
145
+ public function getEstimate($carrier, $quote)
146
+ {
147
+ $shipping = $quote->getShippingAddress();
148
+ if(!$shipping->getRegionId() ||
149
+ !$shipping->getCity() ||
150
+ !$shipping->getPostcode() ||
151
+ !$shipping->getFirstname())
152
+ return 0;
153
+
154
+ if($quote->getCustomerId())
155
+ {
156
+ $cust = Mage::getModel('customer/customer')->load($quote->getCustomerId());
157
+ }
158
+
159
+ $default_store = Mage::getModel('livrarionline/stores')->getCollection()
160
+ ->addFieldToFilter('`default`', 1)
161
+ ->addFieldToFilter('`status`', 1)
162
+ ->getFirstItem();
163
+
164
+ $billing = $quote->getBillingAddress();
165
+ //$shipping = $quote->getShippingAddress();
166
+
167
+ $cartItems = $quote->getAllVisibleItems();
168
+
169
+ $login_id = Mage::getStoreConfig('carriers/'.$this->_code.'/login_id');
170
+ $security_key = Mage::getStoreConfig('carriers/'.$this->_code.'/security_key');
171
+ $store = Mage::app()->getStore();
172
+ $name = $store->getName();
173
+
174
+ $price = 0;
175
+
176
+ $f_request_awb = array();
177
+ $f_request_awb['f_shipping_company_id'] = (int) $carrier->getShippingCompanyId(); // int obligatoriu
178
+ $f_request_awb['request_data_ridicare'] = date('Y-m-d'); // date Y-m-d optional
179
+ $f_request_awb['request_ora_ridicare'] = date('H:i:s'); // time without time zone H:i:s optional
180
+ $f_request_awb['request_ora_ridicare_end'] = date('H:i:s'); // time without time zone optional
181
+ $f_request_awb['request_ora_livrare_sambata'] = date('H:i:s'); // time without time zone optional
182
+ $f_request_awb['request_ora_livrare_end_sambata'] = date('H:i:s'); // time without time zone optional
183
+ $f_request_awb['request_ora_livrare'] = date('H:i:s'); // time without time zone optional
184
+ $f_request_awb['request_ora_livrare_end'] = date('H:i:s'); // time without time zone optional
185
+ $f_request_awb['descriere_livrare'] = 'Estimare pret '.$name;
186
+ $f_request_awb['referinta_expeditor'] = ''; // varchar(255) Obligatoriu
187
+ $f_request_awb['valoare_declarata'] = $quote->getGrandTotal(); // decimal(10,2) Obligatoriu
188
+ $f_request_awb['ramburs'] = $quote->getGrandTotal(); // decimal(10,2) Obligatoriu
189
+ $f_request_awb['asigurare_la_valoarea_declarata'] = false; // Boolean Obligatoriu
190
+ $f_request_awb['retur_documente'] = false; // boolean optional
191
+ $f_request_awb['retur_documente_bancare'] = false; // boolean optional
192
+ $f_request_awb['confirmare_livrare'] = false; // boolean optional
193
+ $f_request_awb['livrare_sambata'] = false; // Boolean optional
194
+ $f_request_awb['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode(); // char(3) Obligatoriu cand "valoare_declarata" > 0
195
+ $f_request_awb['currency_ramburs'] = Mage::app()->getStore()->getCurrentCurrencyCode(); // char(3) Obligatoriu cand "ramburs" > 0
196
+ $f_request_awb['notificare_email'] = false; // Boolean optional
197
+ $f_request_awb['notificare_sms'] = false; // Boolean optional
198
+ $f_request_awb['cine_plateste'] = 0; // 0 - merchant,2 - destinatar,1 - expeditor Obligatoriu
199
+ $f_request_awb['serviciuid'] = (int) $carrier->getServiceId(); // int Obligatoriu
200
+ $f_request_awb['request_mpod'] = false; // Boolean optional
201
+
202
+ $colete = array();
203
+ foreach ($cartItems as $item)
204
+ {
205
+ $colete[] = array(
206
+ 'greutate' => (float) (($item->getWeight() > 0) ? $item->getWeight() : 1), // decimal 10,2 kg
207
+ 'lungime' => ($item->getLength() > 0) ? $item->getLength() : 1, // integer cm
208
+ 'latime' => ($item->getWidth() > 0) ? $item->getWidth() : 1, // integer cm
209
+ 'inaltime' => ($item->getHeight() > 0) ? $item->getHeight() : 1, // integer cm
210
+ 'continut' => 1,
211
+ 'tipcolet' => 1,
212
+ );
213
+ }
214
+
215
+ $f_request_awb['colete'] = $colete;
216
+
217
+ $f_request_awb['destinatar'] = array(
218
+ 'first_name' => $billing->getFirstname(), //Obligatoriu
219
+ 'last_name'=> $billing->getLastname(), //Obligatoriu
220
+ 'email' => $billing->getEmail(), //Obligatoriu
221
+ 'phone' => $billing->getTelephone(), //phone sau mobile Obligatoriu
222
+ 'mobile' => '',
223
+ 'lang' => 'ro', //Obligatoriu ro/en
224
+ 'company_name' => ($billing->getCompany()) ? $billing->getCompany() : '', //optional
225
+ 'j' => '', //optional
226
+ 'bank_account' => '', //optional
227
+ 'bank_name' => '', //optional
228
+ 'cui' => ''//optional
229
+ );
230
+
231
+ $region = Mage::getModel('directory/region')->load($shipping->getRegionId());
232
+ $country = Mage::getModel('directory/country')->loadByCode($shipping->getCountryId());
233
+ //$street = explode("\n", $shipping->getStreet());
234
+ $street = $shipping->getStreet();
235
+ $f_request_awb['shipTOaddress'] = array(
236
+ //Obligatoriu
237
+ 'address1' => $street[0],
238
+ 'address2' => (count($street) == 2) ? $street[1] : '',
239
+ 'city' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $shipping->getCity()),
240
+ 'state' => iconv("UTF-8", "ISO-8859-16//TRANSLIT", $region->getName()),
241
+ 'state' => self::toLatin1($region->getName()),
242
+ 'zip' => $shipping->getPostcode(),
243
+ 'country' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $country->getName()),
244
+ 'phone' => $shipping->getTelephone(),
245
+ 'observatii'=> 'Observatii de test'
246
+ );
247
+
248
+ $region = $country = '';
249
+ if($default_store->getCountry())
250
+ {
251
+ $region = Mage::getModel('directory/region')->loadByCode($default_store->getState(), $default_store->getCountry())->getName();
252
+ $country = Mage::getModel('directory/country')->loadByCode($default_store->getCountry());
253
+ $country = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $country->getName());
254
+ }
255
+ $f_request_awb['shipFROMaddress'] = array(
256
+ 'email' => Mage::getStoreConfig('carriers/livrarionline/shipfrom_email'),
257
+ 'first_name' => Mage::getStoreConfig('carriers/livrarionline/shipfrom_firstname'),
258
+ 'last_name' => Mage::getStoreConfig('carriers/livrarionline/shipfrom_lastname'),
259
+ 'mobile' => '',
260
+ 'main_address' => $default_store->getAddress1(),
261
+ 'city' => iconv("UTF-8", "ISO-8859-1//TRANSLIT", $default_store->getCity()),
262
+ 'state' => $region,
263
+ 'zip' => $default_store->getZipcode(),
264
+ 'country' => $country,
265
+ 'phone' => $default_store->getPhone(),
266
+ 'instructiuni' => ''
267
+ );
268
+
269
+ //print_r($f_request_awb);exit;
270
+
271
+ Mage::log(var_export($f_request_awb, true));
272
+
273
+ $lo = new LO ();
274
+
275
+ $lo->f_login = $login_id;
276
+ $lo->setRSAKey($security_key);
277
+
278
+ $response_awb = $lo->EstimeazaPret($f_request_awb);
279
+ Mage::log($response_awb);
280
+
281
+ //raspuns generare AWB
282
+ if ((isset($response_awb->status) && $response_awb->status == 'error') || empty($response_awb))
283
+ {
284
+ if($response_awb->message == 'Pretul nu se poate calcula.') return false;
285
+
286
+ Mage::log("Error livrarionline:");
287
+ throw new Exception("Error livrarionline (response + f_request_awb dump):<br/>"."<pre>".print_r($response_awb, true).print_r($f_request_awb, true)."</pre>");
288
+ return false;
289
+ }
290
+ else
291
+ return $response_awb->f_pret; //array de awb-uri (awb pe fiecare colet)
292
+ }
293
+
294
+ public function printAWB($awb_id)
295
+ {
296
+ $login_id = Mage::getStoreConfig('carriers/'.$this->_code.'/login_id');
297
+ $security_key = Mage::getStoreConfig('carriers/'.$this->_code.'/security_key');
298
+
299
+ $awb = Mage::getModel('livrarionline/awb')->load($awb_id);
300
+ $url = sprintf("http://api.livrarionline.ro/Lobackend_print/PrintAwb.aspx?f_login=%s&awb=%s", $login_id, $awb->getAwbNo());
301
+
302
+ $client = new Zend_Http_Client($url);
303
+ $response = $client->request();
304
+
305
+ return $response->getBody();
306
+ }
307
+
308
+ public function cancelAWB($awb_id)
309
+ {
310
+ $login_id = Mage::getStoreConfig('carriers/'.$this->_code.'/login_id');
311
+ $security_key = Mage::getStoreConfig('carriers/'.$this->_code.'/security_key');
312
+
313
+ $awb = Mage::getModel('livrarionline/awb')->load($awb_id);
314
+ $f_request_cancel = array('awb'=>$awb->getAwbNo());
315
+ $lo = new LO ();
316
+
317
+ $lo->f_login = $login_id;
318
+ $lo->setRSAKey($security_key);
319
+
320
+ $response_cancel = $lo->CancelLivrare($f_request_cancel);
321
+ Mage::log($response_cancel);
322
+
323
+ //raspuns generare AWB
324
+ if ((isset($response_cancel->status) && $response_cancel->status == 'error') || empty($response_cancel))
325
+ {
326
+ //if($response_cancel->message == 'Pretul nu se poate calcula.') return false;
327
+
328
+ Mage::log("Error livrarionline:");
329
+ throw new Exception("Error livrarionline (response + f_request_cancel dump):<br/>"."<pre>".print_r($response_cancel, true).print_r($f_request_cancel, true)."</pre>");
330
+ return false;
331
+ }
332
+ else
333
+ return $response_cancel->status;
334
+ }
335
+
336
+ public function trackAWB($awb_no)
337
+ {
338
+ $login_id = Mage::getStoreConfig('carriers/'.$this->_code.'/login_id');
339
+ $security_key = Mage::getStoreConfig('carriers/'.$this->_code.'/security_key');
340
+
341
+ //$awb = Mage::getModel('livrarionline/awb')->load($awb_id);
342
+ $f_request_cancel = array('awb'=>$awb_no);
343
+ $lo = new LO ();
344
+
345
+ $lo->f_login = $login_id;
346
+ $lo->setRSAKey($security_key);
347
+
348
+ $response = $lo->Tracking($f_request_cancel);
349
+ Mage::log($response);
350
+
351
+ //raspuns generare AWB
352
+ if ((isset($response->status) && $response->status == 'error') || empty($response))
353
+ {
354
+ //if($response_cancel->message == 'Pretul nu se poate calcula.') return false;
355
+
356
+ Mage::log("Error livrarionline:");
357
+ throw new Exception("Error livrarionline (response + f_request_cancel dump):<br/>"."<pre>".print_r($response, true).print_r($f_request_cancel, true)."</pre>");
358
+ return false;
359
+ }
360
+ else
361
+ return $response;
362
+ }
363
+
364
+ private function toLatin1($str) {
365
+ //Mage::log($str);
366
+
367
+ $from = array('ş', 'ş', 'Ş', 'Ș', 'ț', 'ţ', 'Ţ', 'Ț', 'Ă', 'ă', 'Â', 'â', 'Î', 'î');
368
+ $to = array('s', 's', 'S', 'S', 't', 't', 'T', 'T', 'A', 'a', 'A', 'a', 'I', 'i');
369
+ $str = str_replace($from, $to, $str);
370
+
371
+ //Mage::log($str);
372
+ $str = preg_replace('@[^a-z0-9 \-\.\(\)\,]+@iUs', '', $str);
373
+ //Mage::log($str);
374
+
375
+ return $str;
376
+ }
377
+ }
app/code/local/Xtreme/Livrarionline/Model/Awb.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Awb extends Mage_Core_Model_Abstract
4
+ {
5
+ const TIPCOLET_PLIC = 1;
6
+ const TIPCOLET_COLET = 2;
7
+ const TIPCOLET_PALET = 3;
8
+
9
+ const PARCELCONTENT_ACTE = 1;
10
+ const PARCELCONTENT_TIPIZATE = 2;
11
+ const PARCELCONTENT_FRAGILE = 3;
12
+ const PARCELCONTENT_GENERALE = 4;
13
+
14
+ const STATUS_ENABLED = 1;
15
+ const STATUS_CANCELLED = 2;
16
+
17
+ public function _construct()
18
+ {
19
+ parent::_construct();
20
+ $this->_init('livrarionline/awb');
21
+ }
22
+
23
+ static public function getTipColetOptionArray()
24
+ {
25
+ return array(
26
+ self::TIPCOLET_PLIC => Mage::helper('livrarionline')->__('Envelope'),
27
+ self::TIPCOLET_COLET => Mage::helper('livrarionline')->__('Parcel'),
28
+ self::TIPCOLET_PALET => Mage::helper('livrarionline')->__('Palet')
29
+ );
30
+ }
31
+
32
+ static public function getParcelContentOptionArray()
33
+ {
34
+ return array(
35
+ self::PARCELCONTENT_ACTE => Mage::helper('livrarionline')->__('Documents'),
36
+ self::PARCELCONTENT_TIPIZATE => Mage::helper('livrarionline')->__('Preprinted'),
37
+ self::PARCELCONTENT_FRAGILE => Mage::helper('livrarionline')->__('Fragile'),
38
+ self::PARCELCONTENT_GENERALE => Mage::helper('livrarionline')->__('General')
39
+ );
40
+ }
41
+
42
+ static public function getStatusOptionArray()
43
+ {
44
+ return array(
45
+ self::STATUS_ENABLED => Mage::helper('livrarionline')->__('Enabled'),
46
+ self::STATUS_CANCELLED => Mage::helper('livrarionline')->__('Cancelled')
47
+ );
48
+ }
49
+ }
app/code/local/Xtreme/Livrarionline/Model/Awb/Parcels.php ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Awb_Parcels extends Mage_Core_Model_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/awb_parcels');
9
+ }
10
+ }
11
+
app/code/local/Xtreme/Livrarionline/Model/Carrier/Livrarionline.php ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ //ini_set("memory_limit", "1G");
3
+ require_once('lib/LivrariOnline/lo.php');
4
+ class Xtreme_Livrarionline_Model_Carrier_Livrarionline extends Mage_Shipping_Model_Carrier_Abstract
5
+ implements Mage_Shipping_Model_Carrier_Interface {
6
+ protected $_code = 'livrarionline';
7
+
8
+ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
9
+ {
10
+ if (!Mage::getStoreConfig('carriers/'.$this->_code.'/active')) {
11
+ return false;
12
+ }
13
+
14
+ $quote = Mage::getSingleton('checkout/session')->getQuote();
15
+
16
+ $handling = Mage::getStoreConfig('carriers/'.$this->_code.'/handling');
17
+ $result = Mage::getModel('shipping/rate_result');
18
+ $show = true;
19
+ $carriers = Mage::getModel('livrarionline/carriers')->getCollection();
20
+ foreach($carriers as $carrier)
21
+ {
22
+ $price_res = Mage::helper('livrarionline')->getEstimate($carrier, $quote);
23
+
24
+ if($price_res){
25
+ $method = Mage::getModel('shipping/rate_result_method');
26
+ $method->setCarrier($this->_code);
27
+ $method->setMethod($this->_code."_".$carrier->getCarrierId());
28
+ $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
29
+ $method->setMethodTitle($carrier->getName());
30
+ $method->setPrice($price_res);
31
+ $method->setCost($price_res);
32
+ $result->append($method);
33
+ }
34
+ /*else
35
+ {
36
+ $error = Mage::getModel('shipping/rate_result_error');
37
+ $error->setCarrier($this->_code);
38
+ $error->setCarrierTitle($this->getConfigData('name'));
39
+ $error->setErrorMessage($this->getConfigData('specificerrmsg'));
40
+ $result->append($error);
41
+ }*/
42
+ }
43
+
44
+ return $result;
45
+
46
+ /*
47
+ //Case1: Price Depends on Country,State and Pin Code
48
+ echo $destCountry = $request->getDestCountryId().': Dest Country<br/>';
49
+ echo $destRegion = $request->getDestRegionId().': Dest Region<br/>';
50
+ echo $destRegionCode = $request->getDestRegionCode().': Dest Region Code<br/>';
51
+ print_r($destStreet = $request->getDestStreet()); echo ': Dest Street<br/>';
52
+ echo $destCity = $request->getDestCity().': Dest City<br/>';
53
+ echo $destPostcode = $request->getDestPostcode().': Dest Postcode<br/>';
54
+ echo $country_id = $request->getCountryId().': Package Source Country ID<br/>';
55
+ echo $region_id = $request->getRegionId().': Package Source Region ID<br/>';
56
+ echo $city = $request->getCity().': Package Source City<br/>';
57
+ echo $postcode = $request->getPostcode().': Package Source Post Code<br/>';
58
+
59
+ //Case2: Price Depends on Total Order Value or Weight
60
+ echo $packageValue = $request->getPackageValue().': Dest Package Value<br/>';
61
+ echo $packageValueDiscout = $request->getPackageValueWithDiscount().': Dest Package Value After Discount<br/>';
62
+ echo $packageWeight = $request->getPackageWeight().': Package Weight<br/>';
63
+ echo $packageQty = $request->getPackageQty().': Package Quantity <br/>';
64
+ echo $packageCurrency = $request->getPackageCurrency().': Package Currency <br/>';
65
+
66
+ //Case3: Price Depends on order dimensions
67
+ echo $packageheight = $request->getPackageHeight() .': Package height <br/>';
68
+ echo $request->getPackageWeight().': Package Width <br/>';
69
+ echo $request->getPackageDepth().': Package Depth <br/>';
70
+
71
+
72
+
73
+ //Case4: Price based on product attribute
74
+ if ($request->getAllItems()) {
75
+ foreach ($request->getAllItems() as $item) {
76
+ if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
77
+ continue;
78
+ }
79
+
80
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
81
+ foreach ($item->getChildren() as $child) {
82
+ if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
83
+ $product_id = $child->getProductId();
84
+ $productObj = Mage::getModel('catalog/product')->load($product_id);
85
+ $ship_price = $productObj->getData('shipping_price'); //our shipping attribute code
86
+ $price += (float)$ship_price;
87
+ }
88
+ }
89
+ } else {
90
+ $product_id = $item->getProductId();
91
+ $productObj = Mage::getModel('catalog/product')->load($product_id);
92
+ $ship_price = $productObj->getData('shipping_price'); //our shipping attribute code
93
+ $price += (float)$ship_price;
94
+ }
95
+ }
96
+ }
97
+
98
+ //Case5: Shipping option based configurable product option
99
+ if ($request->getAllItems()) {
100
+ foreach ($request->getAllItems() as $item) {
101
+ if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
102
+ continue;
103
+ }
104
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
105
+ foreach ($item->getChildren() as $child) {
106
+ if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
107
+ $product_id = $child->getProductId();
108
+ $value = $item->getOptionByCode('info_buyRequest')->getValue();
109
+ $params = unserialize($value);
110
+ $attributeObj = Mage::getModel('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY,'shirt_size'); // our configurable attribute
111
+ $attribute_id = $attributeObj->getAttributeId();
112
+ $attribute_selected = $params['super_attribute'][$attribute_id];
113
+
114
+ $label = '';
115
+ foreach($attributeObj->getSource()->getAllOptions(false) as $option){
116
+ if($option['value'] == $attribute_selected){
117
+ $label = $option['label'];
118
+ }
119
+ }
120
+ if($label = 'Small'){
121
+ $price += 15;
122
+ } else if($label = 'Medium'){
123
+ $price += 20;
124
+ } else if($label = 'Large'){
125
+ $price += 22;
126
+ }
127
+ }
128
+ }
129
+ } else {
130
+ $product_id = $item->getProductId();
131
+ $value = $item->getOptionByCode('info_buyRequest')->getValue();
132
+ $params = unserialize($value);
133
+ $attributeObj = Mage::getModel('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY,'shirt_size'); // our configurable attribute
134
+ $attribute_id = $attributeObj->getAttributeId();
135
+ $attribute_selected = $params['super_attribute'][$attribute_id];
136
+
137
+ $label = '';
138
+ foreach($attributeObj->getSource()->getAllOptions(false) as $option){
139
+ if($option['value'] == $attribute_selected){
140
+ $label = $option['label'];
141
+ }
142
+ }
143
+ if($label = 'Small'){
144
+ $price += 15;
145
+ } else if($label = 'Medium'){
146
+ $price += 20;
147
+ } else if($label = 'Large'){
148
+ $price += 22;
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+
155
+ //Case6: Price based on custom options
156
+ if ($request->getAllItems()) {
157
+ foreach ($request->getAllItems() as $item) {
158
+ if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
159
+ continue;
160
+ }
161
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
162
+ foreach ($item->getChildren() as $child) {
163
+ if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
164
+ $product_id = $child->getProductId();
165
+ $value = $item->getOptionByCode('info_buyRequest')->getValue();
166
+ $params = unserialize($value);
167
+ $options_select = $params['options'];
168
+
169
+ $product = Mage::getModel('catalog/product')->load($product_id);
170
+ $options = $product->getOptions();
171
+ foreach ($options as $option) {
172
+ if ($option->getGroupByType() == Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
173
+ $option_id = $option->getId();
174
+ foreach ($option->getValues() as $value) {
175
+ if($value->getId() == $options_select[$option_id]){
176
+ if($value->getTitle() == 'Express'){
177
+ $price += 50;
178
+ }else if($value->getTitle() == 'Normal'){
179
+ $price += 10;
180
+ }
181
+ }
182
+
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+ } else {
189
+ $product_id = $item->getProductId();
190
+ $value = $item->getOptionByCode('info_buyRequest')->getValue();
191
+ $params = unserialize($value);
192
+ $options_select = $params['options'];
193
+
194
+ $product = Mage::getModel('catalog/product')->load($product_id);
195
+ $options = $product->getOptions();
196
+ foreach ($options as $option) {
197
+ if ($option->getGroupByType() == Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
198
+ $option_id = $option->getId();
199
+ foreach ($option->getValues() as $value) {
200
+ if($value->getId() == $options_select[$option_id]){
201
+ if($value->getTitle() == 'Express'){
202
+ $price += 50;
203
+ }else if($value->getTitle() == 'Normal'){
204
+ $price += 10;
205
+ }
206
+ }
207
+
208
+ }
209
+ }
210
+ }
211
+ }
212
+ }
213
+ }
214
+ */
215
+ }
216
+ public function getAllowedMethods()
217
+ {
218
+ return array('livrarionline'=>$this->getConfigData('name'));
219
+ }
220
+
221
+ public function isTrackingAvailable()
222
+ {
223
+ return true;
224
+ }
225
+
226
+ public function getTrackingInfo($tracking)
227
+ {
228
+ $awb_res = Mage::helper('livrarionline')->trackAWB($tracking);
229
+ $track = Mage::getModel('shipping/tracking_result_status');
230
+ $track->setTrackSummary( sprintf("%s : %s", $awb_res->f_stare_curenta->stamp, $awb_res->f_stare_curenta->stare) )
231
+ ->setTracking($tracking)
232
+ ->setCarrierTitle($this->getConfigData('name'));
233
+ return $track;
234
+ }
235
+ }
app/code/local/Xtreme/Livrarionline/Model/Carriers.php ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Carriers extends Mage_Core_Model_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/carriers');
9
+ }
10
+
11
+ public function toOptionArray()
12
+ {
13
+ $collection = $this->getCollection()->addFieldToFilter("status", Xtreme_Livrarionline_Model_Status::STATUS_ENABLED);
14
+ $arr = array();
15
+ foreach ($collection as $carrier) {
16
+ $arr[] = array('value'=>$carrier->getId(), 'label'=>$carrier->getName());
17
+ }
18
+ return $arr;
19
+ }
20
+ }
app/code/local/Xtreme/Livrarionline/Model/Livrarionline.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Livrarionline extends Mage_Core_Model_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/livrarionline');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Awb extends Mage_Core_Model_Mysql4_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ // Note that the awb_id refers to the key field in your database table.
8
+ $this->_init('livrarionline/awb', 'awb_id');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Collection.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Awb_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/awb');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Parcels.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Awb_Parcels extends Mage_Core_Model_Mysql4_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ // Note that the awb_id refers to the key field in your database table.
8
+ $this->_init('livrarionline/awb_parcels', 'parcel_id');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Awb/Parcels/Collection.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Awb_Parcels_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/awb_parcels');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Carriers.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Carriers extends Mage_Core_Model_Mysql4_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ // Note that the livrarionline_id refers to the key field in your database table.
8
+ $this->_init('livrarionline/carriers', 'carrier_id');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Carriers/Collection.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Carriers_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/carriers');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Livrarionline.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Livrarionline extends Mage_Core_Model_Mysql4_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ // Note that the livrarionline_id refers to the key field in your database table.
8
+ $this->_init('livrarionline/livrarionline', 'livrarionline_id');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Livrarionline/Collection.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Livrarionline_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/livrarionline');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Stores.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Stores extends Mage_Core_Model_Mysql4_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ // Note that the livrarionline_id refers to the key field in your database table.
8
+ $this->_init('livrarionline/stores', 'store_id');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Mysql4/Stores/Collection.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Mysql4_Stores_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/stores');
9
+ }
10
+ }
app/code/local/Xtreme/Livrarionline/Model/Payee.php ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Payee extends Varien_Object
4
+ {
5
+ const PAYEE_MERCHANT = 1;
6
+ const PAYEE_DESTINATAR = 2;
7
+ const PAYEE_EXPEDITOR = 3;
8
+
9
+ static public function getOptionArray()
10
+ {
11
+ return array(
12
+ self::PAYEE_MERCHANT => Mage::helper('livrarionline')->__('Merchant'),
13
+ self::PAYEE_DESTINATAR => Mage::helper('livrarionline')->__('Destinatar'),
14
+ self::PAYEE_EXPEDITOR => Mage::helper('livrarionline')->__('Expeditor')
15
+ );
16
+ }
17
+ }
app/code/local/Xtreme/Livrarionline/Model/Status.php ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Status extends Varien_Object
4
+ {
5
+ const STATUS_ENABLED = 1;
6
+ const STATUS_DISABLED = 2;
7
+
8
+ static public function getOptionArray()
9
+ {
10
+ return array(
11
+ self::STATUS_ENABLED => Mage::helper('livrarionline')->__('Enabled'),
12
+ self::STATUS_DISABLED => Mage::helper('livrarionline')->__('Disabled')
13
+ );
14
+ }
15
+ }
app/code/local/Xtreme/Livrarionline/Model/Stores.php ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Model_Stores extends Mage_Core_Model_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('livrarionline/stores');
9
+ }
10
+
11
+ public function toOptionArray()
12
+ {
13
+ $collection = $this->getCollection()->addFieldToFilter("status", Xtreme_Livrarionline_Model_Status::STATUS_ENABLED);
14
+ $arr = array();
15
+ foreach ($collection as $store) {
16
+ $arr[] = array('value'=>$store->getId(), 'label'=>$store->getName());
17
+ }
18
+ return $arr;
19
+ }
20
+
21
+ public function toggleStoresDefault($store_id)
22
+ {
23
+ $resource = Mage::getSingleton('core/resource');
24
+ $tableName = $this->getResource()->getMainTable();
25
+ $sql = "UPDATE `${tableName}` SET `default` = '0' WHERE `store_id` != '${store_id}'";
26
+ $write = $resource->getConnection('core_write');
27
+ $write->query($sql);
28
+ }
29
+ }
app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/AwbController.php ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Adminhtml_AwbController extends Mage_Adminhtml_Controller_Action
4
+ {
5
+ protected function _initAction() {
6
+ $this->loadLayout()
7
+ //->_setActiveMenu('livrarionline/items')
8
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('LO Create AWB'), Mage::helper('adminhtml')->__('LO Create AWB'));
9
+ $order_id = $this->getRequest()->getParam('order_id');
10
+ $order = Mage::getModel("sales/order")->load($order_id);
11
+ $block = $this->getLayout()->getBlock("lo_awb");
12
+ $block->setOrder($order);
13
+ return $this;
14
+ }
15
+
16
+ public function indexAction() {
17
+ $this->_initAction()->renderLayout();
18
+ }
19
+
20
+ public function editAction() {
21
+ $id = $this->getRequest()->getParam('id');
22
+ $model = Mage::getModel('livrarionline/livrarionline')->load($id);
23
+
24
+ if ($model->getId() || $id == 0) {
25
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
26
+ if (!empty($data)) {
27
+ $model->setData($data);
28
+ }
29
+
30
+ Mage::register('livrarionline_data', $model);
31
+
32
+ $this->loadLayout();
33
+ $this->_setActiveMenu('livrarionline/items');
34
+
35
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
36
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
37
+
38
+ $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
39
+
40
+ $this->_addContent($this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_edit'))
41
+ ->_addLeft($this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_edit_tabs'));
42
+
43
+ $this->renderLayout();
44
+ } else {
45
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Item does not exist'));
46
+ $this->_redirect('*/*/');
47
+ }
48
+ }
49
+
50
+ public function newAction() {
51
+ $this->_forward('edit');
52
+ }
53
+
54
+ public function saveAction() {
55
+ if ($data = $this->getRequest()->getPost()) {
56
+
57
+ $model = Mage::getModel('livrarionline/awb');
58
+ $model->setData($data)
59
+ ->setId($this->getRequest()->getParam('id'));
60
+
61
+ try {
62
+ if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
63
+ $model->setCreatedTime(now())
64
+ ->setUpdateTime(now());
65
+ } else {
66
+ $model->setUpdateTime(now());
67
+ }
68
+
69
+ $model->save();
70
+ if($model->getAwbId())
71
+ {
72
+ foreach($data['parcels'] as $parcel)
73
+ {
74
+ $modelparcel = Mage::getModel('livrarionline/awb_parcels');
75
+ $modelparcel->setData($parcel)
76
+ ->setId($this->getRequest()->getParam('parcel_id'));
77
+ if ($modelparcel->getCreatedTime() == NULL || $modelparcel->getUpdateTime() == NULL) {
78
+ $modelparcel->setCreatedTime(now())
79
+ ->setUpdateTime(now());
80
+ } else {
81
+ $modelparcel->setUpdateTime(now());
82
+ }
83
+ $modelparcel->setAwbId($model->getAwbId());
84
+ $modelparcel->save();
85
+ }
86
+ }
87
+
88
+ $awb_res = Mage::helper('livrarionline')->createAwbFromOrder($model->getAwbId());
89
+
90
+ $model->setAwbNo($awb_res);
91
+ $model->save();
92
+
93
+ $order = Mage::getModel('sales/order')->load($model->getOrderId());
94
+ //Mage::log($order->getData());
95
+ $shipments = $order->getShipmentsCollection();
96
+
97
+ foreach($shipments as $ship)
98
+ {
99
+ $data = array();
100
+ $data['carrier_code'] = 'livrarionline';
101
+ $data['title'] = 'Livrari Online';
102
+ $data['number'] = $awb_res;
103
+
104
+ $track = Mage::getModel('sales/order_shipment_track')->addData($data);
105
+ $ship->addTrack($track);
106
+ $ship->save();
107
+
108
+ $ship->sendEmail($order->getCustomerEmail(), '');
109
+ }
110
+
111
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('livrarionline')->__('AWB was successfully saved'));
112
+ Mage::getSingleton('adminhtml/session')->setFormData(false);
113
+
114
+ if ($this->getRequest()->getParam('back')) {
115
+ $this->_redirect('*/*/edit', array('id' => $model->getAwbId()));
116
+ return;
117
+ }
118
+ Mage::app()->getResponse()->setRedirect(Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=>$model->getOrderId())));
119
+ return;
120
+ } catch (Exception $e) {
121
+ //print $e->getMessage();exit;
122
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
123
+ Mage::getSingleton('adminhtml/session')->setFormData($data);
124
+ $this->_redirect('*/*/index', array('order_id' => $this->getRequest()->getParam('order_id')));
125
+ return;
126
+ }
127
+ }
128
+ exit;
129
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Unable to find awb to save'));
130
+ $this->_redirect('*/*/');
131
+ }
132
+
133
+ public function deleteAction() {
134
+ if( $this->getRequest()->getParam('id') > 0 ) {
135
+ try {
136
+ $model = Mage::getModel('livrarionline/livrarionline');
137
+
138
+ $model->setId($this->getRequest()->getParam('id'))
139
+ ->delete();
140
+
141
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
142
+ $this->_redirect('*/*/');
143
+ } catch (Exception $e) {
144
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
145
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
146
+ }
147
+ }
148
+ $this->_redirect('*/*/');
149
+ }
150
+
151
+ public function massDeleteAction() {
152
+ $livrarionlineIds = $this->getRequest()->getParam('livrarionline');
153
+ if(!is_array($livrarionlineIds)) {
154
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
155
+ } else {
156
+ try {
157
+ foreach ($livrarionlineIds as $livrarionlineId) {
158
+ $livrarionline = Mage::getModel('livrarionline/livrarionline')->load($livrarionlineId);
159
+ $livrarionline->delete();
160
+ }
161
+ Mage::getSingleton('adminhtml/session')->addSuccess(
162
+ Mage::helper('adminhtml')->__(
163
+ 'Total of %d record(s) were successfully deleted', count($livrarionlineIds)
164
+ )
165
+ );
166
+ } catch (Exception $e) {
167
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
168
+ }
169
+ }
170
+ $this->_redirect('*/*/index');
171
+ }
172
+
173
+ public function massStatusAction()
174
+ {
175
+ $livrarionlineIds = $this->getRequest()->getParam('livrarionline');
176
+ if(!is_array($livrarionlineIds)) {
177
+ Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
178
+ } else {
179
+ try {
180
+ foreach ($livrarionlineIds as $livrarionlineId) {
181
+ $livrarionline = Mage::getSingleton('livrarionline/livrarionline')
182
+ ->load($livrarionlineId)
183
+ ->setStatus($this->getRequest()->getParam('status'))
184
+ ->setIsMassupdate(true)
185
+ ->save();
186
+ }
187
+ $this->_getSession()->addSuccess(
188
+ $this->__('Total of %d record(s) were successfully updated', count($livrarionlineIds))
189
+ );
190
+ } catch (Exception $e) {
191
+ $this->_getSession()->addError($e->getMessage());
192
+ }
193
+ }
194
+ $this->_redirect('*/*/index');
195
+ }
196
+
197
+ public function exportCsvAction()
198
+ {
199
+ $fileName = 'livrarionline.csv';
200
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
201
+ ->getCsv();
202
+
203
+ $this->_sendUploadResponse($fileName, $content);
204
+ }
205
+
206
+ public function exportXmlAction()
207
+ {
208
+ $fileName = 'livrarionline.xml';
209
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
210
+ ->getXml();
211
+
212
+ $this->_sendUploadResponse($fileName, $content);
213
+ }
214
+
215
+ protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
216
+ {
217
+ $response = $this->getResponse();
218
+ $response->setHeader('HTTP/1.1 200 OK','');
219
+ $response->setHeader('Pragma', 'public', true);
220
+ $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
221
+ $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
222
+ $response->setHeader('Last-Modified', date('r'));
223
+ $response->setHeader('Accept-Ranges', 'bytes');
224
+ $response->setHeader('Content-Length', strlen($content));
225
+ $response->setHeader('Content-type', $contentType);
226
+ $response->setBody($content);
227
+ $response->sendResponse();
228
+ die;
229
+ }
230
+ }
app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/LivrarionlineController.php ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Adminhtml_LivrarionlineController extends Mage_Adminhtml_Controller_action
4
+ {
5
+
6
+ protected function _initAction() {
7
+ $this->loadLayout()
8
+ ->_setActiveMenu('livrarionline/items')
9
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
10
+
11
+ return $this;
12
+ }
13
+
14
+ public function indexAction() {
15
+ $this->_initAction()
16
+ ->renderLayout();
17
+ }
18
+
19
+ public function editAction() {
20
+ $id = $this->getRequest()->getParam('id');
21
+ $model = Mage::getModel('livrarionline/livrarionline')->load($id);
22
+
23
+ if ($model->getId() || $id == 0) {
24
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
25
+ if (!empty($data)) {
26
+ $model->setData($data);
27
+ }
28
+
29
+ Mage::register('livrarionline_data', $model);
30
+
31
+ $this->loadLayout();
32
+ $this->_setActiveMenu('livrarionline/items');
33
+
34
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
35
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
36
+
37
+ $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
38
+
39
+ $this->_addContent($this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_edit'))
40
+ ->_addLeft($this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_edit_tabs'));
41
+
42
+ $this->renderLayout();
43
+ } else {
44
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Item does not exist'));
45
+ $this->_redirect('*/*/');
46
+ }
47
+ }
48
+
49
+ public function newAction() {
50
+ $this->_forward('edit');
51
+ }
52
+
53
+ public function saveAction() {
54
+ if ($data = $this->getRequest()->getPost()) {
55
+
56
+ if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
57
+ try {
58
+ /* Starting upload */
59
+ $uploader = new Varien_File_Uploader('filename');
60
+
61
+ // Any extention would work
62
+ $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
63
+ $uploader->setAllowRenameFiles(false);
64
+
65
+ // Set the file upload mode
66
+ // false -> get the file directly in the specified folder
67
+ // true -> get the file in the product like folders
68
+ // (file.jpg will go in something like /media/f/i/file.jpg)
69
+ $uploader->setFilesDispersion(false);
70
+
71
+ // We set media as the upload dir
72
+ $path = Mage::getBaseDir('media') . DS ;
73
+ $uploader->save($path, $_FILES['filename']['name'] );
74
+
75
+ } catch (Exception $e) {
76
+
77
+ }
78
+
79
+ //this way the name is saved in DB
80
+ $data['filename'] = $_FILES['filename']['name'];
81
+ }
82
+
83
+
84
+ $model = Mage::getModel('livrarionline/livrarionline');
85
+ $model->setData($data)
86
+ ->setId($this->getRequest()->getParam('id'));
87
+
88
+ try {
89
+ if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
90
+ $model->setCreatedTime(now())
91
+ ->setUpdateTime(now());
92
+ } else {
93
+ $model->setUpdateTime(now());
94
+ }
95
+
96
+ $model->save();
97
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('livrarionline')->__('Item was successfully saved'));
98
+ Mage::getSingleton('adminhtml/session')->setFormData(false);
99
+
100
+ if ($this->getRequest()->getParam('back')) {
101
+ $this->_redirect('*/*/edit', array('id' => $model->getId()));
102
+ return;
103
+ }
104
+ $this->_redirect('*/*/');
105
+ return;
106
+ } catch (Exception $e) {
107
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
108
+ Mage::getSingleton('adminhtml/session')->setFormData($data);
109
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
110
+ return;
111
+ }
112
+ }
113
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Unable to find item to save'));
114
+ $this->_redirect('*/*/');
115
+ }
116
+
117
+ public function deleteAction() {
118
+ if( $this->getRequest()->getParam('id') > 0 ) {
119
+ try {
120
+ $model = Mage::getModel('livrarionline/livrarionline');
121
+
122
+ $model->setId($this->getRequest()->getParam('id'))
123
+ ->delete();
124
+
125
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
126
+ $this->_redirect('*/*/');
127
+ } catch (Exception $e) {
128
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
129
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
130
+ }
131
+ }
132
+ $this->_redirect('*/*/');
133
+ }
134
+
135
+ public function massDeleteAction() {
136
+ $livrarionlineIds = $this->getRequest()->getParam('livrarionline');
137
+ if(!is_array($livrarionlineIds)) {
138
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
139
+ } else {
140
+ try {
141
+ foreach ($livrarionlineIds as $livrarionlineId) {
142
+ $livrarionline = Mage::getModel('livrarionline/livrarionline')->load($livrarionlineId);
143
+ $livrarionline->delete();
144
+ }
145
+ Mage::getSingleton('adminhtml/session')->addSuccess(
146
+ Mage::helper('adminhtml')->__(
147
+ 'Total of %d record(s) were successfully deleted', count($livrarionlineIds)
148
+ )
149
+ );
150
+ } catch (Exception $e) {
151
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
152
+ }
153
+ }
154
+ $this->_redirect('*/*/index');
155
+ }
156
+
157
+ public function massStatusAction()
158
+ {
159
+ $livrarionlineIds = $this->getRequest()->getParam('livrarionline');
160
+ if(!is_array($livrarionlineIds)) {
161
+ Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
162
+ } else {
163
+ try {
164
+ foreach ($livrarionlineIds as $livrarionlineId) {
165
+ $livrarionline = Mage::getSingleton('livrarionline/livrarionline')
166
+ ->load($livrarionlineId)
167
+ ->setStatus($this->getRequest()->getParam('status'))
168
+ ->setIsMassupdate(true)
169
+ ->save();
170
+ }
171
+ $this->_getSession()->addSuccess(
172
+ $this->__('Total of %d record(s) were successfully updated', count($livrarionlineIds))
173
+ );
174
+ } catch (Exception $e) {
175
+ $this->_getSession()->addError($e->getMessage());
176
+ }
177
+ }
178
+ $this->_redirect('*/*/index');
179
+ }
180
+
181
+ public function exportCsvAction()
182
+ {
183
+ $fileName = 'livrarionline.csv';
184
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
185
+ ->getCsv();
186
+
187
+ $this->_sendUploadResponse($fileName, $content);
188
+ }
189
+
190
+ public function exportXmlAction()
191
+ {
192
+ $fileName = 'livrarionline.xml';
193
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
194
+ ->getXml();
195
+
196
+ $this->_sendUploadResponse($fileName, $content);
197
+ }
198
+
199
+ protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
200
+ {
201
+ $response = $this->getResponse();
202
+ $response->setHeader('HTTP/1.1 200 OK','');
203
+ $response->setHeader('Pragma', 'public', true);
204
+ $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
205
+ $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
206
+ $response->setHeader('Last-Modified', date('r'));
207
+ $response->setHeader('Accept-Ranges', 'bytes');
208
+ $response->setHeader('Content-Length', strlen($content));
209
+ $response->setHeader('Content-type', $contentType);
210
+ $response->setBody($content);
211
+ $response->sendResponse();
212
+ die;
213
+ }
214
+
215
+ public function awbAction()
216
+ {
217
+ }
218
+ }
app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManageawbController.php ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ //require_once('/lib/lo.php');
3
+ class Xtreme_Livrarionline_Adminhtml_ManageawbController extends Mage_Adminhtml_Controller_action
4
+ {
5
+ protected function _initAction() {
6
+ $this->loadLayout()
7
+ ->_setActiveMenu('livrarionline/awb')
8
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('AWB Manager'), Mage::helper('adminhtml')->__('AWB Manager'));
9
+
10
+ return $this;
11
+ }
12
+
13
+ public function indexAction() {
14
+ $this->_initAction()->renderLayout();
15
+ }
16
+
17
+ public function editAction() {
18
+ $id = $this->getRequest()->getParam('id');
19
+ $model = Mage::getModel('livrarionline/awb')->load($id);
20
+
21
+ if ($model->getId() || $id == 0) {
22
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
23
+ if (!empty($data)) {
24
+ $model->setData($data);
25
+ }
26
+
27
+ Mage::register('awb_data', $model);
28
+
29
+ $this->loadLayout();
30
+ $this->_setActiveMenu('livrarionline/awb');
31
+
32
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('AWB Manager'), Mage::helper('adminhtml')->__('AWB Manager'));
33
+
34
+ $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
35
+
36
+ $this->_addContent($this->getLayout()->createBlock('livrarionline/adminhtml_manageawb_edit'))
37
+ ->_addLeft($this->getLayout()->createBlock('livrarionline/adminhtml_manageawb_edit_tabs'));
38
+
39
+ $this->renderLayout();
40
+ } else {
41
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('AWB does not exist'));
42
+ $this->_redirect('*/*/');
43
+ }
44
+ }
45
+
46
+ public function newAction() {
47
+ $this->_forward('edit');
48
+ }
49
+
50
+ public function saveAction() {
51
+ //Mage::log("saveAction");
52
+ if ($data = $this->getRequest()->getPost()) {
53
+
54
+ //print "<pre>";
55
+ //Mage::log($data);
56
+ //print_r($data);exit;
57
+
58
+ $model = Mage::getModel('livrarionline/awb');
59
+ $model->setData($data)
60
+ ->setId($this->getRequest()->getParam('id'));
61
+
62
+ //print_r($model);
63
+
64
+ try {
65
+ if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
66
+ $model->setCreatedTime(now())
67
+ ->setUpdateTime(now());
68
+ } else {
69
+ $model->setUpdateTime(now());
70
+ }
71
+
72
+ $model->save();
73
+ if($model->getAwbId())
74
+ {
75
+ foreach($data['parcels'] as $parcel)
76
+ {
77
+ $modelparcel = Mage::getModel('livrarionline/awb_parcels');
78
+ $modelparcel->setData($parcel)
79
+ ->setId($this->getRequest()->getParam('parcel_id'));
80
+ if ($modelparcel->getCreatedTime() == NULL || $modelparcel->getUpdateTime() == NULL) {
81
+ $modelparcel->setCreatedTime(now())
82
+ ->setUpdateTime(now());
83
+ } else {
84
+ $modelparcel->setUpdateTime(now());
85
+ }
86
+ $modelparcel->setAwbId($model->getAwbId());
87
+ $modelparcel->save();
88
+ }
89
+ }
90
+
91
+ $awb_res = Mage::helper('livrarionline')->createAwbFromOrder($model->getAwbId());
92
+ $order = Mage::getModel('sales/order')->load($model->getOrderId());
93
+ //$shipment = Mage::getModel('sales/order_shipment')->load($order->getIncrementId());
94
+ $shipments = $order->getShipmentsCollection();
95
+
96
+ foreach($shipments as $ship)
97
+ {
98
+ //print '<pre>';
99
+ //print_r($ship);
100
+
101
+ $data = array();
102
+ $data['carrier_code'] = 'livrarionline';
103
+ $data['title'] = 'Livrari Online';
104
+ $data['number'] = $awb_res;
105
+
106
+ $track = Mage::getModel('sales/order_shipment_track')->addData($data);
107
+ $ship->addTrack($track);
108
+ $ship->save();
109
+
110
+ $ship->sendEmail($email, '');
111
+ }
112
+
113
+ //exit;
114
+
115
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('livrarionline')->__('AWB was successfully saved'));
116
+ Mage::getSingleton('adminhtml/session')->setFormData(false);
117
+
118
+ if ($this->getRequest()->getParam('back')) {
119
+ $this->_redirect('*/*/edit', array('id' => $model->getAwbId()));
120
+ return;
121
+ }
122
+ Mage::app()->getResponse()->setRedirect(Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=>$model->getOrderId())));
123
+ return;
124
+ } catch (Exception $e) {
125
+ //print $e->getMessage();exit;
126
+
127
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
128
+ Mage::getSingleton('adminhtml/session')->setFormData($data);
129
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
130
+ return;
131
+ }
132
+ }
133
+ exit;
134
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Unable to find awb to save'));
135
+ $this->_redirect('*/*/');
136
+ }
137
+
138
+ public function deleteAction() {
139
+ if( $this->getRequest()->getParam('id') > 0 ) {
140
+ try {
141
+ $model = Mage::getModel('livrarionline/awb');
142
+
143
+ $model->setId($this->getRequest()->getParam('id'))
144
+ ->delete();
145
+
146
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('AWB was successfully deleted'));
147
+ $this->_redirect('*/*/');
148
+ } catch (Exception $e) {
149
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
150
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
151
+ }
152
+ }
153
+ $this->_redirect('*/*/');
154
+ }
155
+
156
+ public function printAction() {
157
+ if( $this->getRequest()->getParam('id') > 0 ) {
158
+ try {
159
+ $model = Mage::getModel('livrarionline/awb')->load($this->getRequest()->getParam('id'));
160
+ if($model->getAwbNo())
161
+ {
162
+ $html = Mage::helper('livrarionline')->printAWB($model->getAwbId());
163
+ echo $html;
164
+ exit;
165
+ }
166
+ else
167
+ {
168
+ echo "Missing AWB No";
169
+ exit;
170
+ }
171
+ //Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__($msg));
172
+ //$this->_redirect('*/*/');
173
+ } catch (Exception $e) {
174
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
175
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
176
+ }
177
+ }
178
+ $this->_redirect('*/*/');
179
+ }
180
+
181
+ public function cancelAction() {
182
+ if( $this->getRequest()->getParam('id') > 0 ) {
183
+ try {
184
+ $model = Mage::getModel('livrarionline/awb')->load($this->getRequest()->getParam('id'));
185
+ if($model->getAwbNo())
186
+ {
187
+ $track = Mage::getModel('sales/order_shipment_track')->getCollection()
188
+ ->addFieldToFilter('track_number', $model->getAwbNo())
189
+ ->getFirstItem();
190
+ if($track->getId())
191
+ $track->delete();
192
+
193
+ $result = Mage::helper('livrarionline')->cancelAWB($model->getAwbId());
194
+ $msg = "AWB Cancelled successfully";
195
+ $model->setStatus(Xtreme_Livrarionline_Model_Awb::STATUS_CANCELLED);
196
+ $model->save();
197
+ }
198
+ else
199
+ {
200
+ echo "Missing AWB No";
201
+ exit;
202
+ }
203
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__($msg));
204
+ $this->_redirect('*/*/');
205
+ } catch (Exception $e) {
206
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
207
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
208
+ }
209
+ }
210
+ $this->_redirect('*/*/');
211
+ }
212
+
213
+ public function massDeleteAction() {
214
+ $livrarionlineIds = $this->getRequest()->getParam('awb');
215
+ if(!is_array($livrarionlineIds)) {
216
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select awb(s)'));
217
+ } else {
218
+ try {
219
+ foreach ($livrarionlineIds as $livrarionlineId) {
220
+ $livrarionline = Mage::getModel('livrarionline/awb')->load($livrarionlineId);
221
+ $livrarionline->delete();
222
+ }
223
+ Mage::getSingleton('adminhtml/session')->addSuccess(
224
+ Mage::helper('adminhtml')->__(
225
+ 'Total of %d AWB(s) were successfully deleted', count($livrarionlineIds)
226
+ )
227
+ );
228
+ } catch (Exception $e) {
229
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
230
+ }
231
+ }
232
+ $this->_redirect('*/*/index');
233
+ }
234
+
235
+ public function massStatusAction()
236
+ {
237
+ $livrarionlineIds = $this->getRequest()->getParam('livrarionline');
238
+ if(!is_array($livrarionlineIds)) {
239
+ Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
240
+ } else {
241
+ try {
242
+ foreach ($livrarionlineIds as $livrarionlineId) {
243
+ $livrarionline = Mage::getSingleton('livrarionline/livrarionline')
244
+ ->load($livrarionlineId)
245
+ ->setStatus($this->getRequest()->getParam('status'))
246
+ ->setIsMassupdate(true)
247
+ ->save();
248
+ }
249
+ $this->_getSession()->addSuccess(
250
+ $this->__('Total of %d record(s) were successfully updated', count($livrarionlineIds))
251
+ );
252
+ } catch (Exception $e) {
253
+ $this->_getSession()->addError($e->getMessage());
254
+ }
255
+ }
256
+ $this->_redirect('*/*/index');
257
+ }
258
+
259
+ public function exportCsvAction()
260
+ {
261
+ $fileName = 'livrarionline.csv';
262
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
263
+ ->getCsv();
264
+
265
+ $this->_sendUploadResponse($fileName, $content);
266
+ }
267
+
268
+ public function exportXmlAction()
269
+ {
270
+ $fileName = 'livrarionline.xml';
271
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
272
+ ->getXml();
273
+
274
+ $this->_sendUploadResponse($fileName, $content);
275
+ }
276
+
277
+ protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
278
+ {
279
+ $response = $this->getResponse();
280
+ $response->setHeader('HTTP/1.1 200 OK','');
281
+ $response->setHeader('Pragma', 'public', true);
282
+ $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
283
+ $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
284
+ $response->setHeader('Last-Modified', date('r'));
285
+ $response->setHeader('Accept-Ranges', 'bytes');
286
+ $response->setHeader('Content-Length', strlen($content));
287
+ $response->setHeader('Content-type', $contentType);
288
+ $response->setBody($content);
289
+ $response->sendResponse();
290
+ die;
291
+ }
292
+ }
app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManagecarriersController.php ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Adminhtml_ManagecarriersController extends Mage_Adminhtml_Controller_action
4
+ {
5
+
6
+ protected function _initAction() {
7
+ $this->loadLayout()
8
+ ->_setActiveMenu('livrarionline/carriers')
9
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Carriers Manager'), Mage::helper('adminhtml')->__('Carriers Manager'));
10
+
11
+ return $this;
12
+ }
13
+
14
+ public function indexAction() {
15
+ $this->_initAction()
16
+ ->renderLayout();
17
+ }
18
+
19
+ public function editAction() {
20
+ $id = $this->getRequest()->getParam('id');
21
+ $model = Mage::getModel('livrarionline/carriers')->load($id);
22
+
23
+ if ($model->getId() || $id == 0) {
24
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
25
+ if (!empty($data)) {
26
+ $model->setData($data);
27
+ }
28
+
29
+ Mage::register('carrier_data', $model);
30
+
31
+ $this->loadLayout();
32
+ $this->_setActiveMenu('livrarionline/carriers');
33
+
34
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Carriers Manager'), Mage::helper('adminhtml')->__('Carriers Manager'));
35
+ //$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
36
+
37
+ $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
38
+
39
+ $this->_addContent($this->getLayout()->createBlock('livrarionline/adminhtml_managecarriers_edit'))
40
+ ->_addLeft($this->getLayout()->createBlock('livrarionline/adminhtml_managecarriers_edit_tabs'));
41
+
42
+ $this->renderLayout();
43
+ } else {
44
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Carrier does not exist'));
45
+ $this->_redirect('*/*/');
46
+ }
47
+ }
48
+
49
+ public function newAction() {
50
+ $this->_forward('edit');
51
+ }
52
+
53
+ public function saveAction() {
54
+ if ($data = $this->getRequest()->getPost()) {
55
+
56
+ /*if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
57
+ try {
58
+ // Starting upload
59
+ $uploader = new Varien_File_Uploader('filename');
60
+
61
+ // Any extention would work
62
+ $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
63
+ $uploader->setAllowRenameFiles(false);
64
+
65
+ // Set the file upload mode
66
+ // false -> get the file directly in the specified folder
67
+ // true -> get the file in the product like folders
68
+ // (file.jpg will go in something like /media/f/i/file.jpg)
69
+ $uploader->setFilesDispersion(false);
70
+
71
+ // We set media as the upload dir
72
+ $path = Mage::getBaseDir('media') . DS ;
73
+ $uploader->save($path, $_FILES['filename']['name'] );
74
+
75
+ } catch (Exception $e) {
76
+
77
+ }
78
+
79
+ //this way the name is saved in DB
80
+ $data['filename'] = $_FILES['filename']['name'];
81
+ }*/
82
+
83
+ $model = Mage::getModel('livrarionline/carriers');
84
+ $model->setData($data)
85
+ ->setId($this->getRequest()->getParam('id'));
86
+
87
+ //print_r($data);exit;
88
+
89
+ try {
90
+ if ($model->getCreatedTime() == NULL || $model->getUpdatedTime() == NULL) {
91
+ $model->setCreatedTime(now())
92
+ ->setUpdatedTime(now());
93
+ } else {
94
+ $model->setUpdadteTime(now());
95
+ }
96
+
97
+ $model->save();
98
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('livrarionline')->__('Carrier was successfully saved'));
99
+ Mage::getSingleton('adminhtml/session')->setFormData(false);
100
+
101
+ if ($this->getRequest()->getParam('back')) {
102
+ $this->_redirect('*/*/edit', array('id' => $model->getId()));
103
+ return;
104
+ }
105
+ $this->_redirect('*/*/');
106
+ return;
107
+ } catch (Exception $e) {
108
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
109
+ Mage::getSingleton('adminhtml/session')->setFormData($data);
110
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
111
+ return;
112
+ }
113
+ }
114
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Unable to find carrier to save'));
115
+ $this->_redirect('*/*/');
116
+ }
117
+
118
+ public function deleteAction() {
119
+ if( $this->getRequest()->getParam('id') > 0 ) {
120
+ try {
121
+ $model = Mage::getModel('livrarionline/carriers');
122
+
123
+ $model->setId($this->getRequest()->getParam('id'))
124
+ ->delete();
125
+
126
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Carriers was successfully deleted'));
127
+ $this->_redirect('*/*/');
128
+ } catch (Exception $e) {
129
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
130
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
131
+ }
132
+ }
133
+ $this->_redirect('*/*/');
134
+ }
135
+
136
+ public function massDeleteAction() {
137
+ $carrierIds = $this->getRequest()->getParam('carriers');
138
+ if(!is_array($carrierIds)) {
139
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select carrier(s)'));
140
+ } else {
141
+ try {
142
+ foreach ($carrierIds as $carrierId) {
143
+ $carrier = Mage::getModel('livrarionline/carriers')->load($carrierId);
144
+ $carrier->delete();
145
+ }
146
+ Mage::getSingleton('adminhtml/session')->addSuccess(
147
+ Mage::helper('adminhtml')->__(
148
+ 'Total of %d record(s) were successfully deleted', count($carrierIds)
149
+ )
150
+ );
151
+ } catch (Exception $e) {
152
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
153
+ }
154
+ }
155
+ $this->_redirect('*/*/index');
156
+ }
157
+
158
+ public function massStatusAction()
159
+ {
160
+ $carrierIds = $this->getRequest()->getParam('carriers');
161
+ if(!is_array($carrierIds)) {
162
+ Mage::getSingleton('adminhtml/session')->addError($this->__('Please select carrier(s)'));
163
+ } else {
164
+ try {
165
+ foreach ($carrierIds as $carrierId) {
166
+ $carrier = Mage::getSingleton('livrarionline/carriers')
167
+ ->load($carrierId)
168
+ ->setStatus($this->getRequest()->getParam('status'))
169
+ ->setIsMassupdate(true)
170
+ ->save();
171
+ }
172
+ $this->_getSession()->addSuccess(
173
+ $this->__('Total of %d record(s) were successfully updated', count($carrierIds))
174
+ );
175
+ } catch (Exception $e) {
176
+ $this->_getSession()->addError($e->getMessage());
177
+ }
178
+ }
179
+ $this->_redirect('*/*/index');
180
+ }
181
+
182
+ public function exportCsvAction()
183
+ {
184
+ $fileName = 'carriers.csv';
185
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_managecarriers_grid')
186
+ ->getCsv();
187
+
188
+ $this->_sendUploadResponse($fileName, $content);
189
+ }
190
+
191
+ public function exportXmlAction()
192
+ {
193
+ $fileName = 'livrarionline.xml';
194
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
195
+ ->getXml();
196
+
197
+ $this->_sendUploadResponse($fileName, $content);
198
+ }
199
+
200
+ protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
201
+ {
202
+ $response = $this->getResponse();
203
+ $response->setHeader('HTTP/1.1 200 OK','');
204
+ $response->setHeader('Pragma', 'public', true);
205
+ $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
206
+ $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
207
+ $response->setHeader('Last-Modified', date('r'));
208
+ $response->setHeader('Accept-Ranges', 'bytes');
209
+ $response->setHeader('Content-Length', strlen($content));
210
+ $response->setHeader('Content-type', $contentType);
211
+ $response->setBody($content);
212
+ $response->sendResponse();
213
+ die;
214
+ }
215
+ }
app/code/local/Xtreme/Livrarionline/controllers/Adminhtml/ManagestoresController.php ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Xtreme_Livrarionline_Adminhtml_ManagestoresController extends Mage_Adminhtml_Controller_action
4
+ {
5
+
6
+ protected function _initAction() {
7
+ $this->loadLayout()
8
+ ->_setActiveMenu('livrarionline/stores')
9
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Stores Manager'), Mage::helper('adminhtml')->__('Stores Manager'));
10
+
11
+ return $this;
12
+ }
13
+
14
+ public function indexAction() {
15
+ $this->_initAction()
16
+ ->renderLayout();
17
+ }
18
+
19
+ public function editAction() {
20
+ $id = $this->getRequest()->getParam('id');
21
+ $model = Mage::getModel('livrarionline/stores')->load($id);
22
+
23
+ if ($model->getId() || $id == 0) {
24
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
25
+ if (!empty($data)) {
26
+ $model->setData($data);
27
+ }
28
+
29
+ Mage::register('store_data', $model);
30
+ //print_r($model->getData());exit;
31
+
32
+ $this->loadLayout();
33
+ $this->_setActiveMenu('livrarionline/stores');
34
+ $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Stores Manager'), Mage::helper('adminhtml')->__('Stores Manager'));
35
+ $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
36
+ $this->_addContent($this->getLayout()->createBlock('livrarionline/adminhtml_managestores_edit'))
37
+ ->_addLeft($this->getLayout()->createBlock('livrarionline/adminhtml_managestores_edit_tabs'));
38
+
39
+ $this->renderLayout();
40
+ } else {
41
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Store does not exist'));
42
+ $this->_redirect('*/*/');
43
+ }
44
+ }
45
+
46
+ public function newAction() {
47
+ $this->_forward('edit');
48
+ }
49
+
50
+ public function saveAction() {
51
+ if ($data = $this->getRequest()->getPost()) {
52
+
53
+ //print_r($data);
54
+
55
+ $model = Mage::getModel('livrarionline/stores');
56
+ $model->setData($data)
57
+ ->setId($this->getRequest()->getParam('id'));
58
+ //print_r($model->getData());
59
+ //exit;
60
+
61
+ try {
62
+ if ($model->getCreatedTime() == NULL || $model->getUpdatedTime() == NULL) {
63
+ $model->setCreatedTime(now())
64
+ ->setUpdatedTime(now());
65
+ } else {
66
+ $model->setUpdadteTime(now());
67
+ }
68
+
69
+ $model->setDefault(!empty($data['default']));
70
+ $model->save();
71
+ /*print "<pre>";
72
+ print_r($model->getData());
73
+ exit;*/
74
+
75
+ $id = $this->getRequest()->getParam('id');
76
+ $res = $model->toggleStoresDefault($id);
77
+
78
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('livrarionline')->__('Store was successfully saved'));
79
+ Mage::getSingleton('adminhtml/session')->setFormData(false);
80
+
81
+ if ($this->getRequest()->getParam('back')) {
82
+ $this->_redirect('*/*/edit', array('id' => $model->getId()));
83
+ return;
84
+ }
85
+ $this->_redirect('*/*/');
86
+ return;
87
+ } catch (Exception $e) {
88
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
89
+ Mage::getSingleton('adminhtml/session')->setFormData($data);
90
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
91
+ return;
92
+ }
93
+ }
94
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('livrarionline')->__('Unable to find store to save'));
95
+ $this->_redirect('*/*/');
96
+ }
97
+
98
+ public function deleteAction() {
99
+ if( $this->getRequest()->getParam('id') > 0 ) {
100
+ try {
101
+ $model = Mage::getModel('livrarionline/stores');
102
+
103
+ $model->setId($this->getRequest()->getParam('id'))
104
+ ->delete();
105
+
106
+ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Stores was successfully deleted'));
107
+ $this->_redirect('*/*/');
108
+ } catch (Exception $e) {
109
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
110
+ $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
111
+ }
112
+ }
113
+ $this->_redirect('*/*/');
114
+ }
115
+
116
+ public function massDeleteAction() {
117
+ $storeIds = $this->getRequest()->getParam('stores');
118
+ if(!is_array($storeIds)) {
119
+ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select store(s)'));
120
+ } else {
121
+ try {
122
+ foreach ($storeIds as $storeId) {
123
+ $store = Mage::getModel('livrarionline/stores')->load($storeId);
124
+ $storeIds->delete();
125
+ }
126
+ Mage::getSingleton('adminhtml/session')->addSuccess(
127
+ Mage::helper('adminhtml')->__(
128
+ 'Total of %d record(s) were successfully deleted', count($storeIds)
129
+ )
130
+ );
131
+ } catch (Exception $e) {
132
+ Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
133
+ }
134
+ }
135
+ $this->_redirect('*/*/index');
136
+ }
137
+
138
+ public function massStatusAction()
139
+ {
140
+ $carrierIds = $this->getRequest()->getParam('stores');
141
+ if(!is_array($carrierIds)) {
142
+ Mage::getSingleton('adminhtml/session')->addError($this->__('Please select carrier(s)'));
143
+ } else {
144
+ try {
145
+ foreach ($carrierIds as $carrierId) {
146
+ $carrier = Mage::getSingleton('livrarionline/stores')
147
+ ->load($carrierId)
148
+ ->setStatus($this->getRequest()->getParam('status'))
149
+ ->setIsMassupdate(true)
150
+ ->save();
151
+ }
152
+ $this->_getSession()->addSuccess(
153
+ $this->__('Total of %d record(s) were successfully updated', count($carrierIds))
154
+ );
155
+ } catch (Exception $e) {
156
+ $this->_getSession()->addError($e->getMessage());
157
+ }
158
+ }
159
+ $this->_redirect('*/*/index');
160
+ }
161
+
162
+ public function exportCsvAction()
163
+ {
164
+ $fileName = 'stores.csv';
165
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_managecarriers_grid')
166
+ ->getCsv();
167
+
168
+ $this->_sendUploadResponse($fileName, $content);
169
+ }
170
+
171
+ public function exportXmlAction()
172
+ {
173
+ $fileName = 'livrarionline.xml';
174
+ $content = $this->getLayout()->createBlock('livrarionline/adminhtml_livrarionline_grid')
175
+ ->getXml();
176
+
177
+ $this->_sendUploadResponse($fileName, $content);
178
+ }
179
+
180
+ protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
181
+ {
182
+ $response = $this->getResponse();
183
+ $response->setHeader('HTTP/1.1 200 OK','');
184
+ $response->setHeader('Pragma', 'public', true);
185
+ $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
186
+ $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
187
+ $response->setHeader('Last-Modified', date('r'));
188
+ $response->setHeader('Accept-Ranges', 'bytes');
189
+ $response->setHeader('Content-Length', strlen($content));
190
+ $response->setHeader('Content-type', $contentType);
191
+ $response->setBody($content);
192
+ $response->sendResponse();
193
+ die;
194
+ }
195
+
196
+ public function stateAction()
197
+ {
198
+ $countrycode = $this->getRequest()->getParam('country');
199
+ $state = "<option value=''>Please Select State</option>";
200
+ if ($countrycode != '') {
201
+ $statearray = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter($countrycode)->load();
202
+ foreach ($statearray as $_state) {
203
+ $state .= "<option value='" . $_state->getCode() . "'>" . $_state->getDefaultName() . "</option>";
204
+ }
205
+ }
206
+ echo $state;
207
+ }
208
+ }
app/code/local/Xtreme/Livrarionline/controllers/IndexController.php ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Xtreme_Livrarionline_IndexController extends Mage_Core_Controller_Front_Action
3
+ {
4
+ public function indexAction()
5
+ {
6
+
7
+ /*
8
+ * Load an object by id
9
+ * Request looking like:
10
+ * http://site.com/livrarionline?id=15
11
+ * or
12
+ * http://site.com/livrarionline/id/15
13
+ */
14
+ /*
15
+ $livrarionline_id = $this->getRequest()->getParam('id');
16
+
17
+ if($livrarionline_id != null && $livrarionline_id != '') {
18
+ $livrarionline = Mage::getModel('livrarionline/livrarionline')->load($livrarionline_id)->getData();
19
+ } else {
20
+ $livrarionline = null;
21
+ }
22
+ */
23
+
24
+ /*
25
+ * If no param we load a the last created item
26
+ */
27
+ /*
28
+ if($livrarionline == null) {
29
+ $resource = Mage::getSingleton('core/resource');
30
+ $read= $resource->getConnection('core_read');
31
+ $livrarionlineTable = $resource->getTableName('livrarionline');
32
+
33
+ $select = $read->select()
34
+ ->from($livrarionlineTable,array('livrarionline_id','title','content','status'))
35
+ ->where('status',1)
36
+ ->order('created_time DESC') ;
37
+
38
+ $livrarionline = $read->fetchRow($select);
39
+ }
40
+ Mage::register('livrarionline', $livrarionline);
41
+ */
42
+
43
+
44
+ $this->loadLayout();
45
+ $this->renderLayout();
46
+ }
47
+ }
app/code/local/Xtreme/Livrarionline/etc/config.xml ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <!--
3
+ /**
4
+ * @category Xtreme
5
+ * @package Xtreme_Livrarionline
6
+ * @author ModuleCreator
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ -->
10
+ <config>
11
+ <modules>
12
+ <Xtreme_Livrarionline>
13
+ <version>0.1.0</version>
14
+ </Xtreme_Livrarionline>
15
+ </modules>
16
+ <frontend>
17
+ <routers>
18
+ <livrarionline>
19
+ <use>standard</use>
20
+ <args>
21
+ <module>Xtreme_Livrarionline</module>
22
+ <frontName>livrarionline</frontName>
23
+ </args>
24
+ </livrarionline>
25
+ </routers>
26
+ <layout>
27
+ <updates>
28
+ <livrarionline>
29
+ <file>livrarionline.xml</file>
30
+ </livrarionline>
31
+ </updates>
32
+ </layout>
33
+ </frontend>
34
+ <admin>
35
+ <routers>
36
+ <livrarionline>
37
+ <use>admin</use>
38
+ <args>
39
+ <module>Xtreme_Livrarionline</module>
40
+ <frontName>loadmin</frontName>
41
+ </args>
42
+ </livrarionline>
43
+ </routers>
44
+ </admin>
45
+ <adminhtml>
46
+ <menu>
47
+ <livrarionline module="livrarionline">
48
+ <title>Livrarionline</title>
49
+ <sort_order>71</sort_order>
50
+ <children>
51
+ <awb module="livrarionline">
52
+ <title>Manage AWB</title>
53
+ <sort_order>0</sort_order>
54
+ <action>livrarionline/adminhtml_manageawb</action>
55
+ </awb>
56
+ <carriers module="livrarionline">
57
+ <title>Manage Carriers</title>
58
+ <sort_order>2</sort_order>
59
+ <action>livrarionline/adminhtml_managecarriers</action>
60
+ </carriers>
61
+ <stores module="livrarionline">
62
+ <title>Manage Stores</title>
63
+ <sort_order>4</sort_order>
64
+ <action>livrarionline/adminhtml_managestores</action>
65
+ </stores>
66
+ </children>
67
+ </livrarionline>
68
+ </menu>
69
+ <acl>
70
+ <resources>
71
+ <!-- <all>
72
+ <title>Allow Everything</title>
73
+ </all>
74
+ --> <admin>
75
+ <children>
76
+ <livrarionline>
77
+ <title>Livrarionline Module</title>
78
+ <sort_order>10</sort_order>
79
+
80
+ <children>
81
+ <awb translate="title" module="livrarionline">
82
+ <title>Manage AWB</title>
83
+ </awb>
84
+ <carriers translate="title" module="livrarionline">
85
+ <title>Manage Carriers</title>
86
+ </carriers>
87
+ <stores translate="title" module="livrarionline">
88
+ <title>Manage Stores</title>
89
+ </stores>
90
+ </children>
91
+
92
+ </livrarionline>
93
+ </children>
94
+ </admin>
95
+ </resources>
96
+ </acl>
97
+ <layout>
98
+ <updates>
99
+ <livrarionline>
100
+ <file>livrarionline.xml</file>
101
+ </livrarionline>
102
+ </updates>
103
+ </layout>
104
+ </adminhtml>
105
+ <global>
106
+ <models>
107
+ <livrarionline>
108
+ <class>Xtreme_Livrarionline_Model</class>
109
+ <resourceModel>livrarionline_mysql4</resourceModel>
110
+ </livrarionline>
111
+ <livrarionline_mysql4>
112
+ <class>Xtreme_Livrarionline_Model_Mysql4</class>
113
+ <entities>
114
+ <livrarionline>
115
+ <table>livrarionline</table>
116
+ </livrarionline>
117
+ </entities>
118
+ <entities>
119
+ <carriers>
120
+ <table>livrarionline_carriers</table>
121
+ </carriers>
122
+ </entities>
123
+ <entities>
124
+ <stores>
125
+ <table>livrarionline_stores</table>
126
+ </stores>
127
+ </entities>
128
+ <entities>
129
+ <awb>
130
+ <table>livrarionline_awb</table>
131
+ </awb>
132
+ </entities>
133
+ <entities>
134
+ <awb_parcels>
135
+ <table>livrarionline_awb_parcels</table>
136
+ </awb_parcels>
137
+ </entities>
138
+ </livrarionline_mysql4>
139
+ </models>
140
+ <resources>
141
+ <livrarionline_setup>
142
+ <setup>
143
+ <module>Xtreme_Livrarionline</module>
144
+ </setup>
145
+ <connection>
146
+ <use>core_setup</use>
147
+ </connection>
148
+ </livrarionline_setup>
149
+ <livrarionline_write>
150
+ <connection>
151
+ <use>core_write</use>
152
+ </connection>
153
+ </livrarionline_write>
154
+ <livrarionline_read>
155
+ <connection>
156
+ <use>core_read</use>
157
+ </connection>
158
+ </livrarionline_read>
159
+ </resources>
160
+ <blocks>
161
+ <livrarionline>
162
+ <class>Xtreme_Livrarionline_Block</class>
163
+ </livrarionline>
164
+ <adminhtml>
165
+ <rewrite>
166
+ <sales_order_view>Xtreme_Livrarionline_Block_Adminhtml_Sales_Order_View</sales_order_view>
167
+ </rewrite>
168
+ </adminhtml>
169
+ </blocks>
170
+ <helpers>
171
+ <livrarionline>
172
+ <class>Xtreme_Livrarionline_Helper</class>
173
+ </livrarionline>
174
+ </helpers>
175
+ </global>
176
+ <default>
177
+ <carriers>
178
+ <livrarionline>
179
+ <active>1</active>
180
+ <model>livrarionline/carrier_livrarionline</model>
181
+ <title>Carrier Title</title>
182
+ <name>Method Name</name>
183
+ <login_id></login_id>
184
+ <security_key></security_key>
185
+ <specificerrmsg>This shipping method is currently unavailable. If you would like to ship using this shipping method, please contact us.</specificerrmsg>
186
+ </livrarionline>
187
+ </carriers>
188
+ </default>
189
+ </config>
app/code/local/Xtreme/Livrarionline/etc/system.xml ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <config>
3
+ <sections>
4
+ <carriers>
5
+ <groups>
6
+ <livrarionline translate="label" module="livrarionline">
7
+ <label>Livrari Online</label>
8
+ <frontend_type>text</frontend_type>
9
+ <sort_order>99</sort_order>
10
+ <show_in_default>1</show_in_default>
11
+ <show_in_website>1</show_in_website>
12
+ <show_in_store>1</show_in_store>
13
+ <fields>
14
+ <active translate="label">
15
+ <label>Enabled</label>
16
+ <frontend_type>select</frontend_type>
17
+ <source_model>adminhtml/system_config_source_yesno</source_model>
18
+ <sort_order>1</sort_order>
19
+ <show_in_default>1</show_in_default>
20
+ <show_in_website>1</show_in_website>
21
+ <show_in_store>1</show_in_store>
22
+ </active>
23
+ <title translate="label">
24
+ <label>Title</label>
25
+ <frontend_type>text</frontend_type>
26
+ <sort_order>2</sort_order>
27
+ <show_in_default>1</show_in_default>
28
+ <show_in_website>1</show_in_website>
29
+ <show_in_store>1</show_in_store>
30
+ </title>
31
+ <name translate="label">
32
+ <label>Method Name</label>
33
+ <frontend_type>text</frontend_type>
34
+ <sort_order>2</sort_order>
35
+ <show_in_default>1</show_in_default>
36
+ <show_in_website>1</show_in_website>
37
+ <show_in_store>1</show_in_store>
38
+ </name>
39
+ <login_id translate="label">
40
+ <label>Login ID</label>
41
+ <frontend_type>text</frontend_type>
42
+ <sort_order>3</sort_order>
43
+ <show_in_default>1</show_in_default>
44
+ <show_in_website>1</show_in_website>
45
+ <show_in_store>0</show_in_store>
46
+ </login_id>
47
+ <security_key translate="label">
48
+ <label>Security Key</label>
49
+ <frontend_type>text</frontend_type>
50
+ <sort_order>4</sort_order>
51
+ <show_in_default>1</show_in_default>
52
+ <show_in_website>1</show_in_website>
53
+ <show_in_store>0</show_in_store>
54
+ </security_key>
55
+ <allowed_methods translate="label">
56
+ <label>Allowed Methods</label>
57
+ <frontend_type>multiselect</frontend_type>
58
+ <source_model>livrarionline/carriers</source_model>
59
+ <sort_order>70</sort_order>
60
+ <show_in_default>1</show_in_default>
61
+ <show_in_website>1</show_in_website>
62
+ <show_in_store>0</show_in_store>
63
+ <can_be_empty>1</can_be_empty>
64
+ </allowed_methods>
65
+ <specificerrmsg translate="label">
66
+ <label>Displayed Error Message</label>
67
+ <frontend_type>textarea</frontend_type>
68
+ <sort_order>7</sort_order>
69
+ <show_in_default>1</show_in_default>
70
+ <show_in_website>1</show_in_website>
71
+ <show_in_store>1</show_in_store>
72
+ </specificerrmsg>
73
+ <sallowspecific translate="label">
74
+ <label>Ship to Applicable Countries</label>
75
+ <frontend_type>select</frontend_type>
76
+ <sort_order>90</sort_order>
77
+ <frontend_class>shipping-applicable-country</frontend_class>
78
+ <source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model>
79
+ <show_in_default>1</show_in_default>
80
+ <show_in_website>1</show_in_website>
81
+ <show_in_store>0</show_in_store>
82
+ </sallowspecific>
83
+ <specificcountry translate="label">
84
+ <label>Ship to Specific Countries</label>
85
+ <frontend_type>multiselect</frontend_type>
86
+ <sort_order>91</sort_order>
87
+ <source_model>adminhtml/system_config_source_country</source_model>
88
+ <show_in_default>1</show_in_default>
89
+ <show_in_website>1</show_in_website>
90
+ <show_in_store>0</show_in_store>
91
+ <can_be_empty>1</can_be_empty>
92
+ </specificcountry>
93
+ <!--
94
+ <shipfrom_email translate="label">
95
+ <label>Ship FROM email</label>
96
+ <frontend_type>text</frontend_type>
97
+ <sort_order>100</sort_order>
98
+ <show_in_default>1</show_in_default>
99
+ <show_in_website>1</show_in_website>
100
+ <show_in_store>0</show_in_store>
101
+ <can_be_empty>0</can_be_empty>
102
+ </shipfrom_email>
103
+ <shipfrom_firstname translate="label">
104
+ <label>Ship FROM Firstname</label>
105
+ <frontend_type>text</frontend_type>
106
+ <sort_order>110</sort_order>
107
+ <show_in_default>1</show_in_default>
108
+ <show_in_website>1</show_in_website>
109
+ <show_in_store>0</show_in_store>
110
+ <can_be_empty>0</can_be_empty>
111
+ </shipfrom_firstname>
112
+ <shipfrom_lastname translate="label">
113
+ <label>Ship FROM Lastname</label>
114
+ <frontend_type>text</frontend_type>
115
+ <sort_order>110</sort_order>
116
+ <show_in_default>1</show_in_default>
117
+ <show_in_website>1</show_in_website>
118
+ <show_in_store>0</show_in_store>
119
+ <can_be_empty>0</can_be_empty>
120
+ </shipfrom_lastname>
121
+ -->
122
+ </fields>
123
+ </livrarionline>
124
+ </groups>
125
+ </carriers>
126
+ </sections>
127
+ </config>
app/code/local/Xtreme/Livrarionline/sql/livrarionline_setup/mysql4-install-0.1.0.php ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ $installer = $this;
4
+
5
+ $installer->startSetup();
6
+
7
+ $installer->run("
8
+
9
+ #DROP TABLE IF EXISTS {$this->getTable('livrarionline')};
10
+ CREATE TABLE IF NOT EXISTS {$this->getTable('livrarionline')} (
11
+ `livrarionline_id` int(11) unsigned NOT NULL auto_increment,
12
+ `title` varchar(255) NOT NULL default '',
13
+ `filename` varchar(255) NOT NULL default '',
14
+ `content` text NOT NULL default '',
15
+ `status` smallint(6) NOT NULL default '0',
16
+ `created_time` datetime NULL,
17
+ `update_time` datetime NULL,
18
+ PRIMARY KEY (`livrarionline_id`)
19
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
20
+
21
+ #DROP TABLE IF EXISTS {$this->getTable('livrarionline_carriers')};
22
+ CREATE TABLE IF NOT EXISTS {$this->getTable('livrarionline_carriers')} (
23
+ `carrier_id` int(11) unsigned NOT NULL auto_increment,
24
+ `name` varchar(255) NOT NULL default '',
25
+ `service_id` int(11) unsigned NOT NULL,
26
+ `shipping_company_id` int(11) unsigned NOT NULL,
27
+ `status` smallint(6) NOT NULL default '0',
28
+ `created_time` datetime NULL,
29
+ `updated_time` datetime NULL,
30
+ PRIMARY KEY (`carrier_id`),
31
+ KEY `created_time` (`created_time`),
32
+ KEY `updated_time` (`updated_time`)
33
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
34
+
35
+ #DROP TABLE IF EXISTS {$this->getTable('livrarionline_stores')};
36
+ CREATE TABLE IF NOT EXISTS {$this->getTable('livrarionline_stores')} (
37
+ `store_id` int(11) unsigned NOT NULL auto_increment,
38
+ `name` varchar(255) NOT NULL default '',
39
+ `address1` varchar(255) NOT NULL default '',
40
+ `address2` varchar(255) NULL,
41
+ `zipcode` varchar(20) NULL,
42
+ `city` varchar(255) NULL,
43
+ `country` varchar(2) NOT NULL,
44
+ `state` varchar(2) NOT NULL,
45
+ `latitude` decimal(10,6) unsigned NULL,
46
+ `longtitude` decimal(10,6) unsigned NULL,
47
+ `phone` varchar(50) default NULL,
48
+ `fax` varchar(50) default NULL,
49
+ `email` varchar(255) default NULL,
50
+ `firstname` varchar(255) default NULL,
51
+ `lastname` varchar(255) default NULL,
52
+ `comment` text default NULL,
53
+ `status` smallint(6) NOT NULL default '0',
54
+ `created_time` datetime NULL,
55
+ `updated_time` datetime NULL,
56
+ PRIMARY KEY (`store_id`),
57
+ KEY `created_time` (`created_time`),
58
+ KEY `updated_time` (`updated_time`),
59
+ KEY `name` (`name`)
60
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
61
+
62
+ #DROP TABLE IF EXISTS {$this->getTable('livrarionline_awb')};
63
+ CREATE TABLE IF NOT EXISTS {$this->getTable('livrarionline_awb')} (
64
+ `awb_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
65
+ `order_id` int(11) unsigned NOT NULL,
66
+ `service_id` int(11) unsigned NOT NULL,
67
+ `description` text NOT NULL,
68
+ `reference` text NOT NULL,
69
+ `declared_value` decimal(10,2) DEFAULT NULL,
70
+ `cod` decimal(10,2) DEFAULT NULL,
71
+ `currency` char(3) DEFAULT NULL,
72
+ `payee` int(11) unsigned NOT NULL,
73
+ `pick_from` int(11) unsigned NOT NULL,
74
+ `num_packages` int(11) unsigned NOT NULL,
75
+ `insurance` tinyint(1) NOT NULL DEFAULT '0',
76
+ `returndocs` tinyint(1) NOT NULL DEFAULT '0',
77
+ `returndocsbank` tinyint(1) NOT NULL DEFAULT '0',
78
+ `deliveryconf` tinyint(1) NOT NULL DEFAULT '0',
79
+ `deliverysat` tinyint(1) NOT NULL DEFAULT '0',
80
+ `emailnotify` tinyint(1) NOT NULL DEFAULT '0',
81
+ `smsnotify` tinyint(1) NOT NULL DEFAULT '0',
82
+ `deliveryconfmerchant` tinyint(1) NOT NULL DEFAULT '0',
83
+ `status` tinyint(1) NOT NULL DEFAULT '1',
84
+ `created_time` datetime DEFAULT NULL,
85
+ `updated_time` datetime DEFAULT NULL,
86
+ PRIMARY KEY (`awb_id`),
87
+ KEY `created_time` (`created_time`),
88
+ KEY `updated_time` (`updated_time`),
89
+ KEY `order_id` (`order_id`)
90
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
91
+
92
+ #DROP TABLE IF EXISTS {$this->getTable('livrarionline_awb_parcels')};
93
+ CREATE TABLE IF NOT EXISTS {$this->getTable('livrarionline_awb_parcels')} (
94
+ `parcel_id` int(11) unsigned NOT NULL auto_increment,
95
+ `awb_id` int(11) unsigned NOT NULL,
96
+ `parcel_type` int(11) unsigned NOT NULL,
97
+ `content` text NOT NULL default '',
98
+ `weight` decimal(10,2) NOT NULL default '0',
99
+ `length` decimal(10,2) NOT NULL default '0',
100
+ `width` decimal(10,2) NOT NULL default '0',
101
+ `height` decimal(10,2) NOT NULL default '0',
102
+ `created_time` datetime NULL,
103
+ `updated_time` datetime NULL,
104
+ PRIMARY KEY (`parcel_id`),
105
+ KEY `created_time` (`created_time`),
106
+ KEY `updated_time` (`updated_time`),
107
+ KEY `awb_id` (`awb_id`)
108
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
109
+
110
+
111
+ ALTER TABLE {$this->getTable('livrarionline_awb_parcels')}
112
+ ADD CONSTRAINT `FK_AWB_ID` FOREIGN KEY (`awb_id`) REFERENCES {$this->getTable('livrarionline_awb')} (`awb_id`) ON DELETE CASCADE;
113
+
114
+ ");
115
+
116
+ $installer->endSetup();
app/design/adminhtml/default/default/layout/livrarionline.xml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <layout version="0.1.0">
3
+ <!-- <livrarionline_adminhtml_livrarionline_index>
4
+ <reference name="content">
5
+ <block type="livrarionline/adminhtml_livrarionline" name="livrarionline" />
6
+ </reference>
7
+ </livrarionline_adminhtml_livrarionline_index>
8
+ -->
9
+ <livrarionline_adminhtml_manageawb_index>
10
+ <reference name="content">
11
+ <block type="livrarionline/adminhtml_manageawb" name="manageawb" />
12
+ </reference>
13
+ </livrarionline_adminhtml_manageawb_index>
14
+ <livrarionline_adminhtml_managecarriers_index>
15
+ <reference name="content">
16
+ <block type="livrarionline/adminhtml_managecarriers" name="managecarriers" />
17
+ </reference>
18
+ </livrarionline_adminhtml_managecarriers_index>
19
+ <livrarionline_adminhtml_managestores_index>
20
+ <reference name="content">
21
+ <block type="livrarionline/adminhtml_managestores" name="managestores" />
22
+ </reference>
23
+ </livrarionline_adminhtml_managestores_index>
24
+ <livrarionline_adminhtml_awb_index>
25
+ <reference name="head">
26
+ <action method="addJs"><js>livrarionline/jquery-1.11.1.min.js</js></action>
27
+ <action method="addJs"><js>livrarionline/jquery.noconflict.js</js></action>
28
+ </reference>
29
+ <reference name="content">
30
+ <!-- <block type="livrarionline/adminhtml_awb_form" name="awb" template="livrarionline/awb.phtml" /> -->
31
+ <block type="adminhtml/template" name="lo_awb" template="livrarionline/awb.phtml" />
32
+ </reference>
33
+ </livrarionline_adminhtml_awb_index>
34
+ <adminhtml_sales_order_view>
35
+ <!--
36
+ <reference name="sales_order_tabs">
37
+ <action method="addTab">
38
+ <name>loawb</name>
39
+ <block>livrarionline/Adminhtml_Sales_Order_View_Tab_Loawb</block>
40
+ </action>
41
+ </reference>
42
+ -->
43
+ <reference name="order_tab_info">
44
+ <action method="setTemplate">
45
+ <template>livrarionline/order/view/tab/info.phtml</template>
46
+ </action>
47
+ </reference>
48
+ </adminhtml_sales_order_view>
49
+ </layout>
app/design/adminhtml/default/default/template/livrarionline/awb.phtml ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*print "<pre>";
3
+ print_r($this->getOrder()->getData());
4
+ print "</pre>"; */
5
+ ?>
6
+
7
+ <?php if(preg_match("/^\w+_(\d+)$/", $this->getOrder()->getShippingMethod(), $m)) $service_id = $m[1]; ?>
8
+ <?php $carriers = Mage::getModel('livrarionline/carriers')->toOptionArray(); ?>
9
+ <?php $stores = Mage::getModel('livrarionline/stores')->toOptionArray(); ?>
10
+ <?php $payees = Mage::getModel('livrarionline/payee')->getOptionArray(); ?>
11
+ <?php $parcel_types = Mage::getModel('livrarionline/awb')->getTipColetOptionArray(); ?>
12
+ <?php $parcelcontent_types = Mage::getModel('livrarionline/awb')->getParcelContentOptionArray(); ?>
13
+
14
+ <div class="content-header">
15
+ <table cellspacing="0" class="grid-header">
16
+ <tr>
17
+ <td><h3><?php echo $this->__('LO Create AWB for order #%d', $this->getOrder()->getIncrementId())?></h3></td>
18
+ <td class="a-right">
19
+ <button onclick="$('form-button').click();" class="scalable save" type="button"><span><?php echo $this->__('Create AWB'); ?></span></button>
20
+ <!-- <input onclick="myForm.submit()" class="form-button" id="" type="submit" value="Save" /> -->
21
+ </td>
22
+ </tr>
23
+ </table>
24
+ </div>
25
+ <div class="entry-edit">
26
+ <!-- <form id="edit_form" name="edit_form" method="post" action="<?php echo $this->getUrl('*/*/save')?>"> -->
27
+ <form class="awb_form" id="awb_form" name="awb_form" action="<?php echo $this->getUrl('*/*/save')?>" method="post">
28
+ <div style="position: absolute; width: 300px; right: 100px; margin-top: 40px;">
29
+ <p><input type="checkbox" name="insurance" value="1" />&nbsp;<?php echo $this->__("Contents insurace") ?></p>
30
+ <p><input type="checkbox" name="returndocs" value="1" />&nbsp;<?php echo $this->__("Return documents") ?></p>
31
+ <p><input type="checkbox" name="returndocsbank" value="1" />&nbsp;<?php echo $this->__("Return banking documents") ?></p>
32
+ <p><input type="checkbox" name="deliveryconf" value="1" />&nbsp;<?php echo $this->__("Delivery confirmation") ?></p>
33
+ <p><input type="checkbox" name="deliverysat" value="1" />&nbsp;<?php echo $this->__("Delivery on Saturday") ?></p>
34
+ <p><input type="checkbox" name="emailnotify" value="1" checked />&nbsp;<?php echo $this->__("Email notification") ?></p>
35
+ <p><input type="checkbox" name="smsnotify" value="1" checked />&nbsp;<?php echo $this->__("SMS notification") ?></p>
36
+ <p><input type="checkbox" name="deliveryconfmerchant" value="1" checked />&nbsp;<?php echo $this->__("Delivery confirmation merchant") ?></p>
37
+ </div>
38
+ <input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
39
+ <input name="order_id" type="hidden" value="<?php echo $this->getOrder()->getId() ?>" />
40
+ <h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Delivery details')?></h4>
41
+ <fieldset id="my-fieldset1">
42
+ <table cellspacing="0" class="form-list">
43
+ <tr>
44
+ <td class="label"><?php echo $this->__('Select service')?> <span class="required">*</span></td>
45
+ <td class="input-element">
46
+ <select class="required-entry" name="service_id" id="service_id">
47
+ <?php foreach($carriers as $carrier): ?>
48
+ <option value="<?php echo $carrier['value']?>" <?php if (isset($service_id) && $service_id == $carrier['value']) echo "selected" ?>><?php echo $carrier['label']?></option>
49
+ <?php endforeach; ?>
50
+ </select>
51
+ </td>
52
+ </tr>
53
+ <tr>
54
+ <td class="label"><?php echo $this->__('Description')?></td>
55
+ <td class="input-element"><input class="input-text" name="description" /></td>
56
+ </tr>
57
+ <tr>
58
+ <td class="label"><?php echo $this->__('Reference')?> <span class="required">*</span></td>
59
+ <td class="input-element"><input class="input-text required-entry" name="reference" value="<?php echo $this->__("%s - Order Nr. %s", Mage::app()->getStore($this->getOrder()->getStoreId())->getName(), $this->getOrder()->getIncrementId()) ?>" /></td>
60
+ </tr>
61
+ <tr>
62
+ <td class="label"><?php echo $this->__('Declared value')?> <span class="required">*</span></td>
63
+ <td class="input-element"><input class="input-text required-entry" name="declared_value" value="<?php echo $this->getOrder()->getGrandTotal() ?>" /></td>
64
+ </tr>
65
+ <tr>
66
+ <td class="label"><?php echo $this->__('COD')?> <span class="required">*</span></td>
67
+ <td class="input-element"><input class="input-text required-entry" name="cod" value="<?php echo $this->getOrder()->getGrandTotal() ?>" /></td>
68
+ </tr>
69
+ <tr>
70
+ <td class="label"><?php echo $this->__('Currency')?> <span class="required">*</span></td>
71
+ <td class="input-element"><input class="input-text required-entry" name="currency" value="<?php echo $this->getOrder()->getOrderCurrencyCode() ?>" /></td>
72
+ </tr>
73
+ <tr>
74
+ <td class="label"><?php echo $this->__('Payee?')?> <span class="required">*</span></td>
75
+ <td class="input-element">
76
+ <select class="required-entry" name="payee">
77
+ <?php foreach($payees as $key => $value): ?>
78
+ <option value="<?php echo $key?>" <?php if($key == 2) echo "selected" ?> ><?php echo $value ?></option>
79
+ <?php endforeach; ?>
80
+ </select>
81
+ </td>
82
+ </tr>
83
+ <tr>
84
+ <td class="label"><?php echo $this->__('Pick up from')?> <span class="required">*</span></td>
85
+ <td class="input-element">
86
+ <select class="required-entry" name="pick_from">
87
+ <?php foreach($stores as $store): ?>
88
+ <option value="<?php echo $store['value']?>"><?php echo $store['label']?></option>
89
+ <?php endforeach; ?>
90
+ </select>
91
+ </td>
92
+ </tr>
93
+ </table>
94
+ </fieldset>
95
+ <h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Packages')?></h4>
96
+ <fieldset id="my-fieldset2">
97
+ <!--
98
+ <p>
99
+ <?php echo $this->__('Number of parcels')?> <span class="required">*</span>
100
+ <input class="input-text required-entry" name="num_packages" />
101
+ </p>
102
+ -->
103
+ <div class="grid">
104
+ <table id="table_parcels" cellspacing="0" class="data" style="width:100%;">
105
+ <tr class="headings">
106
+ <th><?php echo $this->__('Parcel type')?></th>
107
+ <th><?php echo $this->__('Content')?></th>
108
+ <th><?php echo $this->__('Weight (kg)')?></th>
109
+ <th><?php echo $this->__('Parcel length (cm)')?></th>
110
+ <th><?php echo $this->__('Parcel width (cm)')?></th>
111
+ <th><?php echo $this->__('Parcel height (cm)')?></th>
112
+ <th align="center"></th>
113
+ </tr>
114
+ <tr id="parcelrow_0">
115
+ <td>
116
+ <select name="parcels[0][parcel_type]">
117
+ <?php foreach($parcel_types as $key => $value): ?>
118
+ <option value="<?php echo $key?>"><?php echo $value ?></option>
119
+ <?php endforeach; ?>
120
+ </select>
121
+ </td>
122
+ <td>
123
+ <select name="parcels[0][content]">
124
+ <?php foreach($parcelcontent_types as $key => $value): ?>
125
+ <option value="<?php echo $key?>"><?php echo $value ?></option>
126
+ <?php endforeach; ?>
127
+ </select>
128
+ </td>
129
+ <td>
130
+ <input class="input-text" name="parcels[0][weight]" value="<?php echo ($this->getOrder()->getWeight() > 0) ? $this->getOrder()->getWeight() : "1" ?>" />
131
+ </td>
132
+ <td>
133
+ <input class="input-text " name="parcels[0][length]" value="1" />
134
+ </td>
135
+ <td>
136
+ <input class="input-text" name="parcels[0][width]" value="1" />
137
+ </td>
138
+ <td>
139
+ <input class="input-text " name="parcels[0][height]" value="1" />
140
+ </td>
141
+ <td>
142
+ </td>
143
+ </tr>
144
+ </table>
145
+ </div>
146
+ <button onclick="addParcel();" class="scalable" type="button"><span><?php echo $this->__('+ Add Parcel') ?></span></button>
147
+ </fieldset>
148
+ <input class="form-button" id="form-button" type="submit" value="Save" style="float: right" />
149
+ <span id="formLoader" style="display:none;">&nbsp;</span>
150
+ </form>
151
+ <div id="formSuccess" style="display:none;">&nbsp;</div>
152
+ </div>
153
+ <script type="text/javascript">
154
+ //<![CDATA[
155
+ var formId = 'awb_form';
156
+ var myForm = new varienForm(formId, 'service_id');
157
+ var postUrl = '<?php echo $this->getUrl("livrarionline/adminhtml_awb/save/") ?>';
158
+ function doAjax() {
159
+ if (myForm.validator.validate()) {
160
+ new Ajax.Updater(
161
+ { success:'formSuccess' }, postUrl, {
162
+ method:'post',
163
+ asynchronous:true,
164
+ evalScripts:false,
165
+ onComplete:function(request, json) {
166
+ Element.hide(formId);
167
+ Element.show('formSuccess');
168
+ },
169
+ onLoading:function(request, json){
170
+ Element.show('formLoader');
171
+ },
172
+ parameters: $(formId).serialize(true),
173
+ }
174
+ );
175
+ }
176
+ }
177
+
178
+ /*new Event.observe(formId, 'submit', function(e){
179
+ e.stop();
180
+ doAjax();
181
+ });*/
182
+ function removeParcel(rowid)
183
+ {
184
+ jQuery('#' + rowid).remove();
185
+ }
186
+ function addParcel()
187
+ {
188
+ var row = jQuery('#table_parcels tr:last');
189
+ var rowid = row.attr('id');
190
+ var no = rowid.match(/parcelrow_(\d+)/);
191
+ if(no.length > 0)
192
+ {
193
+ var newrowId = parseInt(no[1]) + 1;
194
+ var rowhtml =
195
+ '<tr id="parcelrow_' + newrowId + '">' +
196
+ '<td>' +
197
+ '<select name="parcels[' + newrowId + '][parcel_type]">' +
198
+ <?php foreach($parcel_types as $key => $value): ?>
199
+ '<option value="<?php echo $key?>"><?php echo $value ?></option>' +
200
+ <?php endforeach; ?>
201
+ '</select>' +
202
+ '</td>' +
203
+ '<td>' +
204
+ '<select name="parcels[' + newrowId + '][content]">' +
205
+ <?php foreach($parcelcontent_types as $key => $value): ?>
206
+ '<option value="<?php echo $key?>"><?php echo $value ?></option>' +
207
+ <?php endforeach; ?>
208
+ '</select>' +
209
+ '</td>' +
210
+ '<td>' +
211
+ '<input class="input-text" name="parcels[' + newrowId + '][weight]" />' +
212
+ '</td>' +
213
+ '<td>' +
214
+ '<input class="input-text " name="parcels[' + newrowId + '][length]" />' +
215
+ '</td>' +
216
+ '<td>' +
217
+ '<input class="input-text" name="parcels[' + newrowId + '][width]" />' +
218
+ '</td>' +
219
+ '<td>' +
220
+ '<input class="input-text " name="parcels[' + newrowId + '][height]" />' +
221
+ '</td>' +
222
+ '<td align="center">' +
223
+ '<button onclick="removeParcel(\'parcelrow_' + newrowId + '\');" class="scalable" type="button"><span><?php echo $this->__('Remove') ?></span></button>' +
224
+ '</td>' +
225
+ '</tr>';
226
+ jQuery('#table_parcels tr:last').after(rowhtml);
227
+ }
228
+ }
229
+ //]]>
230
+ </script>
app/design/adminhtml/default/default/template/livrarionline/order/view/tab/info.phtml ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Academic Free License (AFL 3.0)
8
+ * that is bundled with this package in the file LICENSE_AFL.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/afl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magentocommerce.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magentocommerce.com for more information.
20
+ *
21
+ * @category design
22
+ * @package default_default
23
+ * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
24
+ * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
25
+ */
26
+ ?>
27
+ <?php /** @var $this Mage_Adminhtml_Block_Sales_Order_View_Tab_Info */ ?>
28
+ <?php $_order = $this->getOrder() ?>
29
+ <div>
30
+ <div id="order-messages">
31
+ <?php echo $this->getChildHtml('order_messages') ?>
32
+ </div>
33
+ <?php echo $this->getChildHtml('order_info') ?>
34
+ <input type="hidden" name="order_id" value="<?php echo $_order->getId() ?>"/>
35
+ <?php if ($_order->getIsVirtual()): ?>
36
+ <div class="box-right">
37
+ <?php else: ?>
38
+ <div class="box-left">
39
+ <?php endif; ?>
40
+ <!--Payment Method-->
41
+ <div class="entry-edit">
42
+ <div class="entry-edit-head">
43
+ <h4 class="icon-head head-payment-method"><?php echo Mage::helper('sales')->__('Payment Information') ?></h4>
44
+ </div>
45
+ <fieldset>
46
+ <?php echo $this->getPaymentHtml() ?>
47
+ <div><?php echo Mage::helper('sales')->__('Order was placed using %s', $_order->getOrderCurrencyCode()) ?></div>
48
+ </fieldset>
49
+ </div>
50
+ </div>
51
+ <?php if (!$_order->getIsVirtual()): ?>
52
+ <div class="box-right">
53
+ <!--Shipping Method-->
54
+ <div class="entry-edit">
55
+ <div class="entry-edit-head">
56
+ <h4 class="icon-head head-shipping-method"><?php echo Mage::helper('sales')->__('Shipping &amp; Handling Information') ?></h4>
57
+ </div>
58
+ <fieldset>
59
+ <?php if ($_order->getTracksCollection()->count()) : ?>
60
+ <a href="#" id="linkId" onclick="popWin('<?php echo $this->helper('shipping')->getTrackingPopupUrlBySalesModel($_order) ?>','trackorder','width=800,height=600,resizable=yes,scrollbars=yes')" title="<?php echo $this->__('Track Order') ?>"><?php echo $this->__('Track Order') ?></a>
61
+ <a href="<?php echo $this->getUrl('loadmin/adminhtml_manageawb/index/'); ?>" title="<?php echo $this->__('Manage AWB') ?>"><?php echo $this->__('=> Manage AWB') ?></a>
62
+ <br/>
63
+ <?php endif; ?>
64
+ <?php if ($_order->getShippingDescription()): ?>
65
+ <strong><?php echo $this->escapeHtml($_order->getShippingDescription()) ?></strong>
66
+
67
+ <?php if ($this->helper('tax')->displayShippingPriceIncludingTax()): ?>
68
+ <?php $_excl = $this->displayShippingPriceInclTax($_order); ?>
69
+ <?php else: ?>
70
+ <?php $_excl = $this->displayPriceAttribute('shipping_amount', false, ' '); ?>
71
+ <?php endif; ?>
72
+ <?php $_incl = $this->displayShippingPriceInclTax($_order); ?>
73
+
74
+ <?php echo $_excl; ?>
75
+ <?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
76
+ (<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
77
+ <?php endif; ?>
78
+ <?php else: ?>
79
+ <?php echo $this->helper('sales')->__('No shipping information available'); ?>
80
+ <?php endif; ?>
81
+ </fieldset>
82
+ </div>
83
+ </div>
84
+ <?php endif; ?>
85
+ <div class="clear"></div>
86
+ <?php echo $this->getGiftOptionsHtml() ?>
87
+ <div class="clear"></div>
88
+ <div class="entry-edit">
89
+ <div class="entry-edit-head">
90
+ <h4 class="icon-head head-products"><?php echo Mage::helper('sales')->__('Items Ordered') ?></h4>
91
+ </div>
92
+ </div>
93
+ <?php echo $this->getItemsHtml() ?>
94
+ <div class="clear"></div>
95
+
96
+ <div class="box-left">
97
+ <div class="entry-edit">
98
+ <div class="entry-edit-head">
99
+ <h4><?php echo Mage::helper('sales')->__('Comments History') ?></h4>
100
+ </div>
101
+ <fieldset><?php echo $this->getChildHtml('order_history') ?></fieldset>
102
+ </div>
103
+ </div>
104
+ <div class="box-right entry-edit">
105
+ <div class="entry-edit-head"><h4><?php echo Mage::helper('sales')->__('Order Totals') ?></h4></div>
106
+ <div class="order-totals"><?php echo $this->getChildHtml('order_totals') ?></div>
107
+ </div>
108
+ <div class="clear"></div>
109
+ </div>
110
+
111
+ <?php echo $this->getChildHtml('popup_window');?>
112
+ <script type="text/javascript">
113
+ //<![CDATA[
114
+ /**
115
+ * Retrieve gift options tooltip content
116
+ */
117
+ function getGiftOptionsTooltipContent(itemId) {
118
+ var contentLines = [];
119
+ var headerLine = null;
120
+ var contentLine = null;
121
+
122
+ $$('#gift_options_data_' + itemId + ' .gift-options-tooltip-content').each(function (element) {
123
+ if (element.down(0)) {
124
+ headerLine = element.down(0).innerHTML;
125
+ contentLine = element.down(0).next().innerHTML;
126
+ if (contentLine.length > 30) {
127
+ contentLine = contentLine.slice(0,30) + '...';
128
+ }
129
+ contentLines.push(headerLine + ' ' + contentLine);
130
+ }
131
+ });
132
+ return contentLines.join('<br/>');
133
+ }
134
+ giftOptionsTooltip.setTooltipContentLoaderFunction(getGiftOptionsTooltipContent);
135
+ //]]>
136
+ </script>
app/design/adminhtml/default/default/template/livrarionline/sales/order/view/loawb.phtml ADDED
@@ -0,0 +1 @@
 
1
+ hello
app/etc/modules/Xtreme_Livrarionline.xml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <!--
3
+ /**
4
+ * @category Xtreme
5
+ * @package Xtreme_Livrarionline
6
+ * @author ModuleCreator
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ -->
10
+ <config>
11
+ <modules>
12
+ <Xtreme_Livrarionline>
13
+ <active>true</active>
14
+ <codePool>local</codePool>
15
+ </Xtreme_Livrarionline>
16
+ </modules>
17
+ </config>
js/livrarionline/jquery-1.11.1.min.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+ /*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
2
+ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;
3
+ if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")
4
+ },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
js/livrarionline/jquery.noconflict.js ADDED
@@ -0,0 +1 @@
 
1
+ $.noConflict();
lib/LivrariOnline/AES.php ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of AES.
5
+ *
6
+ * Uses mcrypt, if available/possible, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * If {@link Crypt_AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
11
+ * {@link Crypt_AES::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits
12
+ * it'll be null-padded to 192-bits and 192 bits will be the key length until {@link Crypt_AES::setKey() setKey()}
13
+ * is called, again, at which point, it'll be recalculated.
14
+ *
15
+ * Since Crypt_AES extends Crypt_Rijndael, some functions are available to be called that, in the context of AES, don't
16
+ * make a whole lot of sense. {@link Crypt_AES::setBlockLength() setBlockLength()}, for instance. Calling that function,
17
+ * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
18
+ *
19
+ * Here's a short example of how to use this library:
20
+ * <code>
21
+ * <?php
22
+ * include('Crypt/AES.php');
23
+ *
24
+ * $aes = new Crypt_AES();
25
+ *
26
+ * $aes->setKey('abcdefghijklmnop');
27
+ *
28
+ * $size = 10 * 1024;
29
+ * $plaintext = '';
30
+ * for ($i = 0; $i < $size; $i++) {
31
+ * $plaintext.= 'a';
32
+ * }
33
+ *
34
+ * echo $aes->decrypt($aes->encrypt($plaintext));
35
+ * ?>
36
+ * </code>
37
+ *
38
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
39
+ * of this software and associated documentation files (the "Software"), to deal
40
+ * in the Software without restriction, including without limitation the rights
41
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
42
+ * copies of the Software, and to permit persons to whom the Software is
43
+ * furnished to do so, subject to the following conditions:
44
+ *
45
+ * The above copyright notice and this permission notice shall be included in
46
+ * all copies or substantial portions of the Software.
47
+ *
48
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
54
+ * THE SOFTWARE.
55
+ *
56
+ * @category Crypt
57
+ * @package Crypt_AES
58
+ * @author Jim Wigginton <terrafrost@php.net>
59
+ * @copyright MMVIII Jim Wigginton
60
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
61
+ * @link http://phpseclib.sourceforge.net
62
+ */
63
+
64
+ /**
65
+ * Include Crypt_Rijndael
66
+ */
67
+ require_once('Rijndael.php');
68
+
69
+ /**#@+
70
+ * @access public
71
+ * @see Crypt_AES::encrypt()
72
+ * @see Crypt_AES::decrypt()
73
+ */
74
+ /**
75
+ * Encrypt / decrypt using the Counter mode.
76
+ *
77
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
78
+ *
79
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
80
+ */
81
+ define('CRYPT_AES_MODE_CTR', CRYPT_MODE_CTR);
82
+ /**
83
+ * Encrypt / decrypt using the Electronic Code Book mode.
84
+ *
85
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
86
+ */
87
+ define('CRYPT_AES_MODE_ECB', CRYPT_MODE_ECB);
88
+ /**
89
+ * Encrypt / decrypt using the Code Book Chaining mode.
90
+ *
91
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
92
+ */
93
+ define('CRYPT_AES_MODE_CBC', CRYPT_MODE_CBC);
94
+ /**
95
+ * Encrypt / decrypt using the Cipher Feedback mode.
96
+ *
97
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
98
+ */
99
+ define('CRYPT_AES_MODE_CFB', CRYPT_MODE_CFB);
100
+ /**
101
+ * Encrypt / decrypt using the Cipher Feedback mode.
102
+ *
103
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
104
+ */
105
+ define('CRYPT_AES_MODE_OFB', CRYPT_MODE_OFB);
106
+ /**#@-*/
107
+
108
+ /**#@+
109
+ * @access private
110
+ * @see Crypt_AES::Crypt_AES()
111
+ */
112
+ /**
113
+ * Toggles the internal implementation
114
+ */
115
+ define('CRYPT_AES_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
116
+ /**
117
+ * Toggles the mcrypt implementation
118
+ */
119
+ define('CRYPT_AES_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
120
+ /**#@-*/
121
+
122
+ /**
123
+ * Pure-PHP implementation of AES.
124
+ *
125
+ * @package Crypt_AES
126
+ * @author Jim Wigginton <terrafrost@php.net>
127
+ * @version 0.1.0
128
+ * @access public
129
+ */
130
+ class Crypt_AES extends Crypt_Rijndael
131
+ {
132
+ /**
133
+ * The namespace used by the cipher for its constants.
134
+ *
135
+ * @see Crypt_Base::const_namespace
136
+ * @var String
137
+ * @access private
138
+ */
139
+ var $const_namespace = 'AES';
140
+
141
+ /**
142
+ * Default Constructor.
143
+ *
144
+ * Determines whether or not the mcrypt extension should be used.
145
+ *
146
+ * $mode could be:
147
+ *
148
+ * - CRYPT_AES_MODE_ECB
149
+ *
150
+ * - CRYPT_AES_MODE_CBC
151
+ *
152
+ * - CRYPT_AES_MODE_CTR
153
+ *
154
+ * - CRYPT_AES_MODE_CFB
155
+ *
156
+ * - CRYPT_AES_MODE_OFB
157
+ *
158
+ * If not explictly set, CRYPT_AES_MODE_CBC will be used.
159
+ *
160
+ * @see Crypt_Rijndael::Crypt_Rijndael()
161
+ * @see Crypt_Base::Crypt_Base()
162
+ * @param optional Integer $mode
163
+ * @access public
164
+ */
165
+ function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
166
+ {
167
+ parent::Crypt_Rijndael($mode);
168
+ }
169
+
170
+ /**
171
+ * Dummy function
172
+ *
173
+ * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
174
+ *
175
+ * @see Crypt_Rijndael::setBlockLength()
176
+ * @access public
177
+ * @param Integer $length
178
+ */
179
+ function setBlockLength($length)
180
+ {
181
+ return;
182
+ }
183
+ }
184
+
lib/LivrariOnline/AES_Encryption.php ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /***
4
+ * AES_Encryption
5
+ * This class allows you to easily encrypt and decrypt text in AES format
6
+ * The class automatically determines whether you need 128, 192, or 256 bits
7
+ * based on your key size. It handles multiple padding formats.
8
+ *
9
+ * Dependencies:
10
+ * This class is dependent on PHP's mcrypt extension and a class called padCrypt
11
+ *
12
+ * Information about mcrypt extension is at:
13
+ * http://us.php.net/mcrypt
14
+ *
15
+ * padCrypt class is published at:
16
+ * http://dev.strategystar.net/2011/10/php-cryptography-padding-ansi-x-923-iso-10126-pkcs7-bit-zero/
17
+ *
18
+ * The padCrypt class provides methods for padding strings with the
19
+ * common methods described at:
20
+ * http://en.wikipedia.org/wiki/Padding_%28cryptography%29
21
+ *
22
+ * -- AES_Encryption Information
23
+ *
24
+ * Key Sizes:
25
+ * 16 bytes = 128 bit encryption
26
+ * 24 bytes = 192 bit encryption
27
+ * 32 bytes = 256 bit encryption
28
+ *
29
+ * Padding Formats:
30
+ * ANSI_X.923
31
+ * ISO_10126
32
+ * PKCS7
33
+ * BIT
34
+ * ZERO
35
+ *
36
+ * The default padding method in this AES_Encryption class is ZERO padding
37
+ * ZERO padding is generally OK for paddings in messages because
38
+ * null bytes stripped at the end of a readable message should not hurt
39
+ * the point of the text. If you are concerned about message integrity,
40
+ * you can use PKCS7 instead
41
+ *
42
+ * This class does not generate keys or vectors for you. You have to
43
+ * generate them yourself because you need to keep track of them yourself
44
+ * anyway in order to decrypt AES encryptions.
45
+ *
46
+ * -- Example Usage:
47
+ *
48
+ * $key = "bac09c63f34c9845c707228b20cac5e0";
49
+ * $iv = "47c743d1b21de03034e0842352ae6b98";
50
+ * $message = "Meet me at 11 o'clock behind the monument.";
51
+ *
52
+ * $AES = new AES_Encryption($key, $iv);
53
+ * $encrypted = $AES->encrypt($message);
54
+ * $decrypted = $AES->decrypt($encrypted);
55
+ * $base64_encrypted = base64_encode($encrypted);
56
+ *
57
+ * -- Credits:
58
+ *
59
+ * @author Strategy Star Inc.
60
+ * @website http://www.strategystar.net
61
+ **/
62
+
63
+ class AES_Encryption
64
+ {
65
+ private $key, $initVector, $mode, $cipher, $encryption = null;
66
+ private $allowed_bits = array(128, 192, 256);
67
+ private $allowed_modes = array('ecb', 'cfb', 'cbc', 'nofb', 'ofb');
68
+ private $vector_modes = array('cbc','cfb','ofb');
69
+ private $allowed_paddings = array(
70
+ 'ANSI_X.923' => 'ANSI_X923',
71
+ 'ISO_10126' => 'ISO_10126',
72
+ 'PKCS7' => 'PKCS7',
73
+ 'BIT' => 'BIT',
74
+ 'ZERO' => 'ZERO',
75
+ );
76
+
77
+ private $padCrypt_url = 'http://dev.strategystar.net/2011/10/php-cryptography-padding-ansi-x-923-iso-10126-pkcs7-bit-zero/';
78
+ private $aesEncrypt_url = 'http://dev.strategystar.net/';
79
+
80
+ /***
81
+ * String $key = Your secret key that you will use to encrypt/decrypt
82
+ * String $initVector = Your secret vector that you will use to encrypt/decrypt if using CBC, CFB, OFB, or a STREAM algorhitm that requires an IV
83
+ * String $padding = The padding method you want to use. The default is ZERO (aka NULL byte) [ANSI_X.923,ISO_10126,PKCS7,BIT,ZERO]
84
+ * String $mode = The encryption mode you want to use. The default is cbc [ecb,cfb,cbc,stream,nofb,ofb]
85
+ **/
86
+ public function __construct($key, $initVector='', $padding='ZERO', $mode='cbc')
87
+ {
88
+ $mode = strtolower($mode);
89
+ $padding = strtoupper($padding);
90
+
91
+ if(!class_exists('padCrypt'))
92
+ {
93
+ throw new Exception('The padCrypt class must be loaded for AES_Encryption to work: '.$padCrypt_url);
94
+ }
95
+
96
+ if(!function_exists('mcrypt_module_open'))
97
+ {
98
+ throw new Exception('The mcrypt extension must be loaded.');
99
+ }
100
+
101
+ if(strlen($initVector) != 16 && in_array($mode, $this->vector_modes))
102
+ {
103
+ throw new Exception('The $initVector is supposed to be 16 bytes in for CBC, CFB, NOFB, and OFB modes.');
104
+ }
105
+ elseif(!in_array($mode, $this->vector_modes) && !empty($initVector))
106
+ {
107
+ throw new Exception('The specified encryption mode does not use an initialization vector. You should pass an empty string, zero, FALSE, or NULL.');
108
+ }
109
+
110
+ $this->encryption = strlen($key)*8;
111
+
112
+ if(!in_array($this->encryption, $this->allowed_bits))
113
+ {
114
+ throw new Exception('The $key must be either 16, 24, or 32 bytes in length for 128, 192, and 256 bit encryption respectively.');
115
+ }
116
+
117
+ $this->key = $key;
118
+ $this->initVector = $initVector;
119
+
120
+ if(!in_array($mode, $this->allowed_modes))
121
+ {
122
+ throw new Exception('The $mode must be one of the following: '.implode(', ', $this->allowed_modes));
123
+ }
124
+
125
+ if(!array_key_exists($padding, $this->allowed_paddings))
126
+ {
127
+ throw new Exception('The $padding must be one of the following: '.implode(', ', $this->allowed_paddings));
128
+ }
129
+
130
+ $this->mode = $mode;
131
+ $this->padding = $padding;
132
+ $this->cipher = mcrypt_module_open('rijndael-128', '', $this->mode, '');
133
+ $this->block_size = mcrypt_get_block_size('rijndael-128', $this->mode);
134
+ }
135
+
136
+ /***
137
+ * String $text = The text that you want to encrypt
138
+ **/
139
+ public function encrypt($text)
140
+ {
141
+ mcrypt_generic_init($this->cipher, $this->key, $this->initVector);
142
+ $encrypted_text = mcrypt_generic($this->cipher, $this->pad($text, $this->block_size));
143
+ mcrypt_generic_deinit($this->cipher);
144
+ return $encrypted_text;
145
+ }
146
+
147
+ /***
148
+ * String $text = The text that you want to decrypt
149
+ **/
150
+ public function decrypt($text)
151
+ {
152
+ mcrypt_generic_init($this->cipher, $this->key, $this->initVector);
153
+ $decrypted_text = mdecrypt_generic($this->cipher, $text);
154
+ mcrypt_generic_deinit($this->cipher);
155
+ return $this->unpad($decrypted_text);
156
+ }
157
+
158
+ /***
159
+ * Use this function to export the key, init_vector, padding, and mode
160
+ * This information is necessary to later decrypt an encrypted message
161
+ **/
162
+ public function getConfiguration()
163
+ {
164
+ return array(
165
+ 'key' => $this->key,
166
+ 'init_vector' => $this->initVector,
167
+ 'padding' => $this->padding,
168
+ 'mode' => $this->mode,
169
+ 'encryption' => $this->encryption . ' Bit',
170
+ 'block_size' => $this->block_size,
171
+ );
172
+ }
173
+
174
+ private function pad($text, $block_size)
175
+ {
176
+ return call_user_func_array(array('padCrypt', 'pad_'.$this->allowed_paddings[$this->padding]), array($text, $block_size));
177
+ }
178
+
179
+ private function unpad($text)
180
+ {
181
+ return call_user_func_array(array('padCrypt', 'unpad_'.$this->allowed_paddings[$this->padding]), array($text));
182
+ }
183
+
184
+ public function __destruct()
185
+ {
186
+ mcrypt_module_close($this->cipher);
187
+ }
188
+ }
lib/LivrariOnline/Base.php ADDED
@@ -0,0 +1,1989 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Base Class for all Crypt_* cipher classes
6
+ *
7
+ * PHP versions 4 and 5
8
+ *
9
+ * Internally for phpseclib developers:
10
+ * If you plan to add a new cipher class, please note following rules:
11
+ *
12
+ * - The new Crypt_* cipher class should extend Crypt_Base
13
+ *
14
+ * - Following methods are then required to be overridden/overloaded:
15
+ *
16
+ * - _encryptBlock()
17
+ *
18
+ * - _decryptBlock()
19
+ *
20
+ * - _setupKey()
21
+ *
22
+ * - All other methods are optional to be overridden/overloaded
23
+ *
24
+ * - Look at the source code of the current ciphers how they extend Crypt_Base
25
+ * and take one of them as a start up for the new cipher class.
26
+ *
27
+ * - Please read all the other comments/notes/hints here also for each class var/method
28
+ *
29
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ * of this software and associated documentation files (the "Software"), to deal
31
+ * in the Software without restriction, including without limitation the rights
32
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ * copies of the Software, and to permit persons to whom the Software is
34
+ * furnished to do so, subject to the following conditions:
35
+ *
36
+ * The above copyright notice and this permission notice shall be included in
37
+ * all copies or substantial portions of the Software.
38
+ *
39
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ * THE SOFTWARE.
46
+ *
47
+ * @category Crypt
48
+ * @package Crypt_Base
49
+ * @author Jim Wigginton <terrafrost@php.net>
50
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
51
+ * @copyright MMVII Jim Wigginton
52
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
53
+ * @version 1.0.1
54
+ * @link http://phpseclib.sourceforge.net
55
+ */
56
+
57
+ /**#@+
58
+ * @access public
59
+ * @see Crypt_Base::encrypt()
60
+ * @see Crypt_Base::decrypt()
61
+ */
62
+ /**
63
+ * Encrypt / decrypt using the Counter mode.
64
+ *
65
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
66
+ *
67
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
68
+ */
69
+ define('CRYPT_MODE_CTR', -1);
70
+ /**
71
+ * Encrypt / decrypt using the Electronic Code Book mode.
72
+ *
73
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
74
+ */
75
+ define('CRYPT_MODE_ECB', 1);
76
+ /**
77
+ * Encrypt / decrypt using the Code Book Chaining mode.
78
+ *
79
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
80
+ */
81
+ define('CRYPT_MODE_CBC', 2);
82
+ /**
83
+ * Encrypt / decrypt using the Cipher Feedback mode.
84
+ *
85
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
86
+ */
87
+ define('CRYPT_MODE_CFB', 3);
88
+ /**
89
+ * Encrypt / decrypt using the Output Feedback mode.
90
+ *
91
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
92
+ */
93
+ define('CRYPT_MODE_OFB', 4);
94
+ /**
95
+ * Encrypt / decrypt using streaming mode.
96
+ *
97
+ */
98
+ define('CRYPT_MODE_STREAM', 5);
99
+ /**#@-*/
100
+
101
+ /**#@+
102
+ * @access private
103
+ * @see Crypt_Base::Crypt_Base()
104
+ */
105
+ /**
106
+ * Base value for the internal implementation $engine switch
107
+ */
108
+ define('CRYPT_MODE_INTERNAL', 1);
109
+ /**
110
+ * Base value for the mcrypt implementation $engine switch
111
+ */
112
+ define('CRYPT_MODE_MCRYPT', 2);
113
+ /**#@-*/
114
+
115
+ /**
116
+ * Base Class for all Crypt_* cipher classes
117
+ *
118
+ * @author Jim Wigginton <terrafrost@php.net>
119
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
120
+ * @version 1.0.0
121
+ * @access public
122
+ * @package Crypt_Base
123
+ */
124
+ class Crypt_Base {
125
+ /**
126
+ * The Encryption Mode
127
+ *
128
+ * @see Crypt_Base::Crypt_Base()
129
+ * @var Integer
130
+ * @access private
131
+ */
132
+ var $mode;
133
+
134
+ /**
135
+ * The Block Length of the block cipher
136
+ *
137
+ * @var Integer
138
+ * @access private
139
+ */
140
+ var $block_size = 16;
141
+
142
+ /**
143
+ * The Key
144
+ *
145
+ * @see Crypt_Base::setKey()
146
+ * @var String
147
+ * @access private
148
+ */
149
+ var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
150
+
151
+ /**
152
+ * The Initialization Vector
153
+ *
154
+ * @see Crypt_Base::setIV()
155
+ * @var String
156
+ * @access private
157
+ */
158
+ var $iv;
159
+
160
+ /**
161
+ * A "sliding" Initialization Vector
162
+ *
163
+ * @see Crypt_Base::enableContinuousBuffer()
164
+ * @see Crypt_Base::_clearBuffers()
165
+ * @var String
166
+ * @access private
167
+ */
168
+ var $encryptIV;
169
+
170
+ /**
171
+ * A "sliding" Initialization Vector
172
+ *
173
+ * @see Crypt_Base::enableContinuousBuffer()
174
+ * @see Crypt_Base::_clearBuffers()
175
+ * @var String
176
+ * @access private
177
+ */
178
+ var $decryptIV;
179
+
180
+ /**
181
+ * Continuous Buffer status
182
+ *
183
+ * @see Crypt_Base::enableContinuousBuffer()
184
+ * @var Boolean
185
+ * @access private
186
+ */
187
+ var $continuousBuffer = false;
188
+
189
+ /**
190
+ * Encryption buffer for CTR, OFB and CFB modes
191
+ *
192
+ * @see Crypt_Base::encrypt()
193
+ * @see Crypt_Base::_clearBuffers()
194
+ * @var Array
195
+ * @access private
196
+ */
197
+ var $enbuffer;
198
+
199
+ /**
200
+ * Decryption buffer for CTR, OFB and CFB modes
201
+ *
202
+ * @see Crypt_Base::decrypt()
203
+ * @see Crypt_Base::_clearBuffers()
204
+ * @var Array
205
+ * @access private
206
+ */
207
+ var $debuffer;
208
+
209
+ /**
210
+ * mcrypt resource for encryption
211
+ *
212
+ * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
213
+ * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
214
+ *
215
+ * @see Crypt_Base::encrypt()
216
+ * @var Resource
217
+ * @access private
218
+ */
219
+ var $enmcrypt;
220
+
221
+ /**
222
+ * mcrypt resource for decryption
223
+ *
224
+ * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
225
+ * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
226
+ *
227
+ * @see Crypt_Base::decrypt()
228
+ * @var Resource
229
+ * @access private
230
+ */
231
+ var $demcrypt;
232
+
233
+ /**
234
+ * Does the enmcrypt resource need to be (re)initialized?
235
+ *
236
+ * @see Crypt_Twofish::setKey()
237
+ * @see Crypt_Twofish::setIV()
238
+ * @var Boolean
239
+ * @access private
240
+ */
241
+ var $enchanged = true;
242
+
243
+ /**
244
+ * Does the demcrypt resource need to be (re)initialized?
245
+ *
246
+ * @see Crypt_Twofish::setKey()
247
+ * @see Crypt_Twofish::setIV()
248
+ * @var Boolean
249
+ * @access private
250
+ */
251
+ var $dechanged = true;
252
+
253
+ /**
254
+ * mcrypt resource for CFB mode
255
+ *
256
+ * mcrypt's CFB mode, in (and only in) buffered context,
257
+ * is broken, so phpseclib implements the CFB mode by it self,
258
+ * even when the mcrypt php extension is available.
259
+ *
260
+ * In order to do the CFB-mode work (fast) phpseclib
261
+ * use a separate ECB-mode mcrypt resource.
262
+ *
263
+ * @link http://phpseclib.sourceforge.net/cfb-demo.phps
264
+ * @see Crypt_Base::encrypt()
265
+ * @see Crypt_Base::decrypt()
266
+ * @see Crypt_Base::_setupMcrypt()
267
+ * @var Resource
268
+ * @access private
269
+ */
270
+ var $ecb;
271
+
272
+ /**
273
+ * Optimizing value while CFB-encrypting
274
+ *
275
+ * Only relevant if $continuousBuffer enabled
276
+ * and $engine == CRYPT_MODE_MCRYPT
277
+ *
278
+ * It's faster to re-init $enmcrypt if
279
+ * $buffer bytes > $cfb_init_len than
280
+ * using the $ecb resource furthermore.
281
+ *
282
+ * This value depends of the choosen cipher
283
+ * and the time it would be needed for it's
284
+ * initialization [by mcrypt_generic_init()]
285
+ * which, typically, depends on the complexity
286
+ * on its internaly Key-expanding algorithm.
287
+ *
288
+ * @see Crypt_Base::encrypt()
289
+ * @var Integer
290
+ * @access private
291
+ */
292
+ var $cfb_init_len = 600;
293
+
294
+ /**
295
+ * Does internal cipher state need to be (re)initialized?
296
+ *
297
+ * @see setKey()
298
+ * @see setIV()
299
+ * @see disableContinuousBuffer()
300
+ * @var Boolean
301
+ * @access private
302
+ */
303
+ var $changed = true;
304
+
305
+ /**
306
+ * Padding status
307
+ *
308
+ * @see Crypt_Base::enablePadding()
309
+ * @var Boolean
310
+ * @access private
311
+ */
312
+ var $padding = true;
313
+
314
+ /**
315
+ * Is the mode one that is paddable?
316
+ *
317
+ * @see Crypt_Base::Crypt_Base()
318
+ * @var Boolean
319
+ * @access private
320
+ */
321
+ var $paddable = false;
322
+
323
+ /**
324
+ * Holds which crypt engine internaly should be use,
325
+ * which will be determined automatically on __construct()
326
+ *
327
+ * Currently available $engines are:
328
+ * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
329
+ * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
330
+ *
331
+ * In the pipeline... maybe. But currently not available:
332
+ * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
333
+ *
334
+ * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
335
+ * Otherwise CRYPT_MODE_INTERNAL
336
+ *
337
+ * @see Crypt_Base::encrypt()
338
+ * @see Crypt_Base::decrypt()
339
+ * @var Integer
340
+ * @access private
341
+ */
342
+ var $engine;
343
+
344
+ /**
345
+ * The mcrypt specific name of the cipher
346
+ *
347
+ * Only used if $engine == CRYPT_MODE_MCRYPT
348
+ *
349
+ * @link http://www.php.net/mcrypt_module_open
350
+ * @link http://www.php.net/mcrypt_list_algorithms
351
+ * @see Crypt_Base::_setupMcrypt()
352
+ * @var String
353
+ * @access private
354
+ */
355
+ var $cipher_name_mcrypt;
356
+
357
+ /**
358
+ * The default password key_size used by setPassword()
359
+ *
360
+ * @see Crypt_Base::setPassword()
361
+ * @var Integer
362
+ * @access private
363
+ */
364
+ var $password_key_size = 32;
365
+
366
+ /**
367
+ * The default salt used by setPassword()
368
+ *
369
+ * @see Crypt_Base::setPassword()
370
+ * @var String
371
+ * @access private
372
+ */
373
+ var $password_default_salt = 'phpseclib/salt';
374
+
375
+ /**
376
+ * The namespace used by the cipher for its constants.
377
+ *
378
+ * ie: AES.php is using CRYPT_AES_MODE_* for its constants
379
+ * so $const_namespace is AES
380
+ *
381
+ * DES.php is using CRYPT_DES_MODE_* for its constants
382
+ * so $const_namespace is DES... and so on
383
+ *
384
+ * All CRYPT_<$const_namespace>_MODE_* are aliases of
385
+ * the generic CRYPT_MODE_* constants, so both could be used
386
+ * for each cipher.
387
+ *
388
+ * Example:
389
+ * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
390
+ * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
391
+ *
392
+ * @see Crypt_Base::Crypt_Base()
393
+ * @var String
394
+ * @access private
395
+ */
396
+ var $const_namespace;
397
+
398
+ /**
399
+ * The name of the performance-optimized callback function
400
+ *
401
+ * Used by encrypt() / decrypt()
402
+ * only if $engine == CRYPT_MODE_INTERNAL
403
+ *
404
+ * @see Crypt_Base::encrypt()
405
+ * @see Crypt_Base::decrypt()
406
+ * @see Crypt_Base::_setupInlineCrypt()
407
+ * @see Crypt_Base::$use_inline_crypt
408
+ * @var Callback
409
+ * @access private
410
+ */
411
+ var $inline_crypt;
412
+
413
+ /**
414
+ * Holds whether performance-optimized $inline_crypt() can/should be used.
415
+ *
416
+ * @see Crypt_Base::encrypt()
417
+ * @see Crypt_Base::decrypt()
418
+ * @see Crypt_Base::inline_crypt
419
+ * @var mixed
420
+ * @access private
421
+ */
422
+ var $use_inline_crypt;
423
+
424
+ /**
425
+ * Default Constructor.
426
+ *
427
+ * Determines whether or not the mcrypt extension should be used.
428
+ *
429
+ * $mode could be:
430
+ *
431
+ * - CRYPT_MODE_ECB
432
+ *
433
+ * - CRYPT_MODE_CBC
434
+ *
435
+ * - CRYPT_MODE_CTR
436
+ *
437
+ * - CRYPT_MODE_CFB
438
+ *
439
+ * - CRYPT_MODE_OFB
440
+ *
441
+ * (or the alias constants of the choosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
442
+ *
443
+ * If not explictly set, CRYPT_MODE_CBC will be used.
444
+ *
445
+ * @param optional Integer $mode
446
+ * @access public
447
+ */
448
+ function Crypt_Base($mode = CRYPT_MODE_CBC)
449
+ {
450
+ $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
451
+
452
+ // Determining the availibility of mcrypt support for the cipher
453
+ if (!defined($const_crypt_mode)) {
454
+ switch (true) {
455
+ case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
456
+ define($const_crypt_mode, CRYPT_MODE_MCRYPT);
457
+ break;
458
+ default:
459
+ define($const_crypt_mode, CRYPT_MODE_INTERNAL);
460
+ }
461
+ }
462
+
463
+ // Determining which internal $engine should be used.
464
+ // The fastes possible first.
465
+ switch (true) {
466
+ case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
467
+ $this->engine = CRYPT_MODE_INTERNAL;
468
+ break;
469
+ case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
470
+ $this->engine = CRYPT_MODE_MCRYPT;
471
+ break;
472
+ default:
473
+ $this->engine = CRYPT_MODE_INTERNAL;
474
+ }
475
+
476
+ // $mode dependent settings
477
+ switch ($mode) {
478
+ case CRYPT_MODE_ECB:
479
+ $this->paddable = true;
480
+ $this->mode = $mode;
481
+ break;
482
+ case CRYPT_MODE_CTR:
483
+ case CRYPT_MODE_CFB:
484
+ case CRYPT_MODE_OFB:
485
+ case CRYPT_MODE_STREAM:
486
+ $this->mode = $mode;
487
+ break;
488
+ case CRYPT_MODE_CBC:
489
+ default:
490
+ $this->paddable = true;
491
+ $this->mode = CRYPT_MODE_CBC;
492
+ }
493
+
494
+ // Determining whether inline crypting can be used by the cipher
495
+ if ($this->use_inline_crypt !== false && function_exists('create_function')) {
496
+ $this->use_inline_crypt = true;
497
+ }
498
+ }
499
+
500
+ /**
501
+ * Sets the initialization vector. (optional)
502
+ *
503
+ * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explictly set, it'll be assumed
504
+ * to be all zero's.
505
+ *
506
+ * Note: Could, but not must, extend by the child Crypt_* class
507
+ *
508
+ * @access public
509
+ * @param String $iv
510
+ */
511
+ function setIV($iv)
512
+ {
513
+ if ($this->mode == CRYPT_MODE_ECB) {
514
+ return;
515
+ }
516
+
517
+ $this->iv = $iv;
518
+ $this->changed = true;
519
+ }
520
+
521
+ /**
522
+ * Sets the key.
523
+ *
524
+ * The min/max length(s) of the key depends on the cipher which is used.
525
+ * If the key not fits the length(s) of the cipher it will paded with null bytes
526
+ * up to the closest valid key length. If the key is more than max length,
527
+ * we trim the excess bits.
528
+ *
529
+ * If the key is not explicitly set, it'll be assumed to be all null bytes.
530
+ *
531
+ * Note: Could, but not must, extend by the child Crypt_* class
532
+ *
533
+ * @access public
534
+ * @param String $key
535
+ */
536
+ function setKey($key)
537
+ {
538
+ $this->key = $key;
539
+ $this->changed = true;
540
+ }
541
+
542
+ /**
543
+ * Sets the password.
544
+ *
545
+ * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
546
+ * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
547
+ * $hash, $salt, $count, $dkLen
548
+ *
549
+ * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
550
+ *
551
+ * Note: Could, but not must, extend by the child Crypt_* class
552
+ *
553
+ * @see Crypt/Hash.php
554
+ * @param String $password
555
+ * @param optional String $method
556
+ * @access public
557
+ */
558
+ function setPassword($password, $method = 'pbkdf2')
559
+ {
560
+ $key = '';
561
+
562
+ switch ($method) {
563
+ default: // 'pbkdf2'
564
+ $func_args = func_get_args();
565
+
566
+ // Hash function
567
+ $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
568
+
569
+ // WPA and WPA2 use the SSID as the salt
570
+ $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
571
+
572
+ // RFC2898#section-4.2 uses 1,000 iterations by default
573
+ // WPA and WPA2 use 4,096.
574
+ $count = isset($func_args[4]) ? $func_args[4] : 1000;
575
+
576
+ // Keylength
577
+ $dkLen = isset($func_args[5]) ? $func_args[5] : $this->password_key_size;
578
+
579
+ // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
580
+ switch (true) {
581
+ case !function_exists('hash_pbkdf2'):
582
+ case !function_exists('hash_algos'):
583
+ case !in_array($hash, hash_algos()):
584
+ if (!class_exists('Crypt_Hash')) {
585
+ require_once('Crypt/Hash.php');
586
+ }
587
+ $i = 1;
588
+ while (strlen($key) < $dkLen) {
589
+ $hmac = new Crypt_Hash();
590
+ $hmac->setHash($hash);
591
+ $hmac->setKey($password);
592
+ $f = $u = $hmac->hash($salt . pack('N', $i++));
593
+ for ($j = 2; $j <= $count; ++$j) {
594
+ $u = $hmac->hash($u);
595
+ $f^= $u;
596
+ }
597
+ $key.= $f;
598
+ }
599
+ $key = substr($key, 0, $dkLen);
600
+ break;
601
+ default:
602
+ $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
603
+ }
604
+ }
605
+
606
+ $this->setKey($key);
607
+ }
608
+
609
+ /**
610
+ * Encrypts a message.
611
+ *
612
+ * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
613
+ * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
614
+ * necessary are discussed in the following
615
+ * URL:
616
+ *
617
+ * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
618
+ *
619
+ * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
620
+ * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
621
+ * length.
622
+ *
623
+ * Note: Could, but not must, extend by the child Crypt_* class
624
+ *
625
+ * @see Crypt_Base::decrypt()
626
+ * @access public
627
+ * @param String $plaintext
628
+ * @return String $cipertext
629
+ */
630
+ function encrypt($plaintext)
631
+ {
632
+ if ($this->engine == CRYPT_MODE_MCRYPT) {
633
+ if ($this->changed) {
634
+ $this->_setupMcrypt();
635
+ $this->changed = false;
636
+ }
637
+ if ($this->enchanged) {
638
+ mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
639
+ $this->enchanged = false;
640
+ }
641
+
642
+ // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
643
+ // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
644
+ // rewritten CFB implementation the above outputs the same thing twice.
645
+ if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
646
+ $block_size = $this->block_size;
647
+ $iv = &$this->encryptIV;
648
+ $pos = &$this->enbuffer['pos'];
649
+ $len = strlen($plaintext);
650
+ $ciphertext = '';
651
+ $i = 0;
652
+ if ($pos) {
653
+ $orig_pos = $pos;
654
+ $max = $block_size - $pos;
655
+ if ($len >= $max) {
656
+ $i = $max;
657
+ $len-= $max;
658
+ $pos = 0;
659
+ } else {
660
+ $i = $len;
661
+ $pos+= $len;
662
+ $len = 0;
663
+ }
664
+ $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
665
+ $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
666
+ $this->enbuffer['enmcrypt_init'] = true;
667
+ }
668
+ if ($len >= $block_size) {
669
+ if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
670
+ if ($this->enbuffer['enmcrypt_init'] === true) {
671
+ mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
672
+ $this->enbuffer['enmcrypt_init'] = false;
673
+ }
674
+ $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
675
+ $iv = substr($ciphertext, -$block_size);
676
+ $len%= $block_size;
677
+ } else {
678
+ while ($len >= $block_size) {
679
+ $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
680
+ $ciphertext.= $iv;
681
+ $len-= $block_size;
682
+ $i+= $block_size;
683
+ }
684
+ }
685
+ }
686
+
687
+ if ($len) {
688
+ $iv = mcrypt_generic($this->ecb, $iv);
689
+ $block = $iv ^ substr($plaintext, -$len);
690
+ $iv = substr_replace($iv, $block, 0, $len);
691
+ $ciphertext.= $block;
692
+ $pos = $len;
693
+ }
694
+
695
+ return $ciphertext;
696
+ }
697
+
698
+ if ($this->paddable) {
699
+ $plaintext = $this->_pad($plaintext);
700
+ }
701
+
702
+ $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
703
+
704
+ if (!$this->continuousBuffer) {
705
+ mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
706
+ }
707
+
708
+ return $ciphertext;
709
+ }
710
+
711
+ if ($this->changed) {
712
+ $this->_setup();
713
+ $this->changed = false;
714
+ }
715
+ if ($this->use_inline_crypt) {
716
+ $inline = $this->inline_crypt;
717
+ return $inline('encrypt', $this, $plaintext);
718
+ }
719
+ if ($this->paddable) {
720
+ $plaintext = $this->_pad($plaintext);
721
+ }
722
+
723
+ $buffer = &$this->enbuffer;
724
+ $block_size = $this->block_size;
725
+ $ciphertext = '';
726
+ switch ($this->mode) {
727
+ case CRYPT_MODE_ECB:
728
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
729
+ $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
730
+ }
731
+ break;
732
+ case CRYPT_MODE_CBC:
733
+ $xor = $this->encryptIV;
734
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
735
+ $block = substr($plaintext, $i, $block_size);
736
+ $block = $this->_encryptBlock($block ^ $xor);
737
+ $xor = $block;
738
+ $ciphertext.= $block;
739
+ }
740
+ if ($this->continuousBuffer) {
741
+ $this->encryptIV = $xor;
742
+ }
743
+ break;
744
+ case CRYPT_MODE_CTR:
745
+ $xor = $this->encryptIV;
746
+ if (strlen($buffer['encrypted'])) {
747
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
748
+ $block = substr($plaintext, $i, $block_size);
749
+ if (strlen($block) > strlen($buffer['encrypted'])) {
750
+ $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
751
+ }
752
+ $key = $this->_stringShift($buffer['encrypted'], $block_size);
753
+ $ciphertext.= $block ^ $key;
754
+ }
755
+ } else {
756
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
757
+ $block = substr($plaintext, $i, $block_size);
758
+ $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
759
+ $ciphertext.= $block ^ $key;
760
+ }
761
+ }
762
+ if ($this->continuousBuffer) {
763
+ $this->encryptIV = $xor;
764
+ if ($start = strlen($plaintext) % $block_size) {
765
+ $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
766
+ }
767
+ }
768
+ break;
769
+ case CRYPT_MODE_CFB:
770
+ // cfb loosely routines inspired by openssl's:
771
+ // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
772
+ if ($this->continuousBuffer) {
773
+ $iv = &$this->encryptIV;
774
+ $pos = &$buffer['pos'];
775
+ } else {
776
+ $iv = $this->encryptIV;
777
+ $pos = 0;
778
+ }
779
+ $len = strlen($plaintext);
780
+ $i = 0;
781
+ if ($pos) {
782
+ $orig_pos = $pos;
783
+ $max = $block_size - $pos;
784
+ if ($len >= $max) {
785
+ $i = $max;
786
+ $len-= $max;
787
+ $pos = 0;
788
+ } else {
789
+ $i = $len;
790
+ $pos+= $len;
791
+ $len = 0;
792
+ }
793
+ // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
794
+ $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
795
+ $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
796
+ }
797
+ while ($len >= $block_size) {
798
+ $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
799
+ $ciphertext.= $iv;
800
+ $len-= $block_size;
801
+ $i+= $block_size;
802
+ }
803
+ if ($len) {
804
+ $iv = $this->_encryptBlock($iv);
805
+ $block = $iv ^ substr($plaintext, $i);
806
+ $iv = substr_replace($iv, $block, 0, $len);
807
+ $ciphertext.= $block;
808
+ $pos = $len;
809
+ }
810
+ break;
811
+ case CRYPT_MODE_OFB:
812
+ $xor = $this->encryptIV;
813
+ if (strlen($buffer['xor'])) {
814
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
815
+ $block = substr($plaintext, $i, $block_size);
816
+ if (strlen($block) > strlen($buffer['xor'])) {
817
+ $xor = $this->_encryptBlock($xor);
818
+ $buffer['xor'].= $xor;
819
+ }
820
+ $key = $this->_stringShift($buffer['xor'], $block_size);
821
+ $ciphertext.= $block ^ $key;
822
+ }
823
+ } else {
824
+ for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
825
+ $xor = $this->_encryptBlock($xor);
826
+ $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
827
+ }
828
+ $key = $xor;
829
+ }
830
+ if ($this->continuousBuffer) {
831
+ $this->encryptIV = $xor;
832
+ if ($start = strlen($plaintext) % $block_size) {
833
+ $buffer['xor'] = substr($key, $start) . $buffer['xor'];
834
+ }
835
+ }
836
+ break;
837
+ case CRYPT_MODE_STREAM:
838
+ $ciphertext = $this->_encryptBlock($plaintext);
839
+ break;
840
+ }
841
+
842
+ return $ciphertext;
843
+ }
844
+
845
+ /**
846
+ * Decrypts a message.
847
+ *
848
+ * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
849
+ * it is.
850
+ *
851
+ * Note: Could, but not must, extend by the child Crypt_* class
852
+ *
853
+ * @see Crypt_Base::encrypt()
854
+ * @access public
855
+ * @param String $ciphertext
856
+ * @return String $plaintext
857
+ */
858
+ function decrypt($ciphertext)
859
+ {
860
+ if ($this->engine == CRYPT_MODE_MCRYPT) {
861
+ $block_size = $this->block_size;
862
+ if ($this->changed) {
863
+ $this->_setupMcrypt();
864
+ $this->changed = false;
865
+ }
866
+ if ($this->dechanged) {
867
+ mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
868
+ $this->dechanged = false;
869
+ }
870
+
871
+ if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
872
+ $iv = &$this->decryptIV;
873
+ $pos = &$this->debuffer['pos'];
874
+ $len = strlen($ciphertext);
875
+ $plaintext = '';
876
+ $i = 0;
877
+ if ($pos) {
878
+ $orig_pos = $pos;
879
+ $max = $block_size - $pos;
880
+ if ($len >= $max) {
881
+ $i = $max;
882
+ $len-= $max;
883
+ $pos = 0;
884
+ } else {
885
+ $i = $len;
886
+ $pos+= $len;
887
+ $len = 0;
888
+ }
889
+ // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
890
+ $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
891
+ $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
892
+ }
893
+ if ($len >= $block_size) {
894
+ $cb = substr($ciphertext, $i, $len - $len % $block_size);
895
+ $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
896
+ $iv = substr($cb, -$block_size);
897
+ $len%= $block_size;
898
+ }
899
+ if ($len) {
900
+ $iv = mcrypt_generic($this->ecb, $iv);
901
+ $plaintext.= $iv ^ substr($ciphertext, -$len);
902
+ $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
903
+ $pos = $len;
904
+ }
905
+
906
+ return $plaintext;
907
+ }
908
+
909
+ if ($this->paddable) {
910
+ // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
911
+ // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
912
+ $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
913
+ }
914
+
915
+ $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
916
+
917
+ if (!$this->continuousBuffer) {
918
+ mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
919
+ }
920
+
921
+ return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
922
+ }
923
+
924
+ if ($this->changed) {
925
+ $this->_setup();
926
+ $this->changed = false;
927
+ }
928
+ if ($this->use_inline_crypt) {
929
+ $inline = $this->inline_crypt;
930
+ return $inline('decrypt', $this, $ciphertext);
931
+ }
932
+
933
+ $block_size = $this->block_size;
934
+ if ($this->paddable) {
935
+ // we pad with chr(0) since that's what mcrypt_generic does [...]
936
+ $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
937
+ }
938
+
939
+ $buffer = &$this->debuffer;
940
+ $plaintext = '';
941
+ switch ($this->mode) {
942
+ case CRYPT_MODE_ECB:
943
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
944
+ $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
945
+ }
946
+ break;
947
+ case CRYPT_MODE_CBC:
948
+ $xor = $this->decryptIV;
949
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
950
+ $block = substr($ciphertext, $i, $block_size);
951
+ $plaintext.= $this->_decryptBlock($block) ^ $xor;
952
+ $xor = $block;
953
+ }
954
+ if ($this->continuousBuffer) {
955
+ $this->decryptIV = $xor;
956
+ }
957
+ break;
958
+ case CRYPT_MODE_CTR:
959
+ $xor = $this->decryptIV;
960
+ if (strlen($buffer['ciphertext'])) {
961
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
962
+ $block = substr($ciphertext, $i, $block_size);
963
+ if (strlen($block) > strlen($buffer['ciphertext'])) {
964
+ $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
965
+ }
966
+ $key = $this->_stringShift($buffer['ciphertext'], $block_size);
967
+ $plaintext.= $block ^ $key;
968
+ }
969
+ } else {
970
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
971
+ $block = substr($ciphertext, $i, $block_size);
972
+ $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
973
+ $plaintext.= $block ^ $key;
974
+ }
975
+ }
976
+ if ($this->continuousBuffer) {
977
+ $this->decryptIV = $xor;
978
+ if ($start = strlen($ciphertext) % $block_size) {
979
+ $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
980
+ }
981
+ }
982
+ break;
983
+ case CRYPT_MODE_CFB:
984
+ if ($this->continuousBuffer) {
985
+ $iv = &$this->decryptIV;
986
+ $pos = &$buffer['pos'];
987
+ } else {
988
+ $iv = $this->decryptIV;
989
+ $pos = 0;
990
+ }
991
+ $len = strlen($ciphertext);
992
+ $i = 0;
993
+ if ($pos) {
994
+ $orig_pos = $pos;
995
+ $max = $block_size - $pos;
996
+ if ($len >= $max) {
997
+ $i = $max;
998
+ $len-= $max;
999
+ $pos = 0;
1000
+ } else {
1001
+ $i = $len;
1002
+ $pos+= $len;
1003
+ $len = 0;
1004
+ }
1005
+ // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
1006
+ $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1007
+ $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1008
+ }
1009
+ while ($len >= $block_size) {
1010
+ $iv = $this->_encryptBlock($iv);
1011
+ $cb = substr($ciphertext, $i, $block_size);
1012
+ $plaintext.= $iv ^ $cb;
1013
+ $iv = $cb;
1014
+ $len-= $block_size;
1015
+ $i+= $block_size;
1016
+ }
1017
+ if ($len) {
1018
+ $iv = $this->_encryptBlock($iv);
1019
+ $plaintext.= $iv ^ substr($ciphertext, $i);
1020
+ $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1021
+ $pos = $len;
1022
+ }
1023
+ break;
1024
+ case CRYPT_MODE_OFB:
1025
+ $xor = $this->decryptIV;
1026
+ if (strlen($buffer['xor'])) {
1027
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1028
+ $block = substr($ciphertext, $i, $block_size);
1029
+ if (strlen($block) > strlen($buffer['xor'])) {
1030
+ $xor = $this->_encryptBlock($xor);
1031
+ $buffer['xor'].= $xor;
1032
+ }
1033
+ $key = $this->_stringShift($buffer['xor'], $block_size);
1034
+ $plaintext.= $block ^ $key;
1035
+ }
1036
+ } else {
1037
+ for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1038
+ $xor = $this->_encryptBlock($xor);
1039
+ $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
1040
+ }
1041
+ $key = $xor;
1042
+ }
1043
+ if ($this->continuousBuffer) {
1044
+ $this->decryptIV = $xor;
1045
+ if ($start = strlen($ciphertext) % $block_size) {
1046
+ $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1047
+ }
1048
+ }
1049
+ break;
1050
+ case CRYPT_MODE_STREAM:
1051
+ $plaintext = $this->_decryptBlock($ciphertext);
1052
+ break;
1053
+ }
1054
+ return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1055
+ }
1056
+
1057
+ /**
1058
+ * Pad "packets".
1059
+ *
1060
+ * Block ciphers working by encrypting between their specified [$this->]block_size at a time
1061
+ * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
1062
+ * pad the input so that it is of the proper length.
1063
+ *
1064
+ * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
1065
+ * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1066
+ * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1067
+ * transmitted separately)
1068
+ *
1069
+ * @see Crypt_Base::disablePadding()
1070
+ * @access public
1071
+ */
1072
+ function enablePadding()
1073
+ {
1074
+ $this->padding = true;
1075
+ }
1076
+
1077
+ /**
1078
+ * Do not pad packets.
1079
+ *
1080
+ * @see Crypt_Base::enablePadding()
1081
+ * @access public
1082
+ */
1083
+ function disablePadding()
1084
+ {
1085
+ $this->padding = false;
1086
+ }
1087
+
1088
+ /**
1089
+ * Treat consecutive "packets" as if they are a continuous buffer.
1090
+ *
1091
+ * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1092
+ * will yield different outputs:
1093
+ *
1094
+ * <code>
1095
+ * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1096
+ * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1097
+ * </code>
1098
+ * <code>
1099
+ * echo $rijndael->encrypt($plaintext);
1100
+ * </code>
1101
+ *
1102
+ * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1103
+ * another, as demonstrated with the following:
1104
+ *
1105
+ * <code>
1106
+ * $rijndael->encrypt(substr($plaintext, 0, 16));
1107
+ * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1108
+ * </code>
1109
+ * <code>
1110
+ * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1111
+ * </code>
1112
+ *
1113
+ * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1114
+ * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1115
+ * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1116
+ *
1117
+ * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
1118
+ * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1119
+ * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1120
+ * however, they are also less intuitive and more likely to cause you problems.
1121
+ *
1122
+ * Note: Could, but not must, extend by the child Crypt_* class
1123
+ *
1124
+ * @see Crypt_Base::disableContinuousBuffer()
1125
+ * @access public
1126
+ */
1127
+ function enableContinuousBuffer()
1128
+ {
1129
+ if ($this->mode == CRYPT_MODE_ECB) {
1130
+ return;
1131
+ }
1132
+
1133
+ $this->continuousBuffer = true;
1134
+ }
1135
+
1136
+ /**
1137
+ * Treat consecutive packets as if they are a discontinuous buffer.
1138
+ *
1139
+ * The default behavior.
1140
+ *
1141
+ * Note: Could, but not must, extend by the child Crypt_* class
1142
+ *
1143
+ * @see Crypt_Base::enableContinuousBuffer()
1144
+ * @access public
1145
+ */
1146
+ function disableContinuousBuffer()
1147
+ {
1148
+ if ($this->mode == CRYPT_MODE_ECB) {
1149
+ return;
1150
+ }
1151
+ if (!$this->continuousBuffer) {
1152
+ return;
1153
+ }
1154
+
1155
+ $this->continuousBuffer = false;
1156
+ $this->changed = true;
1157
+ }
1158
+
1159
+ /**
1160
+ * Encrypts a block
1161
+ *
1162
+ * Note: Must extend by the child Crypt_* class
1163
+ *
1164
+ * @access private
1165
+ * @param String $in
1166
+ * @return String
1167
+ */
1168
+ function _encryptBlock($in)
1169
+ {
1170
+ user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1171
+ }
1172
+
1173
+ /**
1174
+ * Decrypts a block
1175
+ *
1176
+ * Note: Must extend by the child Crypt_* class
1177
+ *
1178
+ * @access private
1179
+ * @param String $in
1180
+ * @return String
1181
+ */
1182
+ function _decryptBlock($in)
1183
+ {
1184
+ user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1185
+ }
1186
+
1187
+ /**
1188
+ * Setup the key (expansion)
1189
+ *
1190
+ * Only used if $engine == CRYPT_MODE_INTERNAL
1191
+ *
1192
+ * Note: Must extend by the child Crypt_* class
1193
+ *
1194
+ * @see Crypt_Base::_setup()
1195
+ * @access private
1196
+ */
1197
+ function _setupKey()
1198
+ {
1199
+ user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1200
+ }
1201
+
1202
+ /**
1203
+ * Setup the CRYPT_MODE_INTERNAL $engine
1204
+ *
1205
+ * (re)init, if necessary, the internal cipher $engine and flush all $buffers
1206
+ * Used (only) if $engine == CRYPT_MODE_INTERNAL
1207
+ *
1208
+ * _setup() will be called each time if $changed === true
1209
+ * typically this happens when using one or more of following public methods:
1210
+ *
1211
+ * - setKey()
1212
+ *
1213
+ * - setIV()
1214
+ *
1215
+ * - disableContinuousBuffer()
1216
+ *
1217
+ * - First run of encrypt() / decrypt() with no init-settings
1218
+ *
1219
+ * Internally: _setup() is called always before(!) en/decryption.
1220
+ *
1221
+ * Note: Could, but not must, extend by the child Crypt_* class
1222
+ *
1223
+ * @see setKey()
1224
+ * @see setIV()
1225
+ * @see disableContinuousBuffer()
1226
+ * @access private
1227
+ */
1228
+ function _setup()
1229
+ {
1230
+ $this->_clearBuffers();
1231
+ $this->_setupKey();
1232
+
1233
+ if ($this->use_inline_crypt) {
1234
+ $this->_setupInlineCrypt();
1235
+ }
1236
+ }
1237
+
1238
+ /**
1239
+ * Setup the CRYPT_MODE_MCRYPT $engine
1240
+ *
1241
+ * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
1242
+ * Used (only) if $engine = CRYPT_MODE_MCRYPT
1243
+ *
1244
+ * _setupMcrypt() will be called each time if $changed === true
1245
+ * typically this happens when using one or more of following public methods:
1246
+ *
1247
+ * - setKey()
1248
+ *
1249
+ * - setIV()
1250
+ *
1251
+ * - disableContinuousBuffer()
1252
+ *
1253
+ * - First run of encrypt() / decrypt()
1254
+ *
1255
+ *
1256
+ * Note: Could, but not must, extend by the child Crypt_* class
1257
+ *
1258
+ * @see setKey()
1259
+ * @see setIV()
1260
+ * @see disableContinuousBuffer()
1261
+ * @access private
1262
+ */
1263
+ function _setupMcrypt()
1264
+ {
1265
+ $this->_clearBuffers();
1266
+ $this->enchanged = $this->dechanged = true;
1267
+
1268
+ if (!isset($this->enmcrypt)) {
1269
+ static $mcrypt_modes = array(
1270
+ CRYPT_MODE_CTR => 'ctr',
1271
+ CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
1272
+ CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
1273
+ CRYPT_MODE_CFB => 'ncfb',
1274
+ CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
1275
+ CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
1276
+ );
1277
+
1278
+ $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1279
+ $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1280
+
1281
+ // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
1282
+ // to workaround mcrypt's broken ncfb implementation in buffered mode
1283
+ // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
1284
+ if ($this->mode == CRYPT_MODE_CFB) {
1285
+ $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
1286
+ }
1287
+
1288
+ } // else should mcrypt_generic_deinit be called?
1289
+
1290
+ if ($this->mode == CRYPT_MODE_CFB) {
1291
+ mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
1292
+ }
1293
+ }
1294
+
1295
+ /**
1296
+ * Pads a string
1297
+ *
1298
+ * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
1299
+ * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
1300
+ * chr($this->block_size - (strlen($text) % $this->block_size)
1301
+ *
1302
+ * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1303
+ * and padding will, hence forth, be enabled.
1304
+ *
1305
+ * @see Crypt_Base::_unpad()
1306
+ * @param String $text
1307
+ * @access private
1308
+ * @return String
1309
+ */
1310
+ function _pad($text)
1311
+ {
1312
+ $length = strlen($text);
1313
+
1314
+ if (!$this->padding) {
1315
+ if ($length % $this->block_size == 0) {
1316
+ return $text;
1317
+ } else {
1318
+ user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
1319
+ $this->padding = true;
1320
+ }
1321
+ }
1322
+
1323
+ $pad = $this->block_size - ($length % $this->block_size);
1324
+
1325
+ return str_pad($text, $length + $pad, chr($pad));
1326
+ }
1327
+
1328
+ /**
1329
+ * Unpads a string.
1330
+ *
1331
+ * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1332
+ * and false will be returned.
1333
+ *
1334
+ * @see Crypt_Base::_pad()
1335
+ * @param String $text
1336
+ * @access private
1337
+ * @return String
1338
+ */
1339
+ function _unpad($text)
1340
+ {
1341
+ if (!$this->padding) {
1342
+ return $text;
1343
+ }
1344
+
1345
+ $length = ord($text[strlen($text) - 1]);
1346
+
1347
+ if (!$length || $length > $this->block_size) {
1348
+ return false;
1349
+ }
1350
+
1351
+ return substr($text, 0, -$length);
1352
+ }
1353
+
1354
+ /**
1355
+ * Clears internal buffers
1356
+ *
1357
+ * Clearing/resetting the internal buffers is done everytime
1358
+ * after disableContinuousBuffer() or on cipher $engine (re)init
1359
+ * ie after setKey() or setIV()
1360
+ *
1361
+ * Note: Could, but not must, extend by the child Crypt_* class
1362
+ *
1363
+ * @access public
1364
+ */
1365
+ function _clearBuffers()
1366
+ {
1367
+ $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1368
+ $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1369
+
1370
+ // mcrypt's handling of invalid's $iv:
1371
+ // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
1372
+ $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
1373
+ }
1374
+
1375
+ /**
1376
+ * String Shift
1377
+ *
1378
+ * Inspired by array_shift
1379
+ *
1380
+ * @param String $string
1381
+ * @param optional Integer $index
1382
+ * @access private
1383
+ * @return String
1384
+ */
1385
+ function _stringShift(&$string, $index = 1)
1386
+ {
1387
+ $substr = substr($string, 0, $index);
1388
+ $string = substr($string, $index);
1389
+ return $substr;
1390
+ }
1391
+
1392
+ /**
1393
+ * Generate CTR XOR encryption key
1394
+ *
1395
+ * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1396
+ * plaintext / ciphertext in CTR mode.
1397
+ *
1398
+ * @see Crypt_Base::decrypt()
1399
+ * @see Crypt_Base::encrypt()
1400
+ * @param String $iv
1401
+ * @param Integer $length
1402
+ * @access private
1403
+ * @return String $xor
1404
+ */
1405
+ function _generateXor(&$iv, $length)
1406
+ {
1407
+ $xor = '';
1408
+ $block_size = $this->block_size;
1409
+ $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
1410
+ for ($i = 0; $i < $num_blocks; $i++) {
1411
+ $xor.= $iv;
1412
+ for ($j = 4; $j <= $block_size; $j+= 4) {
1413
+ $temp = substr($iv, -$j, 4);
1414
+ switch ($temp) {
1415
+ case "\xFF\xFF\xFF\xFF":
1416
+ $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1417
+ break;
1418
+ case "\x7F\xFF\xFF\xFF":
1419
+ $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1420
+ break 2;
1421
+ default:
1422
+ extract(unpack('Ncount', $temp));
1423
+ $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1424
+ break 2;
1425
+ }
1426
+ }
1427
+ }
1428
+
1429
+ return $xor;
1430
+ }
1431
+
1432
+ /**
1433
+ * Setup the performance-optimized function for de/encrypt()
1434
+ *
1435
+ * Stores the created (or existing) callback function-name
1436
+ * in $this->inline_crypt
1437
+ *
1438
+ * Internally for phpseclib developers:
1439
+ *
1440
+ * _setupInlineCrypt() would be called only if:
1441
+ *
1442
+ * - $engine == CRYPT_MODE_INTERNAL and
1443
+ *
1444
+ * - $use_inline_crypt === true
1445
+ *
1446
+ * - each time on _setup(), after(!) _setupKey()
1447
+ *
1448
+ *
1449
+ * This ensures that _setupInlineCrypt() has allways a
1450
+ * full ready2go initializated internal cipher $engine state
1451
+ * where, for example, the keys allready expanded,
1452
+ * keys/block_size calculated and such.
1453
+ *
1454
+ * It is, each time if called, the responsibility of _setupInlineCrypt():
1455
+ *
1456
+ * - to set $this->inline_crypt to a valid and fully working callback function
1457
+ * as a (faster) replacement for encrypt() / decrypt()
1458
+ *
1459
+ * - NOT to create unlimited callback functions (for memory reasons!)
1460
+ * no matter how often _setupInlineCrypt() would be called. At some
1461
+ * point of amount they must be generic re-useable.
1462
+ *
1463
+ * - the code of _setupInlineCrypt() it self,
1464
+ * and the generated callback code,
1465
+ * must be, in following order:
1466
+ * - 100% safe
1467
+ * - 100% compatible to encrypt()/decrypt()
1468
+ * - using only php5+ features/lang-constructs/php-extensions if
1469
+ * compatibility (down to php4) or fallback is provided
1470
+ * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
1471
+ * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
1472
+ * the reason for the existence of _setupInlineCrypt() :-)]
1473
+ * - memory-nice
1474
+ * - short (as good as possible)
1475
+ *
1476
+ * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
1477
+ * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
1478
+ * - The following variable names are reserved:
1479
+ * - $_* (all variable names prefixed with an underscore)
1480
+ * - $self (object reference to it self. Do not use $this, but $self instead)
1481
+ * - $in (the content of $in has to en/decrypt by the generated code)
1482
+ * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
1483
+ *
1484
+ *
1485
+ * @see Crypt_Base::_setup()
1486
+ * @see Crypt_Base::_createInlineCryptFunction()
1487
+ * @see Crypt_Base::encrypt()
1488
+ * @see Crypt_Base::decrypt()
1489
+ * @access private
1490
+ */
1491
+ function _setupInlineCrypt()
1492
+ {
1493
+ // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
1494
+
1495
+ // If, for any reason, an extending Crypt_Base() Crypt_* class
1496
+ // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
1497
+ // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
1498
+ // in the constructor at object instance-time
1499
+ // or, if it's runtime-specific, at runtime
1500
+
1501
+ $this->use_inline_crypt = false;
1502
+ }
1503
+
1504
+ /**
1505
+ * Creates the performance-optimized function for en/decrypt()
1506
+ *
1507
+ * Internally for phpseclib developers:
1508
+ *
1509
+ * _createInlineCryptFunction():
1510
+ *
1511
+ * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
1512
+ * with the current [$this->]mode of operation code
1513
+ *
1514
+ * - create the $inline function, which called by encrypt() / decrypt()
1515
+ * as its replacement to speed up the en/decryption operations.
1516
+ *
1517
+ * - return the name of the created $inline callback function
1518
+ *
1519
+ * - used to speed up en/decryption
1520
+ *
1521
+ *
1522
+ *
1523
+ * The main reason why can speed up things [up to 50%] this way are:
1524
+ *
1525
+ * - using variables more effective then regular.
1526
+ * (ie no use of expensive arrays but integers $k_0, $k_1 ...
1527
+ * or even, for example, the pure $key[] values hardcoded)
1528
+ *
1529
+ * - avoiding 1000's of function calls of ie _encryptBlock()
1530
+ * but inlining the crypt operations.
1531
+ * in the mode of operation for() loop.
1532
+ *
1533
+ * - full loop unroll the (sometimes key-dependent) rounds
1534
+ * avoiding this way ++$i counters and runtime-if's etc...
1535
+ *
1536
+ * The basic code architectur of the generated $inline en/decrypt()
1537
+ * lambda function, in pseudo php, is:
1538
+ *
1539
+ * <code>
1540
+ * +----------------------------------------------------------------------------------------------+
1541
+ * | callback $inline = create_function: |
1542
+ * | lambda_function_0001_crypt_ECB($action, $text) |
1543
+ * | { |
1544
+ * | INSERT PHP CODE OF: |
1545
+ * | $cipher_code['init_crypt']; // general init code. |
1546
+ * | // ie: $sbox'es declarations used for |
1547
+ * | // encrypt and decrypt'ing. |
1548
+ * | |
1549
+ * | switch ($action) { |
1550
+ * | case 'encrypt': |
1551
+ * | INSERT PHP CODE OF: |
1552
+ * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
1553
+ * | ie: specified $key or $box |
1554
+ * | declarations for encrypt'ing. |
1555
+ * | |
1556
+ * | foreach ($ciphertext) { |
1557
+ * | $in = $block_size of $ciphertext; |
1558
+ * | |
1559
+ * | INSERT PHP CODE OF: |
1560
+ * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
1561
+ * | // strlen($in) == $this->block_size |
1562
+ * | // here comes the cipher algorithm in action |
1563
+ * | // for encryption. |
1564
+ * | // $cipher_code['encrypt_block'] has to |
1565
+ * | // encrypt the content of the $in variable |
1566
+ * | |
1567
+ * | $plaintext .= $in; |
1568
+ * | } |
1569
+ * | return $plaintext; |
1570
+ * | |
1571
+ * | case 'decrypt': |
1572
+ * | INSERT PHP CODE OF: |
1573
+ * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
1574
+ * | ie: specified $key or $box |
1575
+ * | declarations for decrypt'ing. |
1576
+ * | foreach ($plaintext) { |
1577
+ * | $in = $block_size of $plaintext; |
1578
+ * | |
1579
+ * | INSERT PHP CODE OF: |
1580
+ * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
1581
+ * | // strlen($in) == $this->block_size |
1582
+ * | // here comes the cipher algorithm in action |
1583
+ * | // for decryption. |
1584
+ * | // $cipher_code['decrypt_block'] has to |
1585
+ * | // decrypt the content of the $in variable |
1586
+ * | $ciphertext .= $in; |
1587
+ * | } |
1588
+ * | return $ciphertext; |
1589
+ * | } |
1590
+ * | } |
1591
+ * +----------------------------------------------------------------------------------------------+
1592
+ * </code>
1593
+ *
1594
+ * See also the Crypt_*::_setupInlineCrypt()'s for
1595
+ * productive inline $cipher_code's how they works.
1596
+ *
1597
+ * Structure of:
1598
+ * <code>
1599
+ * $cipher_code = array(
1600
+ * 'init_crypt' => (string) '', // optional
1601
+ * 'init_encrypt' => (string) '', // optional
1602
+ * 'init_decrypt' => (string) '', // optional
1603
+ * 'encrypt_block' => (string) '', // required
1604
+ * 'decrypt_block' => (string) '' // required
1605
+ * );
1606
+ * </code>
1607
+ *
1608
+ * @see Crypt_Base::_setupInlineCrypt()
1609
+ * @see Crypt_Base::encrypt()
1610
+ * @see Crypt_Base::decrypt()
1611
+ * @param Array $cipher_code
1612
+ * @access private
1613
+ * @return String (the name of the created callback function)
1614
+ */
1615
+ function _createInlineCryptFunction($cipher_code)
1616
+ {
1617
+ $block_size = $this->block_size;
1618
+
1619
+ // optional
1620
+ $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
1621
+ $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
1622
+ $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
1623
+ // required
1624
+ $encrypt_block = $cipher_code['encrypt_block'];
1625
+ $decrypt_block = $cipher_code['decrypt_block'];
1626
+
1627
+ // Generating mode of operation inline code,
1628
+ // merged with the $cipher_code algorithm
1629
+ // for encrypt- and decryption.
1630
+ switch ($this->mode) {
1631
+ case CRYPT_MODE_ECB:
1632
+ $encrypt = $init_encrypt . '
1633
+ $_ciphertext = "";
1634
+ $_text = $self->_pad($_text);
1635
+ $_plaintext_len = strlen($_text);
1636
+
1637
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1638
+ $in = substr($_text, $_i, '.$block_size.');
1639
+ '.$encrypt_block.'
1640
+ $_ciphertext.= $in;
1641
+ }
1642
+
1643
+ return $_ciphertext;
1644
+ ';
1645
+
1646
+ $decrypt = $init_decrypt . '
1647
+ $_plaintext = "";
1648
+ $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1649
+ $_ciphertext_len = strlen($_text);
1650
+
1651
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1652
+ $in = substr($_text, $_i, '.$block_size.');
1653
+ '.$decrypt_block.'
1654
+ $_plaintext.= $in;
1655
+ }
1656
+
1657
+ return $self->_unpad($_plaintext);
1658
+ ';
1659
+ break;
1660
+ case CRYPT_MODE_CTR:
1661
+ $encrypt = $init_encrypt . '
1662
+ $_ciphertext = "";
1663
+ $_plaintext_len = strlen($_text);
1664
+ $_xor = $self->encryptIV;
1665
+ $_buffer = &$self->enbuffer;
1666
+
1667
+ if (strlen($_buffer["encrypted"])) {
1668
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1669
+ $_block = substr($_text, $_i, '.$block_size.');
1670
+ if (strlen($_block) > strlen($_buffer["encrypted"])) {
1671
+ $in = $self->_generateXor($_xor, '.$block_size.');
1672
+ '.$encrypt_block.'
1673
+ $_buffer["encrypted"].= $in;
1674
+ }
1675
+ $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
1676
+ $_ciphertext.= $_block ^ $_key;
1677
+ }
1678
+ } else {
1679
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1680
+ $_block = substr($_text, $_i, '.$block_size.');
1681
+ $in = $self->_generateXor($_xor, '.$block_size.');
1682
+ '.$encrypt_block.'
1683
+ $_key = $in;
1684
+ $_ciphertext.= $_block ^ $_key;
1685
+ }
1686
+ }
1687
+ if ($self->continuousBuffer) {
1688
+ $self->encryptIV = $_xor;
1689
+ if ($_start = $_plaintext_len % '.$block_size.') {
1690
+ $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
1691
+ }
1692
+ }
1693
+
1694
+ return $_ciphertext;
1695
+ ';
1696
+
1697
+ $decrypt = $init_encrypt . '
1698
+ $_plaintext = "";
1699
+ $_ciphertext_len = strlen($_text);
1700
+ $_xor = $self->decryptIV;
1701
+ $_buffer = &$self->debuffer;
1702
+
1703
+ if (strlen($_buffer["ciphertext"])) {
1704
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1705
+ $_block = substr($_text, $_i, '.$block_size.');
1706
+ if (strlen($_block) > strlen($_buffer["ciphertext"])) {
1707
+ $in = $self->_generateXor($_xor, '.$block_size.');
1708
+ '.$encrypt_block.'
1709
+ $_buffer["ciphertext"].= $in;
1710
+ }
1711
+ $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
1712
+ $_plaintext.= $_block ^ $_key;
1713
+ }
1714
+ } else {
1715
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1716
+ $_block = substr($_text, $_i, '.$block_size.');
1717
+ $in = $self->_generateXor($_xor, '.$block_size.');
1718
+ '.$encrypt_block.'
1719
+ $_key = $in;
1720
+ $_plaintext.= $_block ^ $_key;
1721
+ }
1722
+ }
1723
+ if ($self->continuousBuffer) {
1724
+ $self->decryptIV = $_xor;
1725
+ if ($_start = $_ciphertext_len % '.$block_size.') {
1726
+ $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
1727
+ }
1728
+ }
1729
+
1730
+ return $_plaintext;
1731
+ ';
1732
+ break;
1733
+ case CRYPT_MODE_CFB:
1734
+ $encrypt = $init_encrypt . '
1735
+ $_ciphertext = "";
1736
+ $_buffer = &$self->enbuffer;
1737
+
1738
+ if ($self->continuousBuffer) {
1739
+ $_iv = &$self->encryptIV;
1740
+ $_pos = &$_buffer["pos"];
1741
+ } else {
1742
+ $_iv = $self->encryptIV;
1743
+ $_pos = 0;
1744
+ }
1745
+ $_len = strlen($_text);
1746
+ $_i = 0;
1747
+ if ($_pos) {
1748
+ $_orig_pos = $_pos;
1749
+ $_max = '.$block_size.' - $_pos;
1750
+ if ($_len >= $_max) {
1751
+ $_i = $_max;
1752
+ $_len-= $_max;
1753
+ $_pos = 0;
1754
+ } else {
1755
+ $_i = $_len;
1756
+ $_pos+= $_len;
1757
+ $_len = 0;
1758
+ }
1759
+ $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
1760
+ $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
1761
+ }
1762
+ while ($_len >= '.$block_size.') {
1763
+ $in = $_iv;
1764
+ '.$encrypt_block.';
1765
+ $_iv = $in ^ substr($_text, $_i, '.$block_size.');
1766
+ $_ciphertext.= $_iv;
1767
+ $_len-= '.$block_size.';
1768
+ $_i+= '.$block_size.';
1769
+ }
1770
+ if ($_len) {
1771
+ $in = $_iv;
1772
+ '.$encrypt_block.'
1773
+ $_iv = $in;
1774
+ $_block = $_iv ^ substr($_text, $_i);
1775
+ $_iv = substr_replace($_iv, $_block, 0, $_len);
1776
+ $_ciphertext.= $_block;
1777
+ $_pos = $_len;
1778
+ }
1779
+ return $_ciphertext;
1780
+ ';
1781
+
1782
+ $decrypt = $init_encrypt . '
1783
+ $_plaintext = "";
1784
+ $_buffer = &$self->debuffer;
1785
+
1786
+ if ($self->continuousBuffer) {
1787
+ $_iv = &$self->decryptIV;
1788
+ $_pos = &$_buffer["pos"];
1789
+ } else {
1790
+ $_iv = $self->decryptIV;
1791
+ $_pos = 0;
1792
+ }
1793
+ $_len = strlen($_text);
1794
+ $_i = 0;
1795
+ if ($_pos) {
1796
+ $_orig_pos = $_pos;
1797
+ $_max = '.$block_size.' - $_pos;
1798
+ if ($_len >= $_max) {
1799
+ $_i = $_max;
1800
+ $_len-= $_max;
1801
+ $_pos = 0;
1802
+ } else {
1803
+ $_i = $_len;
1804
+ $_pos+= $_len;
1805
+ $_len = 0;
1806
+ }
1807
+ $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
1808
+ $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
1809
+ }
1810
+ while ($_len >= '.$block_size.') {
1811
+ $in = $_iv;
1812
+ '.$encrypt_block.'
1813
+ $_iv = $in;
1814
+ $cb = substr($_text, $_i, '.$block_size.');
1815
+ $_plaintext.= $_iv ^ $cb;
1816
+ $_iv = $cb;
1817
+ $_len-= '.$block_size.';
1818
+ $_i+= '.$block_size.';
1819
+ }
1820
+ if ($_len) {
1821
+ $in = $_iv;
1822
+ '.$encrypt_block.'
1823
+ $_iv = $in;
1824
+ $_plaintext.= $_iv ^ substr($_text, $_i);
1825
+ $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
1826
+ $_pos = $_len;
1827
+ }
1828
+
1829
+ return $_plaintext;
1830
+ ';
1831
+ break;
1832
+ case CRYPT_MODE_OFB:
1833
+ $encrypt = $init_encrypt . '
1834
+ $_ciphertext = "";
1835
+ $_plaintext_len = strlen($_text);
1836
+ $_xor = $self->encryptIV;
1837
+ $_buffer = &$self->enbuffer;
1838
+
1839
+ if (strlen($_buffer["xor"])) {
1840
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1841
+ $_block = substr($_text, $_i, '.$block_size.');
1842
+ if (strlen($_block) > strlen($_buffer["xor"])) {
1843
+ $in = $_xor;
1844
+ '.$encrypt_block.'
1845
+ $_xor = $in;
1846
+ $_buffer["xor"].= $_xor;
1847
+ }
1848
+ $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1849
+ $_ciphertext.= $_block ^ $_key;
1850
+ }
1851
+ } else {
1852
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1853
+ $in = $_xor;
1854
+ '.$encrypt_block.'
1855
+ $_xor = $in;
1856
+ $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1857
+ }
1858
+ $_key = $_xor;
1859
+ }
1860
+ if ($self->continuousBuffer) {
1861
+ $self->encryptIV = $_xor;
1862
+ if ($_start = $_plaintext_len % '.$block_size.') {
1863
+ $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1864
+ }
1865
+ }
1866
+ return $_ciphertext;
1867
+ ';
1868
+
1869
+ $decrypt = $init_encrypt . '
1870
+ $_plaintext = "";
1871
+ $_ciphertext_len = strlen($_text);
1872
+ $_xor = $self->decryptIV;
1873
+ $_buffer = &$self->debuffer;
1874
+
1875
+ if (strlen($_buffer["xor"])) {
1876
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1877
+ $_block = substr($_text, $_i, '.$block_size.');
1878
+ if (strlen($_block) > strlen($_buffer["xor"])) {
1879
+ $in = $_xor;
1880
+ '.$encrypt_block.'
1881
+ $_xor = $in;
1882
+ $_buffer["xor"].= $_xor;
1883
+ }
1884
+ $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1885
+ $_plaintext.= $_block ^ $_key;
1886
+ }
1887
+ } else {
1888
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1889
+ $in = $_xor;
1890
+ '.$encrypt_block.'
1891
+ $_xor = $in;
1892
+ $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1893
+ }
1894
+ $_key = $_xor;
1895
+ }
1896
+ if ($self->continuousBuffer) {
1897
+ $self->decryptIV = $_xor;
1898
+ if ($_start = $_ciphertext_len % '.$block_size.') {
1899
+ $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1900
+ }
1901
+ }
1902
+ return $_plaintext;
1903
+ ';
1904
+ break;
1905
+ case CRYPT_MODE_STREAM:
1906
+ $encrypt = $init_encrypt . '
1907
+ $_ciphertext = "";
1908
+ '.$encrypt_block.'
1909
+ return $_ciphertext;
1910
+ ';
1911
+ $decrypt = $init_decrypt . '
1912
+ $_plaintext = "";
1913
+ '.$decrypt_block.'
1914
+ return $_plaintext;
1915
+ ';
1916
+ break;
1917
+ // case CRYPT_MODE_CBC:
1918
+ default:
1919
+ $encrypt = $init_encrypt . '
1920
+ $_ciphertext = "";
1921
+ $_text = $self->_pad($_text);
1922
+ $_plaintext_len = strlen($_text);
1923
+
1924
+ $in = $self->encryptIV;
1925
+
1926
+ for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1927
+ $in = substr($_text, $_i, '.$block_size.') ^ $in;
1928
+ '.$encrypt_block.'
1929
+ $_ciphertext.= $in;
1930
+ }
1931
+
1932
+ if ($self->continuousBuffer) {
1933
+ $self->encryptIV = $in;
1934
+ }
1935
+
1936
+ return $_ciphertext;
1937
+ ';
1938
+
1939
+ $decrypt = $init_decrypt . '
1940
+ $_plaintext = "";
1941
+ $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1942
+ $_ciphertext_len = strlen($_text);
1943
+
1944
+ $_iv = $self->decryptIV;
1945
+
1946
+ for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1947
+ $in = $_block = substr($_text, $_i, '.$block_size.');
1948
+ '.$decrypt_block.'
1949
+ $_plaintext.= $in ^ $_iv;
1950
+ $_iv = $_block;
1951
+ }
1952
+
1953
+ if ($self->continuousBuffer) {
1954
+ $self->decryptIV = $_iv;
1955
+ }
1956
+
1957
+ return $self->_unpad($_plaintext);
1958
+ ';
1959
+ break;
1960
+ }
1961
+
1962
+ // Create the $inline function and return its name as string. Ready to run!
1963
+ return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
1964
+ }
1965
+
1966
+ /**
1967
+ * Holds the lambda_functions table (classwide)
1968
+ *
1969
+ * Each name of the lambda function, created from
1970
+ * _setupInlineCrypt() && _createInlineCryptFunction()
1971
+ * is stored, classwide (!), here for reusing.
1972
+ *
1973
+ * The string-based index of $function is a classwide
1974
+ * uniqe value representing, at least, the $mode of
1975
+ * operation (or more... depends of the optimizing level)
1976
+ * for which $mode the lambda function was created.
1977
+ *
1978
+ * @access private
1979
+ * @return &Array
1980
+ */
1981
+ function &_getLambdaFunctions()
1982
+ {
1983
+ static $functions = array();
1984
+ return $functions;
1985
+ }
1986
+ }
1987
+
1988
+ // vim: ts=4:sw=4:et:
1989
+ // vim6: fdl=1:
lib/LivrariOnline/BigInteger.php ADDED
@@ -0,0 +1,3651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Pure-PHP arbitrary precision integer arithmetic library.
6
+ *
7
+ * Supports base-2, base-10, base-16, and base-256 numbers. Uses the GMP or BCMath extensions, if available,
8
+ * and an internal implementation, otherwise.
9
+ *
10
+ * PHP versions 4 and 5
11
+ *
12
+ * {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
13
+ * {@link MATH_BIGINTEGER_MODE_INTERNAL MATH_BIGINTEGER_MODE_INTERNAL} mode)
14
+ *
15
+ * Math_BigInteger uses base-2**26 to perform operations such as multiplication and division and
16
+ * base-2**52 (ie. two base 2**26 digits) to perform addition and subtraction. Because the largest possible
17
+ * value when multiplying two base-2**26 numbers together is a base-2**52 number, double precision floating
18
+ * point numbers - numbers that should be supported on most hardware and whose significand is 53 bits - are
19
+ * used. As a consequence, bitwise operators such as >> and << cannot be used, nor can the modulo operator %,
20
+ * which only supports integers. Although this fact will slow this library down, the fact that such a high
21
+ * base is being used should more than compensate.
22
+ *
23
+ * When PHP version 6 is officially released, we'll be able to use 64-bit integers. This should, once again,
24
+ * allow bitwise operators, and will increase the maximum possible base to 2**31 (or 2**62 for addition /
25
+ * subtraction).
26
+ *
27
+ * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie.
28
+ * (new Math_BigInteger(pow(2, 26)))->value = array(0, 1)
29
+ *
30
+ * Useful resources are as follows:
31
+ *
32
+ * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
33
+ * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
34
+ * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
35
+ *
36
+ * Here's an example of how to use this library:
37
+ * <code>
38
+ * <?php
39
+ * include('Math/BigInteger.php');
40
+ *
41
+ * $a = new Math_BigInteger(2);
42
+ * $b = new Math_BigInteger(3);
43
+ *
44
+ * $c = $a->add($b);
45
+ *
46
+ * echo $c->toString(); // outputs 5
47
+ * ?>
48
+ * </code>
49
+ *
50
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
51
+ * of this software and associated documentation files (the "Software"), to deal
52
+ * in the Software without restriction, including without limitation the rights
53
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
54
+ * copies of the Software, and to permit persons to whom the Software is
55
+ * furnished to do so, subject to the following conditions:
56
+ *
57
+ * The above copyright notice and this permission notice shall be included in
58
+ * all copies or substantial portions of the Software.
59
+ *
60
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
63
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
64
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
65
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
66
+ * THE SOFTWARE.
67
+ *
68
+ * @category Math
69
+ * @package Math_BigInteger
70
+ * @author Jim Wigginton <terrafrost@php.net>
71
+ * @copyright MMVI Jim Wigginton
72
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
73
+ * @link http://pear.php.net/package/Math_BigInteger
74
+ */
75
+
76
+ /**#@+
77
+ * Reduction constants
78
+ *
79
+ * @access private
80
+ * @see Math_BigInteger::_reduce()
81
+ */
82
+ /**
83
+ * @see Math_BigInteger::_montgomery()
84
+ * @see Math_BigInteger::_prepMontgomery()
85
+ */
86
+ define('MATH_BIGINTEGER_MONTGOMERY', 0);
87
+ /**
88
+ * @see Math_BigInteger::_barrett()
89
+ */
90
+ define('MATH_BIGINTEGER_BARRETT', 1);
91
+ /**
92
+ * @see Math_BigInteger::_mod2()
93
+ */
94
+ define('MATH_BIGINTEGER_POWEROF2', 2);
95
+ /**
96
+ * @see Math_BigInteger::_remainder()
97
+ */
98
+ define('MATH_BIGINTEGER_CLASSIC', 3);
99
+ /**
100
+ * @see Math_BigInteger::__clone()
101
+ */
102
+ define('MATH_BIGINTEGER_NONE', 4);
103
+ /**#@-*/
104
+
105
+ /**#@+
106
+ * Array constants
107
+ *
108
+ * Rather than create a thousands and thousands of new Math_BigInteger objects in repeated function calls to add() and
109
+ * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them.
110
+ *
111
+ * @access private
112
+ */
113
+ /**
114
+ * $result[MATH_BIGINTEGER_VALUE] contains the value.
115
+ */
116
+ define('MATH_BIGINTEGER_VALUE', 0);
117
+ /**
118
+ * $result[MATH_BIGINTEGER_SIGN] contains the sign.
119
+ */
120
+ define('MATH_BIGINTEGER_SIGN', 1);
121
+ /**#@-*/
122
+
123
+ /**#@+
124
+ * @access private
125
+ * @see Math_BigInteger::_montgomery()
126
+ * @see Math_BigInteger::_barrett()
127
+ */
128
+ /**
129
+ * Cache constants
130
+ *
131
+ * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid.
132
+ */
133
+ define('MATH_BIGINTEGER_VARIABLE', 0);
134
+ /**
135
+ * $cache[MATH_BIGINTEGER_DATA] contains the cached data.
136
+ */
137
+ define('MATH_BIGINTEGER_DATA', 1);
138
+ /**#@-*/
139
+
140
+ /**#@+
141
+ * Mode constants.
142
+ *
143
+ * @access private
144
+ * @see Math_BigInteger::Math_BigInteger()
145
+ */
146
+ /**
147
+ * To use the pure-PHP implementation
148
+ */
149
+ define('MATH_BIGINTEGER_MODE_INTERNAL', 1);
150
+ /**
151
+ * To use the BCMath library
152
+ *
153
+ * (if enabled; otherwise, the internal implementation will be used)
154
+ */
155
+ define('MATH_BIGINTEGER_MODE_BCMATH', 2);
156
+ /**
157
+ * To use the GMP library
158
+ *
159
+ * (if present; otherwise, either the BCMath or the internal implementation will be used)
160
+ */
161
+ define('MATH_BIGINTEGER_MODE_GMP', 3);
162
+ /**#@-*/
163
+
164
+ /**
165
+ * Karatsuba Cutoff
166
+ *
167
+ * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
168
+ *
169
+ * @access private
170
+ */
171
+ define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 25);
172
+
173
+ /**
174
+ * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
175
+ * numbers.
176
+ *
177
+ * @author Jim Wigginton <terrafrost@php.net>
178
+ * @version 1.0.0RC4
179
+ * @access public
180
+ * @package Math_BigInteger
181
+ */
182
+ class Math_BigInteger {
183
+ /**
184
+ * Holds the BigInteger's value.
185
+ *
186
+ * @var Array
187
+ * @access private
188
+ */
189
+ var $value;
190
+
191
+ /**
192
+ * Holds the BigInteger's magnitude.
193
+ *
194
+ * @var Boolean
195
+ * @access private
196
+ */
197
+ var $is_negative = false;
198
+
199
+ /**
200
+ * Random number generator function
201
+ *
202
+ * @see setRandomGenerator()
203
+ * @access private
204
+ */
205
+ var $generator = 'mt_rand';
206
+
207
+ /**
208
+ * Precision
209
+ *
210
+ * @see setPrecision()
211
+ * @access private
212
+ */
213
+ var $precision = -1;
214
+
215
+ /**
216
+ * Precision Bitmask
217
+ *
218
+ * @see setPrecision()
219
+ * @access private
220
+ */
221
+ var $bitmask = false;
222
+
223
+ /**
224
+ * Mode independent value used for serialization.
225
+ *
226
+ * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
227
+ * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
228
+ * however, $this->hex is only calculated when $this->__sleep() is called.
229
+ *
230
+ * @see __sleep()
231
+ * @see __wakeup()
232
+ * @var String
233
+ * @access private
234
+ */
235
+ var $hex;
236
+
237
+ /**
238
+ * Converts base-2, base-10, base-16, and binary strings (base-256) to BigIntegers.
239
+ *
240
+ * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
241
+ * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
242
+ *
243
+ * Here's an example:
244
+ * <code>
245
+ * &lt;?php
246
+ * include('Math/BigInteger.php');
247
+ *
248
+ * $a = new Math_BigInteger('0x32', 16); // 50 in base-16
249
+ *
250
+ * echo $a->toString(); // outputs 50
251
+ * ?&gt;
252
+ * </code>
253
+ *
254
+ * @param optional $x base-10 number or base-$base number if $base set.
255
+ * @param optional integer $base
256
+ * @return Math_BigInteger
257
+ * @access public
258
+ */
259
+ function Math_BigInteger($x = 0, $base = 10)
260
+ {
261
+ if ( !defined('MATH_BIGINTEGER_MODE') ) {
262
+ switch (true) {
263
+ case extension_loaded('gmp'):
264
+ define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP);
265
+ break;
266
+ case extension_loaded('bcmath'):
267
+ define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH);
268
+ break;
269
+ default:
270
+ define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL);
271
+ }
272
+ }
273
+
274
+ if (function_exists('openssl_public_encrypt') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
275
+ define('MATH_BIGINTEGER_OPENSSL_ENABLED', true);
276
+ }
277
+
278
+ if (!defined('PHP_INT_SIZE')) {
279
+ define('PHP_INT_SIZE', 4);
280
+ }
281
+
282
+ if (!defined('MATH_BIGINTEGER_BASE') && MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_INTERNAL) {
283
+ switch (PHP_INT_SIZE) {
284
+ case 8: // use 64-bit integers if int size is 8 bytes
285
+ define('MATH_BIGINTEGER_BASE', 31);
286
+ define('MATH_BIGINTEGER_BASE_FULL', 0x80000000);
287
+ define('MATH_BIGINTEGER_MAX_DIGIT', 0x7FFFFFFF);
288
+ define('MATH_BIGINTEGER_MSB', 0x40000000);
289
+ // 10**9 is the closest we can get to 2**31 without passing it
290
+ define('MATH_BIGINTEGER_MAX10', 1000000000);
291
+ define('MATH_BIGINTEGER_MAX10_LEN', 9);
292
+ // the largest digit that may be used in addition / subtraction
293
+ define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 62));
294
+ break;
295
+ //case 4: // use 64-bit floats if int size is 4 bytes
296
+ default:
297
+ define('MATH_BIGINTEGER_BASE', 26);
298
+ define('MATH_BIGINTEGER_BASE_FULL', 0x4000000);
299
+ define('MATH_BIGINTEGER_MAX_DIGIT', 0x3FFFFFF);
300
+ define('MATH_BIGINTEGER_MSB', 0x2000000);
301
+ // 10**7 is the closest to 2**26 without passing it
302
+ define('MATH_BIGINTEGER_MAX10', 10000000);
303
+ define('MATH_BIGINTEGER_MAX10_LEN', 7);
304
+ // the largest digit that may be used in addition / subtraction
305
+ // we do pow(2, 52) instead of using 4503599627370496 directly because some
306
+ // PHP installations will truncate 4503599627370496.
307
+ define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 52));
308
+ }
309
+ }
310
+
311
+ switch ( MATH_BIGINTEGER_MODE ) {
312
+ case MATH_BIGINTEGER_MODE_GMP:
313
+ if (is_resource($x) && get_resource_type($x) == 'GMP integer') {
314
+ $this->value = $x;
315
+ return;
316
+ }
317
+ $this->value = gmp_init(0);
318
+ break;
319
+ case MATH_BIGINTEGER_MODE_BCMATH:
320
+ $this->value = '0';
321
+ break;
322
+ default:
323
+ $this->value = array();
324
+ }
325
+
326
+ // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48
327
+ // '0' is the only value like this per http://php.net/empty
328
+ if (empty($x) && (abs($base) != 256 || $x !== '0')) {
329
+ return;
330
+ }
331
+
332
+ switch ($base) {
333
+ case -256:
334
+ if (ord($x[0]) & 0x80) {
335
+ $x = ~$x;
336
+ $this->is_negative = true;
337
+ }
338
+ case 256:
339
+ switch ( MATH_BIGINTEGER_MODE ) {
340
+ case MATH_BIGINTEGER_MODE_GMP:
341
+ $sign = $this->is_negative ? '-' : '';
342
+ $this->value = gmp_init($sign . '0x' . bin2hex($x));
343
+ break;
344
+ case MATH_BIGINTEGER_MODE_BCMATH:
345
+ // round $len to the nearest 4 (thanks, DavidMJ!)
346
+ $len = (strlen($x) + 3) & 0xFFFFFFFC;
347
+
348
+ $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
349
+
350
+ for ($i = 0; $i < $len; $i+= 4) {
351
+ $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
352
+ $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
353
+ }
354
+
355
+ if ($this->is_negative) {
356
+ $this->value = '-' . $this->value;
357
+ }
358
+
359
+ break;
360
+ // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
361
+ default:
362
+ while (strlen($x)) {
363
+ $this->value[] = $this->_bytes2int($this->_base256_rshift($x, MATH_BIGINTEGER_BASE));
364
+ }
365
+ }
366
+
367
+ if ($this->is_negative) {
368
+ if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
369
+ $this->is_negative = false;
370
+ }
371
+ $temp = $this->add(new Math_BigInteger('-1'));
372
+ $this->value = $temp->value;
373
+ }
374
+ break;
375
+ case 16:
376
+ case -16:
377
+ if ($base > 0 && $x[0] == '-') {
378
+ $this->is_negative = true;
379
+ $x = substr($x, 1);
380
+ }
381
+
382
+ $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
383
+
384
+ $is_negative = false;
385
+ if ($base < 0 && hexdec($x[0]) >= 8) {
386
+ $this->is_negative = $is_negative = true;
387
+ $x = bin2hex(~pack('H*', $x));
388
+ }
389
+
390
+ switch ( MATH_BIGINTEGER_MODE ) {
391
+ case MATH_BIGINTEGER_MODE_GMP:
392
+ $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
393
+ $this->value = gmp_init($temp);
394
+ $this->is_negative = false;
395
+ break;
396
+ case MATH_BIGINTEGER_MODE_BCMATH:
397
+ $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
398
+ $temp = new Math_BigInteger(pack('H*', $x), 256);
399
+ $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
400
+ $this->is_negative = false;
401
+ break;
402
+ default:
403
+ $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
404
+ $temp = new Math_BigInteger(pack('H*', $x), 256);
405
+ $this->value = $temp->value;
406
+ }
407
+
408
+ if ($is_negative) {
409
+ $temp = $this->add(new Math_BigInteger('-1'));
410
+ $this->value = $temp->value;
411
+ }
412
+ break;
413
+ case 10:
414
+ case -10:
415
+ // (?<!^)(?:-).*: find any -'s that aren't at the beginning and then any characters that follow that
416
+ // (?<=^|-)0*: find any 0's that are preceded by the start of the string or by a - (ie. octals)
417
+ // [^-0-9].*: find any non-numeric characters and then any characters that follow that
418
+ $x = preg_replace('#(?<!^)(?:-).*|(?<=^|-)0*|[^-0-9].*#', '', $x);
419
+
420
+ switch ( MATH_BIGINTEGER_MODE ) {
421
+ case MATH_BIGINTEGER_MODE_GMP:
422
+ $this->value = gmp_init($x);
423
+ break;
424
+ case MATH_BIGINTEGER_MODE_BCMATH:
425
+ // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
426
+ // results then doing it on '-1' does (modInverse does $x[0])
427
+ $this->value = $x === '-' ? '0' : (string) $x;
428
+ break;
429
+ default:
430
+ $temp = new Math_BigInteger();
431
+
432
+ $multiplier = new Math_BigInteger();
433
+ $multiplier->value = array(MATH_BIGINTEGER_MAX10);
434
+
435
+ if ($x[0] == '-') {
436
+ $this->is_negative = true;
437
+ $x = substr($x, 1);
438
+ }
439
+
440
+ $x = str_pad($x, strlen($x) + ((MATH_BIGINTEGER_MAX10_LEN - 1) * strlen($x)) % MATH_BIGINTEGER_MAX10_LEN, 0, STR_PAD_LEFT);
441
+
442
+ while (strlen($x)) {
443
+ $temp = $temp->multiply($multiplier);
444
+ $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, MATH_BIGINTEGER_MAX10_LEN)), 256));
445
+ $x = substr($x, MATH_BIGINTEGER_MAX10_LEN);
446
+ }
447
+
448
+ $this->value = $temp->value;
449
+ }
450
+ break;
451
+ case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
452
+ case -2:
453
+ if ($base > 0 && $x[0] == '-') {
454
+ $this->is_negative = true;
455
+ $x = substr($x, 1);
456
+ }
457
+
458
+ $x = preg_replace('#^([01]*).*#', '$1', $x);
459
+ $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
460
+
461
+ $str = '0x';
462
+ while (strlen($x)) {
463
+ $part = substr($x, 0, 4);
464
+ $str.= dechex(bindec($part));
465
+ $x = substr($x, 4);
466
+ }
467
+
468
+ if ($this->is_negative) {
469
+ $str = '-' . $str;
470
+ }
471
+
472
+ $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16
473
+ $this->value = $temp->value;
474
+ $this->is_negative = $temp->is_negative;
475
+
476
+ break;
477
+ default:
478
+ // base not supported, so we'll let $this == 0
479
+ }
480
+ }
481
+
482
+ /**
483
+ * Converts a BigInteger to a byte string (eg. base-256).
484
+ *
485
+ * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
486
+ * saved as two's compliment.
487
+ *
488
+ * Here's an example:
489
+ * <code>
490
+ * <?php
491
+ * include('Math/BigInteger.php');
492
+ *
493
+ * $a = new Math_BigInteger('65');
494
+ *
495
+ * echo $a->toBytes(); // outputs chr(65)
496
+ * ?>
497
+ * </code>
498
+ *
499
+ * @param Boolean $twos_compliment
500
+ * @return String
501
+ * @access public
502
+ * @internal Converts a base-2**26 number to base-2**8
503
+ */
504
+ function toBytes($twos_compliment = false)
505
+ {
506
+ if ($twos_compliment) {
507
+ $comparison = $this->compare(new Math_BigInteger());
508
+ if ($comparison == 0) {
509
+ return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
510
+ }
511
+
512
+ $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->copy();
513
+ $bytes = $temp->toBytes();
514
+
515
+ if (empty($bytes)) { // eg. if the number we're trying to convert is -1
516
+ $bytes = chr(0);
517
+ }
518
+
519
+ if (ord($bytes[0]) & 0x80) {
520
+ $bytes = chr(0) . $bytes;
521
+ }
522
+
523
+ return $comparison < 0 ? ~$bytes : $bytes;
524
+ }
525
+
526
+ switch ( MATH_BIGINTEGER_MODE ) {
527
+ case MATH_BIGINTEGER_MODE_GMP:
528
+ if (gmp_cmp($this->value, gmp_init(0)) == 0) {
529
+ return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
530
+ }
531
+
532
+ $temp = gmp_strval(gmp_abs($this->value), 16);
533
+ $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
534
+ $temp = pack('H*', $temp);
535
+
536
+ return $this->precision > 0 ?
537
+ substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
538
+ ltrim($temp, chr(0));
539
+ case MATH_BIGINTEGER_MODE_BCMATH:
540
+ if ($this->value === '0') {
541
+ return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
542
+ }
543
+
544
+ $value = '';
545
+ $current = $this->value;
546
+
547
+ if ($current[0] == '-') {
548
+ $current = substr($current, 1);
549
+ }
550
+
551
+ while (bccomp($current, '0', 0) > 0) {
552
+ $temp = bcmod($current, '16777216');
553
+ $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
554
+ $current = bcdiv($current, '16777216', 0);
555
+ }
556
+
557
+ return $this->precision > 0 ?
558
+ substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
559
+ ltrim($value, chr(0));
560
+ }
561
+
562
+ if (!count($this->value)) {
563
+ return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
564
+ }
565
+ $result = $this->_int2bytes($this->value[count($this->value) - 1]);
566
+
567
+ $temp = $this->copy();
568
+
569
+ for ($i = count($temp->value) - 2; $i >= 0; --$i) {
570
+ $temp->_base256_lshift($result, MATH_BIGINTEGER_BASE);
571
+ $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
572
+ }
573
+
574
+ return $this->precision > 0 ?
575
+ str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
576
+ $result;
577
+ }
578
+
579
+ /**
580
+ * Converts a BigInteger to a hex string (eg. base-16)).
581
+ *
582
+ * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
583
+ * saved as two's compliment.
584
+ *
585
+ * Here's an example:
586
+ * <code>
587
+ * <?php
588
+ * include('Math/BigInteger.php');
589
+ *
590
+ * $a = new Math_BigInteger('65');
591
+ *
592
+ * echo $a->toHex(); // outputs '41'
593
+ * ?>
594
+ * </code>
595
+ *
596
+ * @param Boolean $twos_compliment
597
+ * @return String
598
+ * @access public
599
+ * @internal Converts a base-2**26 number to base-2**8
600
+ */
601
+ function toHex($twos_compliment = false)
602
+ {
603
+ return bin2hex($this->toBytes($twos_compliment));
604
+ }
605
+
606
+ /**
607
+ * Converts a BigInteger to a bit string (eg. base-2).
608
+ *
609
+ * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
610
+ * saved as two's compliment.
611
+ *
612
+ * Here's an example:
613
+ * <code>
614
+ * <?php
615
+ * include('Math/BigInteger.php');
616
+ *
617
+ * $a = new Math_BigInteger('65');
618
+ *
619
+ * echo $a->toBits(); // outputs '1000001'
620
+ * ?>
621
+ * </code>
622
+ *
623
+ * @param Boolean $twos_compliment
624
+ * @return String
625
+ * @access public
626
+ * @internal Converts a base-2**26 number to base-2**2
627
+ */
628
+ function toBits($twos_compliment = false)
629
+ {
630
+ $hex = $this->toHex($twos_compliment);
631
+ $bits = '';
632
+ for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) {
633
+ $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits;
634
+ }
635
+ if ($start) { // hexdec('') == 0
636
+ $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits;
637
+ }
638
+ $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
639
+
640
+ if ($twos_compliment && $this->compare(new Math_BigInteger()) > 0 && $this->precision <= 0) {
641
+ return '0' . $result;
642
+ }
643
+
644
+ return $result;
645
+ }
646
+
647
+ /**
648
+ * Converts a BigInteger to a base-10 number.
649
+ *
650
+ * Here's an example:
651
+ * <code>
652
+ * <?php
653
+ * include('Math/BigInteger.php');
654
+ *
655
+ * $a = new Math_BigInteger('50');
656
+ *
657
+ * echo $a->toString(); // outputs 50
658
+ * ?>
659
+ * </code>
660
+ *
661
+ * @return String
662
+ * @access public
663
+ * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
664
+ */
665
+ function toString()
666
+ {
667
+ switch ( MATH_BIGINTEGER_MODE ) {
668
+ case MATH_BIGINTEGER_MODE_GMP:
669
+ return gmp_strval($this->value);
670
+ case MATH_BIGINTEGER_MODE_BCMATH:
671
+ if ($this->value === '0') {
672
+ return '0';
673
+ }
674
+
675
+ return ltrim($this->value, '0');
676
+ }
677
+
678
+ if (!count($this->value)) {
679
+ return '0';
680
+ }
681
+
682
+ $temp = $this->copy();
683
+ $temp->is_negative = false;
684
+
685
+ $divisor = new Math_BigInteger();
686
+ $divisor->value = array(MATH_BIGINTEGER_MAX10);
687
+ $result = '';
688
+ while (count($temp->value)) {
689
+ list($temp, $mod) = $temp->divide($divisor);
690
+ $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', MATH_BIGINTEGER_MAX10_LEN, '0', STR_PAD_LEFT) . $result;
691
+ }
692
+ $result = ltrim($result, '0');
693
+ if (empty($result)) {
694
+ $result = '0';
695
+ }
696
+
697
+ if ($this->is_negative) {
698
+ $result = '-' . $result;
699
+ }
700
+
701
+ return $result;
702
+ }
703
+
704
+ /**
705
+ * Copy an object
706
+ *
707
+ * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
708
+ * that all objects are passed by value, when appropriate. More information can be found here:
709
+ *
710
+ * {@link http://php.net/language.oop5.basic#51624}
711
+ *
712
+ * @access public
713
+ * @see __clone()
714
+ * @return Math_BigInteger
715
+ */
716
+ function copy()
717
+ {
718
+ $temp = new Math_BigInteger();
719
+ $temp->value = $this->value;
720
+ $temp->is_negative = $this->is_negative;
721
+ $temp->generator = $this->generator;
722
+ $temp->precision = $this->precision;
723
+ $temp->bitmask = $this->bitmask;
724
+ return $temp;
725
+ }
726
+
727
+ /**
728
+ * __toString() magic method
729
+ *
730
+ * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
731
+ * toString().
732
+ *
733
+ * @access public
734
+ * @internal Implemented per a suggestion by Techie-Michael - thanks!
735
+ */
736
+ function __toString()
737
+ {
738
+ return $this->toString();
739
+ }
740
+
741
+ /**
742
+ * __clone() magic method
743
+ *
744
+ * Although you can call Math_BigInteger::__toString() directly in PHP5, you cannot call Math_BigInteger::__clone()
745
+ * directly in PHP5. You can in PHP4 since it's not a magic method, but in PHP5, you have to call it by using the PHP5
746
+ * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5,
747
+ * call Math_BigInteger::copy(), instead.
748
+ *
749
+ * @access public
750
+ * @see copy()
751
+ * @return Math_BigInteger
752
+ */
753
+ function __clone()
754
+ {
755
+ return $this->copy();
756
+ }
757
+
758
+ /**
759
+ * __sleep() magic method
760
+ *
761
+ * Will be called, automatically, when serialize() is called on a Math_BigInteger object.
762
+ *
763
+ * @see __wakeup()
764
+ * @access public
765
+ */
766
+ function __sleep()
767
+ {
768
+ $this->hex = $this->toHex(true);
769
+ $vars = array('hex');
770
+ if ($this->generator != 'mt_rand') {
771
+ $vars[] = 'generator';
772
+ }
773
+ if ($this->precision > 0) {
774
+ $vars[] = 'precision';
775
+ }
776
+ return $vars;
777
+
778
+ }
779
+
780
+ /**
781
+ * __wakeup() magic method
782
+ *
783
+ * Will be called, automatically, when unserialize() is called on a Math_BigInteger object.
784
+ *
785
+ * @see __sleep()
786
+ * @access public
787
+ */
788
+ function __wakeup()
789
+ {
790
+ $temp = new Math_BigInteger($this->hex, -16);
791
+ $this->value = $temp->value;
792
+ $this->is_negative = $temp->is_negative;
793
+ $this->setRandomGenerator($this->generator);
794
+ if ($this->precision > 0) {
795
+ // recalculate $this->bitmask
796
+ $this->setPrecision($this->precision);
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Adds two BigIntegers.
802
+ *
803
+ * Here's an example:
804
+ * <code>
805
+ * <?php
806
+ * include('Math/BigInteger.php');
807
+ *
808
+ * $a = new Math_BigInteger('10');
809
+ * $b = new Math_BigInteger('20');
810
+ *
811
+ * $c = $a->add($b);
812
+ *
813
+ * echo $c->toString(); // outputs 30
814
+ * ?>
815
+ * </code>
816
+ *
817
+ * @param Math_BigInteger $y
818
+ * @return Math_BigInteger
819
+ * @access public
820
+ * @internal Performs base-2**52 addition
821
+ */
822
+ function add($y)
823
+ {
824
+ switch ( MATH_BIGINTEGER_MODE ) {
825
+ case MATH_BIGINTEGER_MODE_GMP:
826
+ $temp = new Math_BigInteger();
827
+ $temp->value = gmp_add($this->value, $y->value);
828
+
829
+ return $this->_normalize($temp);
830
+ case MATH_BIGINTEGER_MODE_BCMATH:
831
+ $temp = new Math_BigInteger();
832
+ $temp->value = bcadd($this->value, $y->value, 0);
833
+
834
+ return $this->_normalize($temp);
835
+ }
836
+
837
+ $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative);
838
+
839
+ $result = new Math_BigInteger();
840
+ $result->value = $temp[MATH_BIGINTEGER_VALUE];
841
+ $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
842
+
843
+ return $this->_normalize($result);
844
+ }
845
+
846
+ /**
847
+ * Performs addition.
848
+ *
849
+ * @param Array $x_value
850
+ * @param Boolean $x_negative
851
+ * @param Array $y_value
852
+ * @param Boolean $y_negative
853
+ * @return Array
854
+ * @access private
855
+ */
856
+ function _add($x_value, $x_negative, $y_value, $y_negative)
857
+ {
858
+ $x_size = count($x_value);
859
+ $y_size = count($y_value);
860
+
861
+ if ($x_size == 0) {
862
+ return array(
863
+ MATH_BIGINTEGER_VALUE => $y_value,
864
+ MATH_BIGINTEGER_SIGN => $y_negative
865
+ );
866
+ } else if ($y_size == 0) {
867
+ return array(
868
+ MATH_BIGINTEGER_VALUE => $x_value,
869
+ MATH_BIGINTEGER_SIGN => $x_negative
870
+ );
871
+ }
872
+
873
+ // subtract, if appropriate
874
+ if ( $x_negative != $y_negative ) {
875
+ if ( $x_value == $y_value ) {
876
+ return array(
877
+ MATH_BIGINTEGER_VALUE => array(),
878
+ MATH_BIGINTEGER_SIGN => false
879
+ );
880
+ }
881
+
882
+ $temp = $this->_subtract($x_value, false, $y_value, false);
883
+ $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?
884
+ $x_negative : $y_negative;
885
+
886
+ return $temp;
887
+ }
888
+
889
+ if ($x_size < $y_size) {
890
+ $size = $x_size;
891
+ $value = $y_value;
892
+ } else {
893
+ $size = $y_size;
894
+ $value = $x_value;
895
+ }
896
+
897
+ $value[] = 0; // just in case the carry adds an extra digit
898
+
899
+ $carry = 0;
900
+ for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
901
+ $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] + $y_value[$j] * MATH_BIGINTEGER_BASE_FULL + $y_value[$i] + $carry;
902
+ $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
903
+ $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
904
+
905
+ $temp = (int) ($sum / MATH_BIGINTEGER_BASE_FULL);
906
+
907
+ $value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
908
+ $value[$j] = $temp;
909
+ }
910
+
911
+ if ($j == $size) { // ie. if $y_size is odd
912
+ $sum = $x_value[$i] + $y_value[$i] + $carry;
913
+ $carry = $sum >= MATH_BIGINTEGER_BASE_FULL;
914
+ $value[$i] = $carry ? $sum - MATH_BIGINTEGER_BASE_FULL : $sum;
915
+ ++$i; // ie. let $i = $j since we've just done $value[$i]
916
+ }
917
+
918
+ if ($carry) {
919
+ for (; $value[$i] == MATH_BIGINTEGER_MAX_DIGIT; ++$i) {
920
+ $value[$i] = 0;
921
+ }
922
+ ++$value[$i];
923
+ }
924
+
925
+ return array(
926
+ MATH_BIGINTEGER_VALUE => $this->_trim($value),
927
+ MATH_BIGINTEGER_SIGN => $x_negative
928
+ );
929
+ }
930
+
931
+ /**
932
+ * Subtracts two BigIntegers.
933
+ *
934
+ * Here's an example:
935
+ * <code>
936
+ * <?php
937
+ * include('Math/BigInteger.php');
938
+ *
939
+ * $a = new Math_BigInteger('10');
940
+ * $b = new Math_BigInteger('20');
941
+ *
942
+ * $c = $a->subtract($b);
943
+ *
944
+ * echo $c->toString(); // outputs -10
945
+ * ?>
946
+ * </code>
947
+ *
948
+ * @param Math_BigInteger $y
949
+ * @return Math_BigInteger
950
+ * @access public
951
+ * @internal Performs base-2**52 subtraction
952
+ */
953
+ function subtract($y)
954
+ {
955
+ switch ( MATH_BIGINTEGER_MODE ) {
956
+ case MATH_BIGINTEGER_MODE_GMP:
957
+ $temp = new Math_BigInteger();
958
+ $temp->value = gmp_sub($this->value, $y->value);
959
+
960
+ return $this->_normalize($temp);
961
+ case MATH_BIGINTEGER_MODE_BCMATH:
962
+ $temp = new Math_BigInteger();
963
+ $temp->value = bcsub($this->value, $y->value, 0);
964
+
965
+ return $this->_normalize($temp);
966
+ }
967
+
968
+ $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
969
+
970
+ $result = new Math_BigInteger();
971
+ $result->value = $temp[MATH_BIGINTEGER_VALUE];
972
+ $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
973
+
974
+ return $this->_normalize($result);
975
+ }
976
+
977
+ /**
978
+ * Performs subtraction.
979
+ *
980
+ * @param Array $x_value
981
+ * @param Boolean $x_negative
982
+ * @param Array $y_value
983
+ * @param Boolean $y_negative
984
+ * @return Array
985
+ * @access private
986
+ */
987
+ function _subtract($x_value, $x_negative, $y_value, $y_negative)
988
+ {
989
+ $x_size = count($x_value);
990
+ $y_size = count($y_value);
991
+
992
+ if ($x_size == 0) {
993
+ return array(
994
+ MATH_BIGINTEGER_VALUE => $y_value,
995
+ MATH_BIGINTEGER_SIGN => !$y_negative
996
+ );
997
+ } else if ($y_size == 0) {
998
+ return array(
999
+ MATH_BIGINTEGER_VALUE => $x_value,
1000
+ MATH_BIGINTEGER_SIGN => $x_negative
1001
+ );
1002
+ }
1003
+
1004
+ // add, if appropriate (ie. -$x - +$y or +$x - -$y)
1005
+ if ( $x_negative != $y_negative ) {
1006
+ $temp = $this->_add($x_value, false, $y_value, false);
1007
+ $temp[MATH_BIGINTEGER_SIGN] = $x_negative;
1008
+
1009
+ return $temp;
1010
+ }
1011
+
1012
+ $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative);
1013
+
1014
+ if ( !$diff ) {
1015
+ return array(
1016
+ MATH_BIGINTEGER_VALUE => array(),
1017
+ MATH_BIGINTEGER_SIGN => false
1018
+ );
1019
+ }
1020
+
1021
+ // switch $x and $y around, if appropriate.
1022
+ if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) {
1023
+ $temp = $x_value;
1024
+ $x_value = $y_value;
1025
+ $y_value = $temp;
1026
+
1027
+ $x_negative = !$x_negative;
1028
+
1029
+ $x_size = count($x_value);
1030
+ $y_size = count($y_value);
1031
+ }
1032
+
1033
+ // at this point, $x_value should be at least as big as - if not bigger than - $y_value
1034
+
1035
+ $carry = 0;
1036
+ for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
1037
+ $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] - $y_value[$j] * MATH_BIGINTEGER_BASE_FULL - $y_value[$i] - $carry;
1038
+ $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
1039
+ $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
1040
+
1041
+ $temp = (int) ($sum / MATH_BIGINTEGER_BASE_FULL);
1042
+
1043
+ $x_value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp);
1044
+ $x_value[$j] = $temp;
1045
+ }
1046
+
1047
+ if ($j == $y_size) { // ie. if $y_size is odd
1048
+ $sum = $x_value[$i] - $y_value[$i] - $carry;
1049
+ $carry = $sum < 0;
1050
+ $x_value[$i] = $carry ? $sum + MATH_BIGINTEGER_BASE_FULL : $sum;
1051
+ ++$i;
1052
+ }
1053
+
1054
+ if ($carry) {
1055
+ for (; !$x_value[$i]; ++$i) {
1056
+ $x_value[$i] = MATH_BIGINTEGER_MAX_DIGIT;
1057
+ }
1058
+ --$x_value[$i];
1059
+ }
1060
+
1061
+ return array(
1062
+ MATH_BIGINTEGER_VALUE => $this->_trim($x_value),
1063
+ MATH_BIGINTEGER_SIGN => $x_negative
1064
+ );
1065
+ }
1066
+
1067
+ /**
1068
+ * Multiplies two BigIntegers
1069
+ *
1070
+ * Here's an example:
1071
+ * <code>
1072
+ * <?php
1073
+ * include('Math/BigInteger.php');
1074
+ *
1075
+ * $a = new Math_BigInteger('10');
1076
+ * $b = new Math_BigInteger('20');
1077
+ *
1078
+ * $c = $a->multiply($b);
1079
+ *
1080
+ * echo $c->toString(); // outputs 200
1081
+ * ?>
1082
+ * </code>
1083
+ *
1084
+ * @param Math_BigInteger $x
1085
+ * @return Math_BigInteger
1086
+ * @access public
1087
+ */
1088
+ function multiply($x)
1089
+ {
1090
+ switch ( MATH_BIGINTEGER_MODE ) {
1091
+ case MATH_BIGINTEGER_MODE_GMP:
1092
+ $temp = new Math_BigInteger();
1093
+ $temp->value = gmp_mul($this->value, $x->value);
1094
+
1095
+ return $this->_normalize($temp);
1096
+ case MATH_BIGINTEGER_MODE_BCMATH:
1097
+ $temp = new Math_BigInteger();
1098
+ $temp->value = bcmul($this->value, $x->value, 0);
1099
+
1100
+ return $this->_normalize($temp);
1101
+ }
1102
+
1103
+ $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
1104
+
1105
+ $product = new Math_BigInteger();
1106
+ $product->value = $temp[MATH_BIGINTEGER_VALUE];
1107
+ $product->is_negative = $temp[MATH_BIGINTEGER_SIGN];
1108
+
1109
+ return $this->_normalize($product);
1110
+ }
1111
+
1112
+ /**
1113
+ * Performs multiplication.
1114
+ *
1115
+ * @param Array $x_value
1116
+ * @param Boolean $x_negative
1117
+ * @param Array $y_value
1118
+ * @param Boolean $y_negative
1119
+ * @return Array
1120
+ * @access private
1121
+ */
1122
+ function _multiply($x_value, $x_negative, $y_value, $y_negative)
1123
+ {
1124
+ //if ( $x_value == $y_value ) {
1125
+ // return array(
1126
+ // MATH_BIGINTEGER_VALUE => $this->_square($x_value),
1127
+ // MATH_BIGINTEGER_SIGN => $x_sign != $y_value
1128
+ // );
1129
+ //}
1130
+
1131
+ $x_length = count($x_value);
1132
+ $y_length = count($y_value);
1133
+
1134
+ if ( !$x_length || !$y_length ) { // a 0 is being multiplied
1135
+ return array(
1136
+ MATH_BIGINTEGER_VALUE => array(),
1137
+ MATH_BIGINTEGER_SIGN => false
1138
+ );
1139
+ }
1140
+
1141
+ return array(
1142
+ MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
1143
+ $this->_trim($this->_regularMultiply($x_value, $y_value)) :
1144
+ $this->_trim($this->_karatsuba($x_value, $y_value)),
1145
+ MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
1146
+ );
1147
+ }
1148
+
1149
+ /**
1150
+ * Performs long multiplication on two BigIntegers
1151
+ *
1152
+ * Modeled after 'multiply' in MutableBigInteger.java.
1153
+ *
1154
+ * @param Array $x_value
1155
+ * @param Array $y_value
1156
+ * @return Array
1157
+ * @access private
1158
+ */
1159
+ function _regularMultiply($x_value, $y_value)
1160
+ {
1161
+ $x_length = count($x_value);
1162
+ $y_length = count($y_value);
1163
+
1164
+ if ( !$x_length || !$y_length ) { // a 0 is being multiplied
1165
+ return array();
1166
+ }
1167
+
1168
+ if ( $x_length < $y_length ) {
1169
+ $temp = $x_value;
1170
+ $x_value = $y_value;
1171
+ $y_value = $temp;
1172
+
1173
+ $x_length = count($x_value);
1174
+ $y_length = count($y_value);
1175
+ }
1176
+
1177
+ $product_value = $this->_array_repeat(0, $x_length + $y_length);
1178
+
1179
+ // the following for loop could be removed if the for loop following it
1180
+ // (the one with nested for loops) initially set $i to 0, but
1181
+ // doing so would also make the result in one set of unnecessary adds,
1182
+ // since on the outermost loops first pass, $product->value[$k] is going
1183
+ // to always be 0
1184
+
1185
+ $carry = 0;
1186
+
1187
+ for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
1188
+ $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
1189
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
1190
+ $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
1191
+ }
1192
+
1193
+ $product_value[$j] = $carry;
1194
+
1195
+ // the above for loop is what the previous comment was talking about. the
1196
+ // following for loop is the "one with nested for loops"
1197
+ for ($i = 1; $i < $y_length; ++$i) {
1198
+ $carry = 0;
1199
+
1200
+ for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
1201
+ $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
1202
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
1203
+ $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
1204
+ }
1205
+
1206
+ $product_value[$k] = $carry;
1207
+ }
1208
+
1209
+ return $product_value;
1210
+ }
1211
+
1212
+ /**
1213
+ * Performs Karatsuba multiplication on two BigIntegers
1214
+ *
1215
+ * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
1216
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
1217
+ *
1218
+ * @param Array $x_value
1219
+ * @param Array $y_value
1220
+ * @return Array
1221
+ * @access private
1222
+ */
1223
+ function _karatsuba($x_value, $y_value)
1224
+ {
1225
+ $m = min(count($x_value) >> 1, count($y_value) >> 1);
1226
+
1227
+ if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
1228
+ return $this->_regularMultiply($x_value, $y_value);
1229
+ }
1230
+
1231
+ $x1 = array_slice($x_value, $m);
1232
+ $x0 = array_slice($x_value, 0, $m);
1233
+ $y1 = array_slice($y_value, $m);
1234
+ $y0 = array_slice($y_value, 0, $m);
1235
+
1236
+ $z2 = $this->_karatsuba($x1, $y1);
1237
+ $z0 = $this->_karatsuba($x0, $y0);
1238
+
1239
+ $z1 = $this->_add($x1, false, $x0, false);
1240
+ $temp = $this->_add($y1, false, $y0, false);
1241
+ $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]);
1242
+ $temp = $this->_add($z2, false, $z0, false);
1243
+ $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
1244
+
1245
+ $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
1246
+ $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
1247
+
1248
+ $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
1249
+ $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false);
1250
+
1251
+ return $xy[MATH_BIGINTEGER_VALUE];
1252
+ }
1253
+
1254
+ /**
1255
+ * Performs squaring
1256
+ *
1257
+ * @param Array $x
1258
+ * @return Array
1259
+ * @access private
1260
+ */
1261
+ function _square($x = false)
1262
+ {
1263
+ return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
1264
+ $this->_trim($this->_baseSquare($x)) :
1265
+ $this->_trim($this->_karatsubaSquare($x));
1266
+ }
1267
+
1268
+ /**
1269
+ * Performs traditional squaring on two BigIntegers
1270
+ *
1271
+ * Squaring can be done faster than multiplying a number by itself can be. See
1272
+ * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
1273
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
1274
+ *
1275
+ * @param Array $value
1276
+ * @return Array
1277
+ * @access private
1278
+ */
1279
+ function _baseSquare($value)
1280
+ {
1281
+ if ( empty($value) ) {
1282
+ return array();
1283
+ }
1284
+ $square_value = $this->_array_repeat(0, 2 * count($value));
1285
+
1286
+ for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
1287
+ $i2 = $i << 1;
1288
+
1289
+ $temp = $square_value[$i2] + $value[$i] * $value[$i];
1290
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
1291
+ $square_value[$i2] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
1292
+
1293
+ // note how we start from $i+1 instead of 0 as we do in multiplication.
1294
+ for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
1295
+ $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
1296
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
1297
+ $square_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
1298
+ }
1299
+
1300
+ // the following line can yield values larger 2**15. at this point, PHP should switch
1301
+ // over to floats.
1302
+ $square_value[$i + $max_index + 1] = $carry;
1303
+ }
1304
+
1305
+ return $square_value;
1306
+ }
1307
+
1308
+ /**
1309
+ * Performs Karatsuba "squaring" on two BigIntegers
1310
+ *
1311
+ * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
1312
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
1313
+ *
1314
+ * @param Array $value
1315
+ * @return Array
1316
+ * @access private
1317
+ */
1318
+ function _karatsubaSquare($value)
1319
+ {
1320
+ $m = count($value) >> 1;
1321
+
1322
+ if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
1323
+ return $this->_baseSquare($value);
1324
+ }
1325
+
1326
+ $x1 = array_slice($value, $m);
1327
+ $x0 = array_slice($value, 0, $m);
1328
+
1329
+ $z2 = $this->_karatsubaSquare($x1);
1330
+ $z0 = $this->_karatsubaSquare($x0);
1331
+
1332
+ $z1 = $this->_add($x1, false, $x0, false);
1333
+ $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]);
1334
+ $temp = $this->_add($z2, false, $z0, false);
1335
+ $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
1336
+
1337
+ $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
1338
+ $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
1339
+
1340
+ $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
1341
+ $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false);
1342
+
1343
+ return $xx[MATH_BIGINTEGER_VALUE];
1344
+ }
1345
+
1346
+ /**
1347
+ * Divides two BigIntegers.
1348
+ *
1349
+ * Returns an array whose first element contains the quotient and whose second element contains the
1350
+ * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
1351
+ * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
1352
+ * and the divisor (basically, the "common residue" is the first positive modulo).
1353
+ *
1354
+ * Here's an example:
1355
+ * <code>
1356
+ * <?php
1357
+ * include('Math/BigInteger.php');
1358
+ *
1359
+ * $a = new Math_BigInteger('10');
1360
+ * $b = new Math_BigInteger('20');
1361
+ *
1362
+ * list($quotient, $remainder) = $a->divide($b);
1363
+ *
1364
+ * echo $quotient->toString(); // outputs 0
1365
+ * echo "\r\n";
1366
+ * echo $remainder->toString(); // outputs 10
1367
+ * ?>
1368
+ * </code>
1369
+ *
1370
+ * @param Math_BigInteger $y
1371
+ * @return Array
1372
+ * @access public
1373
+ * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
1374
+ */
1375
+ function divide($y)
1376
+ {
1377
+ switch ( MATH_BIGINTEGER_MODE ) {
1378
+ case MATH_BIGINTEGER_MODE_GMP:
1379
+ $quotient = new Math_BigInteger();
1380
+ $remainder = new Math_BigInteger();
1381
+
1382
+ list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
1383
+
1384
+ if (gmp_sign($remainder->value) < 0) {
1385
+ $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
1386
+ }
1387
+
1388
+ return array($this->_normalize($quotient), $this->_normalize($remainder));
1389
+ case MATH_BIGINTEGER_MODE_BCMATH:
1390
+ $quotient = new Math_BigInteger();
1391
+ $remainder = new Math_BigInteger();
1392
+
1393
+ $quotient->value = bcdiv($this->value, $y->value, 0);
1394
+ $remainder->value = bcmod($this->value, $y->value);
1395
+
1396
+ if ($remainder->value[0] == '-') {
1397
+ $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);
1398
+ }
1399
+
1400
+ return array($this->_normalize($quotient), $this->_normalize($remainder));
1401
+ }
1402
+
1403
+ if (count($y->value) == 1) {
1404
+ list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);
1405
+ $quotient = new Math_BigInteger();
1406
+ $remainder = new Math_BigInteger();
1407
+ $quotient->value = $q;
1408
+ $remainder->value = array($r);
1409
+ $quotient->is_negative = $this->is_negative != $y->is_negative;
1410
+ return array($this->_normalize($quotient), $this->_normalize($remainder));
1411
+ }
1412
+
1413
+ static $zero;
1414
+ if ( !isset($zero) ) {
1415
+ $zero = new Math_BigInteger();
1416
+ }
1417
+
1418
+ $x = $this->copy();
1419
+ $y = $y->copy();
1420
+
1421
+ $x_sign = $x->is_negative;
1422
+ $y_sign = $y->is_negative;
1423
+
1424
+ $x->is_negative = $y->is_negative = false;
1425
+
1426
+ $diff = $x->compare($y);
1427
+
1428
+ if ( !$diff ) {
1429
+ $temp = new Math_BigInteger();
1430
+ $temp->value = array(1);
1431
+ $temp->is_negative = $x_sign != $y_sign;
1432
+ return array($this->_normalize($temp), $this->_normalize(new Math_BigInteger()));
1433
+ }
1434
+
1435
+ if ( $diff < 0 ) {
1436
+ // if $x is negative, "add" $y.
1437
+ if ( $x_sign ) {
1438
+ $x = $y->subtract($x);
1439
+ }
1440
+ return array($this->_normalize(new Math_BigInteger()), $this->_normalize($x));
1441
+ }
1442
+
1443
+ // normalize $x and $y as described in HAC 14.23 / 14.24
1444
+ $msb = $y->value[count($y->value) - 1];
1445
+ for ($shift = 0; !($msb & MATH_BIGINTEGER_MSB); ++$shift) {
1446
+ $msb <<= 1;
1447
+ }
1448
+ $x->_lshift($shift);
1449
+ $y->_lshift($shift);
1450
+ $y_value = &$y->value;
1451
+
1452
+ $x_max = count($x->value) - 1;
1453
+ $y_max = count($y->value) - 1;
1454
+
1455
+ $quotient = new Math_BigInteger();
1456
+ $quotient_value = &$quotient->value;
1457
+ $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1);
1458
+
1459
+ static $temp, $lhs, $rhs;
1460
+ if (!isset($temp)) {
1461
+ $temp = new Math_BigInteger();
1462
+ $lhs = new Math_BigInteger();
1463
+ $rhs = new Math_BigInteger();
1464
+ }
1465
+ $temp_value = &$temp->value;
1466
+ $rhs_value = &$rhs->value;
1467
+
1468
+ // $temp = $y << ($x_max - $y_max-1) in base 2**26
1469
+ $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value);
1470
+
1471
+ while ( $x->compare($temp) >= 0 ) {
1472
+ // calculate the "common residue"
1473
+ ++$quotient_value[$x_max - $y_max];
1474
+ $x = $x->subtract($temp);
1475
+ $x_max = count($x->value) - 1;
1476
+ }
1477
+
1478
+ for ($i = $x_max; $i >= $y_max + 1; --$i) {
1479
+ $x_value = &$x->value;
1480
+ $x_window = array(
1481
+ isset($x_value[$i]) ? $x_value[$i] : 0,
1482
+ isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0,
1483
+ isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0
1484
+ );
1485
+ $y_window = array(
1486
+ $y_value[$y_max],
1487
+ ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0
1488
+ );
1489
+
1490
+ $q_index = $i - $y_max - 1;
1491
+ if ($x_window[0] == $y_window[0]) {
1492
+ $quotient_value[$q_index] = MATH_BIGINTEGER_MAX_DIGIT;
1493
+ } else {
1494
+ $quotient_value[$q_index] = (int) (
1495
+ ($x_window[0] * MATH_BIGINTEGER_BASE_FULL + $x_window[1])
1496
+ /
1497
+ $y_window[0]
1498
+ );
1499
+ }
1500
+
1501
+ $temp_value = array($y_window[1], $y_window[0]);
1502
+
1503
+ $lhs->value = array($quotient_value[$q_index]);
1504
+ $lhs = $lhs->multiply($temp);
1505
+
1506
+ $rhs_value = array($x_window[2], $x_window[1], $x_window[0]);
1507
+
1508
+ while ( $lhs->compare($rhs) > 0 ) {
1509
+ --$quotient_value[$q_index];
1510
+
1511
+ $lhs->value = array($quotient_value[$q_index]);
1512
+ $lhs = $lhs->multiply($temp);
1513
+ }
1514
+
1515
+ $adjust = $this->_array_repeat(0, $q_index);
1516
+ $temp_value = array($quotient_value[$q_index]);
1517
+ $temp = $temp->multiply($y);
1518
+ $temp_value = &$temp->value;
1519
+ $temp_value = array_merge($adjust, $temp_value);
1520
+
1521
+ $x = $x->subtract($temp);
1522
+
1523
+ if ($x->compare($zero) < 0) {
1524
+ $temp_value = array_merge($adjust, $y_value);
1525
+ $x = $x->add($temp);
1526
+
1527
+ --$quotient_value[$q_index];
1528
+ }
1529
+
1530
+ $x_max = count($x_value) - 1;
1531
+ }
1532
+
1533
+ // unnormalize the remainder
1534
+ $x->_rshift($shift);
1535
+
1536
+ $quotient->is_negative = $x_sign != $y_sign;
1537
+
1538
+ // calculate the "common residue", if appropriate
1539
+ if ( $x_sign ) {
1540
+ $y->_rshift($shift);
1541
+ $x = $y->subtract($x);
1542
+ }
1543
+
1544
+ return array($this->_normalize($quotient), $this->_normalize($x));
1545
+ }
1546
+
1547
+ /**
1548
+ * Divides a BigInteger by a regular integer
1549
+ *
1550
+ * abc / x = a00 / x + b0 / x + c / x
1551
+ *
1552
+ * @param Array $dividend
1553
+ * @param Array $divisor
1554
+ * @return Array
1555
+ * @access private
1556
+ */
1557
+ function _divide_digit($dividend, $divisor)
1558
+ {
1559
+ $carry = 0;
1560
+ $result = array();
1561
+
1562
+ for ($i = count($dividend) - 1; $i >= 0; --$i) {
1563
+ $temp = MATH_BIGINTEGER_BASE_FULL * $carry + $dividend[$i];
1564
+ $result[$i] = (int) ($temp / $divisor);
1565
+ $carry = (int) ($temp - $divisor * $result[$i]);
1566
+ }
1567
+
1568
+ return array($result, $carry);
1569
+ }
1570
+
1571
+ /**
1572
+ * Performs modular exponentiation.
1573
+ *
1574
+ * Here's an example:
1575
+ * <code>
1576
+ * <?php
1577
+ * include('Math/BigInteger.php');
1578
+ *
1579
+ * $a = new Math_BigInteger('10');
1580
+ * $b = new Math_BigInteger('20');
1581
+ * $c = new Math_BigInteger('30');
1582
+ *
1583
+ * $c = $a->modPow($b, $c);
1584
+ *
1585
+ * echo $c->toString(); // outputs 10
1586
+ * ?>
1587
+ * </code>
1588
+ *
1589
+ * @param Math_BigInteger $e
1590
+ * @param Math_BigInteger $n
1591
+ * @return Math_BigInteger
1592
+ * @access public
1593
+ * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and
1594
+ * and although the approach involving repeated squaring does vastly better, it, too, is impractical
1595
+ * for our purposes. The reason being that division - by far the most complicated and time-consuming
1596
+ * of the basic operations (eg. +,-,*,/) - occurs multiple times within it.
1597
+ *
1598
+ * Modular reductions resolve this issue. Although an individual modular reduction takes more time
1599
+ * then an individual division, when performed in succession (with the same modulo), they're a lot faster.
1600
+ *
1601
+ * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction,
1602
+ * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the
1603
+ * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because
1604
+ * the product of two odd numbers is odd), but what about when RSA isn't used?
1605
+ *
1606
+ * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a
1607
+ * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the
1608
+ * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however,
1609
+ * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and
1610
+ * the other, a power of two - and recombine them, later. This is the method that this modPow function uses.
1611
+ * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates.
1612
+ */
1613
+ function modPow($e, $n)
1614
+ {
1615
+ $n = $this->bitmask !== false && $this->bitmask->compare($n) < 0 ? $this->bitmask : $n->abs();
1616
+
1617
+ if ($e->compare(new Math_BigInteger()) < 0) {
1618
+ $e = $e->abs();
1619
+
1620
+ $temp = $this->modInverse($n);
1621
+ if ($temp === false) {
1622
+ return false;
1623
+ }
1624
+
1625
+ return $this->_normalize($temp->modPow($e, $n));
1626
+ }
1627
+
1628
+ if ( MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP ) {
1629
+ $temp = new Math_BigInteger();
1630
+ $temp->value = gmp_powm($this->value, $e->value, $n->value);
1631
+
1632
+ return $this->_normalize($temp);
1633
+ }
1634
+
1635
+ if ($this->compare(new Math_BigInteger()) < 0 || $this->compare($n) > 0) {
1636
+ list(, $temp) = $this->divide($n);
1637
+ return $temp->modPow($e, $n);
1638
+ }
1639
+
1640
+ if (defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
1641
+ $components = array(
1642
+ 'modulus' => $n->toBytes(true),
1643
+ 'publicExponent' => $e->toBytes(true)
1644
+ );
1645
+
1646
+ $components = array(
1647
+ 'modulus' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['modulus'])), $components['modulus']),
1648
+ 'publicExponent' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['publicExponent'])), $components['publicExponent'])
1649
+ );
1650
+
1651
+ $RSAPublicKey = pack('Ca*a*a*',
1652
+ 48, $this->_encodeASN1Length(strlen($components['modulus']) + strlen($components['publicExponent'])),
1653
+ $components['modulus'], $components['publicExponent']
1654
+ );
1655
+
1656
+ $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
1657
+ $RSAPublicKey = chr(0) . $RSAPublicKey;
1658
+ $RSAPublicKey = chr(3) . $this->_encodeASN1Length(strlen($RSAPublicKey)) . $RSAPublicKey;
1659
+
1660
+ $encapsulated = pack('Ca*a*',
1661
+ 48, $this->_encodeASN1Length(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
1662
+ );
1663
+
1664
+ $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
1665
+ chunk_split(base64_encode($encapsulated)) .
1666
+ '-----END PUBLIC KEY-----';
1667
+
1668
+ $plaintext = str_pad($this->toBytes(), strlen($n->toBytes(true)) - 1, "\0", STR_PAD_LEFT);
1669
+
1670
+ if (openssl_public_encrypt($plaintext, $result, $RSAPublicKey, OPENSSL_NO_PADDING)) {
1671
+ return new Math_BigInteger($result, 256);
1672
+ }
1673
+ }
1674
+
1675
+ if ( MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH ) {
1676
+ $temp = new Math_BigInteger();
1677
+ $temp->value = bcpowmod($this->value, $e->value, $n->value, 0);
1678
+
1679
+ return $this->_normalize($temp);
1680
+ }
1681
+
1682
+ if ( empty($e->value) ) {
1683
+ $temp = new Math_BigInteger();
1684
+ $temp->value = array(1);
1685
+ return $this->_normalize($temp);
1686
+ }
1687
+
1688
+ if ( $e->value == array(1) ) {
1689
+ list(, $temp) = $this->divide($n);
1690
+ return $this->_normalize($temp);
1691
+ }
1692
+
1693
+ if ( $e->value == array(2) ) {
1694
+ $temp = new Math_BigInteger();
1695
+ $temp->value = $this->_square($this->value);
1696
+ list(, $temp) = $temp->divide($n);
1697
+ return $this->_normalize($temp);
1698
+ }
1699
+
1700
+ return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_BARRETT));
1701
+
1702
+ // is the modulo odd?
1703
+ if ( $n->value[0] & 1 ) {
1704
+ return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_MONTGOMERY));
1705
+ }
1706
+ // if it's not, it's even
1707
+
1708
+ // find the lowest set bit (eg. the max pow of 2 that divides $n)
1709
+ for ($i = 0; $i < count($n->value); ++$i) {
1710
+ if ( $n->value[$i] ) {
1711
+ $temp = decbin($n->value[$i]);
1712
+ $j = strlen($temp) - strrpos($temp, '1') - 1;
1713
+ $j+= 26 * $i;
1714
+ break;
1715
+ }
1716
+ }
1717
+ // at this point, 2^$j * $n/(2^$j) == $n
1718
+
1719
+ $mod1 = $n->copy();
1720
+ $mod1->_rshift($j);
1721
+ $mod2 = new Math_BigInteger();
1722
+ $mod2->value = array(1);
1723
+ $mod2->_lshift($j);
1724
+
1725
+ $part1 = ( $mod1->value != array(1) ) ? $this->_slidingWindow($e, $mod1, MATH_BIGINTEGER_MONTGOMERY) : new Math_BigInteger();
1726
+ $part2 = $this->_slidingWindow($e, $mod2, MATH_BIGINTEGER_POWEROF2);
1727
+
1728
+ $y1 = $mod2->modInverse($mod1);
1729
+ $y2 = $mod1->modInverse($mod2);
1730
+
1731
+ $result = $part1->multiply($mod2);
1732
+ $result = $result->multiply($y1);
1733
+
1734
+ $temp = $part2->multiply($mod1);
1735
+ $temp = $temp->multiply($y2);
1736
+
1737
+ $result = $result->add($temp);
1738
+ list(, $result) = $result->divide($n);
1739
+
1740
+ return $this->_normalize($result);
1741
+ }
1742
+
1743
+ /**
1744
+ * Performs modular exponentiation.
1745
+ *
1746
+ * Alias for Math_BigInteger::modPow()
1747
+ *
1748
+ * @param Math_BigInteger $e
1749
+ * @param Math_BigInteger $n
1750
+ * @return Math_BigInteger
1751
+ * @access public
1752
+ */
1753
+ function powMod($e, $n)
1754
+ {
1755
+ return $this->modPow($e, $n);
1756
+ }
1757
+
1758
+ /**
1759
+ * Sliding Window k-ary Modular Exponentiation
1760
+ *
1761
+ * Based on {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=27 HAC 14.85} /
1762
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=210 MPM 7.7}. In a departure from those algorithims,
1763
+ * however, this function performs a modular reduction after every multiplication and squaring operation.
1764
+ * As such, this function has the same preconditions that the reductions being used do.
1765
+ *
1766
+ * @param Math_BigInteger $e
1767
+ * @param Math_BigInteger $n
1768
+ * @param Integer $mode
1769
+ * @return Math_BigInteger
1770
+ * @access private
1771
+ */
1772
+ function _slidingWindow($e, $n, $mode)
1773
+ {
1774
+ static $window_ranges = array(7, 25, 81, 241, 673, 1793); // from BigInteger.java's oddModPow function
1775
+ //static $window_ranges = array(0, 7, 36, 140, 450, 1303, 3529); // from MPM 7.3.1
1776
+
1777
+ $e_value = $e->value;
1778
+ $e_length = count($e_value) - 1;
1779
+ $e_bits = decbin($e_value[$e_length]);
1780
+ for ($i = $e_length - 1; $i >= 0; --$i) {
1781
+ $e_bits.= str_pad(decbin($e_value[$i]), MATH_BIGINTEGER_BASE, '0', STR_PAD_LEFT);
1782
+ }
1783
+
1784
+ $e_length = strlen($e_bits);
1785
+
1786
+ // calculate the appropriate window size.
1787
+ // $window_size == 3 if $window_ranges is between 25 and 81, for example.
1788
+ for ($i = 0, $window_size = 1; $e_length > $window_ranges[$i] && $i < count($window_ranges); ++$window_size, ++$i);
1789
+
1790
+ $n_value = $n->value;
1791
+
1792
+ // precompute $this^0 through $this^$window_size
1793
+ $powers = array();
1794
+ $powers[1] = $this->_prepareReduce($this->value, $n_value, $mode);
1795
+ $powers[2] = $this->_squareReduce($powers[1], $n_value, $mode);
1796
+
1797
+ // we do every other number since substr($e_bits, $i, $j+1) (see below) is supposed to end
1798
+ // in a 1. ie. it's supposed to be odd.
1799
+ $temp = 1 << ($window_size - 1);
1800
+ for ($i = 1; $i < $temp; ++$i) {
1801
+ $i2 = $i << 1;
1802
+ $powers[$i2 + 1] = $this->_multiplyReduce($powers[$i2 - 1], $powers[2], $n_value, $mode);
1803
+ }
1804
+
1805
+ $result = array(1);
1806
+ $result = $this->_prepareReduce($result, $n_value, $mode);
1807
+
1808
+ for ($i = 0; $i < $e_length; ) {
1809
+ if ( !$e_bits[$i] ) {
1810
+ $result = $this->_squareReduce($result, $n_value, $mode);
1811
+ ++$i;
1812
+ } else {
1813
+ for ($j = $window_size - 1; $j > 0; --$j) {
1814
+ if ( !empty($e_bits[$i + $j]) ) {
1815
+ break;
1816
+ }
1817
+ }
1818
+
1819
+ for ($k = 0; $k <= $j; ++$k) {// eg. the length of substr($e_bits, $i, $j+1)
1820
+ $result = $this->_squareReduce($result, $n_value, $mode);
1821
+ }
1822
+
1823
+ $result = $this->_multiplyReduce($result, $powers[bindec(substr($e_bits, $i, $j + 1))], $n_value, $mode);
1824
+
1825
+ $i+=$j + 1;
1826
+ }
1827
+ }
1828
+
1829
+ $temp = new Math_BigInteger();
1830
+ $temp->value = $this->_reduce($result, $n_value, $mode);
1831
+
1832
+ return $temp;
1833
+ }
1834
+
1835
+ /**
1836
+ * Modular reduction
1837
+ *
1838
+ * For most $modes this will return the remainder.
1839
+ *
1840
+ * @see _slidingWindow()
1841
+ * @access private
1842
+ * @param Array $x
1843
+ * @param Array $n
1844
+ * @param Integer $mode
1845
+ * @return Array
1846
+ */
1847
+ function _reduce($x, $n, $mode)
1848
+ {
1849
+ switch ($mode) {
1850
+ case MATH_BIGINTEGER_MONTGOMERY:
1851
+ return $this->_montgomery($x, $n);
1852
+ case MATH_BIGINTEGER_BARRETT:
1853
+ return $this->_barrett($x, $n);
1854
+ case MATH_BIGINTEGER_POWEROF2:
1855
+ $lhs = new Math_BigInteger();
1856
+ $lhs->value = $x;
1857
+ $rhs = new Math_BigInteger();
1858
+ $rhs->value = $n;
1859
+ return $x->_mod2($n);
1860
+ case MATH_BIGINTEGER_CLASSIC:
1861
+ $lhs = new Math_BigInteger();
1862
+ $lhs->value = $x;
1863
+ $rhs = new Math_BigInteger();
1864
+ $rhs->value = $n;
1865
+ list(, $temp) = $lhs->divide($rhs);
1866
+ return $temp->value;
1867
+ case MATH_BIGINTEGER_NONE:
1868
+ return $x;
1869
+ default:
1870
+ // an invalid $mode was provided
1871
+ }
1872
+ }
1873
+
1874
+ /**
1875
+ * Modular reduction preperation
1876
+ *
1877
+ * @see _slidingWindow()
1878
+ * @access private
1879
+ * @param Array $x
1880
+ * @param Array $n
1881
+ * @param Integer $mode
1882
+ * @return Array
1883
+ */
1884
+ function _prepareReduce($x, $n, $mode)
1885
+ {
1886
+ if ($mode == MATH_BIGINTEGER_MONTGOMERY) {
1887
+ return $this->_prepMontgomery($x, $n);
1888
+ }
1889
+ return $this->_reduce($x, $n, $mode);
1890
+ }
1891
+
1892
+ /**
1893
+ * Modular multiply
1894
+ *
1895
+ * @see _slidingWindow()
1896
+ * @access private
1897
+ * @param Array $x
1898
+ * @param Array $y
1899
+ * @param Array $n
1900
+ * @param Integer $mode
1901
+ * @return Array
1902
+ */
1903
+ function _multiplyReduce($x, $y, $n, $mode)
1904
+ {
1905
+ if ($mode == MATH_BIGINTEGER_MONTGOMERY) {
1906
+ return $this->_montgomeryMultiply($x, $y, $n);
1907
+ }
1908
+ $temp = $this->_multiply($x, false, $y, false);
1909
+ return $this->_reduce($temp[MATH_BIGINTEGER_VALUE], $n, $mode);
1910
+ }
1911
+
1912
+ /**
1913
+ * Modular square
1914
+ *
1915
+ * @see _slidingWindow()
1916
+ * @access private
1917
+ * @param Array $x
1918
+ * @param Array $n
1919
+ * @param Integer $mode
1920
+ * @return Array
1921
+ */
1922
+ function _squareReduce($x, $n, $mode)
1923
+ {
1924
+ if ($mode == MATH_BIGINTEGER_MONTGOMERY) {
1925
+ return $this->_montgomeryMultiply($x, $x, $n);
1926
+ }
1927
+ return $this->_reduce($this->_square($x), $n, $mode);
1928
+ }
1929
+
1930
+ /**
1931
+ * Modulos for Powers of Two
1932
+ *
1933
+ * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1),
1934
+ * we'll just use this function as a wrapper for doing that.
1935
+ *
1936
+ * @see _slidingWindow()
1937
+ * @access private
1938
+ * @param Math_BigInteger
1939
+ * @return Math_BigInteger
1940
+ */
1941
+ function _mod2($n)
1942
+ {
1943
+ $temp = new Math_BigInteger();
1944
+ $temp->value = array(1);
1945
+ return $this->bitwise_and($n->subtract($temp));
1946
+ }
1947
+
1948
+ /**
1949
+ * Barrett Modular Reduction
1950
+ *
1951
+ * See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=14 HAC 14.3.3} /
1952
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=165 MPM 6.2.5} for more information. Modified slightly,
1953
+ * so as not to require negative numbers (initially, this script didn't support negative numbers).
1954
+ *
1955
+ * Employs "folding", as described at
1956
+ * {@link http://www.cosic.esat.kuleuven.be/publications/thesis-149.pdf#page=66 thesis-149.pdf#page=66}. To quote from
1957
+ * it, "the idea [behind folding] is to find a value x' such that x (mod m) = x' (mod m), with x' being smaller than x."
1958
+ *
1959
+ * Unfortunately, the "Barrett Reduction with Folding" algorithm described in thesis-149.pdf is not, as written, all that
1960
+ * usable on account of (1) its not using reasonable radix points as discussed in
1961
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=162 MPM 6.2.2} and (2) the fact that, even with reasonable
1962
+ * radix points, it only works when there are an even number of digits in the denominator. The reason for (2) is that
1963
+ * (x >> 1) + (x >> 1) != x / 2 + x / 2. If x is even, they're the same, but if x is odd, they're not. See the in-line
1964
+ * comments for details.
1965
+ *
1966
+ * @see _slidingWindow()
1967
+ * @access private
1968
+ * @param Array $n
1969
+ * @param Array $m
1970
+ * @return Array
1971
+ */
1972
+ function _barrett($n, $m)
1973
+ {
1974
+ static $cache = array(
1975
+ MATH_BIGINTEGER_VARIABLE => array(),
1976
+ MATH_BIGINTEGER_DATA => array()
1977
+ );
1978
+
1979
+ $m_length = count($m);
1980
+
1981
+ // if ($this->_compare($n, $this->_square($m)) >= 0) {
1982
+ if (count($n) > 2 * $m_length) {
1983
+ $lhs = new Math_BigInteger();
1984
+ $rhs = new Math_BigInteger();
1985
+ $lhs->value = $n;
1986
+ $rhs->value = $m;
1987
+ list(, $temp) = $lhs->divide($rhs);
1988
+ return $temp->value;
1989
+ }
1990
+
1991
+ // if (m.length >> 1) + 2 <= m.length then m is too small and n can't be reduced
1992
+ if ($m_length < 5) {
1993
+ return $this->_regularBarrett($n, $m);
1994
+ }
1995
+
1996
+ // n = 2 * m.length
1997
+
1998
+ if ( ($key = array_search($m, $cache[MATH_BIGINTEGER_VARIABLE])) === false ) {
1999
+ $key = count($cache[MATH_BIGINTEGER_VARIABLE]);
2000
+ $cache[MATH_BIGINTEGER_VARIABLE][] = $m;
2001
+
2002
+ $lhs = new Math_BigInteger();
2003
+ $lhs_value = &$lhs->value;
2004
+ $lhs_value = $this->_array_repeat(0, $m_length + ($m_length >> 1));
2005
+ $lhs_value[] = 1;
2006
+ $rhs = new Math_BigInteger();
2007
+ $rhs->value = $m;
2008
+
2009
+ list($u, $m1) = $lhs->divide($rhs);
2010
+ $u = $u->value;
2011
+ $m1 = $m1->value;
2012
+
2013
+ $cache[MATH_BIGINTEGER_DATA][] = array(
2014
+ 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1)
2015
+ 'm1'=> $m1 // m.length
2016
+ );
2017
+ } else {
2018
+ extract($cache[MATH_BIGINTEGER_DATA][$key]);
2019
+ }
2020
+
2021
+ $cutoff = $m_length + ($m_length >> 1);
2022
+ $lsd = array_slice($n, 0, $cutoff); // m.length + (m.length >> 1)
2023
+ $msd = array_slice($n, $cutoff); // m.length >> 1
2024
+ $lsd = $this->_trim($lsd);
2025
+ $temp = $this->_multiply($msd, false, $m1, false);
2026
+ $n = $this->_add($lsd, false, $temp[MATH_BIGINTEGER_VALUE], false); // m.length + (m.length >> 1) + 1
2027
+
2028
+ if ($m_length & 1) {
2029
+ return $this->_regularBarrett($n[MATH_BIGINTEGER_VALUE], $m);
2030
+ }
2031
+
2032
+ // (m.length + (m.length >> 1) + 1) - (m.length - 1) == (m.length >> 1) + 2
2033
+ $temp = array_slice($n[MATH_BIGINTEGER_VALUE], $m_length - 1);
2034
+ // if even: ((m.length >> 1) + 2) + (m.length >> 1) == m.length + 2
2035
+ // if odd: ((m.length >> 1) + 2) + (m.length >> 1) == (m.length - 1) + 2 == m.length + 1
2036
+ $temp = $this->_multiply($temp, false, $u, false);
2037
+ // if even: (m.length + 2) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) + 1
2038
+ // if odd: (m.length + 1) - ((m.length >> 1) + 1) = m.length - (m.length >> 1)
2039
+ $temp = array_slice($temp[MATH_BIGINTEGER_VALUE], ($m_length >> 1) + 1);
2040
+ // if even: (m.length - (m.length >> 1) + 1) + m.length = 2 * m.length - (m.length >> 1) + 1
2041
+ // if odd: (m.length - (m.length >> 1)) + m.length = 2 * m.length - (m.length >> 1)
2042
+ $temp = $this->_multiply($temp, false, $m, false);
2043
+
2044
+ // at this point, if m had an odd number of digits, we'd be subtracting a 2 * m.length - (m.length >> 1) digit
2045
+ // number from a m.length + (m.length >> 1) + 1 digit number. ie. there'd be an extra digit and the while loop
2046
+ // following this comment would loop a lot (hence our calling _regularBarrett() in that situation).
2047
+
2048
+ $result = $this->_subtract($n[MATH_BIGINTEGER_VALUE], false, $temp[MATH_BIGINTEGER_VALUE], false);
2049
+
2050
+ while ($this->_compare($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $m, false) >= 0) {
2051
+ $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $m, false);
2052
+ }
2053
+
2054
+ return $result[MATH_BIGINTEGER_VALUE];
2055
+ }
2056
+
2057
+ /**
2058
+ * (Regular) Barrett Modular Reduction
2059
+ *
2060
+ * For numbers with more than four digits Math_BigInteger::_barrett() is faster. The difference between that and this
2061
+ * is that this function does not fold the denominator into a smaller form.
2062
+ *
2063
+ * @see _slidingWindow()
2064
+ * @access private
2065
+ * @param Array $x
2066
+ * @param Array $n
2067
+ * @return Array
2068
+ */
2069
+ function _regularBarrett($x, $n)
2070
+ {
2071
+ static $cache = array(
2072
+ MATH_BIGINTEGER_VARIABLE => array(),
2073
+ MATH_BIGINTEGER_DATA => array()
2074
+ );
2075
+
2076
+ $n_length = count($n);
2077
+
2078
+ if (count($x) > 2 * $n_length) {
2079
+ $lhs = new Math_BigInteger();
2080
+ $rhs = new Math_BigInteger();
2081
+ $lhs->value = $x;
2082
+ $rhs->value = $n;
2083
+ list(, $temp) = $lhs->divide($rhs);
2084
+ return $temp->value;
2085
+ }
2086
+
2087
+ if ( ($key = array_search($n, $cache[MATH_BIGINTEGER_VARIABLE])) === false ) {
2088
+ $key = count($cache[MATH_BIGINTEGER_VARIABLE]);
2089
+ $cache[MATH_BIGINTEGER_VARIABLE][] = $n;
2090
+ $lhs = new Math_BigInteger();
2091
+ $lhs_value = &$lhs->value;
2092
+ $lhs_value = $this->_array_repeat(0, 2 * $n_length);
2093
+ $lhs_value[] = 1;
2094
+ $rhs = new Math_BigInteger();
2095
+ $rhs->value = $n;
2096
+ list($temp, ) = $lhs->divide($rhs); // m.length
2097
+ $cache[MATH_BIGINTEGER_DATA][] = $temp->value;
2098
+ }
2099
+
2100
+ // 2 * m.length - (m.length - 1) = m.length + 1
2101
+ $temp = array_slice($x, $n_length - 1);
2102
+ // (m.length + 1) + m.length = 2 * m.length + 1
2103
+ $temp = $this->_multiply($temp, false, $cache[MATH_BIGINTEGER_DATA][$key], false);
2104
+ // (2 * m.length + 1) - (m.length - 1) = m.length + 2
2105
+ $temp = array_slice($temp[MATH_BIGINTEGER_VALUE], $n_length + 1);
2106
+
2107
+ // m.length + 1
2108
+ $result = array_slice($x, 0, $n_length + 1);
2109
+ // m.length + 1
2110
+ $temp = $this->_multiplyLower($temp, false, $n, false, $n_length + 1);
2111
+ // $temp == array_slice($temp->_multiply($temp, false, $n, false)->value, 0, $n_length + 1)
2112
+
2113
+ if ($this->_compare($result, false, $temp[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_SIGN]) < 0) {
2114
+ $corrector_value = $this->_array_repeat(0, $n_length + 1);
2115
+ $corrector_value[] = 1;
2116
+ $result = $this->_add($result, false, $corrector_value, false);
2117
+ $result = $result[MATH_BIGINTEGER_VALUE];
2118
+ }
2119
+
2120
+ // at this point, we're subtracting a number with m.length + 1 digits from another number with m.length + 1 digits
2121
+ $result = $this->_subtract($result, false, $temp[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_SIGN]);
2122
+ while ($this->_compare($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $n, false) > 0) {
2123
+ $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $n, false);
2124
+ }
2125
+
2126
+ return $result[MATH_BIGINTEGER_VALUE];
2127
+ }
2128
+
2129
+ /**
2130
+ * Performs long multiplication up to $stop digits
2131
+ *
2132
+ * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved.
2133
+ *
2134
+ * @see _regularBarrett()
2135
+ * @param Array $x_value
2136
+ * @param Boolean $x_negative
2137
+ * @param Array $y_value
2138
+ * @param Boolean $y_negative
2139
+ * @param Integer $stop
2140
+ * @return Array
2141
+ * @access private
2142
+ */
2143
+ function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop)
2144
+ {
2145
+ $x_length = count($x_value);
2146
+ $y_length = count($y_value);
2147
+
2148
+ if ( !$x_length || !$y_length ) { // a 0 is being multiplied
2149
+ return array(
2150
+ MATH_BIGINTEGER_VALUE => array(),
2151
+ MATH_BIGINTEGER_SIGN => false
2152
+ );
2153
+ }
2154
+
2155
+ if ( $x_length < $y_length ) {
2156
+ $temp = $x_value;
2157
+ $x_value = $y_value;
2158
+ $y_value = $temp;
2159
+
2160
+ $x_length = count($x_value);
2161
+ $y_length = count($y_value);
2162
+ }
2163
+
2164
+ $product_value = $this->_array_repeat(0, $x_length + $y_length);
2165
+
2166
+ // the following for loop could be removed if the for loop following it
2167
+ // (the one with nested for loops) initially set $i to 0, but
2168
+ // doing so would also make the result in one set of unnecessary adds,
2169
+ // since on the outermost loops first pass, $product->value[$k] is going
2170
+ // to always be 0
2171
+
2172
+ $carry = 0;
2173
+
2174
+ for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0, $k = $i
2175
+ $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
2176
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
2177
+ $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
2178
+ }
2179
+
2180
+ if ($j < $stop) {
2181
+ $product_value[$j] = $carry;
2182
+ }
2183
+
2184
+ // the above for loop is what the previous comment was talking about. the
2185
+ // following for loop is the "one with nested for loops"
2186
+
2187
+ for ($i = 1; $i < $y_length; ++$i) {
2188
+ $carry = 0;
2189
+
2190
+ for ($j = 0, $k = $i; $j < $x_length && $k < $stop; ++$j, ++$k) {
2191
+ $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
2192
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
2193
+ $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
2194
+ }
2195
+
2196
+ if ($k < $stop) {
2197
+ $product_value[$k] = $carry;
2198
+ }
2199
+ }
2200
+
2201
+ return array(
2202
+ MATH_BIGINTEGER_VALUE => $this->_trim($product_value),
2203
+ MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
2204
+ );
2205
+ }
2206
+
2207
+ /**
2208
+ * Montgomery Modular Reduction
2209
+ *
2210
+ * ($x->_prepMontgomery($n))->_montgomery($n) yields $x % $n.
2211
+ * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=170 MPM 6.3} provides insights on how this can be
2212
+ * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function
2213
+ * to work correctly.
2214
+ *
2215
+ * @see _prepMontgomery()
2216
+ * @see _slidingWindow()
2217
+ * @access private
2218
+ * @param Array $x
2219
+ * @param Array $n
2220
+ * @return Array
2221
+ */
2222
+ function _montgomery($x, $n)
2223
+ {
2224
+ static $cache = array(
2225
+ MATH_BIGINTEGER_VARIABLE => array(),
2226
+ MATH_BIGINTEGER_DATA => array()
2227
+ );
2228
+
2229
+ if ( ($key = array_search($n, $cache[MATH_BIGINTEGER_VARIABLE])) === false ) {
2230
+ $key = count($cache[MATH_BIGINTEGER_VARIABLE]);
2231
+ $cache[MATH_BIGINTEGER_VARIABLE][] = $x;
2232
+ $cache[MATH_BIGINTEGER_DATA][] = $this->_modInverse67108864($n);
2233
+ }
2234
+
2235
+ $k = count($n);
2236
+
2237
+ $result = array(MATH_BIGINTEGER_VALUE => $x);
2238
+
2239
+ for ($i = 0; $i < $k; ++$i) {
2240
+ $temp = $result[MATH_BIGINTEGER_VALUE][$i] * $cache[MATH_BIGINTEGER_DATA][$key];
2241
+ $temp = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * ((int) ($temp / MATH_BIGINTEGER_BASE_FULL)));
2242
+ $temp = $this->_regularMultiply(array($temp), $n);
2243
+ $temp = array_merge($this->_array_repeat(0, $i), $temp);
2244
+ $result = $this->_add($result[MATH_BIGINTEGER_VALUE], false, $temp, false);
2245
+ }
2246
+
2247
+ $result[MATH_BIGINTEGER_VALUE] = array_slice($result[MATH_BIGINTEGER_VALUE], $k);
2248
+
2249
+ if ($this->_compare($result, false, $n, false) >= 0) {
2250
+ $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], false, $n, false);
2251
+ }
2252
+
2253
+ return $result[MATH_BIGINTEGER_VALUE];
2254
+ }
2255
+
2256
+ /**
2257
+ * Montgomery Multiply
2258
+ *
2259
+ * Interleaves the montgomery reduction and long multiplication algorithms together as described in
2260
+ * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36}
2261
+ *
2262
+ * @see _prepMontgomery()
2263
+ * @see _montgomery()
2264
+ * @access private
2265
+ * @param Array $x
2266
+ * @param Array $y
2267
+ * @param Array $m
2268
+ * @return Array
2269
+ */
2270
+ function _montgomeryMultiply($x, $y, $m)
2271
+ {
2272
+ $temp = $this->_multiply($x, false, $y, false);
2273
+ return $this->_montgomery($temp[MATH_BIGINTEGER_VALUE], $m);
2274
+
2275
+ static $cache = array(
2276
+ MATH_BIGINTEGER_VARIABLE => array(),
2277
+ MATH_BIGINTEGER_DATA => array()
2278
+ );
2279
+
2280
+ if ( ($key = array_search($m, $cache[MATH_BIGINTEGER_VARIABLE])) === false ) {
2281
+ $key = count($cache[MATH_BIGINTEGER_VARIABLE]);
2282
+ $cache[MATH_BIGINTEGER_VARIABLE][] = $m;
2283
+ $cache[MATH_BIGINTEGER_DATA][] = $this->_modInverse67108864($m);
2284
+ }
2285
+
2286
+ $n = max(count($x), count($y), count($m));
2287
+ $x = array_pad($x, $n, 0);
2288
+ $y = array_pad($y, $n, 0);
2289
+ $m = array_pad($m, $n, 0);
2290
+ $a = array(MATH_BIGINTEGER_VALUE => $this->_array_repeat(0, $n + 1));
2291
+ for ($i = 0; $i < $n; ++$i) {
2292
+ $temp = $a[MATH_BIGINTEGER_VALUE][0] + $x[$i] * $y[0];
2293
+ $temp = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * ((int) ($temp / MATH_BIGINTEGER_BASE_FULL)));
2294
+ $temp = $temp * $cache[MATH_BIGINTEGER_DATA][$key];
2295
+ $temp = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * ((int) ($temp / MATH_BIGINTEGER_BASE_FULL)));
2296
+ $temp = $this->_add($this->_regularMultiply(array($x[$i]), $y), false, $this->_regularMultiply(array($temp), $m), false);
2297
+ $a = $this->_add($a[MATH_BIGINTEGER_VALUE], false, $temp[MATH_BIGINTEGER_VALUE], false);
2298
+ $a[MATH_BIGINTEGER_VALUE] = array_slice($a[MATH_BIGINTEGER_VALUE], 1);
2299
+ }
2300
+ if ($this->_compare($a[MATH_BIGINTEGER_VALUE], false, $m, false) >= 0) {
2301
+ $a = $this->_subtract($a[MATH_BIGINTEGER_VALUE], false, $m, false);
2302
+ }
2303
+ return $a[MATH_BIGINTEGER_VALUE];
2304
+ }
2305
+
2306
+ /**
2307
+ * Prepare a number for use in Montgomery Modular Reductions
2308
+ *
2309
+ * @see _montgomery()
2310
+ * @see _slidingWindow()
2311
+ * @access private
2312
+ * @param Array $x
2313
+ * @param Array $n
2314
+ * @return Array
2315
+ */
2316
+ function _prepMontgomery($x, $n)
2317
+ {
2318
+ $lhs = new Math_BigInteger();
2319
+ $lhs->value = array_merge($this->_array_repeat(0, count($n)), $x);
2320
+ $rhs = new Math_BigInteger();
2321
+ $rhs->value = $n;
2322
+
2323
+ list(, $temp) = $lhs->divide($rhs);
2324
+ return $temp->value;
2325
+ }
2326
+
2327
+ /**
2328
+ * Modular Inverse of a number mod 2**26 (eg. 67108864)
2329
+ *
2330
+ * Based off of the bnpInvDigit function implemented and justified in the following URL:
2331
+ *
2332
+ * {@link http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js}
2333
+ *
2334
+ * The following URL provides more info:
2335
+ *
2336
+ * {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85}
2337
+ *
2338
+ * As for why we do all the bitmasking... strange things can happen when converting from floats to ints. For
2339
+ * instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields
2340
+ * int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarantee that ints aren't
2341
+ * auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that
2342
+ * the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the
2343
+ * maximum possible $x is 26 bits and the maximum $result is 16 bits. Thus, we have to be able to handle up to
2344
+ * 40 bits, which only 64-bit floating points will support.
2345
+ *
2346
+ * Thanks to Pedro Gimeno Fortea for input!
2347
+ *
2348
+ * @see _montgomery()
2349
+ * @access private
2350
+ * @param Array $x
2351
+ * @return Integer
2352
+ */
2353
+ function _modInverse67108864($x) // 2**26 == 67,108,864
2354
+ {
2355
+ $x = -$x[0];
2356
+ $result = $x & 0x3; // x**-1 mod 2**2
2357
+ $result = ($result * (2 - $x * $result)) & 0xF; // x**-1 mod 2**4
2358
+ $result = ($result * (2 - ($x & 0xFF) * $result)) & 0xFF; // x**-1 mod 2**8
2359
+ $result = ($result * ((2 - ($x & 0xFFFF) * $result) & 0xFFFF)) & 0xFFFF; // x**-1 mod 2**16
2360
+ $result = fmod($result * (2 - fmod($x * $result, MATH_BIGINTEGER_BASE_FULL)), MATH_BIGINTEGER_BASE_FULL); // x**-1 mod 2**26
2361
+ return $result & MATH_BIGINTEGER_MAX_DIGIT;
2362
+ }
2363
+
2364
+ /**
2365
+ * Calculates modular inverses.
2366
+ *
2367
+ * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses.
2368
+ *
2369
+ * Here's an example:
2370
+ * <code>
2371
+ * <?php
2372
+ * include('Math/BigInteger.php');
2373
+ *
2374
+ * $a = new Math_BigInteger(30);
2375
+ * $b = new Math_BigInteger(17);
2376
+ *
2377
+ * $c = $a->modInverse($b);
2378
+ * echo $c->toString(); // outputs 4
2379
+ *
2380
+ * echo "\r\n";
2381
+ *
2382
+ * $d = $a->multiply($c);
2383
+ * list(, $d) = $d->divide($b);
2384
+ * echo $d; // outputs 1 (as per the definition of modular inverse)
2385
+ * ?>
2386
+ * </code>
2387
+ *
2388
+ * @param Math_BigInteger $n
2389
+ * @return mixed false, if no modular inverse exists, Math_BigInteger, otherwise.
2390
+ * @access public
2391
+ * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information.
2392
+ */
2393
+ function modInverse($n)
2394
+ {
2395
+ switch ( MATH_BIGINTEGER_MODE ) {
2396
+ case MATH_BIGINTEGER_MODE_GMP:
2397
+ $temp = new Math_BigInteger();
2398
+ $temp->value = gmp_invert($this->value, $n->value);
2399
+
2400
+ return ( $temp->value === false ) ? false : $this->_normalize($temp);
2401
+ }
2402
+
2403
+ static $zero, $one;
2404
+ if (!isset($zero)) {
2405
+ $zero = new Math_BigInteger();
2406
+ $one = new Math_BigInteger(1);
2407
+ }
2408
+
2409
+ // $x mod -$n == $x mod $n.
2410
+ $n = $n->abs();
2411
+
2412
+ if ($this->compare($zero) < 0) {
2413
+ $temp = $this->abs();
2414
+ $temp = $temp->modInverse($n);
2415
+ return $this->_normalize($n->subtract($temp));
2416
+ }
2417
+
2418
+ extract($this->extendedGCD($n));
2419
+
2420
+ if (!$gcd->equals($one)) {
2421
+ return false;
2422
+ }
2423
+
2424
+ $x = $x->compare($zero) < 0 ? $x->add($n) : $x;
2425
+
2426
+ return $this->compare($zero) < 0 ? $this->_normalize($n->subtract($x)) : $this->_normalize($x);
2427
+ }
2428
+
2429
+ /**
2430
+ * Calculates the greatest common divisor and Bezout's identity.
2431
+ *
2432
+ * Say you have 693 and 609. The GCD is 21. Bezout's identity states that there exist integers x and y such that
2433
+ * 693*x + 609*y == 21. In point of fact, there are actually an infinite number of x and y combinations and which
2434
+ * combination is returned is dependant upon which mode is in use. See
2435
+ * {@link http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity Bezout's identity - Wikipedia} for more information.
2436
+ *
2437
+ * Here's an example:
2438
+ * <code>
2439
+ * <?php
2440
+ * include('Math/BigInteger.php');
2441
+ *
2442
+ * $a = new Math_BigInteger(693);
2443
+ * $b = new Math_BigInteger(609);
2444
+ *
2445
+ * extract($a->extendedGCD($b));
2446
+ *
2447
+ * echo $gcd->toString() . "\r\n"; // outputs 21
2448
+ * echo $a->toString() * $x->toString() + $b->toString() * $y->toString(); // outputs 21
2449
+ * ?>
2450
+ * </code>
2451
+ *
2452
+ * @param Math_BigInteger $n
2453
+ * @return Math_BigInteger
2454
+ * @access public
2455
+ * @internal Calculates the GCD using the binary xGCD algorithim described in
2456
+ * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=19 HAC 14.61}. As the text above 14.61 notes,
2457
+ * the more traditional algorithim requires "relatively costly multiple-precision divisions".
2458
+ */
2459
+ function extendedGCD($n)
2460
+ {
2461
+ switch ( MATH_BIGINTEGER_MODE ) {
2462
+ case MATH_BIGINTEGER_MODE_GMP:
2463
+ extract(gmp_gcdext($this->value, $n->value));
2464
+
2465
+ return array(
2466
+ 'gcd' => $this->_normalize(new Math_BigInteger($g)),
2467
+ 'x' => $this->_normalize(new Math_BigInteger($s)),
2468
+ 'y' => $this->_normalize(new Math_BigInteger($t))
2469
+ );
2470
+ case MATH_BIGINTEGER_MODE_BCMATH:
2471
+ // it might be faster to use the binary xGCD algorithim here, as well, but (1) that algorithim works
2472
+ // best when the base is a power of 2 and (2) i don't think it'd make much difference, anyway. as is,
2473
+ // the basic extended euclidean algorithim is what we're using.
2474
+
2475
+ $u = $this->value;
2476
+ $v = $n->value;
2477
+
2478
+ $a = '1';
2479
+ $b = '0';
2480
+ $c = '0';
2481
+ $d = '1';
2482
+
2483
+ while (bccomp($v, '0', 0) != 0) {
2484
+ $q = bcdiv($u, $v, 0);
2485
+
2486
+ $temp = $u;
2487
+ $u = $v;
2488
+ $v = bcsub($temp, bcmul($v, $q, 0), 0);
2489
+
2490
+ $temp = $a;
2491
+ $a = $c;
2492
+ $c = bcsub($temp, bcmul($a, $q, 0), 0);
2493
+
2494
+ $temp = $b;
2495
+ $b = $d;
2496
+ $d = bcsub($temp, bcmul($b, $q, 0), 0);
2497
+ }
2498
+
2499
+ return array(
2500
+ 'gcd' => $this->_normalize(new Math_BigInteger($u)),
2501
+ 'x' => $this->_normalize(new Math_BigInteger($a)),
2502
+ 'y' => $this->_normalize(new Math_BigInteger($b))
2503
+ );
2504
+ }
2505
+
2506
+ $y = $n->copy();
2507
+ $x = $this->copy();
2508
+ $g = new Math_BigInteger();
2509
+ $g->value = array(1);
2510
+
2511
+ while ( !(($x->value[0] & 1)|| ($y->value[0] & 1)) ) {
2512
+ $x->_rshift(1);
2513
+ $y->_rshift(1);
2514
+ $g->_lshift(1);
2515
+ }
2516
+
2517
+ $u = $x->copy();
2518
+ $v = $y->copy();
2519
+
2520
+ $a = new Math_BigInteger();
2521
+ $b = new Math_BigInteger();
2522
+ $c = new Math_BigInteger();
2523
+ $d = new Math_BigInteger();
2524
+
2525
+ $a->value = $d->value = $g->value = array(1);
2526
+ $b->value = $c->value = array();
2527
+
2528
+ while ( !empty($u->value) ) {
2529
+ while ( !($u->value[0] & 1) ) {
2530
+ $u->_rshift(1);
2531
+ if ( (!empty($a->value) && ($a->value[0] & 1)) || (!empty($b->value) && ($b->value[0] & 1)) ) {
2532
+ $a = $a->add($y);
2533
+ $b = $b->subtract($x);
2534
+ }
2535
+ $a->_rshift(1);
2536
+ $b->_rshift(1);
2537
+ }
2538
+
2539
+ while ( !($v->value[0] & 1) ) {
2540
+ $v->_rshift(1);
2541
+ if ( (!empty($d->value) && ($d->value[0] & 1)) || (!empty($c->value) && ($c->value[0] & 1)) ) {
2542
+ $c = $c->add($y);
2543
+ $d = $d->subtract($x);
2544
+ }
2545
+ $c->_rshift(1);
2546
+ $d->_rshift(1);
2547
+ }
2548
+
2549
+ if ($u->compare($v) >= 0) {
2550
+ $u = $u->subtract($v);
2551
+ $a = $a->subtract($c);
2552
+ $b = $b->subtract($d);
2553
+ } else {
2554
+ $v = $v->subtract($u);
2555
+ $c = $c->subtract($a);
2556
+ $d = $d->subtract($b);
2557
+ }
2558
+ }
2559
+
2560
+ return array(
2561
+ 'gcd' => $this->_normalize($g->multiply($v)),
2562
+ 'x' => $this->_normalize($c),
2563
+ 'y' => $this->_normalize($d)
2564
+ );
2565
+ }
2566
+
2567
+ /**
2568
+ * Calculates the greatest common divisor
2569
+ *
2570
+ * Say you have 693 and 609. The GCD is 21.
2571
+ *
2572
+ * Here's an example:
2573
+ * <code>
2574
+ * <?php
2575
+ * include('Math/BigInteger.php');
2576
+ *
2577
+ * $a = new Math_BigInteger(693);
2578
+ * $b = new Math_BigInteger(609);
2579
+ *
2580
+ * $gcd = a->extendedGCD($b);
2581
+ *
2582
+ * echo $gcd->toString() . "\r\n"; // outputs 21
2583
+ * ?>
2584
+ * </code>
2585
+ *
2586
+ * @param Math_BigInteger $n
2587
+ * @return Math_BigInteger
2588
+ * @access public
2589
+ */
2590
+ function gcd($n)
2591
+ {
2592
+ extract($this->extendedGCD($n));
2593
+ return $gcd;
2594
+ }
2595
+
2596
+ /**
2597
+ * Absolute value.
2598
+ *
2599
+ * @return Math_BigInteger
2600
+ * @access public
2601
+ */
2602
+ function abs()
2603
+ {
2604
+ $temp = new Math_BigInteger();
2605
+
2606
+ switch ( MATH_BIGINTEGER_MODE ) {
2607
+ case MATH_BIGINTEGER_MODE_GMP:
2608
+ $temp->value = gmp_abs($this->value);
2609
+ break;
2610
+ case MATH_BIGINTEGER_MODE_BCMATH:
2611
+ $temp->value = (bccomp($this->value, '0', 0) < 0) ? substr($this->value, 1) : $this->value;
2612
+ break;
2613
+ default:
2614
+ $temp->value = $this->value;
2615
+ }
2616
+
2617
+ return $temp;
2618
+ }
2619
+
2620
+ /**
2621
+ * Compares two numbers.
2622
+ *
2623
+ * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is
2624
+ * demonstrated thusly:
2625
+ *
2626
+ * $x > $y: $x->compare($y) > 0
2627
+ * $x < $y: $x->compare($y) < 0
2628
+ * $x == $y: $x->compare($y) == 0
2629
+ *
2630
+ * Note how the same comparison operator is used. If you want to test for equality, use $x->equals($y).
2631
+ *
2632
+ * @param Math_BigInteger $y
2633
+ * @return Integer < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal.
2634
+ * @access public
2635
+ * @see equals()
2636
+ * @internal Could return $this->subtract($x), but that's not as fast as what we do do.
2637
+ */
2638
+ function compare($y)
2639
+ {
2640
+ switch ( MATH_BIGINTEGER_MODE ) {
2641
+ case MATH_BIGINTEGER_MODE_GMP:
2642
+ return gmp_cmp($this->value, $y->value);
2643
+ case MATH_BIGINTEGER_MODE_BCMATH:
2644
+ return bccomp($this->value, $y->value, 0);
2645
+ }
2646
+
2647
+ return $this->_compare($this->value, $this->is_negative, $y->value, $y->is_negative);
2648
+ }
2649
+
2650
+ /**
2651
+ * Compares two numbers.
2652
+ *
2653
+ * @param Array $x_value
2654
+ * @param Boolean $x_negative
2655
+ * @param Array $y_value
2656
+ * @param Boolean $y_negative
2657
+ * @return Integer
2658
+ * @see compare()
2659
+ * @access private
2660
+ */
2661
+ function _compare($x_value, $x_negative, $y_value, $y_negative)
2662
+ {
2663
+ if ( $x_negative != $y_negative ) {
2664
+ return ( !$x_negative && $y_negative ) ? 1 : -1;
2665
+ }
2666
+
2667
+ $result = $x_negative ? -1 : 1;
2668
+
2669
+ if ( count($x_value) != count($y_value) ) {
2670
+ return ( count($x_value) > count($y_value) ) ? $result : -$result;
2671
+ }
2672
+ $size = max(count($x_value), count($y_value));
2673
+
2674
+ $x_value = array_pad($x_value, $size, 0);
2675
+ $y_value = array_pad($y_value, $size, 0);
2676
+
2677
+ for ($i = count($x_value) - 1; $i >= 0; --$i) {
2678
+ if ($x_value[$i] != $y_value[$i]) {
2679
+ return ( $x_value[$i] > $y_value[$i] ) ? $result : -$result;
2680
+ }
2681
+ }
2682
+
2683
+ return 0;
2684
+ }
2685
+
2686
+ /**
2687
+ * Tests the equality of two numbers.
2688
+ *
2689
+ * If you need to see if one number is greater than or less than another number, use Math_BigInteger::compare()
2690
+ *
2691
+ * @param Math_BigInteger $x
2692
+ * @return Boolean
2693
+ * @access public
2694
+ * @see compare()
2695
+ */
2696
+ function equals($x)
2697
+ {
2698
+ switch ( MATH_BIGINTEGER_MODE ) {
2699
+ case MATH_BIGINTEGER_MODE_GMP:
2700
+ return gmp_cmp($this->value, $x->value) == 0;
2701
+ default:
2702
+ return $this->value === $x->value && $this->is_negative == $x->is_negative;
2703
+ }
2704
+ }
2705
+
2706
+ /**
2707
+ * Set Precision
2708
+ *
2709
+ * Some bitwise operations give different results depending on the precision being used. Examples include left
2710
+ * shift, not, and rotates.
2711
+ *
2712
+ * @param Integer $bits
2713
+ * @access public
2714
+ */
2715
+ function setPrecision($bits)
2716
+ {
2717
+ $this->precision = $bits;
2718
+ if ( MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_BCMATH ) {
2719
+ $this->bitmask = new Math_BigInteger(chr((1 << ($bits & 0x7)) - 1) . str_repeat(chr(0xFF), $bits >> 3), 256);
2720
+ } else {
2721
+ $this->bitmask = new Math_BigInteger(bcpow('2', $bits, 0));
2722
+ }
2723
+
2724
+ $temp = $this->_normalize($this);
2725
+ $this->value = $temp->value;
2726
+ }
2727
+
2728
+ /**
2729
+ * Logical And
2730
+ *
2731
+ * @param Math_BigInteger $x
2732
+ * @access public
2733
+ * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
2734
+ * @return Math_BigInteger
2735
+ */
2736
+ function bitwise_and($x)
2737
+ {
2738
+ switch ( MATH_BIGINTEGER_MODE ) {
2739
+ case MATH_BIGINTEGER_MODE_GMP:
2740
+ $temp = new Math_BigInteger();
2741
+ $temp->value = gmp_and($this->value, $x->value);
2742
+
2743
+ return $this->_normalize($temp);
2744
+ case MATH_BIGINTEGER_MODE_BCMATH:
2745
+ $left = $this->toBytes();
2746
+ $right = $x->toBytes();
2747
+
2748
+ $length = max(strlen($left), strlen($right));
2749
+
2750
+ $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
2751
+ $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
2752
+
2753
+ return $this->_normalize(new Math_BigInteger($left & $right, 256));
2754
+ }
2755
+
2756
+ $result = $this->copy();
2757
+
2758
+ $length = min(count($x->value), count($this->value));
2759
+
2760
+ $result->value = array_slice($result->value, 0, $length);
2761
+
2762
+ for ($i = 0; $i < $length; ++$i) {
2763
+ $result->value[$i]&= $x->value[$i];
2764
+ }
2765
+
2766
+ return $this->_normalize($result);
2767
+ }
2768
+
2769
+ /**
2770
+ * Logical Or
2771
+ *
2772
+ * @param Math_BigInteger $x
2773
+ * @access public
2774
+ * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
2775
+ * @return Math_BigInteger
2776
+ */
2777
+ function bitwise_or($x)
2778
+ {
2779
+ switch ( MATH_BIGINTEGER_MODE ) {
2780
+ case MATH_BIGINTEGER_MODE_GMP:
2781
+ $temp = new Math_BigInteger();
2782
+ $temp->value = gmp_or($this->value, $x->value);
2783
+
2784
+ return $this->_normalize($temp);
2785
+ case MATH_BIGINTEGER_MODE_BCMATH:
2786
+ $left = $this->toBytes();
2787
+ $right = $x->toBytes();
2788
+
2789
+ $length = max(strlen($left), strlen($right));
2790
+
2791
+ $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
2792
+ $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
2793
+
2794
+ return $this->_normalize(new Math_BigInteger($left | $right, 256));
2795
+ }
2796
+
2797
+ $length = max(count($this->value), count($x->value));
2798
+ $result = $this->copy();
2799
+ $result->value = array_pad($result->value, $length, 0);
2800
+ $x->value = array_pad($x->value, $length, 0);
2801
+
2802
+ for ($i = 0; $i < $length; ++$i) {
2803
+ $result->value[$i]|= $x->value[$i];
2804
+ }
2805
+
2806
+ return $this->_normalize($result);
2807
+ }
2808
+
2809
+ /**
2810
+ * Logical Exclusive-Or
2811
+ *
2812
+ * @param Math_BigInteger $x
2813
+ * @access public
2814
+ * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
2815
+ * @return Math_BigInteger
2816
+ */
2817
+ function bitwise_xor($x)
2818
+ {
2819
+ switch ( MATH_BIGINTEGER_MODE ) {
2820
+ case MATH_BIGINTEGER_MODE_GMP:
2821
+ $temp = new Math_BigInteger();
2822
+ $temp->value = gmp_xor($this->value, $x->value);
2823
+
2824
+ return $this->_normalize($temp);
2825
+ case MATH_BIGINTEGER_MODE_BCMATH:
2826
+ $left = $this->toBytes();
2827
+ $right = $x->toBytes();
2828
+
2829
+ $length = max(strlen($left), strlen($right));
2830
+
2831
+ $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
2832
+ $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
2833
+
2834
+ return $this->_normalize(new Math_BigInteger($left ^ $right, 256));
2835
+ }
2836
+
2837
+ $length = max(count($this->value), count($x->value));
2838
+ $result = $this->copy();
2839
+ $result->value = array_pad($result->value, $length, 0);
2840
+ $x->value = array_pad($x->value, $length, 0);
2841
+
2842
+ for ($i = 0; $i < $length; ++$i) {
2843
+ $result->value[$i]^= $x->value[$i];
2844
+ }
2845
+
2846
+ return $this->_normalize($result);
2847
+ }
2848
+
2849
+ /**
2850
+ * Logical Not
2851
+ *
2852
+ * @access public
2853
+ * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
2854
+ * @return Math_BigInteger
2855
+ */
2856
+ function bitwise_not()
2857
+ {
2858
+ // calculuate "not" without regard to $this->precision
2859
+ // (will always result in a smaller number. ie. ~1 isn't 1111 1110 - it's 0)
2860
+ $temp = $this->toBytes();
2861
+ $pre_msb = decbin(ord($temp[0]));
2862
+ $temp = ~$temp;
2863
+ $msb = decbin(ord($temp[0]));
2864
+ if (strlen($msb) == 8) {
2865
+ $msb = substr($msb, strpos($msb, '0'));
2866
+ }
2867
+ $temp[0] = chr(bindec($msb));
2868
+
2869
+ // see if we need to add extra leading 1's
2870
+ $current_bits = strlen($pre_msb) + 8 * strlen($temp) - 8;
2871
+ $new_bits = $this->precision - $current_bits;
2872
+ if ($new_bits <= 0) {
2873
+ return $this->_normalize(new Math_BigInteger($temp, 256));
2874
+ }
2875
+
2876
+ // generate as many leading 1's as we need to.
2877
+ $leading_ones = chr((1 << ($new_bits & 0x7)) - 1) . str_repeat(chr(0xFF), $new_bits >> 3);
2878
+ $this->_base256_lshift($leading_ones, $current_bits);
2879
+
2880
+ $temp = str_pad($temp, ceil($this->bits / 8), chr(0), STR_PAD_LEFT);
2881
+
2882
+ return $this->_normalize(new Math_BigInteger($leading_ones | $temp, 256));
2883
+ }
2884
+
2885
+ /**
2886
+ * Logical Right Shift
2887
+ *
2888
+ * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift.
2889
+ *
2890
+ * @param Integer $shift
2891
+ * @return Math_BigInteger
2892
+ * @access public
2893
+ * @internal The only version that yields any speed increases is the internal version.
2894
+ */
2895
+ function bitwise_rightShift($shift)
2896
+ {
2897
+ $temp = new Math_BigInteger();
2898
+
2899
+ switch ( MATH_BIGINTEGER_MODE ) {
2900
+ case MATH_BIGINTEGER_MODE_GMP:
2901
+ static $two;
2902
+
2903
+ if (!isset($two)) {
2904
+ $two = gmp_init('2');
2905
+ }
2906
+
2907
+ $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift));
2908
+
2909
+ break;
2910
+ case MATH_BIGINTEGER_MODE_BCMATH:
2911
+ $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0);
2912
+
2913
+ break;
2914
+ default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten
2915
+ // and I don't want to do that...
2916
+ $temp->value = $this->value;
2917
+ $temp->_rshift($shift);
2918
+ }
2919
+
2920
+ return $this->_normalize($temp);
2921
+ }
2922
+
2923
+ /**
2924
+ * Logical Left Shift
2925
+ *
2926
+ * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift.
2927
+ *
2928
+ * @param Integer $shift
2929
+ * @return Math_BigInteger
2930
+ * @access public
2931
+ * @internal The only version that yields any speed increases is the internal version.
2932
+ */
2933
+ function bitwise_leftShift($shift)
2934
+ {
2935
+ $temp = new Math_BigInteger();
2936
+
2937
+ switch ( MATH_BIGINTEGER_MODE ) {
2938
+ case MATH_BIGINTEGER_MODE_GMP:
2939
+ static $two;
2940
+
2941
+ if (!isset($two)) {
2942
+ $two = gmp_init('2');
2943
+ }
2944
+
2945
+ $temp->value = gmp_mul($this->value, gmp_pow($two, $shift));
2946
+
2947
+ break;
2948
+ case MATH_BIGINTEGER_MODE_BCMATH:
2949
+ $temp->value = bcmul($this->value, bcpow('2', $shift, 0), 0);
2950
+
2951
+ break;
2952
+ default: // could just replace _rshift with this, but then all _lshift() calls would need to be rewritten
2953
+ // and I don't want to do that...
2954
+ $temp->value = $this->value;
2955
+ $temp->_lshift($shift);
2956
+ }
2957
+
2958
+ return $this->_normalize($temp);
2959
+ }
2960
+
2961
+ /**
2962
+ * Logical Left Rotate
2963
+ *
2964
+ * Instead of the top x bits being dropped they're appended to the shifted bit string.
2965
+ *
2966
+ * @param Integer $shift
2967
+ * @return Math_BigInteger
2968
+ * @access public
2969
+ */
2970
+ function bitwise_leftRotate($shift)
2971
+ {
2972
+ $bits = $this->toBytes();
2973
+
2974
+ if ($this->precision > 0) {
2975
+ $precision = $this->precision;
2976
+ if ( MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH ) {
2977
+ $mask = $this->bitmask->subtract(new Math_BigInteger(1));
2978
+ $mask = $mask->toBytes();
2979
+ } else {
2980
+ $mask = $this->bitmask->toBytes();
2981
+ }
2982
+ } else {
2983
+ $temp = ord($bits[0]);
2984
+ for ($i = 0; $temp >> $i; ++$i);
2985
+ $precision = 8 * strlen($bits) - 8 + $i;
2986
+ $mask = chr((1 << ($precision & 0x7)) - 1) . str_repeat(chr(0xFF), $precision >> 3);
2987
+ }
2988
+
2989
+ if ($shift < 0) {
2990
+ $shift+= $precision;
2991
+ }
2992
+ $shift%= $precision;
2993
+
2994
+ if (!$shift) {
2995
+ return $this->copy();
2996
+ }
2997
+
2998
+ $left = $this->bitwise_leftShift($shift);
2999
+ $left = $left->bitwise_and(new Math_BigInteger($mask, 256));
3000
+ $right = $this->bitwise_rightShift($precision - $shift);
3001
+ $result = MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_BCMATH ? $left->bitwise_or($right) : $left->add($right);
3002
+ return $this->_normalize($result);
3003
+ }
3004
+
3005
+ /**
3006
+ * Logical Right Rotate
3007
+ *
3008
+ * Instead of the bottom x bits being dropped they're prepended to the shifted bit string.
3009
+ *
3010
+ * @param Integer $shift
3011
+ * @return Math_BigInteger
3012
+ * @access public
3013
+ */
3014
+ function bitwise_rightRotate($shift)
3015
+ {
3016
+ return $this->bitwise_leftRotate(-$shift);
3017
+ }
3018
+
3019
+ /**
3020
+ * Set random number generator function
3021
+ *
3022
+ * This function is deprecated.
3023
+ *
3024
+ * @param String $generator
3025
+ * @access public
3026
+ */
3027
+ function setRandomGenerator($generator)
3028
+ {
3029
+ }
3030
+
3031
+ /**
3032
+ * Generate a random number
3033
+ *
3034
+ * @param optional Integer $min
3035
+ * @param optional Integer $max
3036
+ * @return Math_BigInteger
3037
+ * @access public
3038
+ */
3039
+ function random($min = false, $max = false)
3040
+ {
3041
+ if ($min === false) {
3042
+ $min = new Math_BigInteger(0);
3043
+ }
3044
+
3045
+ if ($max === false) {
3046
+ $max = new Math_BigInteger(0x7FFFFFFF);
3047
+ }
3048
+
3049
+ $compare = $max->compare($min);
3050
+
3051
+ if (!$compare) {
3052
+ return $this->_normalize($min);
3053
+ } else if ($compare < 0) {
3054
+ // if $min is bigger then $max, swap $min and $max
3055
+ $temp = $max;
3056
+ $max = $min;
3057
+ $min = $temp;
3058
+ }
3059
+
3060
+ $max = $max->subtract($min);
3061
+ $max = ltrim($max->toBytes(), chr(0));
3062
+ $size = strlen($max) - 1;
3063
+
3064
+ $crypt_random = function_exists('crypt_random_string') || (!class_exists('Crypt_Random') && function_exists('crypt_random_string'));
3065
+ if ($crypt_random) {
3066
+ $random = crypt_random_string($size);
3067
+ } else {
3068
+ $random = '';
3069
+
3070
+ if ($size & 1) {
3071
+ $random.= chr(mt_rand(0, 255));
3072
+ }
3073
+
3074
+ $blocks = $size >> 1;
3075
+ for ($i = 0; $i < $blocks; ++$i) {
3076
+ // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems
3077
+ $random.= pack('n', mt_rand(0, 0xFFFF));
3078
+ }
3079
+ }
3080
+
3081
+ $fragment = new Math_BigInteger($random, 256);
3082
+ $leading = $fragment->compare(new Math_BigInteger(substr($max, 1), 256)) > 0 ?
3083
+ ord($max[0]) - 1 : ord($max[0]);
3084
+
3085
+ if (!$crypt_random) {
3086
+ $msb = chr(mt_rand(0, $leading));
3087
+ } else {
3088
+ $cutoff = floor(0xFF / $leading) * $leading;
3089
+ while (true) {
3090
+ $msb = ord(crypt_random_string(1));
3091
+ if ($msb <= $cutoff) {
3092
+ $msb%= $leading;
3093
+ break;
3094
+ }
3095
+ }
3096
+ $msb = chr($msb);
3097
+ }
3098
+
3099
+ $random = new Math_BigInteger($msb . $random, 256);
3100
+
3101
+ return $this->_normalize($random->add($min));
3102
+ }
3103
+
3104
+ /**
3105
+ * Generate a random prime number.
3106
+ *
3107
+ * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed,
3108
+ * give up and return false.
3109
+ *
3110
+ * @param optional Integer $min
3111
+ * @param optional Integer $max
3112
+ * @param optional Integer $timeout
3113
+ * @return Math_BigInteger
3114
+ * @access public
3115
+ * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}.
3116
+ */
3117
+ function randomPrime($min = false, $max = false, $timeout = false)
3118
+ {
3119
+ if ($min === false) {
3120
+ $min = new Math_BigInteger(0);
3121
+ }
3122
+
3123
+ if ($max === false) {
3124
+ $max = new Math_BigInteger(0x7FFFFFFF);
3125
+ }
3126
+
3127
+ $compare = $max->compare($min);
3128
+
3129
+ if (!$compare) {
3130
+ return $min->isPrime() ? $min : false;
3131
+ } else if ($compare < 0) {
3132
+ // if $min is bigger then $max, swap $min and $max
3133
+ $temp = $max;
3134
+ $max = $min;
3135
+ $min = $temp;
3136
+ }
3137
+
3138
+ static $one, $two;
3139
+ if (!isset($one)) {
3140
+ $one = new Math_BigInteger(1);
3141
+ $two = new Math_BigInteger(2);
3142
+ }
3143
+
3144
+ $start = time();
3145
+
3146
+ $x = $this->random($min, $max);
3147
+
3148
+ // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>.
3149
+ if ( MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && function_exists('gmp_nextprime') ) {
3150
+ $p = new Math_BigInteger();
3151
+ $p->value = gmp_nextprime($x->value);
3152
+
3153
+ if ($p->compare($max) <= 0) {
3154
+ return $p;
3155
+ }
3156
+
3157
+ if (!$min->equals($x)) {
3158
+ $x = $x->subtract($one);
3159
+ }
3160
+
3161
+ return $x->randomPrime($min, $x);
3162
+ }
3163
+
3164
+ if ($x->equals($two)) {
3165
+ return $x;
3166
+ }
3167
+
3168
+ $x->_make_odd();
3169
+ if ($x->compare($max) > 0) {
3170
+ // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range
3171
+ if ($min->equals($max)) {
3172
+ return false;
3173
+ }
3174
+ $x = $min->copy();
3175
+ $x->_make_odd();
3176
+ }
3177
+
3178
+ $initial_x = $x->copy();
3179
+
3180
+ while (true) {
3181
+ if ($timeout !== false && time() - $start > $timeout) {
3182
+ return false;
3183
+ }
3184
+
3185
+ if ($x->isPrime()) {
3186
+ return $x;
3187
+ }
3188
+
3189
+ $x = $x->add($two);
3190
+
3191
+ if ($x->compare($max) > 0) {
3192
+ $x = $min->copy();
3193
+ if ($x->equals($two)) {
3194
+ return $x;
3195
+ }
3196
+ $x->_make_odd();
3197
+ }
3198
+
3199
+ if ($x->equals($initial_x)) {
3200
+ return false;
3201
+ }
3202
+ }
3203
+ }
3204
+
3205
+ /**
3206
+ * Make the current number odd
3207
+ *
3208
+ * If the current number is odd it'll be unchanged. If it's even, one will be added to it.
3209
+ *
3210
+ * @see randomPrime()
3211
+ * @access private
3212
+ */
3213
+ function _make_odd()
3214
+ {
3215
+ switch ( MATH_BIGINTEGER_MODE ) {
3216
+ case MATH_BIGINTEGER_MODE_GMP:
3217
+ gmp_setbit($this->value, 0);
3218
+ break;
3219
+ case MATH_BIGINTEGER_MODE_BCMATH:
3220
+ if ($this->value[strlen($this->value) - 1] % 2 == 0) {
3221
+ $this->value = bcadd($this->value, '1');
3222
+ }
3223
+ break;
3224
+ default:
3225
+ $this->value[0] |= 1;
3226
+ }
3227
+ }
3228
+
3229
+ /**
3230
+ * Checks a numer to see if it's prime
3231
+ *
3232
+ * Assuming the $t parameter is not set, this function has an error rate of 2**-80. The main motivation for the
3233
+ * $t parameter is distributability. Math_BigInteger::randomPrime() can be distributed accross multiple pageloads
3234
+ * on a website instead of just one.
3235
+ *
3236
+ * @param optional Integer $t
3237
+ * @return Boolean
3238
+ * @access public
3239
+ * @internal Uses the
3240
+ * {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See
3241
+ * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=8 HAC 4.24}.
3242
+ */
3243
+ function isPrime($t = false)
3244
+ {
3245
+ $length = strlen($this->toBytes());
3246
+
3247
+ if (!$t) {
3248
+ // see HAC 4.49 "Note (controlling the error probability)"
3249
+ if ($length >= 163) { $t = 2; } // floor(1300 / 8)
3250
+ else if ($length >= 106) { $t = 3; } // floor( 850 / 8)
3251
+ else if ($length >= 81 ) { $t = 4; } // floor( 650 / 8)
3252
+ else if ($length >= 68 ) { $t = 5; } // floor( 550 / 8)
3253
+ else if ($length >= 56 ) { $t = 6; } // floor( 450 / 8)
3254
+ else if ($length >= 50 ) { $t = 7; } // floor( 400 / 8)
3255
+ else if ($length >= 43 ) { $t = 8; } // floor( 350 / 8)
3256
+ else if ($length >= 37 ) { $t = 9; } // floor( 300 / 8)
3257
+ else if ($length >= 31 ) { $t = 12; } // floor( 250 / 8)
3258
+ else if ($length >= 25 ) { $t = 15; } // floor( 200 / 8)
3259
+ else if ($length >= 18 ) { $t = 18; } // floor( 150 / 8)
3260
+ else { $t = 27; }
3261
+ }
3262
+
3263
+ // ie. gmp_testbit($this, 0)
3264
+ // ie. isEven() or !isOdd()
3265
+ switch ( MATH_BIGINTEGER_MODE ) {
3266
+ case MATH_BIGINTEGER_MODE_GMP:
3267
+ return gmp_prob_prime($this->value, $t) != 0;
3268
+ case MATH_BIGINTEGER_MODE_BCMATH:
3269
+ if ($this->value === '2') {
3270
+ return true;
3271
+ }
3272
+ if ($this->value[strlen($this->value) - 1] % 2 == 0) {
3273
+ return false;
3274
+ }
3275
+ break;
3276
+ default:
3277
+ if ($this->value == array(2)) {
3278
+ return true;
3279
+ }
3280
+ if (~$this->value[0] & 1) {
3281
+ return false;
3282
+ }
3283
+ }
3284
+
3285
+ static $primes, $zero, $one, $two;
3286
+
3287
+ if (!isset($primes)) {
3288
+ $primes = array(
3289
+ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
3290
+ 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
3291
+ 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
3292
+ 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
3293
+ 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
3294
+ 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
3295
+ 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617,
3296
+ 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
3297
+ 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,
3298
+ 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
3299
+ 953, 967, 971, 977, 983, 991, 997
3300
+ );
3301
+
3302
+ if ( MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL ) {
3303
+ for ($i = 0; $i < count($primes); ++$i) {
3304
+ $primes[$i] = new Math_BigInteger($primes[$i]);
3305
+ }
3306
+ }
3307
+
3308
+ $zero = new Math_BigInteger();
3309
+ $one = new Math_BigInteger(1);
3310
+ $two = new Math_BigInteger(2);
3311
+ }
3312
+
3313
+ if ($this->equals($one)) {
3314
+ return false;
3315
+ }
3316
+
3317
+ // see HAC 4.4.1 "Random search for probable primes"
3318
+ if ( MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL ) {
3319
+ foreach ($primes as $prime) {
3320
+ list(, $r) = $this->divide($prime);
3321
+ if ($r->equals($zero)) {
3322
+ return $this->equals($prime);
3323
+ }
3324
+ }
3325
+ } else {
3326
+ $value = $this->value;
3327
+ foreach ($primes as $prime) {
3328
+ list(, $r) = $this->_divide_digit($value, $prime);
3329
+ if (!$r) {
3330
+ return count($value) == 1 && $value[0] == $prime;
3331
+ }
3332
+ }
3333
+ }
3334
+
3335
+ $n = $this->copy();
3336
+ $n_1 = $n->subtract($one);
3337
+ $n_2 = $n->subtract($two);
3338
+
3339
+ $r = $n_1->copy();
3340
+ $r_value = $r->value;
3341
+ // ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s));
3342
+ if ( MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH ) {
3343
+ $s = 0;
3344
+ // if $n was 1, $r would be 0 and this would be an infinite loop, hence our $this->equals($one) check earlier
3345
+ while ($r->value[strlen($r->value) - 1] % 2 == 0) {
3346
+ $r->value = bcdiv($r->value, '2', 0);
3347
+ ++$s;
3348
+ }
3349
+ } else {
3350
+ for ($i = 0, $r_length = count($r_value); $i < $r_length; ++$i) {
3351
+ $temp = ~$r_value[$i] & 0xFFFFFF;
3352
+ for ($j = 1; ($temp >> $j) & 1; ++$j);
3353
+ if ($j != 25) {
3354
+ break;
3355
+ }
3356
+ }
3357
+ $s = 26 * $i + $j - 1;
3358
+ $r->_rshift($s);
3359
+ }
3360
+
3361
+ for ($i = 0; $i < $t; ++$i) {
3362
+ $a = $this->random($two, $n_2);
3363
+ $y = $a->modPow($r, $n);
3364
+
3365
+ if (!$y->equals($one) && !$y->equals($n_1)) {
3366
+ for ($j = 1; $j < $s && !$y->equals($n_1); ++$j) {
3367
+ $y = $y->modPow($two, $n);
3368
+ if ($y->equals($one)) {
3369
+ return false;
3370
+ }
3371
+ }
3372
+
3373
+ if (!$y->equals($n_1)) {
3374
+ return false;
3375
+ }
3376
+ }
3377
+ }
3378
+ return true;
3379
+ }
3380
+
3381
+ /**
3382
+ * Logical Left Shift
3383
+ *
3384
+ * Shifts BigInteger's by $shift bits.
3385
+ *
3386
+ * @param Integer $shift
3387
+ * @access private
3388
+ */
3389
+ function _lshift($shift)
3390
+ {
3391
+ if ( $shift == 0 ) {
3392
+ return;
3393
+ }
3394
+
3395
+ $num_digits = (int) ($shift / MATH_BIGINTEGER_BASE);
3396
+ $shift %= MATH_BIGINTEGER_BASE;
3397
+ $shift = 1 << $shift;
3398
+
3399
+ $carry = 0;
3400
+
3401
+ for ($i = 0; $i < count($this->value); ++$i) {
3402
+ $temp = $this->value[$i] * $shift + $carry;
3403
+ $carry = (int) ($temp / MATH_BIGINTEGER_BASE_FULL);
3404
+ $this->value[$i] = (int) ($temp - $carry * MATH_BIGINTEGER_BASE_FULL);
3405
+ }
3406
+
3407
+ if ( $carry ) {
3408
+ $this->value[] = $carry;
3409
+ }
3410
+
3411
+ while ($num_digits--) {
3412
+ array_unshift($this->value, 0);
3413
+ }
3414
+ }
3415
+
3416
+ /**
3417
+ * Logical Right Shift
3418
+ *
3419
+ * Shifts BigInteger's by $shift bits.
3420
+ *
3421
+ * @param Integer $shift
3422
+ * @access private
3423
+ */
3424
+ function _rshift($shift)
3425
+ {
3426
+ if ($shift == 0) {
3427
+ return;
3428
+ }
3429
+
3430
+ $num_digits = (int) ($shift / MATH_BIGINTEGER_BASE);
3431
+ $shift %= MATH_BIGINTEGER_BASE;
3432
+ $carry_shift = MATH_BIGINTEGER_BASE - $shift;
3433
+ $carry_mask = (1 << $shift) - 1;
3434
+
3435
+ if ( $num_digits ) {
3436
+ $this->value = array_slice($this->value, $num_digits);
3437
+ }
3438
+
3439
+ $carry = 0;
3440
+
3441
+ for ($i = count($this->value) - 1; $i >= 0; --$i) {
3442
+ $temp = $this->value[$i] >> $shift | $carry;
3443
+ $carry = ($this->value[$i] & $carry_mask) << $carry_shift;
3444
+ $this->value[$i] = $temp;
3445
+ }
3446
+
3447
+ $this->value = $this->_trim($this->value);
3448
+ }
3449
+
3450
+ /**
3451
+ * Normalize
3452
+ *
3453
+ * Removes leading zeros and truncates (if necessary) to maintain the appropriate precision
3454
+ *
3455
+ * @param Math_BigInteger
3456
+ * @return Math_BigInteger
3457
+ * @see _trim()
3458
+ * @access private
3459
+ */
3460
+ function _normalize($result)
3461
+ {
3462
+ $result->precision = $this->precision;
3463
+ $result->bitmask = $this->bitmask;
3464
+
3465
+ switch ( MATH_BIGINTEGER_MODE ) {
3466
+ case MATH_BIGINTEGER_MODE_GMP:
3467
+ if (!empty($result->bitmask->value)) {
3468
+ $result->value = gmp_and($result->value, $result->bitmask->value);
3469
+ }
3470
+
3471
+ return $result;
3472
+ case MATH_BIGINTEGER_MODE_BCMATH:
3473
+ if (!empty($result->bitmask->value)) {
3474
+ $result->value = bcmod($result->value, $result->bitmask->value);
3475
+ }
3476
+
3477
+ return $result;
3478
+ }
3479
+
3480
+ $value = &$result->value;
3481
+
3482
+ if ( !count($value) ) {
3483
+ return $result;
3484
+ }
3485
+
3486
+ $value = $this->_trim($value);
3487
+
3488
+ if (!empty($result->bitmask->value)) {
3489
+ $length = min(count($value), count($this->bitmask->value));
3490
+ $value = array_slice($value, 0, $length);
3491
+
3492
+ for ($i = 0; $i < $length; ++$i) {
3493
+ $value[$i] = $value[$i] & $this->bitmask->value[$i];
3494
+ }
3495
+ }
3496
+
3497
+ return $result;
3498
+ }
3499
+
3500
+ /**
3501
+ * Trim
3502
+ *
3503
+ * Removes leading zeros
3504
+ *
3505
+ * @param Array $value
3506
+ * @return Math_BigInteger
3507
+ * @access private
3508
+ */
3509
+ function _trim($value)
3510
+ {
3511
+ for ($i = count($value) - 1; $i >= 0; --$i) {
3512
+ if ( $value[$i] ) {
3513
+ break;
3514
+ }
3515
+ unset($value[$i]);
3516
+ }
3517
+
3518
+ return $value;
3519
+ }
3520
+
3521
+ /**
3522
+ * Array Repeat
3523
+ *
3524
+ * @param $input Array
3525
+ * @param $multiplier mixed
3526
+ * @return Array
3527
+ * @access private
3528
+ */
3529
+ function _array_repeat($input, $multiplier)
3530
+ {
3531
+ return ($multiplier) ? array_fill(0, $multiplier, $input) : array();
3532
+ }
3533
+
3534
+ /**
3535
+ * Logical Left Shift
3536
+ *
3537
+ * Shifts binary strings $shift bits, essentially multiplying by 2**$shift.
3538
+ *
3539
+ * @param $x String
3540
+ * @param $shift Integer
3541
+ * @return String
3542
+ * @access private
3543
+ */
3544
+ function _base256_lshift(&$x, $shift)
3545
+ {
3546
+ if ($shift == 0) {
3547
+ return;
3548
+ }
3549
+
3550
+ $num_bytes = $shift >> 3; // eg. floor($shift/8)
3551
+ $shift &= 7; // eg. $shift % 8
3552
+
3553
+ $carry = 0;
3554
+ for ($i = strlen($x) - 1; $i >= 0; --$i) {
3555
+ $temp = ord($x[$i]) << $shift | $carry;
3556
+ $x[$i] = chr($temp);
3557
+ $carry = $temp >> 8;
3558
+ }
3559
+ $carry = ($carry != 0) ? chr($carry) : '';
3560
+ $x = $carry . $x . str_repeat(chr(0), $num_bytes);
3561
+ }
3562
+
3563
+ /**
3564
+ * Logical Right Shift
3565
+ *
3566
+ * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder.
3567
+ *
3568
+ * @param $x String
3569
+ * @param $shift Integer
3570
+ * @return String
3571
+ * @access private
3572
+ */
3573
+ function _base256_rshift(&$x, $shift)
3574
+ {
3575
+ if ($shift == 0) {
3576
+ $x = ltrim($x, chr(0));
3577
+ return '';
3578
+ }
3579
+
3580
+ $num_bytes = $shift >> 3; // eg. floor($shift/8)
3581
+ $shift &= 7; // eg. $shift % 8
3582
+
3583
+ $remainder = '';
3584
+ if ($num_bytes) {
3585
+ $start = $num_bytes > strlen($x) ? -strlen($x) : -$num_bytes;
3586
+ $remainder = substr($x, $start);
3587
+ $x = substr($x, 0, -$num_bytes);
3588
+ }
3589
+
3590
+ $carry = 0;
3591
+ $carry_shift = 8 - $shift;
3592
+ for ($i = 0; $i < strlen($x); ++$i) {
3593
+ $temp = (ord($x[$i]) >> $shift) | $carry;
3594
+ $carry = (ord($x[$i]) << $carry_shift) & 0xFF;
3595
+ $x[$i] = chr($temp);
3596
+ }
3597
+ $x = ltrim($x, chr(0));
3598
+
3599
+ $remainder = chr($carry >> $carry_shift) . $remainder;
3600
+
3601
+ return ltrim($remainder, chr(0));
3602
+ }
3603
+
3604
+ // one quirk about how the following functions are implemented is that PHP defines N to be an unsigned long
3605
+ // at 32-bits, while java's longs are 64-bits.
3606
+
3607
+ /**
3608
+ * Converts 32-bit integers to bytes.
3609
+ *
3610
+ * @param Integer $x
3611
+ * @return String
3612
+ * @access private
3613
+ */
3614
+ function _int2bytes($x)
3615
+ {
3616
+ return ltrim(pack('N', $x), chr(0));
3617
+ }
3618
+
3619
+ /**
3620
+ * Converts bytes to 32-bit integers
3621
+ *
3622
+ * @param String $x
3623
+ * @return Integer
3624
+ * @access private
3625
+ */
3626
+ function _bytes2int($x)
3627
+ {
3628
+ $temp = unpack('Nint', str_pad($x, 4, chr(0), STR_PAD_LEFT));
3629
+ return $temp['int'];
3630
+ }
3631
+
3632
+ /**
3633
+ * DER-encode an integer
3634
+ *
3635
+ * The ability to DER-encode integers is needed to create RSA public keys for use with OpenSSL
3636
+ *
3637
+ * @see modPow()
3638
+ * @access private
3639
+ * @param Integer $length
3640
+ * @return String
3641
+ */
3642
+ function _encodeASN1Length($length)
3643
+ {
3644
+ if ($length <= 0x7F) {
3645
+ return chr($length);
3646
+ }
3647
+
3648
+ $temp = ltrim(pack('N', $length), chr(0));
3649
+ return pack('Ca*', 0x80 | strlen($temp), $temp);
3650
+ }
3651
+ }
lib/LivrariOnline/Blowfish.php ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of Blowfish.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Useful resources are as follows:
11
+ *
12
+ * - {@link http://en.wikipedia.org/wiki/Blowfish_(cipher) Wikipedia description of Blowfish}
13
+ *
14
+ * Here's a short example of how to use this library:
15
+ * <code>
16
+ * <?php
17
+ * include('Crypt/Blowfish.php');
18
+ *
19
+ * $blowfish = new Crypt_Blowfish();
20
+ *
21
+ * $blowfish->setKey('12345678901234567890123456789012');
22
+ *
23
+ * $plaintext = str_repeat('a', 1024);
24
+ *
25
+ * echo $blowfish->decrypt($blowfish->encrypt($plaintext));
26
+ * ?>
27
+ * </code>
28
+ *
29
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ * of this software and associated documentation files (the "Software"), to deal
31
+ * in the Software without restriction, including without limitation the rights
32
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ * copies of the Software, and to permit persons to whom the Software is
34
+ * furnished to do so, subject to the following conditions:
35
+ *
36
+ * The above copyright notice and this permission notice shall be included in
37
+ * all copies or substantial portions of the Software.
38
+ *
39
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ * THE SOFTWARE.
46
+ *
47
+ * @category Crypt
48
+ * @package Crypt_Blowfish
49
+ * @author Jim Wigginton <terrafrost@php.net>
50
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
51
+ * @copyright MMVII Jim Wigginton
52
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
53
+ * @version 1.0
54
+ * @link http://phpseclib.sourceforge.net
55
+ */
56
+
57
+ /**
58
+ * Include Crypt_Base
59
+ *
60
+ * Base cipher class
61
+ */
62
+ require_once('Base.php');
63
+
64
+ /**#@+
65
+ * @access public
66
+ * @see Crypt_Blowfish::encrypt()
67
+ * @see Crypt_Blowfish::decrypt()
68
+ */
69
+ /**
70
+ * Encrypt / decrypt using the Counter mode.
71
+ *
72
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
73
+ *
74
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
75
+ */
76
+ define('CRYPT_BLOWFISH_MODE_CTR', CRYPT_MODE_CTR);
77
+ /**
78
+ * Encrypt / decrypt using the Electronic Code Book mode.
79
+ *
80
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
81
+ */
82
+ define('CRYPT_BLOWFISH_MODE_ECB', CRYPT_MODE_ECB);
83
+ /**
84
+ * Encrypt / decrypt using the Code Book Chaining mode.
85
+ *
86
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
87
+ */
88
+ define('CRYPT_BLOWFISH_MODE_CBC', CRYPT_MODE_CBC);
89
+ /**
90
+ * Encrypt / decrypt using the Cipher Feedback mode.
91
+ *
92
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
93
+ */
94
+ define('CRYPT_BLOWFISH_MODE_CFB', CRYPT_MODE_CFB);
95
+ /**
96
+ * Encrypt / decrypt using the Cipher Feedback mode.
97
+ *
98
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
99
+ */
100
+ define('CRYPT_BLOWFISH_MODE_OFB', CRYPT_MODE_OFB);
101
+ /**#@-*/
102
+
103
+ /**#@+
104
+ * @access private
105
+ * @see Crypt_Blowfish::Crypt_Blowfish()
106
+ */
107
+ /**
108
+ * Toggles the internal implementation
109
+ */
110
+ define('CRYPT_BLOWFISH_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
111
+ /**
112
+ * Toggles the mcrypt implementation
113
+ */
114
+ define('CRYPT_BLOWFISH_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
115
+ /**#@-*/
116
+
117
+ /**
118
+ * Pure-PHP implementation of Blowfish.
119
+ *
120
+ * @package Crypt_Blowfish
121
+ * @author Jim Wigginton <terrafrost@php.net>
122
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
123
+ * @version 1.0
124
+ * @access public
125
+ */
126
+ class Crypt_Blowfish extends Crypt_Base
127
+ {
128
+ /**
129
+ * Block Length of the cipher
130
+ *
131
+ * @see Crypt_Base::block_size
132
+ * @var Integer
133
+ * @access private
134
+ */
135
+ var $block_size = 8;
136
+
137
+ /**
138
+ * The default password key_size used by setPassword()
139
+ *
140
+ * @see Crypt_Base::password_key_size
141
+ * @see Crypt_Base::setPassword()
142
+ * @var Integer
143
+ * @access private
144
+ */
145
+ var $password_key_size = 56;
146
+
147
+ /**
148
+ * The namespace used by the cipher for its constants.
149
+ *
150
+ * @see Crypt_Base::const_namespace
151
+ * @var String
152
+ * @access private
153
+ */
154
+ var $const_namespace = 'BLOWFISH';
155
+
156
+ /**
157
+ * The mcrypt specific name of the cipher
158
+ *
159
+ * @see Crypt_Base::cipher_name_mcrypt
160
+ * @var String
161
+ * @access private
162
+ */
163
+ var $cipher_name_mcrypt = 'blowfish';
164
+
165
+ /**
166
+ * Optimizing value while CFB-encrypting
167
+ *
168
+ * @see Crypt_Base::cfb_init_len
169
+ * @var Integer
170
+ * @access private
171
+ */
172
+ var $cfb_init_len = 500;
173
+
174
+ /**
175
+ * The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each
176
+ *
177
+ * S-Box 1
178
+ *
179
+ * @access private
180
+ * @var array
181
+ */
182
+ var $sbox0 = array (
183
+ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
184
+ 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
185
+ 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
186
+ 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
187
+ 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
188
+ 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
189
+ 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
190
+ 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
191
+ 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
192
+ 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
193
+ 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
194
+ 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
195
+ 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
196
+ 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
197
+ 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
198
+ 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
199
+ 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
200
+ 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
201
+ 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
202
+ 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
203
+ 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
204
+ 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
205
+ 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
206
+ 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
207
+ 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
208
+ 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
209
+ 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
210
+ 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
211
+ 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
212
+ 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
213
+ 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
214
+ 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
215
+ );
216
+
217
+ /**
218
+ * S-Box 1
219
+ *
220
+ * @access private
221
+ * @var array
222
+ */
223
+ var $sbox1 = array(
224
+ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
225
+ 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
226
+ 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
227
+ 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
228
+ 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
229
+ 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
230
+ 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
231
+ 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
232
+ 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
233
+ 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
234
+ 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
235
+ 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
236
+ 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
237
+ 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
238
+ 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
239
+ 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
240
+ 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
241
+ 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
242
+ 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
243
+ 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
244
+ 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
245
+ 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
246
+ 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
247
+ 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
248
+ 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
249
+ 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
250
+ 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
251
+ 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
252
+ 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
253
+ 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
254
+ 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
255
+ 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
256
+ );
257
+
258
+ /**
259
+ * S-Box 2
260
+ *
261
+ * @access private
262
+ * @var array
263
+ */
264
+ var $sbox2 = array(
265
+ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
266
+ 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
267
+ 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
268
+ 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
269
+ 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
270
+ 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
271
+ 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
272
+ 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
273
+ 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
274
+ 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
275
+ 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
276
+ 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
277
+ 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
278
+ 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
279
+ 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
280
+ 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
281
+ 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
282
+ 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
283
+ 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
284
+ 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
285
+ 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
286
+ 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
287
+ 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
288
+ 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
289
+ 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
290
+ 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
291
+ 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
292
+ 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
293
+ 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
294
+ 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
295
+ 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
296
+ 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
297
+ );
298
+
299
+ /**
300
+ * S-Box 3
301
+ *
302
+ * @access private
303
+ * @var array
304
+ */
305
+ var $sbox3 = array(
306
+ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
307
+ 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
308
+ 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
309
+ 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
310
+ 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
311
+ 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
312
+ 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
313
+ 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
314
+ 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
315
+ 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
316
+ 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
317
+ 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
318
+ 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
319
+ 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
320
+ 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
321
+ 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
322
+ 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
323
+ 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
324
+ 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
325
+ 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
326
+ 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
327
+ 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
328
+ 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
329
+ 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
330
+ 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
331
+ 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
332
+ 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
333
+ 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
334
+ 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
335
+ 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
336
+ 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
337
+ 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
338
+ );
339
+
340
+ /**
341
+ * P-Array consists of 18 32-bit subkeys
342
+ *
343
+ * @var array $parray
344
+ * @access private
345
+ */
346
+ var $parray = array(
347
+ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
348
+ 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
349
+ 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
350
+ );
351
+
352
+ /**
353
+ * The BCTX-working Array
354
+ *
355
+ * Holds the expanded key [p] and the key-depended s-boxes [sb]
356
+ *
357
+ * @var array $bctx
358
+ * @access private
359
+ */
360
+ var $bctx;
361
+
362
+ /**
363
+ * Holds the last used key
364
+ *
365
+ * @var Array
366
+ * @access private
367
+ */
368
+ var $kl;
369
+
370
+ /**
371
+ * Default Constructor.
372
+ *
373
+ * Determines whether or not the mcrypt extension should be used.
374
+ *
375
+ * $mode could be:
376
+ *
377
+ * - CRYPT_BLOWFISH_MODE_ECB
378
+ *
379
+ * - CRYPT_BLOWFISH_MODE_CBC
380
+ *
381
+ * - CRYPT_BLOWFISH_MODE_CTR
382
+ *
383
+ * - CRYPT_BLOWFISH_MODE_CFB
384
+ *
385
+ * - CRYPT_BLOWFISH_MODE_OFB
386
+ *
387
+ * If not explictly set, CRYPT_BLOWFISH_MODE_CBC will be used.
388
+ *
389
+ * @see Crypt_Base::Crypt_Base()
390
+ * @param optional Integer $mode
391
+ * @access public
392
+ */
393
+ function Crypt_Blowfish($mode = CRYPT_BLOWFISH_MODE_CBC)
394
+ {
395
+ parent::Crypt_Base($mode);
396
+ }
397
+
398
+ /**
399
+ * Sets the key.
400
+ *
401
+ * Keys can be of any length. Blowfish, itself, requires the use of a key between 32 and max. 448-bits long.
402
+ * If the key is less than 32-bits we NOT fill the key to 32bit but let the key as it is to be compatible
403
+ * with mcrypt because mcrypt act this way with blowfish key's < 32 bits.
404
+ *
405
+ * If the key is more than 448-bits, we trim the excess bits.
406
+ *
407
+ * If the key is not explicitly set, or empty, it'll be assumed a 128 bits key to be all null bytes.
408
+ *
409
+ * @access public
410
+ * @see Crypt_Base::setKey()
411
+ * @param String $key
412
+ */
413
+ function setKey($key)
414
+ {
415
+ $keylength = strlen($key);
416
+
417
+ if (!$keylength) {
418
+ $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
419
+ } elseif ($keylength > 56) {
420
+ $key = substr($key, 0, 56);
421
+ }
422
+
423
+ parent::setKey($key);
424
+ }
425
+
426
+ /**
427
+ * Setup the key (expansion)
428
+ *
429
+ * @see Crypt_Base::_setupKey()
430
+ * @access private
431
+ */
432
+ function _setupKey()
433
+ {
434
+ if (isset($this->kl['key']) && $this->key === $this->kl['key']) {
435
+ // already expanded
436
+ return;
437
+ }
438
+ $this->kl = array('key' => $this->key);
439
+
440
+ /* key-expanding p[] and S-Box building sb[] */
441
+ $this->bctx = array(
442
+ 'p' => array(),
443
+ 'sb' => array(
444
+ $this->sbox0,
445
+ $this->sbox1,
446
+ $this->sbox2,
447
+ $this->sbox3
448
+ )
449
+ );
450
+
451
+ // unpack binary string in unsigned chars
452
+ $key = array_values(unpack('C*', $this->key));
453
+ $keyl = count($key);
454
+ for ($j = 0, $i = 0; $i < 18; ++$i) {
455
+ // xor P1 with the first 32-bits of the key, xor P2 with the second 32-bits ...
456
+ for ($data = 0, $k = 0; $k < 4; ++$k) {
457
+ $data = ($data << 8) | $key[$j];
458
+ if (++$j >= $keyl) {
459
+ $j = 0;
460
+ }
461
+ }
462
+ $this->bctx['p'][] = $this->parray[$i] ^ $data;
463
+ }
464
+
465
+ // encrypt the zero-string, replace P1 and P2 with the encrypted data,
466
+ // encrypt P3 and P4 with the new P1 and P2, do it with all P-array and subkeys
467
+ $data = "\0\0\0\0\0\0\0\0";
468
+ for ($i = 0; $i < 18; $i += 2) {
469
+ list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data)));
470
+ $this->bctx['p'][$i ] = $l;
471
+ $this->bctx['p'][$i + 1] = $r;
472
+ }
473
+ for ($i = 0; $i < 4; ++$i) {
474
+ for ($j = 0; $j < 256; $j += 2) {
475
+ list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data)));
476
+ $this->bctx['sb'][$i][$j ] = $l;
477
+ $this->bctx['sb'][$i][$j + 1] = $r;
478
+ }
479
+ }
480
+ }
481
+
482
+ /**
483
+ * Encrypts a block
484
+ *
485
+ * @access private
486
+ * @param String $in
487
+ * @return String
488
+ */
489
+ function _encryptBlock($in)
490
+ {
491
+ $p = $this->bctx["p"];
492
+ // extract($this->bctx["sb"], EXTR_PREFIX_ALL, "sb"); // slower
493
+ $sb_0 = $this->bctx["sb"][0];
494
+ $sb_1 = $this->bctx["sb"][1];
495
+ $sb_2 = $this->bctx["sb"][2];
496
+ $sb_3 = $this->bctx["sb"][3];
497
+
498
+ $in = unpack("N*", $in);
499
+ $l = $in[1];
500
+ $r = $in[2];
501
+
502
+ for ($i = 0; $i < 16; $i+= 2) {
503
+ $l^= $p[$i];
504
+ $r^= ($sb_0[$l >> 24 & 0xff] +
505
+ $sb_1[$l >> 16 & 0xff] ^
506
+ $sb_2[$l >> 8 & 0xff]) +
507
+ $sb_3[$l & 0xff];
508
+
509
+ $r^= $p[$i + 1];
510
+ $l^= ($sb_0[$r >> 24 & 0xff] +
511
+ $sb_1[$r >> 16 & 0xff] ^
512
+ $sb_2[$r >> 8 & 0xff]) +
513
+ $sb_3[$r & 0xff];
514
+ }
515
+ return pack("N*", $r ^ $p[17], $l ^ $p[16]);
516
+ }
517
+
518
+ /**
519
+ * Decrypts a block
520
+ *
521
+ * @access private
522
+ * @param String $in
523
+ * @return String
524
+ */
525
+ function _decryptBlock($in)
526
+ {
527
+ $p = $this->bctx["p"];
528
+ $sb_0 = $this->bctx["sb"][0];
529
+ $sb_1 = $this->bctx["sb"][1];
530
+ $sb_2 = $this->bctx["sb"][2];
531
+ $sb_3 = $this->bctx["sb"][3];
532
+
533
+ $in = unpack("N*", $in);
534
+ $l = $in[1];
535
+ $r = $in[2];
536
+
537
+ for ($i = 17; $i > 2; $i-= 2) {
538
+ $l^= $p[$i];
539
+ $r^= ($sb_0[$l >> 24 & 0xff] +
540
+ $sb_1[$l >> 16 & 0xff] ^
541
+ $sb_2[$l >> 8 & 0xff]) +
542
+ $sb_3[$l & 0xff];
543
+
544
+ $r^= $p[$i - 1];
545
+ $l^= ($sb_0[$r >> 24 & 0xff] +
546
+ $sb_1[$r >> 16 & 0xff] ^
547
+ $sb_2[$r >> 8 & 0xff]) +
548
+ $sb_3[$r & 0xff];
549
+ }
550
+
551
+ return pack("N*", $r ^ $p[0], $l ^ $p[1]);
552
+ }
553
+
554
+ /**
555
+ * Setup the performance-optimized function for de/encrypt()
556
+ *
557
+ * @see Crypt_Base::_setupInlineCrypt()
558
+ * @access private
559
+ */
560
+ function _setupInlineCrypt()
561
+ {
562
+ $lambda_functions =& Crypt_Blowfish::_getLambdaFunctions();
563
+
564
+ // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
565
+ // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one.
566
+ $gen_hi_opt_code = (bool)( count($lambda_functions) < 10);
567
+
568
+ switch (true) {
569
+ case $gen_hi_opt_code:
570
+ $code_hash = md5(str_pad("Crypt_Blowfish, {$this->mode}, ", 32, "\0") . $this->key);
571
+ break;
572
+ default:
573
+ $code_hash = "Crypt_Blowfish, {$this->mode}";
574
+ }
575
+
576
+ if (!isset($lambda_functions[$code_hash])) {
577
+ switch (true) {
578
+ case $gen_hi_opt_code:
579
+ $p = $this->bctx['p'];
580
+ $init_crypt = '
581
+ static $sb_0, $sb_1, $sb_2, $sb_3;
582
+ if (!$sb_0) {
583
+ $sb_0 = $self->bctx["sb"][0];
584
+ $sb_1 = $self->bctx["sb"][1];
585
+ $sb_2 = $self->bctx["sb"][2];
586
+ $sb_3 = $self->bctx["sb"][3];
587
+ }
588
+ ';
589
+ break;
590
+ default:
591
+ $p = array();
592
+ for ($i = 0; $i < 18; ++$i) {
593
+ $p[] = '$p_' . $i;
594
+ }
595
+ $init_crypt = '
596
+ list($sb_0, $sb_1, $sb_2, $sb_3) = $self->bctx["sb"];
597
+ list(' . implode(',', $p) . ') = $self->bctx["p"];
598
+
599
+ ';
600
+ }
601
+
602
+ // Generating encrypt code:
603
+ $encrypt_block = '
604
+ $in = unpack("N*", $in);
605
+ $l = $in[1];
606
+ $r = $in[2];
607
+ ';
608
+ for ($i = 0; $i < 16; $i+= 2) {
609
+ $encrypt_block.= '
610
+ $l^= ' . $p[$i] . ';
611
+ $r^= ($sb_0[$l >> 24 & 0xff] +
612
+ $sb_1[$l >> 16 & 0xff] ^
613
+ $sb_2[$l >> 8 & 0xff]) +
614
+ $sb_3[$l & 0xff];
615
+
616
+ $r^= ' . $p[$i + 1] . ';
617
+ $l^= ($sb_0[$r >> 24 & 0xff] +
618
+ $sb_1[$r >> 16 & 0xff] ^
619
+ $sb_2[$r >> 8 & 0xff]) +
620
+ $sb_3[$r & 0xff];
621
+ ';
622
+ }
623
+ $encrypt_block.= '
624
+ $in = pack("N*",
625
+ $r ^ ' . $p[17] . ',
626
+ $l ^ ' . $p[16] . '
627
+ );
628
+ ';
629
+
630
+ // Generating decrypt code:
631
+ $decrypt_block = '
632
+ $in = unpack("N*", $in);
633
+ $l = $in[1];
634
+ $r = $in[2];
635
+ ';
636
+
637
+ for ($i = 17; $i > 2; $i-= 2) {
638
+ $decrypt_block.= '
639
+ $l^= ' . $p[$i] . ';
640
+ $r^= ($sb_0[$l >> 24 & 0xff] +
641
+ $sb_1[$l >> 16 & 0xff] ^
642
+ $sb_2[$l >> 8 & 0xff]) +
643
+ $sb_3[$l & 0xff];
644
+
645
+ $r^= ' . $p[$i - 1] . ';
646
+ $l^= ($sb_0[$r >> 24 & 0xff] +
647
+ $sb_1[$r >> 16 & 0xff] ^
648
+ $sb_2[$r >> 8 & 0xff]) +
649
+ $sb_3[$r & 0xff];
650
+ ';
651
+ }
652
+
653
+ $decrypt_block.= '
654
+ $in = pack("N*",
655
+ $r ^ ' . $p[0] . ',
656
+ $l ^ ' . $p[1] . '
657
+ );
658
+ ';
659
+
660
+ $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
661
+ array(
662
+ 'init_crypt' => $init_crypt,
663
+ 'init_encrypt' => '',
664
+ 'init_decrypt' => '',
665
+ 'encrypt_block' => $encrypt_block,
666
+ 'decrypt_block' => $decrypt_block
667
+ )
668
+ );
669
+ }
670
+ $this->inline_crypt = $lambda_functions[$code_hash];
671
+ }
672
+ }
673
+
lib/LivrariOnline/DES.php ADDED
@@ -0,0 +1,1534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of DES.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Useful resources are as follows:
11
+ *
12
+ * - {@link http://en.wikipedia.org/wiki/DES_supplementary_material Wikipedia: DES supplementary material}
13
+ * - {@link http://www.itl.nist.gov/fipspubs/fip46-2.htm FIPS 46-2 - (DES), Data Encryption Standard}
14
+ * - {@link http://www.cs.eku.edu/faculty/styer/460/Encrypt/JS-DES.html JavaScript DES Example}
15
+ *
16
+ * Here's a short example of how to use this library:
17
+ * <code>
18
+ * <?php
19
+ * include('Crypt/DES.php');
20
+ *
21
+ * $des = new Crypt_DES();
22
+ *
23
+ * $des->setKey('abcdefgh');
24
+ *
25
+ * $size = 10 * 1024;
26
+ * $plaintext = '';
27
+ * for ($i = 0; $i < $size; $i++) {
28
+ * $plaintext.= 'a';
29
+ * }
30
+ *
31
+ * echo $des->decrypt($des->encrypt($plaintext));
32
+ * ?>
33
+ * </code>
34
+ *
35
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
36
+ * of this software and associated documentation files (the "Software"), to deal
37
+ * in the Software without restriction, including without limitation the rights
38
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+ * copies of the Software, and to permit persons to whom the Software is
40
+ * furnished to do so, subject to the following conditions:
41
+ *
42
+ * The above copyright notice and this permission notice shall be included in
43
+ * all copies or substantial portions of the Software.
44
+ *
45
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
51
+ * THE SOFTWARE.
52
+ *
53
+ * @category Crypt
54
+ * @package Crypt_DES
55
+ * @author Jim Wigginton <terrafrost@php.net>
56
+ * @copyright MMVII Jim Wigginton
57
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
58
+ * @link http://phpseclib.sourceforge.net
59
+ */
60
+
61
+ /**
62
+ * Include Crypt_Base
63
+ *
64
+ * Base cipher class
65
+ */
66
+ require_once('Base.php');
67
+
68
+ /**#@+
69
+ * @access private
70
+ * @see Crypt_DES::_setupKey()
71
+ * @see Crypt_DES::_processBlock()
72
+ */
73
+ /**
74
+ * Contains $keys[CRYPT_DES_ENCRYPT]
75
+ */
76
+ define('CRYPT_DES_ENCRYPT', 0);
77
+ /**
78
+ * Contains $keys[CRYPT_DES_DECRYPT]
79
+ */
80
+ define('CRYPT_DES_DECRYPT', 1);
81
+ /**#@-*/
82
+
83
+ /**#@+
84
+ * @access public
85
+ * @see Crypt_DES::encrypt()
86
+ * @see Crypt_DES::decrypt()
87
+ */
88
+ /**
89
+ * Encrypt / decrypt using the Counter mode.
90
+ *
91
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
92
+ *
93
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
94
+ */
95
+ define('CRYPT_DES_MODE_CTR', CRYPT_MODE_CTR);
96
+ /**
97
+ * Encrypt / decrypt using the Electronic Code Book mode.
98
+ *
99
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
100
+ */
101
+ define('CRYPT_DES_MODE_ECB', CRYPT_MODE_ECB);
102
+ /**
103
+ * Encrypt / decrypt using the Code Book Chaining mode.
104
+ *
105
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
106
+ */
107
+ define('CRYPT_DES_MODE_CBC', CRYPT_MODE_CBC);
108
+ /**
109
+ * Encrypt / decrypt using the Cipher Feedback mode.
110
+ *
111
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
112
+ */
113
+ define('CRYPT_DES_MODE_CFB', CRYPT_MODE_CFB);
114
+ /**
115
+ * Encrypt / decrypt using the Cipher Feedback mode.
116
+ *
117
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
118
+ */
119
+ define('CRYPT_DES_MODE_OFB', CRYPT_MODE_OFB);
120
+ /**#@-*/
121
+
122
+ /**#@+
123
+ * @access private
124
+ * @see Crypt_DES::Crypt_DES()
125
+ */
126
+ /**
127
+ * Toggles the internal implementation
128
+ */
129
+ define('CRYPT_DES_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
130
+ /**
131
+ * Toggles the mcrypt implementation
132
+ */
133
+ define('CRYPT_DES_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
134
+ /**#@-*/
135
+
136
+ /**
137
+ * Pure-PHP implementation of DES.
138
+ *
139
+ * @package Crypt_DES
140
+ * @author Jim Wigginton <terrafrost@php.net>
141
+ * @version 0.1.0
142
+ * @access public
143
+ */
144
+ class Crypt_DES extends Crypt_Base
145
+ {
146
+ /**
147
+ * Block Length of the cipher
148
+ *
149
+ * @see Crypt_Base::block_size
150
+ * @var Integer
151
+ * @access private
152
+ */
153
+ var $block_size = 8;
154
+
155
+ /**
156
+ * The Key
157
+ *
158
+ * @see Crypt_Base::key
159
+ * @see setKey()
160
+ * @var String
161
+ * @access private
162
+ */
163
+ var $key = "\0\0\0\0\0\0\0\0";
164
+
165
+ /**
166
+ * The default password key_size used by setPassword()
167
+ *
168
+ * @see Crypt_Base::password_key_size
169
+ * @see Crypt_Base::setPassword()
170
+ * @var Integer
171
+ * @access private
172
+ */
173
+ var $password_key_size = 8;
174
+
175
+ /**
176
+ * The namespace used by the cipher for its constants.
177
+ *
178
+ * @see Crypt_Base::const_namespace
179
+ * @var String
180
+ * @access private
181
+ */
182
+ var $const_namespace = 'DES';
183
+
184
+ /**
185
+ * The mcrypt specific name of the cipher
186
+ *
187
+ * @see Crypt_Base::cipher_name_mcrypt
188
+ * @var String
189
+ * @access private
190
+ */
191
+ var $cipher_name_mcrypt = 'des';
192
+
193
+ /**
194
+ * Optimizing value while CFB-encrypting
195
+ *
196
+ * @see Crypt_Base::cfb_init_len
197
+ * @var Integer
198
+ * @access private
199
+ */
200
+ var $cfb_init_len = 500;
201
+
202
+ /**
203
+ * Switch for DES/3DES encryption
204
+ *
205
+ * Used only if $engine == CRYPT_DES_MODE_INTERNAL
206
+ *
207
+ * @see Crypt_DES::_setupKey()
208
+ * @see Crypt_DES::_processBlock()
209
+ * @var Integer
210
+ * @access private
211
+ */
212
+ var $des_rounds = 1;
213
+
214
+ /**
215
+ * max possible size of $key
216
+ *
217
+ * @see Crypt_DES::setKey()
218
+ * @var String
219
+ * @access private
220
+ */
221
+ var $key_size_max = 8;
222
+
223
+ /**
224
+ * The Key Schedule
225
+ *
226
+ * @see Crypt_DES::_setupKey()
227
+ * @var Array
228
+ * @access private
229
+ */
230
+ var $keys;
231
+
232
+ /**
233
+ * Shuffle table.
234
+ *
235
+ * For each byte value index, the entry holds an 8-byte string
236
+ * with each byte containing all bits in the same state as the
237
+ * corresponding bit in the index value.
238
+ *
239
+ * @see Crypt_DES::_processBlock()
240
+ * @see Crypt_DES::_setupKey()
241
+ * @var Array
242
+ * @access private
243
+ */
244
+ var $shuffle = array(
245
+ "\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\xFF",
246
+ "\x00\x00\x00\x00\x00\x00\xFF\x00", "\x00\x00\x00\x00\x00\x00\xFF\xFF",
247
+ "\x00\x00\x00\x00\x00\xFF\x00\x00", "\x00\x00\x00\x00\x00\xFF\x00\xFF",
248
+ "\x00\x00\x00\x00\x00\xFF\xFF\x00", "\x00\x00\x00\x00\x00\xFF\xFF\xFF",
249
+ "\x00\x00\x00\x00\xFF\x00\x00\x00", "\x00\x00\x00\x00\xFF\x00\x00\xFF",
250
+ "\x00\x00\x00\x00\xFF\x00\xFF\x00", "\x00\x00\x00\x00\xFF\x00\xFF\xFF",
251
+ "\x00\x00\x00\x00\xFF\xFF\x00\x00", "\x00\x00\x00\x00\xFF\xFF\x00\xFF",
252
+ "\x00\x00\x00\x00\xFF\xFF\xFF\x00", "\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
253
+ "\x00\x00\x00\xFF\x00\x00\x00\x00", "\x00\x00\x00\xFF\x00\x00\x00\xFF",
254
+ "\x00\x00\x00\xFF\x00\x00\xFF\x00", "\x00\x00\x00\xFF\x00\x00\xFF\xFF",
255
+ "\x00\x00\x00\xFF\x00\xFF\x00\x00", "\x00\x00\x00\xFF\x00\xFF\x00\xFF",
256
+ "\x00\x00\x00\xFF\x00\xFF\xFF\x00", "\x00\x00\x00\xFF\x00\xFF\xFF\xFF",
257
+ "\x00\x00\x00\xFF\xFF\x00\x00\x00", "\x00\x00\x00\xFF\xFF\x00\x00\xFF",
258
+ "\x00\x00\x00\xFF\xFF\x00\xFF\x00", "\x00\x00\x00\xFF\xFF\x00\xFF\xFF",
259
+ "\x00\x00\x00\xFF\xFF\xFF\x00\x00", "\x00\x00\x00\xFF\xFF\xFF\x00\xFF",
260
+ "\x00\x00\x00\xFF\xFF\xFF\xFF\x00", "\x00\x00\x00\xFF\xFF\xFF\xFF\xFF",
261
+ "\x00\x00\xFF\x00\x00\x00\x00\x00", "\x00\x00\xFF\x00\x00\x00\x00\xFF",
262
+ "\x00\x00\xFF\x00\x00\x00\xFF\x00", "\x00\x00\xFF\x00\x00\x00\xFF\xFF",
263
+ "\x00\x00\xFF\x00\x00\xFF\x00\x00", "\x00\x00\xFF\x00\x00\xFF\x00\xFF",
264
+ "\x00\x00\xFF\x00\x00\xFF\xFF\x00", "\x00\x00\xFF\x00\x00\xFF\xFF\xFF",
265
+ "\x00\x00\xFF\x00\xFF\x00\x00\x00", "\x00\x00\xFF\x00\xFF\x00\x00\xFF",
266
+ "\x00\x00\xFF\x00\xFF\x00\xFF\x00", "\x00\x00\xFF\x00\xFF\x00\xFF\xFF",
267
+ "\x00\x00\xFF\x00\xFF\xFF\x00\x00", "\x00\x00\xFF\x00\xFF\xFF\x00\xFF",
268
+ "\x00\x00\xFF\x00\xFF\xFF\xFF\x00", "\x00\x00\xFF\x00\xFF\xFF\xFF\xFF",
269
+ "\x00\x00\xFF\xFF\x00\x00\x00\x00", "\x00\x00\xFF\xFF\x00\x00\x00\xFF",
270
+ "\x00\x00\xFF\xFF\x00\x00\xFF\x00", "\x00\x00\xFF\xFF\x00\x00\xFF\xFF",
271
+ "\x00\x00\xFF\xFF\x00\xFF\x00\x00", "\x00\x00\xFF\xFF\x00\xFF\x00\xFF",
272
+ "\x00\x00\xFF\xFF\x00\xFF\xFF\x00", "\x00\x00\xFF\xFF\x00\xFF\xFF\xFF",
273
+ "\x00\x00\xFF\xFF\xFF\x00\x00\x00", "\x00\x00\xFF\xFF\xFF\x00\x00\xFF",
274
+ "\x00\x00\xFF\xFF\xFF\x00\xFF\x00", "\x00\x00\xFF\xFF\xFF\x00\xFF\xFF",
275
+ "\x00\x00\xFF\xFF\xFF\xFF\x00\x00", "\x00\x00\xFF\xFF\xFF\xFF\x00\xFF",
276
+ "\x00\x00\xFF\xFF\xFF\xFF\xFF\x00", "\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF",
277
+ "\x00\xFF\x00\x00\x00\x00\x00\x00", "\x00\xFF\x00\x00\x00\x00\x00\xFF",
278
+ "\x00\xFF\x00\x00\x00\x00\xFF\x00", "\x00\xFF\x00\x00\x00\x00\xFF\xFF",
279
+ "\x00\xFF\x00\x00\x00\xFF\x00\x00", "\x00\xFF\x00\x00\x00\xFF\x00\xFF",
280
+ "\x00\xFF\x00\x00\x00\xFF\xFF\x00", "\x00\xFF\x00\x00\x00\xFF\xFF\xFF",
281
+ "\x00\xFF\x00\x00\xFF\x00\x00\x00", "\x00\xFF\x00\x00\xFF\x00\x00\xFF",
282
+ "\x00\xFF\x00\x00\xFF\x00\xFF\x00", "\x00\xFF\x00\x00\xFF\x00\xFF\xFF",
283
+ "\x00\xFF\x00\x00\xFF\xFF\x00\x00", "\x00\xFF\x00\x00\xFF\xFF\x00\xFF",
284
+ "\x00\xFF\x00\x00\xFF\xFF\xFF\x00", "\x00\xFF\x00\x00\xFF\xFF\xFF\xFF",
285
+ "\x00\xFF\x00\xFF\x00\x00\x00\x00", "\x00\xFF\x00\xFF\x00\x00\x00\xFF",
286
+ "\x00\xFF\x00\xFF\x00\x00\xFF\x00", "\x00\xFF\x00\xFF\x00\x00\xFF\xFF",
287
+ "\x00\xFF\x00\xFF\x00\xFF\x00\x00", "\x00\xFF\x00\xFF\x00\xFF\x00\xFF",
288
+ "\x00\xFF\x00\xFF\x00\xFF\xFF\x00", "\x00\xFF\x00\xFF\x00\xFF\xFF\xFF",
289
+ "\x00\xFF\x00\xFF\xFF\x00\x00\x00", "\x00\xFF\x00\xFF\xFF\x00\x00\xFF",
290
+ "\x00\xFF\x00\xFF\xFF\x00\xFF\x00", "\x00\xFF\x00\xFF\xFF\x00\xFF\xFF",
291
+ "\x00\xFF\x00\xFF\xFF\xFF\x00\x00", "\x00\xFF\x00\xFF\xFF\xFF\x00\xFF",
292
+ "\x00\xFF\x00\xFF\xFF\xFF\xFF\x00", "\x00\xFF\x00\xFF\xFF\xFF\xFF\xFF",
293
+ "\x00\xFF\xFF\x00\x00\x00\x00\x00", "\x00\xFF\xFF\x00\x00\x00\x00\xFF",
294
+ "\x00\xFF\xFF\x00\x00\x00\xFF\x00", "\x00\xFF\xFF\x00\x00\x00\xFF\xFF",
295
+ "\x00\xFF\xFF\x00\x00\xFF\x00\x00", "\x00\xFF\xFF\x00\x00\xFF\x00\xFF",
296
+ "\x00\xFF\xFF\x00\x00\xFF\xFF\x00", "\x00\xFF\xFF\x00\x00\xFF\xFF\xFF",
297
+ "\x00\xFF\xFF\x00\xFF\x00\x00\x00", "\x00\xFF\xFF\x00\xFF\x00\x00\xFF",
298
+ "\x00\xFF\xFF\x00\xFF\x00\xFF\x00", "\x00\xFF\xFF\x00\xFF\x00\xFF\xFF",
299
+ "\x00\xFF\xFF\x00\xFF\xFF\x00\x00", "\x00\xFF\xFF\x00\xFF\xFF\x00\xFF",
300
+ "\x00\xFF\xFF\x00\xFF\xFF\xFF\x00", "\x00\xFF\xFF\x00\xFF\xFF\xFF\xFF",
301
+ "\x00\xFF\xFF\xFF\x00\x00\x00\x00", "\x00\xFF\xFF\xFF\x00\x00\x00\xFF",
302
+ "\x00\xFF\xFF\xFF\x00\x00\xFF\x00", "\x00\xFF\xFF\xFF\x00\x00\xFF\xFF",
303
+ "\x00\xFF\xFF\xFF\x00\xFF\x00\x00", "\x00\xFF\xFF\xFF\x00\xFF\x00\xFF",
304
+ "\x00\xFF\xFF\xFF\x00\xFF\xFF\x00", "\x00\xFF\xFF\xFF\x00\xFF\xFF\xFF",
305
+ "\x00\xFF\xFF\xFF\xFF\x00\x00\x00", "\x00\xFF\xFF\xFF\xFF\x00\x00\xFF",
306
+ "\x00\xFF\xFF\xFF\xFF\x00\xFF\x00", "\x00\xFF\xFF\xFF\xFF\x00\xFF\xFF",
307
+ "\x00\xFF\xFF\xFF\xFF\xFF\x00\x00", "\x00\xFF\xFF\xFF\xFF\xFF\x00\xFF",
308
+ "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
309
+ "\xFF\x00\x00\x00\x00\x00\x00\x00", "\xFF\x00\x00\x00\x00\x00\x00\xFF",
310
+ "\xFF\x00\x00\x00\x00\x00\xFF\x00", "\xFF\x00\x00\x00\x00\x00\xFF\xFF",
311
+ "\xFF\x00\x00\x00\x00\xFF\x00\x00", "\xFF\x00\x00\x00\x00\xFF\x00\xFF",
312
+ "\xFF\x00\x00\x00\x00\xFF\xFF\x00", "\xFF\x00\x00\x00\x00\xFF\xFF\xFF",
313
+ "\xFF\x00\x00\x00\xFF\x00\x00\x00", "\xFF\x00\x00\x00\xFF\x00\x00\xFF",
314
+ "\xFF\x00\x00\x00\xFF\x00\xFF\x00", "\xFF\x00\x00\x00\xFF\x00\xFF\xFF",
315
+ "\xFF\x00\x00\x00\xFF\xFF\x00\x00", "\xFF\x00\x00\x00\xFF\xFF\x00\xFF",
316
+ "\xFF\x00\x00\x00\xFF\xFF\xFF\x00", "\xFF\x00\x00\x00\xFF\xFF\xFF\xFF",
317
+ "\xFF\x00\x00\xFF\x00\x00\x00\x00", "\xFF\x00\x00\xFF\x00\x00\x00\xFF",
318
+ "\xFF\x00\x00\xFF\x00\x00\xFF\x00", "\xFF\x00\x00\xFF\x00\x00\xFF\xFF",
319
+ "\xFF\x00\x00\xFF\x00\xFF\x00\x00", "\xFF\x00\x00\xFF\x00\xFF\x00\xFF",
320
+ "\xFF\x00\x00\xFF\x00\xFF\xFF\x00", "\xFF\x00\x00\xFF\x00\xFF\xFF\xFF",
321
+ "\xFF\x00\x00\xFF\xFF\x00\x00\x00", "\xFF\x00\x00\xFF\xFF\x00\x00\xFF",
322
+ "\xFF\x00\x00\xFF\xFF\x00\xFF\x00", "\xFF\x00\x00\xFF\xFF\x00\xFF\xFF",
323
+ "\xFF\x00\x00\xFF\xFF\xFF\x00\x00", "\xFF\x00\x00\xFF\xFF\xFF\x00\xFF",
324
+ "\xFF\x00\x00\xFF\xFF\xFF\xFF\x00", "\xFF\x00\x00\xFF\xFF\xFF\xFF\xFF",
325
+ "\xFF\x00\xFF\x00\x00\x00\x00\x00", "\xFF\x00\xFF\x00\x00\x00\x00\xFF",
326
+ "\xFF\x00\xFF\x00\x00\x00\xFF\x00", "\xFF\x00\xFF\x00\x00\x00\xFF\xFF",
327
+ "\xFF\x00\xFF\x00\x00\xFF\x00\x00", "\xFF\x00\xFF\x00\x00\xFF\x00\xFF",
328
+ "\xFF\x00\xFF\x00\x00\xFF\xFF\x00", "\xFF\x00\xFF\x00\x00\xFF\xFF\xFF",
329
+ "\xFF\x00\xFF\x00\xFF\x00\x00\x00", "\xFF\x00\xFF\x00\xFF\x00\x00\xFF",
330
+ "\xFF\x00\xFF\x00\xFF\x00\xFF\x00", "\xFF\x00\xFF\x00\xFF\x00\xFF\xFF",
331
+ "\xFF\x00\xFF\x00\xFF\xFF\x00\x00", "\xFF\x00\xFF\x00\xFF\xFF\x00\xFF",
332
+ "\xFF\x00\xFF\x00\xFF\xFF\xFF\x00", "\xFF\x00\xFF\x00\xFF\xFF\xFF\xFF",
333
+ "\xFF\x00\xFF\xFF\x00\x00\x00\x00", "\xFF\x00\xFF\xFF\x00\x00\x00\xFF",
334
+ "\xFF\x00\xFF\xFF\x00\x00\xFF\x00", "\xFF\x00\xFF\xFF\x00\x00\xFF\xFF",
335
+ "\xFF\x00\xFF\xFF\x00\xFF\x00\x00", "\xFF\x00\xFF\xFF\x00\xFF\x00\xFF",
336
+ "\xFF\x00\xFF\xFF\x00\xFF\xFF\x00", "\xFF\x00\xFF\xFF\x00\xFF\xFF\xFF",
337
+ "\xFF\x00\xFF\xFF\xFF\x00\x00\x00", "\xFF\x00\xFF\xFF\xFF\x00\x00\xFF",
338
+ "\xFF\x00\xFF\xFF\xFF\x00\xFF\x00", "\xFF\x00\xFF\xFF\xFF\x00\xFF\xFF",
339
+ "\xFF\x00\xFF\xFF\xFF\xFF\x00\x00", "\xFF\x00\xFF\xFF\xFF\xFF\x00\xFF",
340
+ "\xFF\x00\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\x00\xFF\xFF\xFF\xFF\xFF\xFF",
341
+ "\xFF\xFF\x00\x00\x00\x00\x00\x00", "\xFF\xFF\x00\x00\x00\x00\x00\xFF",
342
+ "\xFF\xFF\x00\x00\x00\x00\xFF\x00", "\xFF\xFF\x00\x00\x00\x00\xFF\xFF",
343
+ "\xFF\xFF\x00\x00\x00\xFF\x00\x00", "\xFF\xFF\x00\x00\x00\xFF\x00\xFF",
344
+ "\xFF\xFF\x00\x00\x00\xFF\xFF\x00", "\xFF\xFF\x00\x00\x00\xFF\xFF\xFF",
345
+ "\xFF\xFF\x00\x00\xFF\x00\x00\x00", "\xFF\xFF\x00\x00\xFF\x00\x00\xFF",
346
+ "\xFF\xFF\x00\x00\xFF\x00\xFF\x00", "\xFF\xFF\x00\x00\xFF\x00\xFF\xFF",
347
+ "\xFF\xFF\x00\x00\xFF\xFF\x00\x00", "\xFF\xFF\x00\x00\xFF\xFF\x00\xFF",
348
+ "\xFF\xFF\x00\x00\xFF\xFF\xFF\x00", "\xFF\xFF\x00\x00\xFF\xFF\xFF\xFF",
349
+ "\xFF\xFF\x00\xFF\x00\x00\x00\x00", "\xFF\xFF\x00\xFF\x00\x00\x00\xFF",
350
+ "\xFF\xFF\x00\xFF\x00\x00\xFF\x00", "\xFF\xFF\x00\xFF\x00\x00\xFF\xFF",
351
+ "\xFF\xFF\x00\xFF\x00\xFF\x00\x00", "\xFF\xFF\x00\xFF\x00\xFF\x00\xFF",
352
+ "\xFF\xFF\x00\xFF\x00\xFF\xFF\x00", "\xFF\xFF\x00\xFF\x00\xFF\xFF\xFF",
353
+ "\xFF\xFF\x00\xFF\xFF\x00\x00\x00", "\xFF\xFF\x00\xFF\xFF\x00\x00\xFF",
354
+ "\xFF\xFF\x00\xFF\xFF\x00\xFF\x00", "\xFF\xFF\x00\xFF\xFF\x00\xFF\xFF",
355
+ "\xFF\xFF\x00\xFF\xFF\xFF\x00\x00", "\xFF\xFF\x00\xFF\xFF\xFF\x00\xFF",
356
+ "\xFF\xFF\x00\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\x00\xFF\xFF\xFF\xFF\xFF",
357
+ "\xFF\xFF\xFF\x00\x00\x00\x00\x00", "\xFF\xFF\xFF\x00\x00\x00\x00\xFF",
358
+ "\xFF\xFF\xFF\x00\x00\x00\xFF\x00", "\xFF\xFF\xFF\x00\x00\x00\xFF\xFF",
359
+ "\xFF\xFF\xFF\x00\x00\xFF\x00\x00", "\xFF\xFF\xFF\x00\x00\xFF\x00\xFF",
360
+ "\xFF\xFF\xFF\x00\x00\xFF\xFF\x00", "\xFF\xFF\xFF\x00\x00\xFF\xFF\xFF",
361
+ "\xFF\xFF\xFF\x00\xFF\x00\x00\x00", "\xFF\xFF\xFF\x00\xFF\x00\x00\xFF",
362
+ "\xFF\xFF\xFF\x00\xFF\x00\xFF\x00", "\xFF\xFF\xFF\x00\xFF\x00\xFF\xFF",
363
+ "\xFF\xFF\xFF\x00\xFF\xFF\x00\x00", "\xFF\xFF\xFF\x00\xFF\xFF\x00\xFF",
364
+ "\xFF\xFF\xFF\x00\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\x00\xFF\xFF\xFF\xFF",
365
+ "\xFF\xFF\xFF\xFF\x00\x00\x00\x00", "\xFF\xFF\xFF\xFF\x00\x00\x00\xFF",
366
+ "\xFF\xFF\xFF\xFF\x00\x00\xFF\x00", "\xFF\xFF\xFF\xFF\x00\x00\xFF\xFF",
367
+ "\xFF\xFF\xFF\xFF\x00\xFF\x00\x00", "\xFF\xFF\xFF\xFF\x00\xFF\x00\xFF",
368
+ "\xFF\xFF\xFF\xFF\x00\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\x00\xFF\xFF\xFF",
369
+ "\xFF\xFF\xFF\xFF\xFF\x00\x00\x00", "\xFF\xFF\xFF\xFF\xFF\x00\x00\xFF",
370
+ "\xFF\xFF\xFF\xFF\xFF\x00\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\x00\xFF\xFF",
371
+ "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\x00\xFF",
372
+ "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
373
+ );
374
+
375
+ /**
376
+ * IP mapping helper table.
377
+ *
378
+ * Indexing this table with each source byte performs the initial bit permutation.
379
+ *
380
+ * @var Array
381
+ * @access private
382
+ */
383
+ var $ipmap = array(
384
+ 0x00, 0x10, 0x01, 0x11, 0x20, 0x30, 0x21, 0x31,
385
+ 0x02, 0x12, 0x03, 0x13, 0x22, 0x32, 0x23, 0x33,
386
+ 0x40, 0x50, 0x41, 0x51, 0x60, 0x70, 0x61, 0x71,
387
+ 0x42, 0x52, 0x43, 0x53, 0x62, 0x72, 0x63, 0x73,
388
+ 0x04, 0x14, 0x05, 0x15, 0x24, 0x34, 0x25, 0x35,
389
+ 0x06, 0x16, 0x07, 0x17, 0x26, 0x36, 0x27, 0x37,
390
+ 0x44, 0x54, 0x45, 0x55, 0x64, 0x74, 0x65, 0x75,
391
+ 0x46, 0x56, 0x47, 0x57, 0x66, 0x76, 0x67, 0x77,
392
+ 0x80, 0x90, 0x81, 0x91, 0xA0, 0xB0, 0xA1, 0xB1,
393
+ 0x82, 0x92, 0x83, 0x93, 0xA2, 0xB2, 0xA3, 0xB3,
394
+ 0xC0, 0xD0, 0xC1, 0xD1, 0xE0, 0xF0, 0xE1, 0xF1,
395
+ 0xC2, 0xD2, 0xC3, 0xD3, 0xE2, 0xF2, 0xE3, 0xF3,
396
+ 0x84, 0x94, 0x85, 0x95, 0xA4, 0xB4, 0xA5, 0xB5,
397
+ 0x86, 0x96, 0x87, 0x97, 0xA6, 0xB6, 0xA7, 0xB7,
398
+ 0xC4, 0xD4, 0xC5, 0xD5, 0xE4, 0xF4, 0xE5, 0xF5,
399
+ 0xC6, 0xD6, 0xC7, 0xD7, 0xE6, 0xF6, 0xE7, 0xF7,
400
+ 0x08, 0x18, 0x09, 0x19, 0x28, 0x38, 0x29, 0x39,
401
+ 0x0A, 0x1A, 0x0B, 0x1B, 0x2A, 0x3A, 0x2B, 0x3B,
402
+ 0x48, 0x58, 0x49, 0x59, 0x68, 0x78, 0x69, 0x79,
403
+ 0x4A, 0x5A, 0x4B, 0x5B, 0x6A, 0x7A, 0x6B, 0x7B,
404
+ 0x0C, 0x1C, 0x0D, 0x1D, 0x2C, 0x3C, 0x2D, 0x3D,
405
+ 0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F,
406
+ 0x4C, 0x5C, 0x4D, 0x5D, 0x6C, 0x7C, 0x6D, 0x7D,
407
+ 0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F,
408
+ 0x88, 0x98, 0x89, 0x99, 0xA8, 0xB8, 0xA9, 0xB9,
409
+ 0x8A, 0x9A, 0x8B, 0x9B, 0xAA, 0xBA, 0xAB, 0xBB,
410
+ 0xC8, 0xD8, 0xC9, 0xD9, 0xE8, 0xF8, 0xE9, 0xF9,
411
+ 0xCA, 0xDA, 0xCB, 0xDB, 0xEA, 0xFA, 0xEB, 0xFB,
412
+ 0x8C, 0x9C, 0x8D, 0x9D, 0xAC, 0xBC, 0xAD, 0xBD,
413
+ 0x8E, 0x9E, 0x8F, 0x9F, 0xAE, 0xBE, 0xAF, 0xBF,
414
+ 0xCC, 0xDC, 0xCD, 0xDD, 0xEC, 0xFC, 0xED, 0xFD,
415
+ 0xCE, 0xDE, 0xCF, 0xDF, 0xEE, 0xFE, 0xEF, 0xFF
416
+ );
417
+
418
+ /**
419
+ * Inverse IP mapping helper table.
420
+ * Indexing this table with a byte value reverses the bit order.
421
+ *
422
+ * @var Array
423
+ * @access private
424
+ */
425
+ var $invipmap = array(
426
+ 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
427
+ 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
428
+ 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
429
+ 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
430
+ 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
431
+ 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
432
+ 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
433
+ 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
434
+ 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
435
+ 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
436
+ 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
437
+ 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
438
+ 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
439
+ 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
440
+ 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
441
+ 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
442
+ 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
443
+ 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
444
+ 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
445
+ 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
446
+ 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
447
+ 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
448
+ 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
449
+ 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
450
+ 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
451
+ 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
452
+ 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
453
+ 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
454
+ 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
455
+ 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
456
+ 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
457
+ 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
458
+ );
459
+
460
+ /**
461
+ * Pre-permuted S-box1
462
+ *
463
+ * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the
464
+ * P table: concatenation can then be replaced by exclusive ORs.
465
+ *
466
+ * @var Array
467
+ * @access private
468
+ */
469
+ var $sbox1 = array(
470
+ 0x00808200, 0x00000000, 0x00008000, 0x00808202,
471
+ 0x00808002, 0x00008202, 0x00000002, 0x00008000,
472
+ 0x00000200, 0x00808200, 0x00808202, 0x00000200,
473
+ 0x00800202, 0x00808002, 0x00800000, 0x00000002,
474
+ 0x00000202, 0x00800200, 0x00800200, 0x00008200,
475
+ 0x00008200, 0x00808000, 0x00808000, 0x00800202,
476
+ 0x00008002, 0x00800002, 0x00800002, 0x00008002,
477
+ 0x00000000, 0x00000202, 0x00008202, 0x00800000,
478
+ 0x00008000, 0x00808202, 0x00000002, 0x00808000,
479
+ 0x00808200, 0x00800000, 0x00800000, 0x00000200,
480
+ 0x00808002, 0x00008000, 0x00008200, 0x00800002,
481
+ 0x00000200, 0x00000002, 0x00800202, 0x00008202,
482
+ 0x00808202, 0x00008002, 0x00808000, 0x00800202,
483
+ 0x00800002, 0x00000202, 0x00008202, 0x00808200,
484
+ 0x00000202, 0x00800200, 0x00800200, 0x00000000,
485
+ 0x00008002, 0x00008200, 0x00000000, 0x00808002
486
+ );
487
+
488
+ /**
489
+ * Pre-permuted S-box2
490
+ *
491
+ * @var Array
492
+ * @access private
493
+ */
494
+ var $sbox2 = array(
495
+ 0x40084010, 0x40004000, 0x00004000, 0x00084010,
496
+ 0x00080000, 0x00000010, 0x40080010, 0x40004010,
497
+ 0x40000010, 0x40084010, 0x40084000, 0x40000000,
498
+ 0x40004000, 0x00080000, 0x00000010, 0x40080010,
499
+ 0x00084000, 0x00080010, 0x40004010, 0x00000000,
500
+ 0x40000000, 0x00004000, 0x00084010, 0x40080000,
501
+ 0x00080010, 0x40000010, 0x00000000, 0x00084000,
502
+ 0x00004010, 0x40084000, 0x40080000, 0x00004010,
503
+ 0x00000000, 0x00084010, 0x40080010, 0x00080000,
504
+ 0x40004010, 0x40080000, 0x40084000, 0x00004000,
505
+ 0x40080000, 0x40004000, 0x00000010, 0x40084010,
506
+ 0x00084010, 0x00000010, 0x00004000, 0x40000000,
507
+ 0x00004010, 0x40084000, 0x00080000, 0x40000010,
508
+ 0x00080010, 0x40004010, 0x40000010, 0x00080010,
509
+ 0x00084000, 0x00000000, 0x40004000, 0x00004010,
510
+ 0x40000000, 0x40080010, 0x40084010, 0x00084000
511
+ );
512
+
513
+ /**
514
+ * Pre-permuted S-box3
515
+ *
516
+ * @var Array
517
+ * @access private
518
+ */
519
+ var $sbox3 = array(
520
+ 0x00000104, 0x04010100, 0x00000000, 0x04010004,
521
+ 0x04000100, 0x00000000, 0x00010104, 0x04000100,
522
+ 0x00010004, 0x04000004, 0x04000004, 0x00010000,
523
+ 0x04010104, 0x00010004, 0x04010000, 0x00000104,
524
+ 0x04000000, 0x00000004, 0x04010100, 0x00000100,
525
+ 0x00010100, 0x04010000, 0x04010004, 0x00010104,
526
+ 0x04000104, 0x00010100, 0x00010000, 0x04000104,
527
+ 0x00000004, 0x04010104, 0x00000100, 0x04000000,
528
+ 0x04010100, 0x04000000, 0x00010004, 0x00000104,
529
+ 0x00010000, 0x04010100, 0x04000100, 0x00000000,
530
+ 0x00000100, 0x00010004, 0x04010104, 0x04000100,
531
+ 0x04000004, 0x00000100, 0x00000000, 0x04010004,
532
+ 0x04000104, 0x00010000, 0x04000000, 0x04010104,
533
+ 0x00000004, 0x00010104, 0x00010100, 0x04000004,
534
+ 0x04010000, 0x04000104, 0x00000104, 0x04010000,
535
+ 0x00010104, 0x00000004, 0x04010004, 0x00010100
536
+ );
537
+
538
+ /**
539
+ * Pre-permuted S-box4
540
+ *
541
+ * @var Array
542
+ * @access private
543
+ */
544
+ var $sbox4 = array(
545
+ 0x80401000, 0x80001040, 0x80001040, 0x00000040,
546
+ 0x00401040, 0x80400040, 0x80400000, 0x80001000,
547
+ 0x00000000, 0x00401000, 0x00401000, 0x80401040,
548
+ 0x80000040, 0x00000000, 0x00400040, 0x80400000,
549
+ 0x80000000, 0x00001000, 0x00400000, 0x80401000,
550
+ 0x00000040, 0x00400000, 0x80001000, 0x00001040,
551
+ 0x80400040, 0x80000000, 0x00001040, 0x00400040,
552
+ 0x00001000, 0x00401040, 0x80401040, 0x80000040,
553
+ 0x00400040, 0x80400000, 0x00401000, 0x80401040,
554
+ 0x80000040, 0x00000000, 0x00000000, 0x00401000,
555
+ 0x00001040, 0x00400040, 0x80400040, 0x80000000,
556
+ 0x80401000, 0x80001040, 0x80001040, 0x00000040,
557
+ 0x80401040, 0x80000040, 0x80000000, 0x00001000,
558
+ 0x80400000, 0x80001000, 0x00401040, 0x80400040,
559
+ 0x80001000, 0x00001040, 0x00400000, 0x80401000,
560
+ 0x00000040, 0x00400000, 0x00001000, 0x00401040
561
+ );
562
+
563
+ /**
564
+ * Pre-permuted S-box5
565
+ *
566
+ * @var Array
567
+ * @access private
568
+ */
569
+ var $sbox5 = array(
570
+ 0x00000080, 0x01040080, 0x01040000, 0x21000080,
571
+ 0x00040000, 0x00000080, 0x20000000, 0x01040000,
572
+ 0x20040080, 0x00040000, 0x01000080, 0x20040080,
573
+ 0x21000080, 0x21040000, 0x00040080, 0x20000000,
574
+ 0x01000000, 0x20040000, 0x20040000, 0x00000000,
575
+ 0x20000080, 0x21040080, 0x21040080, 0x01000080,
576
+ 0x21040000, 0x20000080, 0x00000000, 0x21000000,
577
+ 0x01040080, 0x01000000, 0x21000000, 0x00040080,
578
+ 0x00040000, 0x21000080, 0x00000080, 0x01000000,
579
+ 0x20000000, 0x01040000, 0x21000080, 0x20040080,
580
+ 0x01000080, 0x20000000, 0x21040000, 0x01040080,
581
+ 0x20040080, 0x00000080, 0x01000000, 0x21040000,
582
+ 0x21040080, 0x00040080, 0x21000000, 0x21040080,
583
+ 0x01040000, 0x00000000, 0x20040000, 0x21000000,
584
+ 0x00040080, 0x01000080, 0x20000080, 0x00040000,
585
+ 0x00000000, 0x20040000, 0x01040080, 0x20000080
586
+ );
587
+
588
+ /**
589
+ * Pre-permuted S-box6
590
+ *
591
+ * @var Array
592
+ * @access private
593
+ */
594
+ var $sbox6 = array(
595
+ 0x10000008, 0x10200000, 0x00002000, 0x10202008,
596
+ 0x10200000, 0x00000008, 0x10202008, 0x00200000,
597
+ 0x10002000, 0x00202008, 0x00200000, 0x10000008,
598
+ 0x00200008, 0x10002000, 0x10000000, 0x00002008,
599
+ 0x00000000, 0x00200008, 0x10002008, 0x00002000,
600
+ 0x00202000, 0x10002008, 0x00000008, 0x10200008,
601
+ 0x10200008, 0x00000000, 0x00202008, 0x10202000,
602
+ 0x00002008, 0x00202000, 0x10202000, 0x10000000,
603
+ 0x10002000, 0x00000008, 0x10200008, 0x00202000,
604
+ 0x10202008, 0x00200000, 0x00002008, 0x10000008,
605
+ 0x00200000, 0x10002000, 0x10000000, 0x00002008,
606
+ 0x10000008, 0x10202008, 0x00202000, 0x10200000,
607
+ 0x00202008, 0x10202000, 0x00000000, 0x10200008,
608
+ 0x00000008, 0x00002000, 0x10200000, 0x00202008,
609
+ 0x00002000, 0x00200008, 0x10002008, 0x00000000,
610
+ 0x10202000, 0x10000000, 0x00200008, 0x10002008
611
+ );
612
+
613
+ /**
614
+ * Pre-permuted S-box7
615
+ *
616
+ * @var Array
617
+ * @access private
618
+ */
619
+ var $sbox7 = array(
620
+ 0x00100000, 0x02100001, 0x02000401, 0x00000000,
621
+ 0x00000400, 0x02000401, 0x00100401, 0x02100400,
622
+ 0x02100401, 0x00100000, 0x00000000, 0x02000001,
623
+ 0x00000001, 0x02000000, 0x02100001, 0x00000401,
624
+ 0x02000400, 0x00100401, 0x00100001, 0x02000400,
625
+ 0x02000001, 0x02100000, 0x02100400, 0x00100001,
626
+ 0x02100000, 0x00000400, 0x00000401, 0x02100401,
627
+ 0x00100400, 0x00000001, 0x02000000, 0x00100400,
628
+ 0x02000000, 0x00100400, 0x00100000, 0x02000401,
629
+ 0x02000401, 0x02100001, 0x02100001, 0x00000001,
630
+ 0x00100001, 0x02000000, 0x02000400, 0x00100000,
631
+ 0x02100400, 0x00000401, 0x00100401, 0x02100400,
632
+ 0x00000401, 0x02000001, 0x02100401, 0x02100000,
633
+ 0x00100400, 0x00000000, 0x00000001, 0x02100401,
634
+ 0x00000000, 0x00100401, 0x02100000, 0x00000400,
635
+ 0x02000001, 0x02000400, 0x00000400, 0x00100001
636
+ );
637
+
638
+ /**
639
+ * Pre-permuted S-box8
640
+ *
641
+ * @var Array
642
+ * @access private
643
+ */
644
+ var $sbox8 = array(
645
+ 0x08000820, 0x00000800, 0x00020000, 0x08020820,
646
+ 0x08000000, 0x08000820, 0x00000020, 0x08000000,
647
+ 0x00020020, 0x08020000, 0x08020820, 0x00020800,
648
+ 0x08020800, 0x00020820, 0x00000800, 0x00000020,
649
+ 0x08020000, 0x08000020, 0x08000800, 0x00000820,
650
+ 0x00020800, 0x00020020, 0x08020020, 0x08020800,
651
+ 0x00000820, 0x00000000, 0x00000000, 0x08020020,
652
+ 0x08000020, 0x08000800, 0x00020820, 0x00020000,
653
+ 0x00020820, 0x00020000, 0x08020800, 0x00000800,
654
+ 0x00000020, 0x08020020, 0x00000800, 0x00020820,
655
+ 0x08000800, 0x00000020, 0x08000020, 0x08020000,
656
+ 0x08020020, 0x08000000, 0x00020000, 0x08000820,
657
+ 0x00000000, 0x08020820, 0x00020020, 0x08000020,
658
+ 0x08020000, 0x08000800, 0x08000820, 0x00000000,
659
+ 0x08020820, 0x00020800, 0x00020800, 0x00000820,
660
+ 0x00000820, 0x00020020, 0x08000000, 0x08020800
661
+ );
662
+
663
+ /**
664
+ * Default Constructor.
665
+ *
666
+ * Determines whether or not the mcrypt extension should be used.
667
+ *
668
+ * $mode could be:
669
+ *
670
+ * - CRYPT_DES_MODE_ECB
671
+ *
672
+ * - CRYPT_DES_MODE_CBC
673
+ *
674
+ * - CRYPT_DES_MODE_CTR
675
+ *
676
+ * - CRYPT_DES_MODE_CFB
677
+ *
678
+ * - CRYPT_DES_MODE_OFB
679
+ *
680
+ * If not explictly set, CRYPT_DES_MODE_CBC will be used.
681
+ *
682
+ * @see Crypt_Base::Crypt_Base()
683
+ * @param optional Integer $mode
684
+ * @access public
685
+ */
686
+ function Crypt_DES($mode = CRYPT_DES_MODE_CBC)
687
+ {
688
+ parent::Crypt_Base($mode);
689
+ }
690
+
691
+ /**
692
+ * Sets the key.
693
+ *
694
+ * Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we
695
+ * only use the first eight, if $key has more then eight characters in it, and pad $key with the
696
+ * null byte if it is less then eight characters long.
697
+ *
698
+ * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
699
+ *
700
+ * If the key is not explicitly set, it'll be assumed to be all zero's.
701
+ *
702
+ * @see Crypt_Base::setKey()
703
+ * @access public
704
+ * @param String $key
705
+ */
706
+ function setKey($key)
707
+ {
708
+ // We check/cut here only up to max length of the key.
709
+ // Key padding to the proper length will be done in _setupKey()
710
+ if (strlen($key) > $this->key_size_max) {
711
+ $key = substr($key, 0, $this->key_size_max);
712
+ }
713
+
714
+ // Sets the key
715
+ parent::setKey($key);
716
+ }
717
+
718
+ /**
719
+ * Encrypts a block
720
+ *
721
+ * @see Crypt_Base::_encryptBlock()
722
+ * @see Crypt_Base::encrypt()
723
+ * @see Crypt_DES::encrypt()
724
+ * @access private
725
+ * @param String $in
726
+ * @return String
727
+ */
728
+ function _encryptBlock($in)
729
+ {
730
+ return $this->_processBlock($in, CRYPT_DES_ENCRYPT);
731
+ }
732
+
733
+ /**
734
+ * Decrypts a block
735
+ *
736
+ * @see Crypt_Base::_decryptBlock()
737
+ * @see Crypt_Base::decrypt()
738
+ * @see Crypt_DES::decrypt()
739
+ * @access private
740
+ * @param String $in
741
+ * @return String
742
+ */
743
+ function _decryptBlock($in)
744
+ {
745
+ return $this->_processBlock($in, CRYPT_DES_DECRYPT);
746
+ }
747
+
748
+ /**
749
+ * Encrypts or decrypts a 64-bit block
750
+ *
751
+ * $mode should be either CRYPT_DES_ENCRYPT or CRYPT_DES_DECRYPT. See
752
+ * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general
753
+ * idea of what this function does.
754
+ *
755
+ * @see Crypt_DES::_encryptBlock()
756
+ * @see Crypt_DES::_decryptBlock()
757
+ * @access private
758
+ * @param String $block
759
+ * @param Integer $mode
760
+ * @return String
761
+ */
762
+ function _processBlock($block, $mode)
763
+ {
764
+ static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip;
765
+ if (!$sbox1) {
766
+ $sbox1 = array_map("intval", $this->sbox1);
767
+ $sbox2 = array_map("intval", $this->sbox2);
768
+ $sbox3 = array_map("intval", $this->sbox3);
769
+ $sbox4 = array_map("intval", $this->sbox4);
770
+ $sbox5 = array_map("intval", $this->sbox5);
771
+ $sbox6 = array_map("intval", $this->sbox6);
772
+ $sbox7 = array_map("intval", $this->sbox7);
773
+ $sbox8 = array_map("intval", $this->sbox8);
774
+ /* Merge $shuffle with $[inv]ipmap */
775
+ for ($i = 0; $i < 256; ++$i) {
776
+ $shuffleip[] = $this->shuffle[$this->ipmap[$i]];
777
+ $shuffleinvip[] = $this->shuffle[$this->invipmap[$i]];
778
+ }
779
+ }
780
+
781
+ $keys = $this->keys[$mode];
782
+ $ki = -1;
783
+
784
+ // Do the initial IP permutation.
785
+ $t = unpack('Nl/Nr', $block);
786
+ list($l, $r) = array($t['l'], $t['r']);
787
+ $block = ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
788
+ ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
789
+ ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
790
+ ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
791
+ ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
792
+ ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
793
+ ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
794
+ ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01");
795
+
796
+ // Extract L0 and R0.
797
+ $t = unpack('Nl/Nr', $block);
798
+ list($l, $r) = array($t['l'], $t['r']);
799
+
800
+ for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) {
801
+ // Perform the 16 steps.
802
+ for ($i = 0; $i < 16; $i++) {
803
+ // start of "the Feistel (F) function" - see the following URL:
804
+ // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png
805
+ // Merge key schedule.
806
+ $b1 = (($r >> 3) & 0x1FFFFFFF) ^ ($r << 29) ^ $keys[++$ki];
807
+ $b2 = (($r >> 31) & 0x00000001) ^ ($r << 1) ^ $keys[++$ki];
808
+
809
+ // S-box indexing.
810
+ $t = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^
811
+ $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^
812
+ $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^
813
+ $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ $l;
814
+ // end of "the Feistel (F) function"
815
+
816
+ $l = $r;
817
+ $r = $t;
818
+ }
819
+
820
+ // Last step should not permute L & R.
821
+ $t = $l;
822
+ $l = $r;
823
+ $r = $t;
824
+ }
825
+
826
+ // Perform the inverse IP permutation.
827
+ return ($shuffleinvip[($r >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
828
+ ($shuffleinvip[($l >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
829
+ ($shuffleinvip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
830
+ ($shuffleinvip[($l >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
831
+ ($shuffleinvip[($r >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
832
+ ($shuffleinvip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
833
+ ($shuffleinvip[ $r & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
834
+ ($shuffleinvip[ $l & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01");
835
+ }
836
+
837
+ /**
838
+ * Creates the key schedule
839
+ *
840
+ * @see Crypt_Base::_setupKey()
841
+ * @access private
842
+ */
843
+ function _setupKey()
844
+ {
845
+ if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->des_rounds === $this->kl['des_rounds']) {
846
+ // already expanded
847
+ return;
848
+ }
849
+ $this->kl = array('key' => $this->key, 'des_rounds' => $this->des_rounds);
850
+
851
+ static $shifts = array( // number of key bits shifted per round
852
+ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
853
+ );
854
+
855
+ static $pc1map = array(
856
+ 0x00, 0x00, 0x08, 0x08, 0x04, 0x04, 0x0C, 0x0C,
857
+ 0x02, 0x02, 0x0A, 0x0A, 0x06, 0x06, 0x0E, 0x0E,
858
+ 0x10, 0x10, 0x18, 0x18, 0x14, 0x14, 0x1C, 0x1C,
859
+ 0x12, 0x12, 0x1A, 0x1A, 0x16, 0x16, 0x1E, 0x1E,
860
+ 0x20, 0x20, 0x28, 0x28, 0x24, 0x24, 0x2C, 0x2C,
861
+ 0x22, 0x22, 0x2A, 0x2A, 0x26, 0x26, 0x2E, 0x2E,
862
+ 0x30, 0x30, 0x38, 0x38, 0x34, 0x34, 0x3C, 0x3C,
863
+ 0x32, 0x32, 0x3A, 0x3A, 0x36, 0x36, 0x3E, 0x3E,
864
+ 0x40, 0x40, 0x48, 0x48, 0x44, 0x44, 0x4C, 0x4C,
865
+ 0x42, 0x42, 0x4A, 0x4A, 0x46, 0x46, 0x4E, 0x4E,
866
+ 0x50, 0x50, 0x58, 0x58, 0x54, 0x54, 0x5C, 0x5C,
867
+ 0x52, 0x52, 0x5A, 0x5A, 0x56, 0x56, 0x5E, 0x5E,
868
+ 0x60, 0x60, 0x68, 0x68, 0x64, 0x64, 0x6C, 0x6C,
869
+ 0x62, 0x62, 0x6A, 0x6A, 0x66, 0x66, 0x6E, 0x6E,
870
+ 0x70, 0x70, 0x78, 0x78, 0x74, 0x74, 0x7C, 0x7C,
871
+ 0x72, 0x72, 0x7A, 0x7A, 0x76, 0x76, 0x7E, 0x7E,
872
+ 0x80, 0x80, 0x88, 0x88, 0x84, 0x84, 0x8C, 0x8C,
873
+ 0x82, 0x82, 0x8A, 0x8A, 0x86, 0x86, 0x8E, 0x8E,
874
+ 0x90, 0x90, 0x98, 0x98, 0x94, 0x94, 0x9C, 0x9C,
875
+ 0x92, 0x92, 0x9A, 0x9A, 0x96, 0x96, 0x9E, 0x9E,
876
+ 0xA0, 0xA0, 0xA8, 0xA8, 0xA4, 0xA4, 0xAC, 0xAC,
877
+ 0xA2, 0xA2, 0xAA, 0xAA, 0xA6, 0xA6, 0xAE, 0xAE,
878
+ 0xB0, 0xB0, 0xB8, 0xB8, 0xB4, 0xB4, 0xBC, 0xBC,
879
+ 0xB2, 0xB2, 0xBA, 0xBA, 0xB6, 0xB6, 0xBE, 0xBE,
880
+ 0xC0, 0xC0, 0xC8, 0xC8, 0xC4, 0xC4, 0xCC, 0xCC,
881
+ 0xC2, 0xC2, 0xCA, 0xCA, 0xC6, 0xC6, 0xCE, 0xCE,
882
+ 0xD0, 0xD0, 0xD8, 0xD8, 0xD4, 0xD4, 0xDC, 0xDC,
883
+ 0xD2, 0xD2, 0xDA, 0xDA, 0xD6, 0xD6, 0xDE, 0xDE,
884
+ 0xE0, 0xE0, 0xE8, 0xE8, 0xE4, 0xE4, 0xEC, 0xEC,
885
+ 0xE2, 0xE2, 0xEA, 0xEA, 0xE6, 0xE6, 0xEE, 0xEE,
886
+ 0xF0, 0xF0, 0xF8, 0xF8, 0xF4, 0xF4, 0xFC, 0xFC,
887
+ 0xF2, 0xF2, 0xFA, 0xFA, 0xF6, 0xF6, 0xFE, 0xFE
888
+ );
889
+
890
+ // Mapping tables for the PC-2 transformation.
891
+ static $pc2mapc1 = array(
892
+ 0x00000000, 0x00000400, 0x00200000, 0x00200400,
893
+ 0x00000001, 0x00000401, 0x00200001, 0x00200401,
894
+ 0x02000000, 0x02000400, 0x02200000, 0x02200400,
895
+ 0x02000001, 0x02000401, 0x02200001, 0x02200401
896
+ );
897
+ static $pc2mapc2 = array(
898
+ 0x00000000, 0x00000800, 0x08000000, 0x08000800,
899
+ 0x00010000, 0x00010800, 0x08010000, 0x08010800,
900
+ 0x00000000, 0x00000800, 0x08000000, 0x08000800,
901
+ 0x00010000, 0x00010800, 0x08010000, 0x08010800,
902
+ 0x00000100, 0x00000900, 0x08000100, 0x08000900,
903
+ 0x00010100, 0x00010900, 0x08010100, 0x08010900,
904
+ 0x00000100, 0x00000900, 0x08000100, 0x08000900,
905
+ 0x00010100, 0x00010900, 0x08010100, 0x08010900,
906
+ 0x00000010, 0x00000810, 0x08000010, 0x08000810,
907
+ 0x00010010, 0x00010810, 0x08010010, 0x08010810,
908
+ 0x00000010, 0x00000810, 0x08000010, 0x08000810,
909
+ 0x00010010, 0x00010810, 0x08010010, 0x08010810,
910
+ 0x00000110, 0x00000910, 0x08000110, 0x08000910,
911
+ 0x00010110, 0x00010910, 0x08010110, 0x08010910,
912
+ 0x00000110, 0x00000910, 0x08000110, 0x08000910,
913
+ 0x00010110, 0x00010910, 0x08010110, 0x08010910,
914
+ 0x00040000, 0x00040800, 0x08040000, 0x08040800,
915
+ 0x00050000, 0x00050800, 0x08050000, 0x08050800,
916
+ 0x00040000, 0x00040800, 0x08040000, 0x08040800,
917
+ 0x00050000, 0x00050800, 0x08050000, 0x08050800,
918
+ 0x00040100, 0x00040900, 0x08040100, 0x08040900,
919
+ 0x00050100, 0x00050900, 0x08050100, 0x08050900,
920
+ 0x00040100, 0x00040900, 0x08040100, 0x08040900,
921
+ 0x00050100, 0x00050900, 0x08050100, 0x08050900,
922
+ 0x00040010, 0x00040810, 0x08040010, 0x08040810,
923
+ 0x00050010, 0x00050810, 0x08050010, 0x08050810,
924
+ 0x00040010, 0x00040810, 0x08040010, 0x08040810,
925
+ 0x00050010, 0x00050810, 0x08050010, 0x08050810,
926
+ 0x00040110, 0x00040910, 0x08040110, 0x08040910,
927
+ 0x00050110, 0x00050910, 0x08050110, 0x08050910,
928
+ 0x00040110, 0x00040910, 0x08040110, 0x08040910,
929
+ 0x00050110, 0x00050910, 0x08050110, 0x08050910,
930
+ 0x01000000, 0x01000800, 0x09000000, 0x09000800,
931
+ 0x01010000, 0x01010800, 0x09010000, 0x09010800,
932
+ 0x01000000, 0x01000800, 0x09000000, 0x09000800,
933
+ 0x01010000, 0x01010800, 0x09010000, 0x09010800,
934
+ 0x01000100, 0x01000900, 0x09000100, 0x09000900,
935
+ 0x01010100, 0x01010900, 0x09010100, 0x09010900,
936
+ 0x01000100, 0x01000900, 0x09000100, 0x09000900,
937
+ 0x01010100, 0x01010900, 0x09010100, 0x09010900,
938
+ 0x01000010, 0x01000810, 0x09000010, 0x09000810,
939
+ 0x01010010, 0x01010810, 0x09010010, 0x09010810,
940
+ 0x01000010, 0x01000810, 0x09000010, 0x09000810,
941
+ 0x01010010, 0x01010810, 0x09010010, 0x09010810,
942
+ 0x01000110, 0x01000910, 0x09000110, 0x09000910,
943
+ 0x01010110, 0x01010910, 0x09010110, 0x09010910,
944
+ 0x01000110, 0x01000910, 0x09000110, 0x09000910,
945
+ 0x01010110, 0x01010910, 0x09010110, 0x09010910,
946
+ 0x01040000, 0x01040800, 0x09040000, 0x09040800,
947
+ 0x01050000, 0x01050800, 0x09050000, 0x09050800,
948
+ 0x01040000, 0x01040800, 0x09040000, 0x09040800,
949
+ 0x01050000, 0x01050800, 0x09050000, 0x09050800,
950
+ 0x01040100, 0x01040900, 0x09040100, 0x09040900,
951
+ 0x01050100, 0x01050900, 0x09050100, 0x09050900,
952
+ 0x01040100, 0x01040900, 0x09040100, 0x09040900,
953
+ 0x01050100, 0x01050900, 0x09050100, 0x09050900,
954
+ 0x01040010, 0x01040810, 0x09040010, 0x09040810,
955
+ 0x01050010, 0x01050810, 0x09050010, 0x09050810,
956
+ 0x01040010, 0x01040810, 0x09040010, 0x09040810,
957
+ 0x01050010, 0x01050810, 0x09050010, 0x09050810,
958
+ 0x01040110, 0x01040910, 0x09040110, 0x09040910,
959
+ 0x01050110, 0x01050910, 0x09050110, 0x09050910,
960
+ 0x01040110, 0x01040910, 0x09040110, 0x09040910,
961
+ 0x01050110, 0x01050910, 0x09050110, 0x09050910
962
+ );
963
+ static $pc2mapc3 = array(
964
+ 0x00000000, 0x00000004, 0x00001000, 0x00001004,
965
+ 0x00000000, 0x00000004, 0x00001000, 0x00001004,
966
+ 0x10000000, 0x10000004, 0x10001000, 0x10001004,
967
+ 0x10000000, 0x10000004, 0x10001000, 0x10001004,
968
+ 0x00000020, 0x00000024, 0x00001020, 0x00001024,
969
+ 0x00000020, 0x00000024, 0x00001020, 0x00001024,
970
+ 0x10000020, 0x10000024, 0x10001020, 0x10001024,
971
+ 0x10000020, 0x10000024, 0x10001020, 0x10001024,
972
+ 0x00080000, 0x00080004, 0x00081000, 0x00081004,
973
+ 0x00080000, 0x00080004, 0x00081000, 0x00081004,
974
+ 0x10080000, 0x10080004, 0x10081000, 0x10081004,
975
+ 0x10080000, 0x10080004, 0x10081000, 0x10081004,
976
+ 0x00080020, 0x00080024, 0x00081020, 0x00081024,
977
+ 0x00080020, 0x00080024, 0x00081020, 0x00081024,
978
+ 0x10080020, 0x10080024, 0x10081020, 0x10081024,
979
+ 0x10080020, 0x10080024, 0x10081020, 0x10081024,
980
+ 0x20000000, 0x20000004, 0x20001000, 0x20001004,
981
+ 0x20000000, 0x20000004, 0x20001000, 0x20001004,
982
+ 0x30000000, 0x30000004, 0x30001000, 0x30001004,
983
+ 0x30000000, 0x30000004, 0x30001000, 0x30001004,
984
+ 0x20000020, 0x20000024, 0x20001020, 0x20001024,
985
+ 0x20000020, 0x20000024, 0x20001020, 0x20001024,
986
+ 0x30000020, 0x30000024, 0x30001020, 0x30001024,
987
+ 0x30000020, 0x30000024, 0x30001020, 0x30001024,
988
+ 0x20080000, 0x20080004, 0x20081000, 0x20081004,
989
+ 0x20080000, 0x20080004, 0x20081000, 0x20081004,
990
+ 0x30080000, 0x30080004, 0x30081000, 0x30081004,
991
+ 0x30080000, 0x30080004, 0x30081000, 0x30081004,
992
+ 0x20080020, 0x20080024, 0x20081020, 0x20081024,
993
+ 0x20080020, 0x20080024, 0x20081020, 0x20081024,
994
+ 0x30080020, 0x30080024, 0x30081020, 0x30081024,
995
+ 0x30080020, 0x30080024, 0x30081020, 0x30081024,
996
+ 0x00000002, 0x00000006, 0x00001002, 0x00001006,
997
+ 0x00000002, 0x00000006, 0x00001002, 0x00001006,
998
+ 0x10000002, 0x10000006, 0x10001002, 0x10001006,
999
+ 0x10000002, 0x10000006, 0x10001002, 0x10001006,
1000
+ 0x00000022, 0x00000026, 0x00001022, 0x00001026,
1001
+ 0x00000022, 0x00000026, 0x00001022, 0x00001026,
1002
+ 0x10000022, 0x10000026, 0x10001022, 0x10001026,
1003
+ 0x10000022, 0x10000026, 0x10001022, 0x10001026,
1004
+ 0x00080002, 0x00080006, 0x00081002, 0x00081006,
1005
+ 0x00080002, 0x00080006, 0x00081002, 0x00081006,
1006
+ 0x10080002, 0x10080006, 0x10081002, 0x10081006,
1007
+ 0x10080002, 0x10080006, 0x10081002, 0x10081006,
1008
+ 0x00080022, 0x00080026, 0x00081022, 0x00081026,
1009
+ 0x00080022, 0x00080026, 0x00081022, 0x00081026,
1010
+ 0x10080022, 0x10080026, 0x10081022, 0x10081026,
1011
+ 0x10080022, 0x10080026, 0x10081022, 0x10081026,
1012
+ 0x20000002, 0x20000006, 0x20001002, 0x20001006,
1013
+ 0x20000002, 0x20000006, 0x20001002, 0x20001006,
1014
+ 0x30000002, 0x30000006, 0x30001002, 0x30001006,
1015
+ 0x30000002, 0x30000006, 0x30001002, 0x30001006,
1016
+ 0x20000022, 0x20000026, 0x20001022, 0x20001026,
1017
+ 0x20000022, 0x20000026, 0x20001022, 0x20001026,
1018
+ 0x30000022, 0x30000026, 0x30001022, 0x30001026,
1019
+ 0x30000022, 0x30000026, 0x30001022, 0x30001026,
1020
+ 0x20080002, 0x20080006, 0x20081002, 0x20081006,
1021
+ 0x20080002, 0x20080006, 0x20081002, 0x20081006,
1022
+ 0x30080002, 0x30080006, 0x30081002, 0x30081006,
1023
+ 0x30080002, 0x30080006, 0x30081002, 0x30081006,
1024
+ 0x20080022, 0x20080026, 0x20081022, 0x20081026,
1025
+ 0x20080022, 0x20080026, 0x20081022, 0x20081026,
1026
+ 0x30080022, 0x30080026, 0x30081022, 0x30081026,
1027
+ 0x30080022, 0x30080026, 0x30081022, 0x30081026
1028
+ );
1029
+ static $pc2mapc4 = array(
1030
+ 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1031
+ 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1032
+ 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1033
+ 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1034
+ 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1035
+ 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1036
+ 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1037
+ 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1038
+ 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1039
+ 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1040
+ 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1041
+ 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1042
+ 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1043
+ 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1044
+ 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1045
+ 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1046
+ 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1047
+ 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1048
+ 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1049
+ 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1050
+ 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1051
+ 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1052
+ 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1053
+ 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1054
+ 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1055
+ 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1056
+ 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1057
+ 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1058
+ 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1059
+ 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1060
+ 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1061
+ 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1062
+ 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1063
+ 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1064
+ 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1065
+ 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1066
+ 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1067
+ 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1068
+ 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1069
+ 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1070
+ 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1071
+ 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1072
+ 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1073
+ 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1074
+ 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1075
+ 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1076
+ 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1077
+ 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1078
+ 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1079
+ 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1080
+ 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1081
+ 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1082
+ 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1083
+ 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1084
+ 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1085
+ 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1086
+ 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1087
+ 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1088
+ 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1089
+ 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1090
+ 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1091
+ 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1092
+ 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1093
+ 0x04022200, 0x04122200, 0x04022208, 0x04122208
1094
+ );
1095
+ static $pc2mapd1 = array(
1096
+ 0x00000000, 0x00000001, 0x08000000, 0x08000001,
1097
+ 0x00200000, 0x00200001, 0x08200000, 0x08200001,
1098
+ 0x00000002, 0x00000003, 0x08000002, 0x08000003,
1099
+ 0x00200002, 0x00200003, 0x08200002, 0x08200003
1100
+ );
1101
+ static $pc2mapd2 = array(
1102
+ 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1103
+ 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1104
+ 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1105
+ 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1106
+ 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1107
+ 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1108
+ 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1109
+ 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1110
+ 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1111
+ 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1112
+ 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1113
+ 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1114
+ 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1115
+ 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1116
+ 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1117
+ 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1118
+ 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1119
+ 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1120
+ 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1121
+ 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1122
+ 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1123
+ 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1124
+ 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1125
+ 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1126
+ 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1127
+ 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1128
+ 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1129
+ 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1130
+ 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1131
+ 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1132
+ 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1133
+ 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1134
+ 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1135
+ 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1136
+ 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1137
+ 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1138
+ 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1139
+ 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1140
+ 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1141
+ 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1142
+ 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1143
+ 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1144
+ 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1145
+ 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1146
+ 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1147
+ 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1148
+ 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1149
+ 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1150
+ 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1151
+ 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1152
+ 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1153
+ 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1154
+ 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1155
+ 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1156
+ 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1157
+ 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1158
+ 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1159
+ 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1160
+ 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1161
+ 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1162
+ 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1163
+ 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1164
+ 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1165
+ 0x04020204, 0x04120204, 0x04020A04, 0x04120A04
1166
+ );
1167
+ static $pc2mapd3 = array(
1168
+ 0x00000000, 0x00010000, 0x02000000, 0x02010000,
1169
+ 0x00000020, 0x00010020, 0x02000020, 0x02010020,
1170
+ 0x00040000, 0x00050000, 0x02040000, 0x02050000,
1171
+ 0x00040020, 0x00050020, 0x02040020, 0x02050020,
1172
+ 0x00002000, 0x00012000, 0x02002000, 0x02012000,
1173
+ 0x00002020, 0x00012020, 0x02002020, 0x02012020,
1174
+ 0x00042000, 0x00052000, 0x02042000, 0x02052000,
1175
+ 0x00042020, 0x00052020, 0x02042020, 0x02052020,
1176
+ 0x00000000, 0x00010000, 0x02000000, 0x02010000,
1177
+ 0x00000020, 0x00010020, 0x02000020, 0x02010020,
1178
+ 0x00040000, 0x00050000, 0x02040000, 0x02050000,
1179
+ 0x00040020, 0x00050020, 0x02040020, 0x02050020,
1180
+ 0x00002000, 0x00012000, 0x02002000, 0x02012000,
1181
+ 0x00002020, 0x00012020, 0x02002020, 0x02012020,
1182
+ 0x00042000, 0x00052000, 0x02042000, 0x02052000,
1183
+ 0x00042020, 0x00052020, 0x02042020, 0x02052020,
1184
+ 0x00000010, 0x00010010, 0x02000010, 0x02010010,
1185
+ 0x00000030, 0x00010030, 0x02000030, 0x02010030,
1186
+ 0x00040010, 0x00050010, 0x02040010, 0x02050010,
1187
+ 0x00040030, 0x00050030, 0x02040030, 0x02050030,
1188
+ 0x00002010, 0x00012010, 0x02002010, 0x02012010,
1189
+ 0x00002030, 0x00012030, 0x02002030, 0x02012030,
1190
+ 0x00042010, 0x00052010, 0x02042010, 0x02052010,
1191
+ 0x00042030, 0x00052030, 0x02042030, 0x02052030,
1192
+ 0x00000010, 0x00010010, 0x02000010, 0x02010010,
1193
+ 0x00000030, 0x00010030, 0x02000030, 0x02010030,
1194
+ 0x00040010, 0x00050010, 0x02040010, 0x02050010,
1195
+ 0x00040030, 0x00050030, 0x02040030, 0x02050030,
1196
+ 0x00002010, 0x00012010, 0x02002010, 0x02012010,
1197
+ 0x00002030, 0x00012030, 0x02002030, 0x02012030,
1198
+ 0x00042010, 0x00052010, 0x02042010, 0x02052010,
1199
+ 0x00042030, 0x00052030, 0x02042030, 0x02052030,
1200
+ 0x20000000, 0x20010000, 0x22000000, 0x22010000,
1201
+ 0x20000020, 0x20010020, 0x22000020, 0x22010020,
1202
+ 0x20040000, 0x20050000, 0x22040000, 0x22050000,
1203
+ 0x20040020, 0x20050020, 0x22040020, 0x22050020,
1204
+ 0x20002000, 0x20012000, 0x22002000, 0x22012000,
1205
+ 0x20002020, 0x20012020, 0x22002020, 0x22012020,
1206
+ 0x20042000, 0x20052000, 0x22042000, 0x22052000,
1207
+ 0x20042020, 0x20052020, 0x22042020, 0x22052020,
1208
+ 0x20000000, 0x20010000, 0x22000000, 0x22010000,
1209
+ 0x20000020, 0x20010020, 0x22000020, 0x22010020,
1210
+ 0x20040000, 0x20050000, 0x22040000, 0x22050000,
1211
+ 0x20040020, 0x20050020, 0x22040020, 0x22050020,
1212
+ 0x20002000, 0x20012000, 0x22002000, 0x22012000,
1213
+ 0x20002020, 0x20012020, 0x22002020, 0x22012020,
1214
+ 0x20042000, 0x20052000, 0x22042000, 0x22052000,
1215
+ 0x20042020, 0x20052020, 0x22042020, 0x22052020,
1216
+ 0x20000010, 0x20010010, 0x22000010, 0x22010010,
1217
+ 0x20000030, 0x20010030, 0x22000030, 0x22010030,
1218
+ 0x20040010, 0x20050010, 0x22040010, 0x22050010,
1219
+ 0x20040030, 0x20050030, 0x22040030, 0x22050030,
1220
+ 0x20002010, 0x20012010, 0x22002010, 0x22012010,
1221
+ 0x20002030, 0x20012030, 0x22002030, 0x22012030,
1222
+ 0x20042010, 0x20052010, 0x22042010, 0x22052010,
1223
+ 0x20042030, 0x20052030, 0x22042030, 0x22052030,
1224
+ 0x20000010, 0x20010010, 0x22000010, 0x22010010,
1225
+ 0x20000030, 0x20010030, 0x22000030, 0x22010030,
1226
+ 0x20040010, 0x20050010, 0x22040010, 0x22050010,
1227
+ 0x20040030, 0x20050030, 0x22040030, 0x22050030,
1228
+ 0x20002010, 0x20012010, 0x22002010, 0x22012010,
1229
+ 0x20002030, 0x20012030, 0x22002030, 0x22012030,
1230
+ 0x20042010, 0x20052010, 0x22042010, 0x22052010,
1231
+ 0x20042030, 0x20052030, 0x22042030, 0x22052030
1232
+ );
1233
+ static $pc2mapd4 = array(
1234
+ 0x00000000, 0x00000400, 0x01000000, 0x01000400,
1235
+ 0x00000000, 0x00000400, 0x01000000, 0x01000400,
1236
+ 0x00000100, 0x00000500, 0x01000100, 0x01000500,
1237
+ 0x00000100, 0x00000500, 0x01000100, 0x01000500,
1238
+ 0x10000000, 0x10000400, 0x11000000, 0x11000400,
1239
+ 0x10000000, 0x10000400, 0x11000000, 0x11000400,
1240
+ 0x10000100, 0x10000500, 0x11000100, 0x11000500,
1241
+ 0x10000100, 0x10000500, 0x11000100, 0x11000500,
1242
+ 0x00080000, 0x00080400, 0x01080000, 0x01080400,
1243
+ 0x00080000, 0x00080400, 0x01080000, 0x01080400,
1244
+ 0x00080100, 0x00080500, 0x01080100, 0x01080500,
1245
+ 0x00080100, 0x00080500, 0x01080100, 0x01080500,
1246
+ 0x10080000, 0x10080400, 0x11080000, 0x11080400,
1247
+ 0x10080000, 0x10080400, 0x11080000, 0x11080400,
1248
+ 0x10080100, 0x10080500, 0x11080100, 0x11080500,
1249
+ 0x10080100, 0x10080500, 0x11080100, 0x11080500,
1250
+ 0x00000008, 0x00000408, 0x01000008, 0x01000408,
1251
+ 0x00000008, 0x00000408, 0x01000008, 0x01000408,
1252
+ 0x00000108, 0x00000508, 0x01000108, 0x01000508,
1253
+ 0x00000108, 0x00000508, 0x01000108, 0x01000508,
1254
+ 0x10000008, 0x10000408, 0x11000008, 0x11000408,
1255
+ 0x10000008, 0x10000408, 0x11000008, 0x11000408,
1256
+ 0x10000108, 0x10000508, 0x11000108, 0x11000508,
1257
+ 0x10000108, 0x10000508, 0x11000108, 0x11000508,
1258
+ 0x00080008, 0x00080408, 0x01080008, 0x01080408,
1259
+ 0x00080008, 0x00080408, 0x01080008, 0x01080408,
1260
+ 0x00080108, 0x00080508, 0x01080108, 0x01080508,
1261
+ 0x00080108, 0x00080508, 0x01080108, 0x01080508,
1262
+ 0x10080008, 0x10080408, 0x11080008, 0x11080408,
1263
+ 0x10080008, 0x10080408, 0x11080008, 0x11080408,
1264
+ 0x10080108, 0x10080508, 0x11080108, 0x11080508,
1265
+ 0x10080108, 0x10080508, 0x11080108, 0x11080508,
1266
+ 0x00001000, 0x00001400, 0x01001000, 0x01001400,
1267
+ 0x00001000, 0x00001400, 0x01001000, 0x01001400,
1268
+ 0x00001100, 0x00001500, 0x01001100, 0x01001500,
1269
+ 0x00001100, 0x00001500, 0x01001100, 0x01001500,
1270
+ 0x10001000, 0x10001400, 0x11001000, 0x11001400,
1271
+ 0x10001000, 0x10001400, 0x11001000, 0x11001400,
1272
+ 0x10001100, 0x10001500, 0x11001100, 0x11001500,
1273
+ 0x10001100, 0x10001500, 0x11001100, 0x11001500,
1274
+ 0x00081000, 0x00081400, 0x01081000, 0x01081400,
1275
+ 0x00081000, 0x00081400, 0x01081000, 0x01081400,
1276
+ 0x00081100, 0x00081500, 0x01081100, 0x01081500,
1277
+ 0x00081100, 0x00081500, 0x01081100, 0x01081500,
1278
+ 0x10081000, 0x10081400, 0x11081000, 0x11081400,
1279
+ 0x10081000, 0x10081400, 0x11081000, 0x11081400,
1280
+ 0x10081100, 0x10081500, 0x11081100, 0x11081500,
1281
+ 0x10081100, 0x10081500, 0x11081100, 0x11081500,
1282
+ 0x00001008, 0x00001408, 0x01001008, 0x01001408,
1283
+ 0x00001008, 0x00001408, 0x01001008, 0x01001408,
1284
+ 0x00001108, 0x00001508, 0x01001108, 0x01001508,
1285
+ 0x00001108, 0x00001508, 0x01001108, 0x01001508,
1286
+ 0x10001008, 0x10001408, 0x11001008, 0x11001408,
1287
+ 0x10001008, 0x10001408, 0x11001008, 0x11001408,
1288
+ 0x10001108, 0x10001508, 0x11001108, 0x11001508,
1289
+ 0x10001108, 0x10001508, 0x11001108, 0x11001508,
1290
+ 0x00081008, 0x00081408, 0x01081008, 0x01081408,
1291
+ 0x00081008, 0x00081408, 0x01081008, 0x01081408,
1292
+ 0x00081108, 0x00081508, 0x01081108, 0x01081508,
1293
+ 0x00081108, 0x00081508, 0x01081108, 0x01081508,
1294
+ 0x10081008, 0x10081408, 0x11081008, 0x11081408,
1295
+ 0x10081008, 0x10081408, 0x11081008, 0x11081408,
1296
+ 0x10081108, 0x10081508, 0x11081108, 0x11081508,
1297
+ 0x10081108, 0x10081508, 0x11081108, 0x11081508
1298
+ );
1299
+
1300
+ $keys = array();
1301
+ for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) {
1302
+ // pad the key and remove extra characters as appropriate.
1303
+ $key = str_pad(substr($this->key, $des_round * 8, 8), 8, "\0");
1304
+
1305
+ // Perform the PC/1 transformation and compute C and D.
1306
+ $t = unpack('Nl/Nr', $key);
1307
+ list($l, $r) = array($t['l'], $t['r']);
1308
+ $key = ($this->shuffle[$pc1map[ $r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x00") |
1309
+ ($this->shuffle[$pc1map[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x00") |
1310
+ ($this->shuffle[$pc1map[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x00") |
1311
+ ($this->shuffle[$pc1map[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x00") |
1312
+ ($this->shuffle[$pc1map[ $l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x00") |
1313
+ ($this->shuffle[$pc1map[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x00") |
1314
+ ($this->shuffle[$pc1map[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x00") |
1315
+ ($this->shuffle[$pc1map[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x00");
1316
+ $key = unpack('Nc/Nd', $key);
1317
+ $c = ( $key['c'] >> 4) & 0x0FFFFFFF;
1318
+ $d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F);
1319
+
1320
+ $keys[$des_round] = array(
1321
+ CRYPT_DES_ENCRYPT => array(),
1322
+ CRYPT_DES_DECRYPT => array_fill(0, 32, 0)
1323
+ );
1324
+ for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) {
1325
+ $c <<= $shifts[$i];
1326
+ $c = ($c | ($c >> 28)) & 0x0FFFFFFF;
1327
+ $d <<= $shifts[$i];
1328
+ $d = ($d | ($d >> 28)) & 0x0FFFFFFF;
1329
+
1330
+ // Perform the PC-2 transformation.
1331
+ $cp = $pc2mapc1[ $c >> 24 ] | $pc2mapc2[($c >> 16) & 0xFF] |
1332
+ $pc2mapc3[($c >> 8) & 0xFF] | $pc2mapc4[ $c & 0xFF];
1333
+ $dp = $pc2mapd1[ $d >> 24 ] | $pc2mapd2[($d >> 16) & 0xFF] |
1334
+ $pc2mapd3[($d >> 8) & 0xFF] | $pc2mapd4[ $d & 0xFF];
1335
+
1336
+ // Reorder: odd bytes/even bytes. Push the result in key schedule.
1337
+ $val1 = ( $cp & 0xFF000000) | (($cp << 8) & 0x00FF0000) |
1338
+ (($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF);
1339
+ $val2 = (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) |
1340
+ (($dp >> 8) & 0x0000FF00) | ( $dp & 0x000000FF);
1341
+ $keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val1;
1342
+ $keys[$des_round][CRYPT_DES_DECRYPT][$ki - 1] = $val1;
1343
+ $keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val2;
1344
+ $keys[$des_round][CRYPT_DES_DECRYPT][$ki ] = $val2;
1345
+ }
1346
+ }
1347
+
1348
+ switch ($this->des_rounds) {
1349
+ case 3: // 3DES keys
1350
+ $this->keys = array(
1351
+ CRYPT_DES_ENCRYPT => array_merge(
1352
+ $keys[0][CRYPT_DES_ENCRYPT],
1353
+ $keys[1][CRYPT_DES_DECRYPT],
1354
+ $keys[2][CRYPT_DES_ENCRYPT]
1355
+ ),
1356
+ CRYPT_DES_DECRYPT => array_merge(
1357
+ $keys[2][CRYPT_DES_DECRYPT],
1358
+ $keys[1][CRYPT_DES_ENCRYPT],
1359
+ $keys[0][CRYPT_DES_DECRYPT]
1360
+ )
1361
+ );
1362
+ break;
1363
+ // case 1: // DES keys
1364
+ default:
1365
+ $this->keys = array(
1366
+ CRYPT_DES_ENCRYPT => $keys[0][CRYPT_DES_ENCRYPT],
1367
+ CRYPT_DES_DECRYPT => $keys[0][CRYPT_DES_DECRYPT]
1368
+ );
1369
+ }
1370
+ }
1371
+
1372
+ /**
1373
+ * Setup the performance-optimized function for de/encrypt()
1374
+ *
1375
+ * @see Crypt_Base::_setupInlineCrypt()
1376
+ * @access private
1377
+ */
1378
+ function _setupInlineCrypt()
1379
+ {
1380
+ $lambda_functions =& Crypt_DES::_getLambdaFunctions();
1381
+
1382
+ // Engine configuration for:
1383
+ // - DES ($des_rounds == 1) or
1384
+ // - 3DES ($des_rounds == 3)
1385
+ $des_rounds = $this->des_rounds;
1386
+
1387
+ // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
1388
+ // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one
1389
+ $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 );
1390
+
1391
+ // Generation of a uniqe hash for our generated code
1392
+ switch (true) {
1393
+ case $gen_hi_opt_code:
1394
+ // For hi-optimized code, we create for each combination of
1395
+ // $mode, $des_rounds and $this->key its own encrypt/decrypt function.
1396
+ $code_hash = md5(str_pad("Crypt_DES, $des_rounds, {$this->mode}, ", 32, "\0") . $this->key);
1397
+ break;
1398
+ default:
1399
+ // After max 10 hi-optimized functions, we create generic
1400
+ // (still very fast.. but not ultra) functions for each $mode/$des_rounds
1401
+ // Currently 2 * 5 generic functions will be then max. possible.
1402
+ $code_hash = "Crypt_DES, $des_rounds, {$this->mode}";
1403
+ }
1404
+
1405
+ // Is there a re-usable $lambda_functions in there? If not, we have to create it.
1406
+ if (!isset($lambda_functions[$code_hash])) {
1407
+ // Init code for both, encrypt and decrypt.
1408
+ $init_crypt = 'static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip;
1409
+ if (!$sbox1) {
1410
+ $sbox1 = array_map("intval", $self->sbox1);
1411
+ $sbox2 = array_map("intval", $self->sbox2);
1412
+ $sbox3 = array_map("intval", $self->sbox3);
1413
+ $sbox4 = array_map("intval", $self->sbox4);
1414
+ $sbox5 = array_map("intval", $self->sbox5);
1415
+ $sbox6 = array_map("intval", $self->sbox6);
1416
+ $sbox7 = array_map("intval", $self->sbox7);
1417
+ $sbox8 = array_map("intval", $self->sbox8);'
1418
+ /* Merge $shuffle with $[inv]ipmap */ . '
1419
+ for ($i = 0; $i < 256; ++$i) {
1420
+ $shuffleip[] = $self->shuffle[$self->ipmap[$i]];
1421
+ $shuffleinvip[] = $self->shuffle[$self->invipmap[$i]];
1422
+ }
1423
+ }
1424
+ ';
1425
+
1426
+ switch (true) {
1427
+ case $gen_hi_opt_code:
1428
+ // In Hi-optimized code mode, we use our [3]DES key schedule as hardcoded integers.
1429
+ // No futher initialisation of the $keys schedule is necessary.
1430
+ // That is the extra performance boost.
1431
+ $k = array(
1432
+ CRYPT_DES_ENCRYPT => $this->keys[CRYPT_DES_ENCRYPT],
1433
+ CRYPT_DES_DECRYPT => $this->keys[CRYPT_DES_DECRYPT]
1434
+ );
1435
+ $init_encrypt = '';
1436
+ $init_decrypt = '';
1437
+ break;
1438
+ default:
1439
+ // In generic optimized code mode, we have to use, as the best compromise [currently],
1440
+ // our key schedule as $ke/$kd arrays. (with hardcoded indexes...)
1441
+ $k = array(
1442
+ CRYPT_DES_ENCRYPT => array(),
1443
+ CRYPT_DES_DECRYPT => array()
1444
+ );
1445
+ for ($i = 0, $c = count($this->keys[CRYPT_DES_ENCRYPT]); $i < $c; ++$i) {
1446
+ $k[CRYPT_DES_ENCRYPT][$i] = '$ke[' . $i . ']';
1447
+ $k[CRYPT_DES_DECRYPT][$i] = '$kd[' . $i . ']';
1448
+ }
1449
+ $init_encrypt = '$ke = $self->keys[CRYPT_DES_ENCRYPT];';
1450
+ $init_decrypt = '$kd = $self->keys[CRYPT_DES_DECRYPT];';
1451
+ break;
1452
+ }
1453
+
1454
+ // Creating code for en- and decryption.
1455
+ $crypt_block = array();
1456
+ foreach (array(CRYPT_DES_ENCRYPT, CRYPT_DES_DECRYPT) as $c) {
1457
+
1458
+ /* Do the initial IP permutation. */
1459
+ $crypt_block[$c] = '
1460
+ $in = unpack("N*", $in);
1461
+ $l = $in[1];
1462
+ $r = $in[2];
1463
+ $in = unpack("N*",
1464
+ ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
1465
+ ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
1466
+ ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
1467
+ ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
1468
+ ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
1469
+ ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
1470
+ ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
1471
+ ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01")
1472
+ );
1473
+ ' . /* Extract L0 and R0 */ '
1474
+ $l = $in[1];
1475
+ $r = $in[2];
1476
+ ';
1477
+
1478
+ $l = '$l';
1479
+ $r = '$r';
1480
+
1481
+ // Perform DES or 3DES.
1482
+ for ($ki = -1, $des_round = 0; $des_round < $des_rounds; ++$des_round) {
1483
+ // Perform the 16 steps.
1484
+ for ($i = 0; $i < 16; ++$i) {
1485
+ // start of "the Feistel (F) function" - see the following URL:
1486
+ // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png
1487
+ // Merge key schedule.
1488
+ $crypt_block[$c].= '
1489
+ $b1 = ((' . $r . ' >> 3) & 0x1FFFFFFF) ^ (' . $r . ' << 29) ^ ' . $k[$c][++$ki] . ';
1490
+ $b2 = ((' . $r . ' >> 31) & 0x00000001) ^ (' . $r . ' << 1) ^ ' . $k[$c][++$ki] . ';' .
1491
+ /* S-box indexing. */
1492
+ $l . ' = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^
1493
+ $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^
1494
+ $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^
1495
+ $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ ' . $l . ';
1496
+ ';
1497
+ // end of "the Feistel (F) function"
1498
+
1499
+ // swap L & R
1500
+ list($l, $r) = array($r, $l);
1501
+ }
1502
+ list($l, $r) = array($r, $l);
1503
+ }
1504
+
1505
+ // Perform the inverse IP permutation.
1506
+ $crypt_block[$c].= '$in =
1507
+ ($shuffleinvip[($l >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
1508
+ ($shuffleinvip[($r >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
1509
+ ($shuffleinvip[($l >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
1510
+ ($shuffleinvip[($r >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
1511
+ ($shuffleinvip[($l >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
1512
+ ($shuffleinvip[($r >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
1513
+ ($shuffleinvip[ $l & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
1514
+ ($shuffleinvip[ $r & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01");
1515
+ ';
1516
+ }
1517
+
1518
+ // Creates the inline-crypt function
1519
+ $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
1520
+ array(
1521
+ 'init_crypt' => $init_crypt,
1522
+ 'init_encrypt' => $init_encrypt,
1523
+ 'init_decrypt' => $init_decrypt,
1524
+ 'encrypt_block' => $crypt_block[CRYPT_DES_ENCRYPT],
1525
+ 'decrypt_block' => $crypt_block[CRYPT_DES_DECRYPT]
1526
+ )
1527
+ );
1528
+ }
1529
+
1530
+ // Set the inline-crypt function as callback in: $this->inline_crypt
1531
+ $this->inline_crypt = $lambda_functions[$code_hash];
1532
+ }
1533
+ }
1534
+
lib/LivrariOnline/Hash.php ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions.
6
+ *
7
+ * Uses hash() or mhash() if available and an internal implementation, otherwise. Currently supports the following:
8
+ *
9
+ * md2, md5, md5-96, sha1, sha1-96, sha256, sha384, and sha512
10
+ *
11
+ * If {@link Crypt_Hash::setKey() setKey()} is called, {@link Crypt_Hash::hash() hash()} will return the HMAC as opposed to
12
+ * the hash. If no valid algorithm is provided, sha1 will be used.
13
+ *
14
+ * PHP versions 4 and 5
15
+ *
16
+ * {@internal The variable names are the same as those in
17
+ * {@link http://tools.ietf.org/html/rfc2104#section-2 RFC2104}.}}
18
+ *
19
+ * Here's a short example of how to use this library:
20
+ * <code>
21
+ * <?php
22
+ * include('Crypt/Hash.php');
23
+ *
24
+ * $hash = new Crypt_Hash('sha1');
25
+ *
26
+ * $hash->setKey('abcdefg');
27
+ *
28
+ * echo base64_encode($hash->hash('abcdefg'));
29
+ * ?>
30
+ * </code>
31
+ *
32
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ * of this software and associated documentation files (the "Software"), to deal
34
+ * in the Software without restriction, including without limitation the rights
35
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ * copies of the Software, and to permit persons to whom the Software is
37
+ * furnished to do so, subject to the following conditions:
38
+ *
39
+ * The above copyright notice and this permission notice shall be included in
40
+ * all copies or substantial portions of the Software.
41
+ *
42
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
48
+ * THE SOFTWARE.
49
+ *
50
+ * @category Crypt
51
+ * @package Crypt_Hash
52
+ * @author Jim Wigginton <terrafrost@php.net>
53
+ * @copyright MMVII Jim Wigginton
54
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
55
+ * @link http://phpseclib.sourceforge.net
56
+ */
57
+
58
+ /**#@+
59
+ * @access private
60
+ * @see Crypt_Hash::Crypt_Hash()
61
+ */
62
+ /**
63
+ * Toggles the internal implementation
64
+ */
65
+ define('CRYPT_HASH_MODE_INTERNAL', 1);
66
+ /**
67
+ * Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+.
68
+ */
69
+ define('CRYPT_HASH_MODE_MHASH', 2);
70
+ /**
71
+ * Toggles the hash() implementation, which works on PHP 5.1.2+.
72
+ */
73
+ define('CRYPT_HASH_MODE_HASH', 3);
74
+ /**#@-*/
75
+
76
+ /**
77
+ * Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions.
78
+ *
79
+ * @author Jim Wigginton <terrafrost@php.net>
80
+ * @version 0.1.0
81
+ * @access public
82
+ * @package Crypt_Hash
83
+ */
84
+ class Crypt_Hash {
85
+ /**
86
+ * Byte-length of compression blocks / key (Internal HMAC)
87
+ *
88
+ * @see Crypt_Hash::setAlgorithm()
89
+ * @var Integer
90
+ * @access private
91
+ */
92
+ var $b;
93
+
94
+ /**
95
+ * Byte-length of hash output (Internal HMAC)
96
+ *
97
+ * @see Crypt_Hash::setHash()
98
+ * @var Integer
99
+ * @access private
100
+ */
101
+ var $l = false;
102
+
103
+ /**
104
+ * Hash Algorithm
105
+ *
106
+ * @see Crypt_Hash::setHash()
107
+ * @var String
108
+ * @access private
109
+ */
110
+ var $hash;
111
+
112
+ /**
113
+ * Key
114
+ *
115
+ * @see Crypt_Hash::setKey()
116
+ * @var String
117
+ * @access private
118
+ */
119
+ var $key = false;
120
+
121
+ /**
122
+ * Outer XOR (Internal HMAC)
123
+ *
124
+ * @see Crypt_Hash::setKey()
125
+ * @var String
126
+ * @access private
127
+ */
128
+ var $opad;
129
+
130
+ /**
131
+ * Inner XOR (Internal HMAC)
132
+ *
133
+ * @see Crypt_Hash::setKey()
134
+ * @var String
135
+ * @access private
136
+ */
137
+ var $ipad;
138
+
139
+ /**
140
+ * Default Constructor.
141
+ *
142
+ * @param optional String $hash
143
+ * @return Crypt_Hash
144
+ * @access public
145
+ */
146
+ function Crypt_Hash($hash = 'sha1')
147
+ {
148
+ if ( !defined('CRYPT_HASH_MODE') ) {
149
+ switch (true) {
150
+ case extension_loaded('hash'):
151
+ define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_HASH);
152
+ break;
153
+ case extension_loaded('mhash'):
154
+ define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_MHASH);
155
+ break;
156
+ default:
157
+ define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_INTERNAL);
158
+ }
159
+ }
160
+
161
+ $this->setHash($hash);
162
+ }
163
+
164
+ /**
165
+ * Sets the key for HMACs
166
+ *
167
+ * Keys can be of any length.
168
+ *
169
+ * @access public
170
+ * @param optional String $key
171
+ */
172
+ function setKey($key = false)
173
+ {
174
+ $this->key = $key;
175
+ }
176
+
177
+ /**
178
+ * Sets the hash function.
179
+ *
180
+ * @access public
181
+ * @param String $hash
182
+ */
183
+ function setHash($hash)
184
+ {
185
+ $hash = strtolower($hash);
186
+ switch ($hash) {
187
+ case 'md5-96':
188
+ case 'sha1-96':
189
+ $this->l = 12; // 96 / 8 = 12
190
+ break;
191
+ case 'md2':
192
+ case 'md5':
193
+ $this->l = 16;
194
+ break;
195
+ case 'sha1':
196
+ $this->l = 20;
197
+ break;
198
+ case 'sha256':
199
+ $this->l = 32;
200
+ break;
201
+ case 'sha384':
202
+ $this->l = 48;
203
+ break;
204
+ case 'sha512':
205
+ $this->l = 64;
206
+ }
207
+
208
+ switch ($hash) {
209
+ case 'md2':
210
+ $mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_HASH && in_array('md2', hash_algos()) ?
211
+ CRYPT_HASH_MODE_HASH : CRYPT_HASH_MODE_INTERNAL;
212
+ break;
213
+ case 'sha384':
214
+ case 'sha512':
215
+ $mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_MHASH ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE;
216
+ break;
217
+ default:
218
+ $mode = CRYPT_HASH_MODE;
219
+ }
220
+
221
+ switch ( $mode ) {
222
+ case CRYPT_HASH_MODE_MHASH:
223
+ switch ($hash) {
224
+ case 'md5':
225
+ case 'md5-96':
226
+ $this->hash = MHASH_MD5;
227
+ break;
228
+ case 'sha256':
229
+ $this->hash = MHASH_SHA256;
230
+ break;
231
+ case 'sha1':
232
+ case 'sha1-96':
233
+ default:
234
+ $this->hash = MHASH_SHA1;
235
+ }
236
+ return;
237
+ case CRYPT_HASH_MODE_HASH:
238
+ switch ($hash) {
239
+ case 'md5':
240
+ case 'md5-96':
241
+ $this->hash = 'md5';
242
+ return;
243
+ case 'md2':
244
+ case 'sha256':
245
+ case 'sha384':
246
+ case 'sha512':
247
+ $this->hash = $hash;
248
+ return;
249
+ case 'sha1':
250
+ case 'sha1-96':
251
+ default:
252
+ $this->hash = 'sha1';
253
+ }
254
+ return;
255
+ }
256
+
257
+ switch ($hash) {
258
+ case 'md2':
259
+ $this->b = 16;
260
+ $this->hash = array($this, '_md2');
261
+ break;
262
+ case 'md5':
263
+ case 'md5-96':
264
+ $this->b = 64;
265
+ $this->hash = array($this, '_md5');
266
+ break;
267
+ case 'sha256':
268
+ $this->b = 64;
269
+ $this->hash = array($this, '_sha256');
270
+ break;
271
+ case 'sha384':
272
+ case 'sha512':
273
+ $this->b = 128;
274
+ $this->hash = array($this, '_sha512');
275
+ break;
276
+ case 'sha1':
277
+ case 'sha1-96':
278
+ default:
279
+ $this->b = 64;
280
+ $this->hash = array($this, '_sha1');
281
+ }
282
+
283
+ $this->ipad = str_repeat(chr(0x36), $this->b);
284
+ $this->opad = str_repeat(chr(0x5C), $this->b);
285
+ }
286
+
287
+ /**
288
+ * Compute the HMAC.
289
+ *
290
+ * @access public
291
+ * @param String $text
292
+ * @return String
293
+ */
294
+ function hash($text)
295
+ {
296
+ $mode = is_array($this->hash) ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE;
297
+
298
+ if (!empty($this->key) || is_string($this->key)) {
299
+ switch ( $mode ) {
300
+ case CRYPT_HASH_MODE_MHASH:
301
+ $output = mhash($this->hash, $text, $this->key);
302
+ break;
303
+ case CRYPT_HASH_MODE_HASH:
304
+ $output = hash_hmac($this->hash, $text, $this->key, true);
305
+ break;
306
+ case CRYPT_HASH_MODE_INTERNAL:
307
+ /* "Applications that use keys longer than B bytes will first hash the key using H and then use the
308
+ resultant L byte string as the actual key to HMAC."
309
+
310
+ -- http://tools.ietf.org/html/rfc2104#section-2 */
311
+ $key = strlen($this->key) > $this->b ? call_user_func($this->hash, $this->key) : $this->key;
312
+
313
+ $key = str_pad($key, $this->b, chr(0)); // step 1
314
+ $temp = $this->ipad ^ $key; // step 2
315
+ $temp .= $text; // step 3
316
+ $temp = call_user_func($this->hash, $temp); // step 4
317
+ $output = $this->opad ^ $key; // step 5
318
+ $output.= $temp; // step 6
319
+ $output = call_user_func($this->hash, $output); // step 7
320
+ }
321
+ } else {
322
+ switch ( $mode ) {
323
+ case CRYPT_HASH_MODE_MHASH:
324
+ $output = mhash($this->hash, $text);
325
+ break;
326
+ case CRYPT_HASH_MODE_HASH:
327
+ $output = hash($this->hash, $text, true);
328
+ break;
329
+ case CRYPT_HASH_MODE_INTERNAL:
330
+ $output = call_user_func($this->hash, $text);
331
+ }
332
+ }
333
+
334
+ return substr($output, 0, $this->l);
335
+ }
336
+
337
+ /**
338
+ * Returns the hash length (in bytes)
339
+ *
340
+ * @access public
341
+ * @return Integer
342
+ */
343
+ function getLength()
344
+ {
345
+ return $this->l;
346
+ }
347
+
348
+ /**
349
+ * Wrapper for MD5
350
+ *
351
+ * @access private
352
+ * @param String $m
353
+ */
354
+ function _md5($m)
355
+ {
356
+ return pack('H*', md5($m));
357
+ }
358
+
359
+ /**
360
+ * Wrapper for SHA1
361
+ *
362
+ * @access private
363
+ * @param String $m
364
+ */
365
+ function _sha1($m)
366
+ {
367
+ return pack('H*', sha1($m));
368
+ }
369
+
370
+ /**
371
+ * Pure-PHP implementation of MD2
372
+ *
373
+ * See {@link http://tools.ietf.org/html/rfc1319 RFC1319}.
374
+ *
375
+ * @access private
376
+ * @param String $m
377
+ */
378
+ function _md2($m)
379
+ {
380
+ static $s = array(
381
+ 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
382
+ 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
383
+ 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
384
+ 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
385
+ 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
386
+ 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
387
+ 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
388
+ 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
389
+ 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
390
+ 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
391
+ 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
392
+ 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
393
+ 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
394
+ 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
395
+ 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
396
+ 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
397
+ 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
398
+ 31, 26, 219, 153, 141, 51, 159, 17, 131, 20
399
+ );
400
+
401
+ // Step 1. Append Padding Bytes
402
+ $pad = 16 - (strlen($m) & 0xF);
403
+ $m.= str_repeat(chr($pad), $pad);
404
+
405
+ $length = strlen($m);
406
+
407
+ // Step 2. Append Checksum
408
+ $c = str_repeat(chr(0), 16);
409
+ $l = chr(0);
410
+ for ($i = 0; $i < $length; $i+= 16) {
411
+ for ($j = 0; $j < 16; $j++) {
412
+ // RFC1319 incorrectly states that C[j] should be set to S[c xor L]
413
+ //$c[$j] = chr($s[ord($m[$i + $j] ^ $l)]);
414
+ // per <http://www.rfc-editor.org/errata_search.php?rfc=1319>, however, C[j] should be set to S[c xor L] xor C[j]
415
+ $c[$j] = chr($s[ord($m[$i + $j] ^ $l)] ^ ord($c[$j]));
416
+ $l = $c[$j];
417
+ }
418
+ }
419
+ $m.= $c;
420
+
421
+ $length+= 16;
422
+
423
+ // Step 3. Initialize MD Buffer
424
+ $x = str_repeat(chr(0), 48);
425
+
426
+ // Step 4. Process Message in 16-Byte Blocks
427
+ for ($i = 0; $i < $length; $i+= 16) {
428
+ for ($j = 0; $j < 16; $j++) {
429
+ $x[$j + 16] = $m[$i + $j];
430
+ $x[$j + 32] = $x[$j + 16] ^ $x[$j];
431
+ }
432
+ $t = chr(0);
433
+ for ($j = 0; $j < 18; $j++) {
434
+ for ($k = 0; $k < 48; $k++) {
435
+ $x[$k] = $t = $x[$k] ^ chr($s[ord($t)]);
436
+ //$t = $x[$k] = $x[$k] ^ chr($s[ord($t)]);
437
+ }
438
+ $t = chr(ord($t) + $j);
439
+ }
440
+ }
441
+
442
+ // Step 5. Output
443
+ return substr($x, 0, 16);
444
+ }
445
+
446
+ /**
447
+ * Pure-PHP implementation of SHA256
448
+ *
449
+ * See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}.
450
+ *
451
+ * @access private
452
+ * @param String $m
453
+ */
454
+ function _sha256($m)
455
+ {
456
+ if (extension_loaded('suhosin')) {
457
+ return pack('H*', sha256($m));
458
+ }
459
+
460
+ // Initialize variables
461
+ $hash = array(
462
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
463
+ );
464
+ // Initialize table of round constants
465
+ // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
466
+ static $k = array(
467
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
468
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
469
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
470
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
471
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
472
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
473
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
474
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
475
+ );
476
+
477
+ // Pre-processing
478
+ $length = strlen($m);
479
+ // to round to nearest 56 mod 64, we'll add 64 - (length + (64 - 56)) % 64
480
+ $m.= str_repeat(chr(0), 64 - (($length + 8) & 0x3F));
481
+ $m[$length] = chr(0x80);
482
+ // we don't support hashing strings 512MB long
483
+ $m.= pack('N2', 0, $length << 3);
484
+
485
+ // Process the message in successive 512-bit chunks
486
+ $chunks = str_split($m, 64);
487
+ foreach ($chunks as $chunk) {
488
+ $w = array();
489
+ for ($i = 0; $i < 16; $i++) {
490
+ extract(unpack('Ntemp', $this->_string_shift($chunk, 4)));
491
+ $w[] = $temp;
492
+ }
493
+
494
+ // Extend the sixteen 32-bit words into sixty-four 32-bit words
495
+ for ($i = 16; $i < 64; $i++) {
496
+ $s0 = $this->_rightRotate($w[$i - 15], 7) ^
497
+ $this->_rightRotate($w[$i - 15], 18) ^
498
+ $this->_rightShift( $w[$i - 15], 3);
499
+ $s1 = $this->_rightRotate($w[$i - 2], 17) ^
500
+ $this->_rightRotate($w[$i - 2], 19) ^
501
+ $this->_rightShift( $w[$i - 2], 10);
502
+ $w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1);
503
+
504
+ }
505
+
506
+ // Initialize hash value for this chunk
507
+ list($a, $b, $c, $d, $e, $f, $g, $h) = $hash;
508
+
509
+ // Main loop
510
+ for ($i = 0; $i < 64; $i++) {
511
+ $s0 = $this->_rightRotate($a, 2) ^
512
+ $this->_rightRotate($a, 13) ^
513
+ $this->_rightRotate($a, 22);
514
+ $maj = ($a & $b) ^
515
+ ($a & $c) ^
516
+ ($b & $c);
517
+ $t2 = $this->_add($s0, $maj);
518
+
519
+ $s1 = $this->_rightRotate($e, 6) ^
520
+ $this->_rightRotate($e, 11) ^
521
+ $this->_rightRotate($e, 25);
522
+ $ch = ($e & $f) ^
523
+ ($this->_not($e) & $g);
524
+ $t1 = $this->_add($h, $s1, $ch, $k[$i], $w[$i]);
525
+
526
+ $h = $g;
527
+ $g = $f;
528
+ $f = $e;
529
+ $e = $this->_add($d, $t1);
530
+ $d = $c;
531
+ $c = $b;
532
+ $b = $a;
533
+ $a = $this->_add($t1, $t2);
534
+ }
535
+
536
+ // Add this chunk's hash to result so far
537
+ $hash = array(
538
+ $this->_add($hash[0], $a),
539
+ $this->_add($hash[1], $b),
540
+ $this->_add($hash[2], $c),
541
+ $this->_add($hash[3], $d),
542
+ $this->_add($hash[4], $e),
543
+ $this->_add($hash[5], $f),
544
+ $this->_add($hash[6], $g),
545
+ $this->_add($hash[7], $h)
546
+ );
547
+ }
548
+
549
+ // Produce the final hash value (big-endian)
550
+ return pack('N8', $hash[0], $hash[1], $hash[2], $hash[3], $hash[4], $hash[5], $hash[6], $hash[7]);
551
+ }
552
+
553
+ /**
554
+ * Pure-PHP implementation of SHA384 and SHA512
555
+ *
556
+ * @access private
557
+ * @param String $m
558
+ */
559
+ function _sha512($m)
560
+ {
561
+ if (!class_exists('Math_BigInteger')) {
562
+ require_once('Math/BigInteger.php');
563
+ }
564
+
565
+ static $init384, $init512, $k;
566
+
567
+ if (!isset($k)) {
568
+ // Initialize variables
569
+ $init384 = array( // initial values for SHA384
570
+ 'cbbb9d5dc1059ed8', '629a292a367cd507', '9159015a3070dd17', '152fecd8f70e5939',
571
+ '67332667ffc00b31', '8eb44a8768581511', 'db0c2e0d64f98fa7', '47b5481dbefa4fa4'
572
+ );
573
+ $init512 = array( // initial values for SHA512
574
+ '6a09e667f3bcc908', 'bb67ae8584caa73b', '3c6ef372fe94f82b', 'a54ff53a5f1d36f1',
575
+ '510e527fade682d1', '9b05688c2b3e6c1f', '1f83d9abfb41bd6b', '5be0cd19137e2179'
576
+ );
577
+
578
+ for ($i = 0; $i < 8; $i++) {
579
+ $init384[$i] = new Math_BigInteger($init384[$i], 16);
580
+ $init384[$i]->setPrecision(64);
581
+ $init512[$i] = new Math_BigInteger($init512[$i], 16);
582
+ $init512[$i]->setPrecision(64);
583
+ }
584
+
585
+ // Initialize table of round constants
586
+ // (first 64 bits of the fractional parts of the cube roots of the first 80 primes 2..409)
587
+ $k = array(
588
+ '428a2f98d728ae22', '7137449123ef65cd', 'b5c0fbcfec4d3b2f', 'e9b5dba58189dbbc',
589
+ '3956c25bf348b538', '59f111f1b605d019', '923f82a4af194f9b', 'ab1c5ed5da6d8118',
590
+ 'd807aa98a3030242', '12835b0145706fbe', '243185be4ee4b28c', '550c7dc3d5ffb4e2',
591
+ '72be5d74f27b896f', '80deb1fe3b1696b1', '9bdc06a725c71235', 'c19bf174cf692694',
592
+ 'e49b69c19ef14ad2', 'efbe4786384f25e3', '0fc19dc68b8cd5b5', '240ca1cc77ac9c65',
593
+ '2de92c6f592b0275', '4a7484aa6ea6e483', '5cb0a9dcbd41fbd4', '76f988da831153b5',
594
+ '983e5152ee66dfab', 'a831c66d2db43210', 'b00327c898fb213f', 'bf597fc7beef0ee4',
595
+ 'c6e00bf33da88fc2', 'd5a79147930aa725', '06ca6351e003826f', '142929670a0e6e70',
596
+ '27b70a8546d22ffc', '2e1b21385c26c926', '4d2c6dfc5ac42aed', '53380d139d95b3df',
597
+ '650a73548baf63de', '766a0abb3c77b2a8', '81c2c92e47edaee6', '92722c851482353b',
598
+ 'a2bfe8a14cf10364', 'a81a664bbc423001', 'c24b8b70d0f89791', 'c76c51a30654be30',
599
+ 'd192e819d6ef5218', 'd69906245565a910', 'f40e35855771202a', '106aa07032bbd1b8',
600
+ '19a4c116b8d2d0c8', '1e376c085141ab53', '2748774cdf8eeb99', '34b0bcb5e19b48a8',
601
+ '391c0cb3c5c95a63', '4ed8aa4ae3418acb', '5b9cca4f7763e373', '682e6ff3d6b2b8a3',
602
+ '748f82ee5defb2fc', '78a5636f43172f60', '84c87814a1f0ab72', '8cc702081a6439ec',
603
+ '90befffa23631e28', 'a4506cebde82bde9', 'bef9a3f7b2c67915', 'c67178f2e372532b',
604
+ 'ca273eceea26619c', 'd186b8c721c0c207', 'eada7dd6cde0eb1e', 'f57d4f7fee6ed178',
605
+ '06f067aa72176fba', '0a637dc5a2c898a6', '113f9804bef90dae', '1b710b35131c471b',
606
+ '28db77f523047d84', '32caab7b40c72493', '3c9ebe0a15c9bebc', '431d67c49c100d4c',
607
+ '4cc5d4becb3e42b6', '597f299cfc657e2a', '5fcb6fab3ad6faec', '6c44198c4a475817'
608
+ );
609
+
610
+ for ($i = 0; $i < 80; $i++) {
611
+ $k[$i] = new Math_BigInteger($k[$i], 16);
612
+ }
613
+ }
614
+
615
+ $hash = $this->l == 48 ? $init384 : $init512;
616
+
617
+ // Pre-processing
618
+ $length = strlen($m);
619
+ // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128
620
+ $m.= str_repeat(chr(0), 128 - (($length + 16) & 0x7F));
621
+ $m[$length] = chr(0x80);
622
+ // we don't support hashing strings 512MB long
623
+ $m.= pack('N4', 0, 0, 0, $length << 3);
624
+
625
+ // Process the message in successive 1024-bit chunks
626
+ $chunks = str_split($m, 128);
627
+ foreach ($chunks as $chunk) {
628
+ $w = array();
629
+ for ($i = 0; $i < 16; $i++) {
630
+ $temp = new Math_BigInteger($this->_string_shift($chunk, 8), 256);
631
+ $temp->setPrecision(64);
632
+ $w[] = $temp;
633
+ }
634
+
635
+ // Extend the sixteen 32-bit words into eighty 32-bit words
636
+ for ($i = 16; $i < 80; $i++) {
637
+ $temp = array(
638
+ $w[$i - 15]->bitwise_rightRotate(1),
639
+ $w[$i - 15]->bitwise_rightRotate(8),
640
+ $w[$i - 15]->bitwise_rightShift(7)
641
+ );
642
+ $s0 = $temp[0]->bitwise_xor($temp[1]);
643
+ $s0 = $s0->bitwise_xor($temp[2]);
644
+ $temp = array(
645
+ $w[$i - 2]->bitwise_rightRotate(19),
646
+ $w[$i - 2]->bitwise_rightRotate(61),
647
+ $w[$i - 2]->bitwise_rightShift(6)
648
+ );
649
+ $s1 = $temp[0]->bitwise_xor($temp[1]);
650
+ $s1 = $s1->bitwise_xor($temp[2]);
651
+ $w[$i] = $w[$i - 16]->copy();
652
+ $w[$i] = $w[$i]->add($s0);
653
+ $w[$i] = $w[$i]->add($w[$i - 7]);
654
+ $w[$i] = $w[$i]->add($s1);
655
+ }
656
+
657
+ // Initialize hash value for this chunk
658
+ $a = $hash[0]->copy();
659
+ $b = $hash[1]->copy();
660
+ $c = $hash[2]->copy();
661
+ $d = $hash[3]->copy();
662
+ $e = $hash[4]->copy();
663
+ $f = $hash[5]->copy();
664
+ $g = $hash[6]->copy();
665
+ $h = $hash[7]->copy();
666
+
667
+ // Main loop
668
+ for ($i = 0; $i < 80; $i++) {
669
+ $temp = array(
670
+ $a->bitwise_rightRotate(28),
671
+ $a->bitwise_rightRotate(34),
672
+ $a->bitwise_rightRotate(39)
673
+ );
674
+ $s0 = $temp[0]->bitwise_xor($temp[1]);
675
+ $s0 = $s0->bitwise_xor($temp[2]);
676
+ $temp = array(
677
+ $a->bitwise_and($b),
678
+ $a->bitwise_and($c),
679
+ $b->bitwise_and($c)
680
+ );
681
+ $maj = $temp[0]->bitwise_xor($temp[1]);
682
+ $maj = $maj->bitwise_xor($temp[2]);
683
+ $t2 = $s0->add($maj);
684
+
685
+ $temp = array(
686
+ $e->bitwise_rightRotate(14),
687
+ $e->bitwise_rightRotate(18),
688
+ $e->bitwise_rightRotate(41)
689
+ );
690
+ $s1 = $temp[0]->bitwise_xor($temp[1]);
691
+ $s1 = $s1->bitwise_xor($temp[2]);
692
+ $temp = array(
693
+ $e->bitwise_and($f),
694
+ $g->bitwise_and($e->bitwise_not())
695
+ );
696
+ $ch = $temp[0]->bitwise_xor($temp[1]);
697
+ $t1 = $h->add($s1);
698
+ $t1 = $t1->add($ch);
699
+ $t1 = $t1->add($k[$i]);
700
+ $t1 = $t1->add($w[$i]);
701
+
702
+ $h = $g->copy();
703
+ $g = $f->copy();
704
+ $f = $e->copy();
705
+ $e = $d->add($t1);
706
+ $d = $c->copy();
707
+ $c = $b->copy();
708
+ $b = $a->copy();
709
+ $a = $t1->add($t2);
710
+ }
711
+
712
+ // Add this chunk's hash to result so far
713
+ $hash = array(
714
+ $hash[0]->add($a),
715
+ $hash[1]->add($b),
716
+ $hash[2]->add($c),
717
+ $hash[3]->add($d),
718
+ $hash[4]->add($e),
719
+ $hash[5]->add($f),
720
+ $hash[6]->add($g),
721
+ $hash[7]->add($h)
722
+ );
723
+ }
724
+
725
+ // Produce the final hash value (big-endian)
726
+ // (Crypt_Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here)
727
+ $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() .
728
+ $hash[4]->toBytes() . $hash[5]->toBytes();
729
+ if ($this->l != 48) {
730
+ $temp.= $hash[6]->toBytes() . $hash[7]->toBytes();
731
+ }
732
+
733
+ return $temp;
734
+ }
735
+
736
+ /**
737
+ * Right Rotate
738
+ *
739
+ * @access private
740
+ * @param Integer $int
741
+ * @param Integer $amt
742
+ * @see _sha256()
743
+ * @return Integer
744
+ */
745
+ function _rightRotate($int, $amt)
746
+ {
747
+ $invamt = 32 - $amt;
748
+ $mask = (1 << $invamt) - 1;
749
+ return (($int << $invamt) & 0xFFFFFFFF) | (($int >> $amt) & $mask);
750
+ }
751
+
752
+ /**
753
+ * Right Shift
754
+ *
755
+ * @access private
756
+ * @param Integer $int
757
+ * @param Integer $amt
758
+ * @see _sha256()
759
+ * @return Integer
760
+ */
761
+ function _rightShift($int, $amt)
762
+ {
763
+ $mask = (1 << (32 - $amt)) - 1;
764
+ return ($int >> $amt) & $mask;
765
+ }
766
+
767
+ /**
768
+ * Not
769
+ *
770
+ * @access private
771
+ * @param Integer $int
772
+ * @see _sha256()
773
+ * @return Integer
774
+ */
775
+ function _not($int)
776
+ {
777
+ return ~$int & 0xFFFFFFFF;
778
+ }
779
+
780
+ /**
781
+ * Add
782
+ *
783
+ * _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the
784
+ * possibility of overflow exists, care has to be taken. Math_BigInteger() could be used but this should be faster.
785
+ *
786
+ * @param Integer $...
787
+ * @return Integer
788
+ * @see _sha256()
789
+ * @access private
790
+ */
791
+ function _add()
792
+ {
793
+ static $mod;
794
+ if (!isset($mod)) {
795
+ $mod = pow(2, 32);
796
+ }
797
+
798
+ $result = 0;
799
+ $arguments = func_get_args();
800
+ foreach ($arguments as $argument) {
801
+ $result+= $argument < 0 ? ($argument & 0x7FFFFFFF) + 0x80000000 : $argument;
802
+ }
803
+
804
+ return fmod($result, $mod);
805
+ }
806
+
807
+ /**
808
+ * String Shift
809
+ *
810
+ * Inspired by array_shift
811
+ *
812
+ * @param String $string
813
+ * @param optional Integer $index
814
+ * @return String
815
+ * @access private
816
+ */
817
+ function _string_shift(&$string, $index = 1)
818
+ {
819
+ $substr = substr($string, 0, $index);
820
+ $string = substr($string, $index);
821
+ return $substr;
822
+ }
823
+ }
lib/LivrariOnline/RC2.php ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of RC2.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Useful resources are as follows:
11
+ *
12
+ * - {@link http://tools.ietf.org/html/rfc2268}
13
+ *
14
+ * Here's a short example of how to use this library:
15
+ * <code>
16
+ * <?php
17
+ * include('Crypt/RC2.php');
18
+ *
19
+ * $rc2 = new Crypt_RC2();
20
+ *
21
+ * $rc2->setKey('abcdefgh');
22
+ *
23
+ * $plaintext = str_repeat('a', 1024);
24
+ *
25
+ * echo $rc2->decrypt($rc2->encrypt($plaintext));
26
+ * ?>
27
+ * </code>
28
+ *
29
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ * of this software and associated documentation files (the "Software"), to deal
31
+ * in the Software without restriction, including without limitation the rights
32
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ * copies of the Software, and to permit persons to whom the Software is
34
+ * furnished to do so, subject to the following conditions:
35
+ *
36
+ * The above copyright notice and this permission notice shall be included in
37
+ * all copies or substantial portions of the Software.
38
+ *
39
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ * THE SOFTWARE.
46
+ *
47
+ * @category Crypt
48
+ * @package Crypt_RC2
49
+ * @author Patrick Monnerat <pm@datasphere.ch>
50
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
51
+ * @link http://phpseclib.sourceforge.net
52
+ */
53
+
54
+ /**
55
+ * Include Crypt_Base
56
+ *
57
+ * Base cipher class
58
+ */
59
+ require_once('Base.php');
60
+
61
+ /**#@+
62
+ * @access public
63
+ * @see Crypt_RC2::encrypt()
64
+ * @see Crypt_RC2::decrypt()
65
+ */
66
+ /**
67
+ * Encrypt / decrypt using the Counter mode.
68
+ *
69
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
70
+ *
71
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
72
+ */
73
+ define('CRYPT_RC2_MODE_CTR', CRYPT_MODE_CTR);
74
+ /**
75
+ * Encrypt / decrypt using the Electronic Code Book mode.
76
+ *
77
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
78
+ */
79
+ define('CRYPT_RC2_MODE_ECB', CRYPT_MODE_ECB);
80
+ /**
81
+ * Encrypt / decrypt using the Code Book Chaining mode.
82
+ *
83
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
84
+ */
85
+ define('CRYPT_RC2_MODE_CBC', CRYPT_MODE_CBC);
86
+ /**
87
+ * Encrypt / decrypt using the Cipher Feedback mode.
88
+ *
89
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
90
+ */
91
+ define('CRYPT_RC2_MODE_CFB', CRYPT_MODE_CFB);
92
+ /**
93
+ * Encrypt / decrypt using the Cipher Feedback mode.
94
+ *
95
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
96
+ */
97
+ define('CRYPT_RC2_MODE_OFB', CRYPT_MODE_OFB);
98
+ /**#@-*/
99
+
100
+ /**#@+
101
+ * @access private
102
+ * @see Crypt_RC2::Crypt_RC2()
103
+ */
104
+ /**
105
+ * Toggles the internal implementation
106
+ */
107
+ define('CRYPT_RC2_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
108
+ /**
109
+ * Toggles the mcrypt implementation
110
+ */
111
+ define('CRYPT_RC2_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
112
+ /**#@-*/
113
+
114
+ /**
115
+ * Pure-PHP implementation of RC2.
116
+ *
117
+ * @package Crypt_RC2
118
+ * @version 0.1.1
119
+ * @access public
120
+ */
121
+ class Crypt_RC2 extends Crypt_Base
122
+ {
123
+ /**
124
+ * Block Length of the cipher
125
+ *
126
+ * @see Crypt_Base::block_size
127
+ * @var Integer
128
+ * @access private
129
+ */
130
+ var $block_size = 8;
131
+
132
+ /**
133
+ * The Key
134
+ *
135
+ * @see Crypt_Base::key
136
+ * @see setKey()
137
+ * @var String
138
+ * @access private
139
+ */
140
+ var $key = "\0";
141
+
142
+ /**
143
+ * The default password key_size used by setPassword()
144
+ *
145
+ * @see Crypt_Base::password_key_size
146
+ * @see Crypt_Base::setPassword()
147
+ * @var Integer
148
+ * @access private
149
+ */
150
+ var $password_key_size = 16; // = 128 bits
151
+
152
+ /**
153
+ * The namespace used by the cipher for its constants.
154
+ *
155
+ * @see Crypt_Base::const_namespace
156
+ * @var String
157
+ * @access private
158
+ */
159
+ var $const_namespace = 'RC2';
160
+
161
+ /**
162
+ * The mcrypt specific name of the cipher
163
+ *
164
+ * @see Crypt_Base::cipher_name_mcrypt
165
+ * @var String
166
+ * @access private
167
+ */
168
+ var $cipher_name_mcrypt = 'rc2';
169
+
170
+ /**
171
+ * Optimizing value while CFB-encrypting
172
+ *
173
+ * @see Crypt_Base::cfb_init_len
174
+ * @var Integer
175
+ * @access private
176
+ */
177
+ var $cfb_init_len = 500;
178
+
179
+ /**
180
+ * The key length in bits.
181
+ *
182
+ * @see Crypt_RC2::setKeyLength()
183
+ * @see Crypt_RC2::setKey()
184
+ * @var Integer
185
+ * @access private
186
+ * @internal Should be in range [1..1024].
187
+ * @internal Changing this value after setting the key has no effect.
188
+ */
189
+ var $default_key_length = 1024;
190
+
191
+ /**
192
+ * The Key Schedule
193
+ *
194
+ * @see Crypt_RC2::_setupKey()
195
+ * @var Array
196
+ * @access private
197
+ */
198
+ var $keys;
199
+
200
+ /**
201
+ * Key expansion randomization table.
202
+ * Twice the same 256-value sequence to save a modulus in key expansion.
203
+ *
204
+ * @see Crypt_RC2::setKey()
205
+ * @var Array
206
+ * @access private
207
+ */
208
+ var $pitable = array(
209
+ 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED,
210
+ 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D,
211
+ 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E,
212
+ 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2,
213
+ 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13,
214
+ 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32,
215
+ 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B,
216
+ 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82,
217
+ 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C,
218
+ 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC,
219
+ 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1,
220
+ 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26,
221
+ 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57,
222
+ 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03,
223
+ 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7,
224
+ 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7,
225
+ 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7,
226
+ 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A,
227
+ 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74,
228
+ 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC,
229
+ 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC,
230
+ 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39,
231
+ 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A,
232
+ 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31,
233
+ 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE,
234
+ 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9,
235
+ 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C,
236
+ 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9,
237
+ 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0,
238
+ 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E,
239
+ 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77,
240
+ 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD,
241
+ 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED,
242
+ 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D,
243
+ 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E,
244
+ 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2,
245
+ 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13,
246
+ 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32,
247
+ 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B,
248
+ 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82,
249
+ 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C,
250
+ 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC,
251
+ 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1,
252
+ 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26,
253
+ 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57,
254
+ 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03,
255
+ 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7,
256
+ 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7,
257
+ 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7,
258
+ 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A,
259
+ 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74,
260
+ 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC,
261
+ 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC,
262
+ 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39,
263
+ 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A,
264
+ 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31,
265
+ 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE,
266
+ 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9,
267
+ 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C,
268
+ 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9,
269
+ 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0,
270
+ 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E,
271
+ 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77,
272
+ 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD
273
+ );
274
+
275
+ /**
276
+ * Inverse key expansion randomization table.
277
+ *
278
+ * @see Crypt_RC2::setKey()
279
+ * @var Array
280
+ * @access private
281
+ */
282
+ var $invpitable = array(
283
+ 0xD1, 0xDA, 0xB9, 0x6F, 0x9C, 0xC8, 0x78, 0x66,
284
+ 0x80, 0x2C, 0xF8, 0x37, 0xEA, 0xE0, 0x62, 0xA4,
285
+ 0xCB, 0x71, 0x50, 0x27, 0x4B, 0x95, 0xD9, 0x20,
286
+ 0x9D, 0x04, 0x91, 0xE3, 0x47, 0x6A, 0x7E, 0x53,
287
+ 0xFA, 0x3A, 0x3B, 0xB4, 0xA8, 0xBC, 0x5F, 0x68,
288
+ 0x08, 0xCA, 0x8F, 0x14, 0xD7, 0xC0, 0xEF, 0x7B,
289
+ 0x5B, 0xBF, 0x2F, 0xE5, 0xE2, 0x8C, 0xBA, 0x12,
290
+ 0xE1, 0xAF, 0xB2, 0x54, 0x5D, 0x59, 0x76, 0xDB,
291
+ 0x32, 0xA2, 0x58, 0x6E, 0x1C, 0x29, 0x64, 0xF3,
292
+ 0xE9, 0x96, 0x0C, 0x98, 0x19, 0x8D, 0x3E, 0x26,
293
+ 0xAB, 0xA5, 0x85, 0x16, 0x40, 0xBD, 0x49, 0x67,
294
+ 0xDC, 0x22, 0x94, 0xBB, 0x3C, 0xC1, 0x9B, 0xEB,
295
+ 0x45, 0x28, 0x18, 0xD8, 0x1A, 0x42, 0x7D, 0xCC,
296
+ 0xFB, 0x65, 0x8E, 0x3D, 0xCD, 0x2A, 0xA3, 0x60,
297
+ 0xAE, 0x93, 0x8A, 0x48, 0x97, 0x51, 0x15, 0xF7,
298
+ 0x01, 0x0B, 0xB7, 0x36, 0xB1, 0x2E, 0x11, 0xFD,
299
+ 0x84, 0x2D, 0x3F, 0x13, 0x88, 0xB3, 0x34, 0x24,
300
+ 0x1B, 0xDE, 0xC5, 0x1D, 0x4D, 0x2B, 0x17, 0x31,
301
+ 0x74, 0xA9, 0xC6, 0x43, 0x6D, 0x39, 0x90, 0xBE,
302
+ 0xC3, 0xB0, 0x21, 0x6B, 0xF6, 0x0F, 0xD5, 0x99,
303
+ 0x0D, 0xAC, 0x1F, 0x5C, 0x9E, 0xF5, 0xF9, 0x4C,
304
+ 0xD6, 0xDF, 0x89, 0xE4, 0x8B, 0xFF, 0xC7, 0xAA,
305
+ 0xE7, 0xED, 0x46, 0x25, 0xB6, 0x06, 0x5E, 0x35,
306
+ 0xB5, 0xEC, 0xCE, 0xE8, 0x6C, 0x30, 0x55, 0x61,
307
+ 0x4A, 0xFE, 0xA0, 0x79, 0x03, 0xF0, 0x10, 0x72,
308
+ 0x7C, 0xCF, 0x52, 0xA6, 0xA7, 0xEE, 0x44, 0xD3,
309
+ 0x9A, 0x57, 0x92, 0xD0, 0x5A, 0x7A, 0x41, 0x7F,
310
+ 0x0E, 0x00, 0x63, 0xF2, 0x4F, 0x05, 0x83, 0xC9,
311
+ 0xA1, 0xD4, 0xDD, 0xC4, 0x56, 0xF4, 0xD2, 0x77,
312
+ 0x81, 0x09, 0x82, 0x33, 0x9F, 0x07, 0x86, 0x75,
313
+ 0x38, 0x4E, 0x69, 0xF1, 0xAD, 0x23, 0x73, 0x87,
314
+ 0x70, 0x02, 0xC2, 0x1E, 0xB8, 0x0A, 0xFC, 0xE6
315
+ );
316
+
317
+ /**
318
+ * Default Constructor.
319
+ *
320
+ * Determines whether or not the mcrypt extension should be used.
321
+ *
322
+ * $mode could be:
323
+ *
324
+ * - CRYPT_RC2_MODE_ECB
325
+ *
326
+ * - CRYPT_RC2_MODE_CBC
327
+ *
328
+ * - CRYPT_RC2_MODE_CTR
329
+ *
330
+ * - CRYPT_RC2_MODE_CFB
331
+ *
332
+ * - CRYPT_RC2_MODE_OFB
333
+ *
334
+ * If not explictly set, CRYPT_RC2_MODE_CBC will be used.
335
+ *
336
+ * @see Crypt_Base::Crypt_Base()
337
+ * @param optional Integer $mode
338
+ * @access public
339
+ */
340
+ function Crypt_RC2($mode = CRYPT_RC2_MODE_CBC)
341
+ {
342
+ parent::Crypt_Base($mode);
343
+ $this->setKey('');
344
+ }
345
+
346
+ /**
347
+ * Sets the key length
348
+ *
349
+ * Valid key lengths are 1 to 1024.
350
+ * Calling this function after setting the key has no effect until the next
351
+ * Crypt_RC2::setKey() call.
352
+ *
353
+ * @access public
354
+ * @param Integer $length in bits
355
+ */
356
+ function setKeyLength($length)
357
+ {
358
+ if ($length >= 1 && $length <= 1024) {
359
+ $this->default_key_length = $length;
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Sets the key.
365
+ *
366
+ * Keys can be of any length. RC2, itself, uses 1 to 1024 bit keys (eg.
367
+ * strlen($key) <= 128), however, we only use the first 128 bytes if $key
368
+ * has more then 128 bytes in it, and set $key to a single null byte if
369
+ * it is empty.
370
+ *
371
+ * If the key is not explicitly set, it'll be assumed to be a single
372
+ * null byte.
373
+ *
374
+ * @see Crypt_Base::setKey()
375
+ * @access public
376
+ * @param String $key
377
+ * @param Integer $t1 optional Effective key length in bits.
378
+ */
379
+ function setKey($key, $t1 = 0)
380
+ {
381
+ if ($t1 <= 0) {
382
+ $t1 = $this->default_key_length;
383
+ } else if ($t1 > 1024) {
384
+ $t1 = 1024;
385
+ }
386
+ // Key byte count should be 1..128.
387
+ $key = strlen($key) ? substr($key, 0, 128): "\x00";
388
+ $t = strlen($key);
389
+
390
+ // The mcrypt RC2 implementation only supports effective key length
391
+ // of 1024 bits. It is however possible to handle effective key
392
+ // lengths in range 1..1024 by expanding the key and applying
393
+ // inverse pitable mapping to the first byte before submitting it
394
+ // to mcrypt.
395
+
396
+ // Key expansion.
397
+ $l = array_values(unpack('C*', $key));
398
+ $t8 = ($t1 + 7) >> 3;
399
+ $tm = 0xFF >> (8 * $t8 - $t1);
400
+
401
+ // Expand key.
402
+ $pitable = $this->pitable;
403
+ for ($i = $t; $i < 128; $i++) {
404
+ $l[$i] = $pitable[$l[$i - 1] + $l[$i - $t]];
405
+ }
406
+ $i = 128 - $t8;
407
+ $l[$i] = $pitable[$l[$i] & $tm];
408
+ while ($i--) {
409
+ $l[$i] = $pitable[$l[$i + 1] ^ $l[$i + $t8]];
410
+ }
411
+
412
+ // Prepare the key for mcrypt.
413
+ $l[0] = $this->invpitable[$l[0]];
414
+ array_unshift($l, 'C*');
415
+ parent::setKey(call_user_func_array('pack', $l));
416
+ }
417
+
418
+ /**
419
+ * Encrypts a block
420
+ *
421
+ * @see Crypt_Base::_encryptBlock()
422
+ * @see Crypt_Base::encrypt()
423
+ * @access private
424
+ * @param String $in
425
+ * @return String
426
+ */
427
+ function _encryptBlock($in)
428
+ {
429
+ list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in));
430
+ $keys = $this->keys;
431
+ $limit = 20;
432
+ $actions = array($limit => 44, 44 => 64);
433
+ $j = 0;
434
+
435
+ for (;;) {
436
+ // Mixing round.
437
+ $r0 = (($r0 + $keys[$j++] + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1;
438
+ $r0 |= $r0 >> 16;
439
+ $r1 = (($r1 + $keys[$j++] + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2;
440
+ $r1 |= $r1 >> 16;
441
+ $r2 = (($r2 + $keys[$j++] + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3;
442
+ $r2 |= $r2 >> 16;
443
+ $r3 = (($r3 + $keys[$j++] + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5;
444
+ $r3 |= $r3 >> 16;
445
+
446
+ if ($j == $limit) {
447
+ if ($limit == 64) {
448
+ break;
449
+ }
450
+
451
+ // Mashing round.
452
+ $r0 += $keys[$r3 & 0x3F];
453
+ $r1 += $keys[$r0 & 0x3F];
454
+ $r2 += $keys[$r1 & 0x3F];
455
+ $r3 += $keys[$r2 & 0x3F];
456
+ $limit = $actions[$limit];
457
+ }
458
+ }
459
+
460
+ return pack('vvvv', $r0, $r1, $r2, $r3);
461
+ }
462
+
463
+ /**
464
+ * Decrypts a block
465
+ *
466
+ * @see Crypt_Base::_decryptBlock()
467
+ * @see Crypt_Base::decrypt()
468
+ * @access private
469
+ * @param String $in
470
+ * @return String
471
+ */
472
+ function _decryptBlock($in)
473
+ {
474
+ list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in));
475
+ $keys = $this->keys;
476
+ $limit = 44;
477
+ $actions = array($limit => 20, 20 => 0);
478
+ $j = 64;
479
+
480
+ for (;;) {
481
+ // R-mixing round.
482
+ $r3 = ($r3 | ($r3 << 16)) >> 5;
483
+ $r3 = ($r3 - $keys[--$j] - ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF;
484
+ $r2 = ($r2 | ($r2 << 16)) >> 3;
485
+ $r2 = ($r2 - $keys[--$j] - ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF;
486
+ $r1 = ($r1 | ($r1 << 16)) >> 2;
487
+ $r1 = ($r1 - $keys[--$j] - ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF;
488
+ $r0 = ($r0 | ($r0 << 16)) >> 1;
489
+ $r0 = ($r0 - $keys[--$j] - ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF;
490
+
491
+ if ($j == $limit) {
492
+ if (!$limit) {
493
+ break;
494
+ }
495
+
496
+ // R-mashing round.
497
+ $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF;
498
+ $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF;
499
+ $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF;
500
+ $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF;
501
+ $limit = $actions[$limit];
502
+ }
503
+ }
504
+
505
+ return pack('vvvv', $r0, $r1, $r2, $r3);
506
+ }
507
+
508
+ /**
509
+ * Creates the key schedule
510
+ *
511
+ * @see Crypt_Base::_setupKey()
512
+ * @access private
513
+ */
514
+ function _setupKey()
515
+ {
516
+ // Key has already been expanded in Crypt_RC2::setKey():
517
+ // Only the first value must be altered.
518
+ $l = unpack('Ca/Cb/v*', $this->key);
519
+ array_unshift($l, $this->pitable[$l['a']] | ($l['b'] << 8));
520
+ unset($l['a']);
521
+ unset($l['b']);
522
+ $this->keys = $l;
523
+ }
524
+
525
+ /**
526
+ * Setup the performance-optimized function for de/encrypt()
527
+ *
528
+ * @see Crypt_Base::_setupInlineCrypt()
529
+ * @access private
530
+ */
531
+ function _setupInlineCrypt()
532
+ {
533
+ $lambda_functions = &Crypt_RC2::_getLambdaFunctions();
534
+
535
+ // The first 10 generated $lambda_functions will use the $keys hardcoded as integers
536
+ // for the mixing rounds, for better inline crypt performance [~20% faster].
537
+ // But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10.
538
+ $keys = $this->keys;
539
+ if (count($lambda_functions) >= 10) {
540
+ foreach ($this->keys as $k => $v) {
541
+ $keys[$k] = '$keys[' . $k . ']';
542
+ }
543
+ }
544
+
545
+ $code_hash = md5(str_pad("Crypt_RC2, {$this->mode}, ", 32, "\0") . implode(',', $keys));
546
+
547
+ // Is there a re-usable $lambda_functions in there?
548
+ // If not, we have to create it.
549
+ if (!isset($lambda_functions[$code_hash])) {
550
+ // Init code for both, encrypt and decrypt.
551
+ $init_crypt = '$keys = $self->keys;';
552
+
553
+ // $in is the current 8 bytes block which has to be en/decrypt
554
+ $encrypt_block = $decrypt_block = '
555
+ $in = unpack("v4", $in);
556
+ $r0 = $in[1];
557
+ $r1 = $in[2];
558
+ $r2 = $in[3];
559
+ $r3 = $in[4];
560
+ ';
561
+
562
+ // Create code for encryption.
563
+ $limit = 20;
564
+ $actions = array($limit => 44, 44 => 64);
565
+ $j = 0;
566
+
567
+ for (;;) {
568
+ // Mixing round.
569
+ $encrypt_block .= '
570
+ $r0 = (($r0 + ' . $keys[$j++] . ' +
571
+ ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1;
572
+ $r0 |= $r0 >> 16;
573
+ $r1 = (($r1 + ' . $keys[$j++] . ' +
574
+ ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2;
575
+ $r1 |= $r1 >> 16;
576
+ $r2 = (($r2 + ' . $keys[$j++] . ' +
577
+ ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3;
578
+ $r2 |= $r2 >> 16;
579
+ $r3 = (($r3 + ' . $keys[$j++] . ' +
580
+ ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5;
581
+ $r3 |= $r3 >> 16;';
582
+
583
+ if ($j == $limit) {
584
+ if ($limit == 64) {
585
+ break;
586
+ }
587
+
588
+ // Mashing round.
589
+ $encrypt_block .= '
590
+ $r0 += $keys[$r3 & 0x3F];
591
+ $r1 += $keys[$r0 & 0x3F];
592
+ $r2 += $keys[$r1 & 0x3F];
593
+ $r3 += $keys[$r2 & 0x3F];';
594
+ $limit = $actions[$limit];
595
+ }
596
+ }
597
+
598
+ $encrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);';
599
+
600
+ // Create code for decryption.
601
+ $limit = 44;
602
+ $actions = array($limit => 20, 20 => 0);
603
+ $j = 64;
604
+
605
+ for (;;) {
606
+ // R-mixing round.
607
+ $decrypt_block .= '
608
+ $r3 = ($r3 | ($r3 << 16)) >> 5;
609
+ $r3 = ($r3 - ' . $keys[--$j] . ' -
610
+ ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF;
611
+ $r2 = ($r2 | ($r2 << 16)) >> 3;
612
+ $r2 = ($r2 - ' . $keys[--$j] . ' -
613
+ ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF;
614
+ $r1 = ($r1 | ($r1 << 16)) >> 2;
615
+ $r1 = ($r1 - ' . $keys[--$j] . ' -
616
+ ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF;
617
+ $r0 = ($r0 | ($r0 << 16)) >> 1;
618
+ $r0 = ($r0 - ' . $keys[--$j] . ' -
619
+ ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF;';
620
+
621
+ if ($j == $limit) {
622
+ if (!$limit) {
623
+ break;
624
+ }
625
+
626
+ // R-mashing round.
627
+ $decrypt_block .= '
628
+ $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF;
629
+ $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF;
630
+ $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF;
631
+ $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF;';
632
+ $limit = $actions[$limit];
633
+ }
634
+ }
635
+
636
+ $decrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);';
637
+
638
+ // Creates the inline-crypt function
639
+ $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
640
+ array(
641
+ 'init_crypt' => $init_crypt,
642
+ 'encrypt_block' => $encrypt_block,
643
+ 'decrypt_block' => $decrypt_block
644
+ )
645
+ );
646
+ }
647
+
648
+ // Set the inline-crypt function as callback in: $this->inline_crypt
649
+ $this->inline_crypt = $lambda_functions[$code_hash];
650
+ }
651
+ }
652
+
lib/LivrariOnline/RC4.php ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of RC4.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Useful resources are as follows:
11
+ *
12
+ * - {@link http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt ARCFOUR Algorithm}
13
+ * - {@link http://en.wikipedia.org/wiki/RC4 - Wikipedia: RC4}
14
+ *
15
+ * RC4 is also known as ARCFOUR or ARC4. The reason is elaborated upon at Wikipedia. This class is named RC4 and not
16
+ * ARCFOUR or ARC4 because RC4 is how it is referred to in the SSH1 specification.
17
+ *
18
+ * Here's a short example of how to use this library:
19
+ * <code>
20
+ * <?php
21
+ * include('Crypt/RC4.php');
22
+ *
23
+ * $rc4 = new Crypt_RC4();
24
+ *
25
+ * $rc4->setKey('abcdefgh');
26
+ *
27
+ * $size = 10 * 1024;
28
+ * $plaintext = '';
29
+ * for ($i = 0; $i < $size; $i++) {
30
+ * $plaintext.= 'a';
31
+ * }
32
+ *
33
+ * echo $rc4->decrypt($rc4->encrypt($plaintext));
34
+ * ?>
35
+ * </code>
36
+ *
37
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
38
+ * of this software and associated documentation files (the "Software"), to deal
39
+ * in the Software without restriction, including without limitation the rights
40
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41
+ * copies of the Software, and to permit persons to whom the Software is
42
+ * furnished to do so, subject to the following conditions:
43
+ *
44
+ * The above copyright notice and this permission notice shall be included in
45
+ * all copies or substantial portions of the Software.
46
+ *
47
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
53
+ * THE SOFTWARE.
54
+ *
55
+ * @category Crypt
56
+ * @package Crypt_RC4
57
+ * @author Jim Wigginton <terrafrost@php.net>
58
+ * @copyright MMVII Jim Wigginton
59
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
60
+ * @link http://phpseclib.sourceforge.net
61
+ */
62
+
63
+ /**
64
+ * Include Crypt_Base
65
+ *
66
+ * Base cipher class
67
+ */
68
+ require_once('Base.php');
69
+
70
+ /**#@+
71
+ * @access private
72
+ * @see Crypt_RC4::Crypt_RC4()
73
+ */
74
+ /**
75
+ * Toggles the internal implementation
76
+ */
77
+ define('CRYPT_RC4_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
78
+ /**
79
+ * Toggles the mcrypt implementation
80
+ */
81
+ define('CRYPT_RC4_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
82
+ /**#@-*/
83
+
84
+ /**#@+
85
+ * @access private
86
+ * @see Crypt_RC4::_crypt()
87
+ */
88
+ define('CRYPT_RC4_ENCRYPT', 0);
89
+ define('CRYPT_RC4_DECRYPT', 1);
90
+ /**#@-*/
91
+
92
+ /**
93
+ * Pure-PHP implementation of RC4.
94
+ *
95
+ * @package Crypt_RC4
96
+ * @author Jim Wigginton <terrafrost@php.net>
97
+ * @version 0.1.0
98
+ * @access public
99
+ */
100
+ class Crypt_RC4 extends Crypt_Base
101
+ {
102
+ /**
103
+ * Block Length of the cipher
104
+ *
105
+ * RC4 is a stream cipher
106
+ * so we the block_size to 0
107
+ *
108
+ * @see Crypt_Base::block_size
109
+ * @var Integer
110
+ * @access private
111
+ */
112
+ var $block_size = 0;
113
+
114
+ /**
115
+ * The default password key_size used by setPassword()
116
+ *
117
+ * @see Crypt_Base::password_key_size
118
+ * @see Crypt_Base::setPassword()
119
+ * @var Integer
120
+ * @access private
121
+ */
122
+ var $password_key_size = 128; // = 1024 bits
123
+
124
+ /**
125
+ * The namespace used by the cipher for its constants.
126
+ *
127
+ * @see Crypt_Base::const_namespace
128
+ * @var String
129
+ * @access private
130
+ */
131
+ var $const_namespace = 'RC4';
132
+
133
+
134
+ /**
135
+ * The mcrypt specific name of the cipher
136
+ *
137
+ * @see Crypt_Base::cipher_name_mcrypt
138
+ * @var String
139
+ * @access private
140
+ */
141
+ var $cipher_name_mcrypt = 'arcfour';
142
+
143
+ /**
144
+ * Holds whether performance-optimized $inline_crypt() can/should be used.
145
+ *
146
+ * @see Crypt_Base::inline_crypt
147
+ * @var mixed
148
+ * @access private
149
+ */
150
+ var $use_inline_crypt = false; // currently not available
151
+
152
+ /**
153
+ * The Key
154
+ *
155
+ * @see Crypt_RC4::setKey()
156
+ * @var String
157
+ * @access private
158
+ */
159
+ var $key = "\0";
160
+
161
+ /**
162
+ * The Key Stream for decryption and encryption
163
+ *
164
+ * @see Crypt_RC4::setKey()
165
+ * @var Array
166
+ * @access private
167
+ */
168
+ var $stream;
169
+
170
+ /**
171
+ * Default Constructor.
172
+ *
173
+ * Determines whether or not the mcrypt extension should be used.
174
+ *
175
+ * @see Crypt_Base::Crypt_Base()
176
+ * @return Crypt_RC4
177
+ * @access public
178
+ */
179
+ function Crypt_RC4()
180
+ {
181
+ parent::Crypt_Base(CRYPT_MODE_STREAM);
182
+ }
183
+
184
+ /**
185
+ * Dummy function.
186
+ *
187
+ * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1].
188
+ * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before
189
+ * calling setKey().
190
+ *
191
+ * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol,
192
+ * the IV's are relatively easy to predict, an attack described by
193
+ * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir}
194
+ * can be used to quickly guess at the rest of the key. The following links elaborate:
195
+ *
196
+ * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009}
197
+ * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack}
198
+ *
199
+ * @param String $iv
200
+ * @see Crypt_RC4::setKey()
201
+ * @access public
202
+ */
203
+ function setIV($iv)
204
+ {
205
+ }
206
+
207
+ /**
208
+ * Sets the key.
209
+ *
210
+ * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will
211
+ * be used. If no key is explicitly set, it'll be assumed to be a single null byte.
212
+ *
213
+ * @access public
214
+ * @see Crypt_Base::setKey()
215
+ * @param String $key
216
+ */
217
+ function setKey($key)
218
+ {
219
+ parent::setKey(substr($key, 0, 256));
220
+ }
221
+
222
+ /**
223
+ * Encrypts a message.
224
+ *
225
+ * @see Crypt_Base::decrypt()
226
+ * @see Crypt_RC4::_crypt()
227
+ * @access public
228
+ * @param String $plaintext
229
+ * @return String $ciphertext
230
+ */
231
+ function encrypt($plaintext)
232
+ {
233
+ if ($this->engine == CRYPT_MODE_MCRYPT) {
234
+ return parent::encrypt($plaintext);
235
+ }
236
+ return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT);
237
+ }
238
+
239
+ /**
240
+ * Decrypts a message.
241
+ *
242
+ * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
243
+ * Atleast if the continuous buffer is disabled.
244
+ *
245
+ * @see Crypt_Base::encrypt()
246
+ * @see Crypt_RC4::_crypt()
247
+ * @access public
248
+ * @param String $ciphertext
249
+ * @return String $plaintext
250
+ */
251
+ function decrypt($ciphertext)
252
+ {
253
+ if ($this->engine == CRYPT_MODE_MCRYPT) {
254
+ return parent::decrypt($ciphertext);
255
+ }
256
+ return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT);
257
+ }
258
+
259
+
260
+ /**
261
+ * Setup the key (expansion)
262
+ *
263
+ * @see Crypt_Base::_setupKey()
264
+ * @access private
265
+ */
266
+ function _setupKey()
267
+ {
268
+ $key = $this->key;
269
+ $keyLength = strlen($key);
270
+ $keyStream = array();
271
+ for ($i = 0; $i < 256; $i++) {
272
+ $keyStream[$i] = $i;
273
+ }
274
+ $j = 0;
275
+ for ($i = 0; $i < 256; $i++) {
276
+ $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
277
+ $temp = $keyStream[$i];
278
+ $keyStream[$i] = $keyStream[$j];
279
+ $keyStream[$j] = $temp;
280
+ }
281
+
282
+ $this->stream = array();
283
+ $this->stream[CRYPT_RC4_DECRYPT] = $this->stream[CRYPT_RC4_ENCRYPT] = array(
284
+ 0, // index $i
285
+ 0, // index $j
286
+ $keyStream
287
+ );
288
+ }
289
+
290
+ /**
291
+ * Encrypts or decrypts a message.
292
+ *
293
+ * @see Crypt_RC4::encrypt()
294
+ * @see Crypt_RC4::decrypt()
295
+ * @access private
296
+ * @param String $text
297
+ * @param Integer $mode
298
+ * @return String $text
299
+ */
300
+ function _crypt($text, $mode)
301
+ {
302
+ if ($this->changed) {
303
+ $this->_setup();
304
+ $this->changed = false;
305
+ }
306
+
307
+ $stream = &$this->stream[$mode];
308
+ if ($this->continuousBuffer) {
309
+ $i = &$stream[0];
310
+ $j = &$stream[1];
311
+ $keyStream = &$stream[2];
312
+ } else {
313
+ $i = $stream[0];
314
+ $j = $stream[1];
315
+ $keyStream = $stream[2];
316
+ }
317
+
318
+ $len = strlen($text);
319
+ for ($k = 0; $k < $len; ++$k) {
320
+ $i = ($i + 1) & 255;
321
+ $ksi = $keyStream[$i];
322
+ $j = ($j + $ksi) & 255;
323
+ $ksj = $keyStream[$j];
324
+
325
+ $keyStream[$i] = $ksj;
326
+ $keyStream[$j] = $ksi;
327
+ $text[$k] = chr(ord($text[$k]) ^ $keyStream[($ksj + $ksi) & 255]);
328
+ }
329
+
330
+ return $text;
331
+ }
332
+ }
333
+
lib/LivrariOnline/RSA.php ADDED
@@ -0,0 +1,2661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
6
+ *
7
+ * PHP versions 4 and 5
8
+ *
9
+ * Here's an example of how to encrypt and decrypt text with this library:
10
+ * <code>
11
+ * <?php
12
+ * include('Crypt/RSA.php');
13
+ *
14
+ * $rsa = new Crypt_RSA();
15
+ * extract($rsa->createKey());
16
+ *
17
+ * $plaintext = 'terrafrost';
18
+ *
19
+ * $rsa->loadKey($privatekey);
20
+ * $ciphertext = $rsa->encrypt($plaintext);
21
+ *
22
+ * $rsa->loadKey($publickey);
23
+ * echo $rsa->decrypt($ciphertext);
24
+ * ?>
25
+ * </code>
26
+ *
27
+ * Here's an example of how to create signatures and verify signatures with this library:
28
+ * <code>
29
+ * <?php
30
+ * include('Crypt/RSA.php');
31
+ *
32
+ * $rsa = new Crypt_RSA();
33
+ * extract($rsa->createKey());
34
+ *
35
+ * $plaintext = 'terrafrost';
36
+ *
37
+ * $rsa->loadKey($privatekey);
38
+ * $signature = $rsa->sign($plaintext);
39
+ *
40
+ * $rsa->loadKey($publickey);
41
+ * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
42
+ * ?>
43
+ * </code>
44
+ *
45
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
46
+ * of this software and associated documentation files (the "Software"), to deal
47
+ * in the Software without restriction, including without limitation the rights
48
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
49
+ * copies of the Software, and to permit persons to whom the Software is
50
+ * furnished to do so, subject to the following conditions:
51
+ *
52
+ * The above copyright notice and this permission notice shall be included in
53
+ * all copies or substantial portions of the Software.
54
+ *
55
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
56
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
57
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
58
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
59
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
60
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
61
+ * THE SOFTWARE.
62
+ *
63
+ * @category Crypt
64
+ * @package Crypt_RSA
65
+ * @author Jim Wigginton <terrafrost@php.net>
66
+ * @copyright MMIX Jim Wigginton
67
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
68
+ * @link http://phpseclib.sourceforge.net
69
+ */
70
+
71
+ define("LIBPATH", "lib/LivrariOnline/Crypt");
72
+ /**
73
+ * Include Crypt_Random
74
+ */
75
+ // the class_exists() will only be called if the crypt_random_string function hasn't been defined and
76
+ // will trigger a call to __autoload() if you're wanting to auto-load classes
77
+ // call function_exists() a second time to stop the require_once from being called outside
78
+ // of the auto loader
79
+ require_once('Random.php');
80
+ require_once('Hash.php');
81
+ require_once('BigInteger.php');
82
+ require_once('Rijndael.php');
83
+ require_once('AES.php');
84
+ require_once('TripleDES.php');
85
+ require_once('DES.php');
86
+
87
+
88
+ /**#@+
89
+ * @access public
90
+ * @see Crypt_RSA::encrypt()
91
+ * @see Crypt_RSA::decrypt()
92
+ */
93
+ /**
94
+ * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
95
+ * (OAEP) for encryption / decryption.
96
+ *
97
+ * Uses sha1 by default.
98
+ *
99
+ * @see Crypt_RSA::setHash()
100
+ * @see Crypt_RSA::setMGFHash()
101
+ */
102
+ define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
103
+ /**
104
+ * Use PKCS#1 padding.
105
+ *
106
+ * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
107
+ * compatability with protocols (like SSH-1) written before OAEP's introduction.
108
+ */
109
+ define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
110
+ /**#@-*/
111
+
112
+ /**#@+
113
+ * @access public
114
+ * @see Crypt_RSA::sign()
115
+ * @see Crypt_RSA::verify()
116
+ * @see Crypt_RSA::setHash()
117
+ */
118
+ /**
119
+ * Use the Probabilistic Signature Scheme for signing
120
+ *
121
+ * Uses sha1 by default.
122
+ *
123
+ * @see Crypt_RSA::setSaltLength()
124
+ * @see Crypt_RSA::setMGFHash()
125
+ */
126
+ define('CRYPT_RSA_SIGNATURE_PSS', 1);
127
+ /**
128
+ * Use the PKCS#1 scheme by default.
129
+ *
130
+ * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
131
+ * compatability with protocols (like SSH-2) written before PSS's introduction.
132
+ */
133
+ define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
134
+ /**#@-*/
135
+
136
+ /**#@+
137
+ * @access private
138
+ * @see Crypt_RSA::createKey()
139
+ */
140
+ /**
141
+ * ASN1 Integer
142
+ */
143
+ define('CRYPT_RSA_ASN1_INTEGER', 2);
144
+ /**
145
+ * ASN1 Bit String
146
+ */
147
+ define('CRYPT_RSA_ASN1_BITSTRING', 3);
148
+ /**
149
+ * ASN1 Sequence (with the constucted bit set)
150
+ */
151
+ define('CRYPT_RSA_ASN1_SEQUENCE', 48);
152
+ /**#@-*/
153
+
154
+ /**#@+
155
+ * @access private
156
+ * @see Crypt_RSA::Crypt_RSA()
157
+ */
158
+ /**
159
+ * To use the pure-PHP implementation
160
+ */
161
+ define('CRYPT_RSA_MODE_INTERNAL', 1);
162
+ /**
163
+ * To use the OpenSSL library
164
+ *
165
+ * (if enabled; otherwise, the internal implementation will be used)
166
+ */
167
+ define('CRYPT_RSA_MODE_OPENSSL', 2);
168
+ /**#@-*/
169
+
170
+ /**
171
+ * Default openSSL configuration file.
172
+ */
173
+ define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/openssl.cnf');
174
+
175
+
176
+ /**#@+
177
+ * @access public
178
+ * @see Crypt_RSA::createKey()
179
+ * @see Crypt_RSA::setPrivateKeyFormat()
180
+ */
181
+ /**
182
+ * PKCS#1 formatted private key
183
+ *
184
+ * Used by OpenSSH
185
+ */
186
+ define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
187
+ /**
188
+ * PuTTY formatted private key
189
+ */
190
+ define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
191
+ /**
192
+ * XML formatted private key
193
+ */
194
+ define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
195
+ /**#@-*/
196
+
197
+ /**#@+
198
+ * @access public
199
+ * @see Crypt_RSA::createKey()
200
+ * @see Crypt_RSA::setPublicKeyFormat()
201
+ */
202
+ /**
203
+ * Raw public key
204
+ *
205
+ * An array containing two Math_BigInteger objects.
206
+ *
207
+ * The exponent can be indexed with any of the following:
208
+ *
209
+ * 0, e, exponent, publicExponent
210
+ *
211
+ * The modulus can be indexed with any of the following:
212
+ *
213
+ * 1, n, modulo, modulus
214
+ */
215
+ define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
216
+ /**
217
+ * PKCS#1 formatted public key (raw)
218
+ *
219
+ * Used by File/X509.php
220
+ */
221
+ define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
222
+ /**
223
+ * XML formatted public key
224
+ */
225
+ define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
226
+ /**
227
+ * OpenSSH formatted public key
228
+ *
229
+ * Place in $HOME/.ssh/authorized_keys
230
+ */
231
+ define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
232
+ /**
233
+ * PKCS#1 formatted public key (encapsulated)
234
+ *
235
+ * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
236
+ */
237
+ define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 7);
238
+ /**#@-*/
239
+
240
+ /**
241
+ * Pure-PHP PKCS#1 compliant implementation of RSA.
242
+ *
243
+ * @author Jim Wigginton <terrafrost@php.net>
244
+ * @version 0.1.0
245
+ * @access public
246
+ * @package Crypt_RSA
247
+ */
248
+ class Crypt_RSA {
249
+ /**
250
+ * Precomputed Zero
251
+ *
252
+ * @var Array
253
+ * @access private
254
+ */
255
+ var $zero;
256
+
257
+ /**
258
+ * Precomputed One
259
+ *
260
+ * @var Array
261
+ * @access private
262
+ */
263
+ var $one;
264
+
265
+ /**
266
+ * Private Key Format
267
+ *
268
+ * @var Integer
269
+ * @access private
270
+ */
271
+ var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
272
+
273
+ /**
274
+ * Public Key Format
275
+ *
276
+ * @var Integer
277
+ * @access public
278
+ */
279
+ var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
280
+
281
+ /**
282
+ * Modulus (ie. n)
283
+ *
284
+ * @var Math_BigInteger
285
+ * @access private
286
+ */
287
+ var $modulus;
288
+
289
+ /**
290
+ * Modulus length
291
+ *
292
+ * @var Math_BigInteger
293
+ * @access private
294
+ */
295
+ var $k;
296
+
297
+ /**
298
+ * Exponent (ie. e or d)
299
+ *
300
+ * @var Math_BigInteger
301
+ * @access private
302
+ */
303
+ var $exponent;
304
+
305
+ /**
306
+ * Primes for Chinese Remainder Theorem (ie. p and q)
307
+ *
308
+ * @var Array
309
+ * @access private
310
+ */
311
+ var $primes;
312
+
313
+ /**
314
+ * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
315
+ *
316
+ * @var Array
317
+ * @access private
318
+ */
319
+ var $exponents;
320
+
321
+ /**
322
+ * Coefficients for Chinese Remainder Theorem (ie. qInv)
323
+ *
324
+ * @var Array
325
+ * @access private
326
+ */
327
+ var $coefficients;
328
+
329
+ /**
330
+ * Hash name
331
+ *
332
+ * @var String
333
+ * @access private
334
+ */
335
+ var $hashName;
336
+
337
+ /**
338
+ * Hash function
339
+ *
340
+ * @var Crypt_Hash
341
+ * @access private
342
+ */
343
+ var $hash;
344
+
345
+ /**
346
+ * Length of hash function output
347
+ *
348
+ * @var Integer
349
+ * @access private
350
+ */
351
+ var $hLen;
352
+
353
+ /**
354
+ * Length of salt
355
+ *
356
+ * @var Integer
357
+ * @access private
358
+ */
359
+ var $sLen;
360
+
361
+ /**
362
+ * Hash function for the Mask Generation Function
363
+ *
364
+ * @var Crypt_Hash
365
+ * @access private
366
+ */
367
+ var $mgfHash;
368
+
369
+ /**
370
+ * Length of MGF hash function output
371
+ *
372
+ * @var Integer
373
+ * @access private
374
+ */
375
+ var $mgfHLen;
376
+
377
+ /**
378
+ * Encryption mode
379
+ *
380
+ * @var Integer
381
+ * @access private
382
+ */
383
+ var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
384
+
385
+ /**
386
+ * Signature mode
387
+ *
388
+ * @var Integer
389
+ * @access private
390
+ */
391
+ var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
392
+
393
+ /**
394
+ * Public Exponent
395
+ *
396
+ * @var Mixed
397
+ * @access private
398
+ */
399
+ var $publicExponent = false;
400
+
401
+ /**
402
+ * Password
403
+ *
404
+ * @var String
405
+ * @access private
406
+ */
407
+ var $password = false;
408
+
409
+ /**
410
+ * Components
411
+ *
412
+ * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
413
+ * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
414
+ *
415
+ * @see Crypt_RSA::_start_element_handler()
416
+ * @var Array
417
+ * @access private
418
+ */
419
+ var $components = array();
420
+
421
+ /**
422
+ * Current String
423
+ *
424
+ * For use with parsing XML formatted keys.
425
+ *
426
+ * @see Crypt_RSA::_character_handler()
427
+ * @see Crypt_RSA::_stop_element_handler()
428
+ * @var Mixed
429
+ * @access private
430
+ */
431
+ var $current;
432
+
433
+ /**
434
+ * OpenSSL configuration file name.
435
+ *
436
+ * Set to NULL to use system configuration file.
437
+ * @see Crypt_RSA::createKey()
438
+ * @var Mixed
439
+ * @Access public
440
+ */
441
+ var $configFile;
442
+
443
+ /**
444
+ * Public key comment field.
445
+ *
446
+ * @var String
447
+ * @access private
448
+ */
449
+ var $comment = 'phpseclib-generated-key';
450
+
451
+ /**
452
+ * The constructor
453
+ *
454
+ * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
455
+ * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
456
+ * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
457
+ *
458
+ * @return Crypt_RSA
459
+ * @access public
460
+ */
461
+ function Crypt_RSA()
462
+ {
463
+
464
+
465
+ $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
466
+
467
+ if ( !defined('CRYPT_RSA_MODE') ) {
468
+ switch (true) {
469
+ case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
470
+ define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
471
+ break;
472
+ default:
473
+ define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
474
+ }
475
+ }
476
+
477
+ $this->zero = new Math_BigInteger();
478
+ $this->one = new Math_BigInteger(1);
479
+
480
+ $this->hash = new Crypt_Hash('sha1');
481
+ $this->hLen = $this->hash->getLength();
482
+ $this->hashName = 'sha1';
483
+ $this->mgfHash = new Crypt_Hash('sha1');
484
+ $this->mgfHLen = $this->mgfHash->getLength();
485
+ }
486
+
487
+ /**
488
+ * Create public / private key pair
489
+ *
490
+ * Returns an array with the following three elements:
491
+ * - 'privatekey': The private key.
492
+ * - 'publickey': The public key.
493
+ * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
494
+ * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
495
+ *
496
+ * @access public
497
+ * @param optional Integer $bits
498
+ * @param optional Integer $timeout
499
+ * @param optional Math_BigInteger $p
500
+ */
501
+ function createKey($bits = 1024, $timeout = false, $partial = array())
502
+ {
503
+ if (!defined('CRYPT_RSA_EXPONENT')) {
504
+ // http://en.wikipedia.org/wiki/65537_%28number%29
505
+ define('CRYPT_RSA_EXPONENT', '65537');
506
+ }
507
+ // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
508
+ // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
509
+ // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
510
+ // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
511
+ // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
512
+ // generation when there's a chance neither gmp nor OpenSSL are installed)
513
+ if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
514
+ define('CRYPT_RSA_SMALLEST_PRIME', 4096);
515
+ }
516
+
517
+ // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
518
+ if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
519
+ $config = array();
520
+ if (isset($this->configFile)) {
521
+ $config['config'] = $this->configFile;
522
+ }
523
+ $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
524
+ openssl_pkey_export($rsa, $privatekey, NULL, $config);
525
+ $publickey = openssl_pkey_get_details($rsa);
526
+ $publickey = $publickey['key'];
527
+
528
+ $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
529
+ $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
530
+
531
+ // clear the buffer of error strings stemming from a minimalistic openssl.cnf
532
+ while (openssl_error_string() !== false);
533
+
534
+ return array(
535
+ 'privatekey' => $privatekey,
536
+ 'publickey' => $publickey,
537
+ 'partialkey' => false
538
+ );
539
+ }
540
+
541
+ static $e;
542
+ if (!isset($e)) {
543
+ $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
544
+ }
545
+
546
+ extract($this->_generateMinMax($bits));
547
+ $absoluteMin = $min;
548
+ $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
549
+ if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
550
+ $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
551
+ $temp = CRYPT_RSA_SMALLEST_PRIME;
552
+ } else {
553
+ $num_primes = 2;
554
+ }
555
+ extract($this->_generateMinMax($temp + $bits % $temp));
556
+ $finalMax = $max;
557
+ extract($this->_generateMinMax($temp));
558
+
559
+ $generator = new Math_BigInteger();
560
+
561
+ $n = $this->one->copy();
562
+ if (!empty($partial)) {
563
+ extract(unserialize($partial));
564
+ } else {
565
+ $exponents = $coefficients = $primes = array();
566
+ $lcm = array(
567
+ 'top' => $this->one->copy(),
568
+ 'bottom' => false
569
+ );
570
+ }
571
+
572
+ $start = time();
573
+ $i0 = count($primes) + 1;
574
+
575
+ do {
576
+ for ($i = $i0; $i <= $num_primes; $i++) {
577
+ if ($timeout !== false) {
578
+ $timeout-= time() - $start;
579
+ $start = time();
580
+ if ($timeout <= 0) {
581
+ return array(
582
+ 'privatekey' => '',
583
+ 'publickey' => '',
584
+ 'partialkey' => serialize(array(
585
+ 'primes' => $primes,
586
+ 'coefficients' => $coefficients,
587
+ 'lcm' => $lcm,
588
+ 'exponents' => $exponents
589
+ ))
590
+ );
591
+ }
592
+ }
593
+
594
+ if ($i == $num_primes) {
595
+ list($min, $temp) = $absoluteMin->divide($n);
596
+ if (!$temp->equals($this->zero)) {
597
+ $min = $min->add($this->one); // ie. ceil()
598
+ }
599
+ $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
600
+ } else {
601
+ $primes[$i] = $generator->randomPrime($min, $max, $timeout);
602
+ }
603
+
604
+ if ($primes[$i] === false) { // if we've reached the timeout
605
+ if (count($primes) > 1) {
606
+ $partialkey = '';
607
+ } else {
608
+ array_pop($primes);
609
+ $partialkey = serialize(array(
610
+ 'primes' => $primes,
611
+ 'coefficients' => $coefficients,
612
+ 'lcm' => $lcm,
613
+ 'exponents' => $exponents
614
+ ));
615
+ }
616
+
617
+ return array(
618
+ 'privatekey' => '',
619
+ 'publickey' => '',
620
+ 'partialkey' => $partialkey
621
+ );
622
+ }
623
+
624
+ // the first coefficient is calculated differently from the rest
625
+ // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
626
+ if ($i > 2) {
627
+ $coefficients[$i] = $n->modInverse($primes[$i]);
628
+ }
629
+
630
+ $n = $n->multiply($primes[$i]);
631
+
632
+ $temp = $primes[$i]->subtract($this->one);
633
+
634
+ // textbook RSA implementations use Euler's totient function instead of the least common multiple.
635
+ // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
636
+ $lcm['top'] = $lcm['top']->multiply($temp);
637
+ $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
638
+
639
+ $exponents[$i] = $e->modInverse($temp);
640
+ }
641
+
642
+ list($lcm) = $lcm['top']->divide($lcm['bottom']);
643
+ $gcd = $lcm->gcd($e);
644
+ $i0 = 1;
645
+ } while (!$gcd->equals($this->one));
646
+
647
+ $d = $e->modInverse($lcm);
648
+
649
+ $coefficients[2] = $primes[2]->modInverse($primes[1]);
650
+
651
+ // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
652
+ // RSAPrivateKey ::= SEQUENCE {
653
+ // version Version,
654
+ // modulus INTEGER, -- n
655
+ // publicExponent INTEGER, -- e
656
+ // privateExponent INTEGER, -- d
657
+ // prime1 INTEGER, -- p
658
+ // prime2 INTEGER, -- q
659
+ // exponent1 INTEGER, -- d mod (p-1)
660
+ // exponent2 INTEGER, -- d mod (q-1)
661
+ // coefficient INTEGER, -- (inverse of q) mod p
662
+ // otherPrimeInfos OtherPrimeInfos OPTIONAL
663
+ // }
664
+
665
+ return array(
666
+ 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
667
+ 'publickey' => $this->_convertPublicKey($n, $e),
668
+ 'partialkey' => false
669
+ );
670
+ }
671
+
672
+ /**
673
+ * Convert a private key to the appropriate format.
674
+ *
675
+ * @access private
676
+ * @see setPrivateKeyFormat()
677
+ * @param String $RSAPrivateKey
678
+ * @return String
679
+ */
680
+ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
681
+ {
682
+ $num_primes = count($primes);
683
+ $raw = array(
684
+ 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
685
+ 'modulus' => $n->toBytes(true),
686
+ 'publicExponent' => $e->toBytes(true),
687
+ 'privateExponent' => $d->toBytes(true),
688
+ 'prime1' => $primes[1]->toBytes(true),
689
+ 'prime2' => $primes[2]->toBytes(true),
690
+ 'exponent1' => $exponents[1]->toBytes(true),
691
+ 'exponent2' => $exponents[2]->toBytes(true),
692
+ 'coefficient' => $coefficients[2]->toBytes(true)
693
+ );
694
+
695
+ // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
696
+ // call _convertPublicKey() instead.
697
+ switch ($this->privateKeyFormat) {
698
+ case CRYPT_RSA_PRIVATE_FORMAT_XML:
699
+ if ($num_primes != 2) {
700
+ return false;
701
+ }
702
+ return "<RSAKeyValue>\r\n" .
703
+ ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
704
+ ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
705
+ ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
706
+ ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
707
+ ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
708
+ ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
709
+ ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
710
+ ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
711
+ '</RSAKeyValue>';
712
+ break;
713
+ case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
714
+ if ($num_primes != 2) {
715
+ return false;
716
+ }
717
+ $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
718
+ $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
719
+ $key.= $encryption;
720
+ $key.= "\r\nComment: " . $this->comment . "\r\n";
721
+ $public = pack('Na*Na*Na*',
722
+ strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
723
+ );
724
+ $source = pack('Na*Na*Na*Na*',
725
+ strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
726
+ strlen($this->comment), $this->comment, strlen($public), $public
727
+ );
728
+ $public = base64_encode($public);
729
+ $key.= "Public-Lines: " . ((strlen($public) + 32) >> 6) . "\r\n";
730
+ $key.= chunk_split($public, 64);
731
+ $private = pack('Na*Na*Na*Na*',
732
+ strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
733
+ strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
734
+ );
735
+ if (empty($this->password) && !is_string($this->password)) {
736
+ $source.= pack('Na*', strlen($private), $private);
737
+ $hashkey = 'putty-private-key-file-mac-key';
738
+ } else {
739
+ $private.= crypt_random_string(16 - (strlen($private) & 15));
740
+ $source.= pack('Na*', strlen($private), $private);
741
+ $sequence = 0;
742
+ $symkey = '';
743
+ while (strlen($symkey) < 32) {
744
+ $temp = pack('Na*', $sequence++, $this->password);
745
+ $symkey.= pack('H*', sha1($temp));
746
+ }
747
+ $symkey = substr($symkey, 0, 32);
748
+ $crypto = new Crypt_AES();
749
+
750
+ $crypto->setKey($symkey);
751
+ $crypto->disablePadding();
752
+ $private = $crypto->encrypt($private);
753
+ $hashkey = 'putty-private-key-file-mac-key' . $this->password;
754
+ }
755
+
756
+ $private = base64_encode($private);
757
+ $key.= 'Private-Lines: ' . ((strlen($private) + 32) >> 6) . "\r\n";
758
+ $key.= chunk_split($private, 64);
759
+ $hash = new Crypt_Hash('sha1');
760
+ $hash->setKey(pack('H*', sha1($hashkey)));
761
+ $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
762
+
763
+ return $key;
764
+ default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
765
+ $components = array();
766
+ foreach ($raw as $name => $value) {
767
+ $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
768
+ }
769
+
770
+ $RSAPrivateKey = implode('', $components);
771
+
772
+ if ($num_primes > 2) {
773
+ $OtherPrimeInfos = '';
774
+ for ($i = 3; $i <= $num_primes; $i++) {
775
+ // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
776
+ //
777
+ // OtherPrimeInfo ::= SEQUENCE {
778
+ // prime INTEGER, -- ri
779
+ // exponent INTEGER, -- di
780
+ // coefficient INTEGER -- ti
781
+ // }
782
+ $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
783
+ $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
784
+ $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
785
+ $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
786
+ }
787
+ $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
788
+ }
789
+
790
+ $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
791
+
792
+ if (!empty($this->password) || is_string($this->password)) {
793
+ $iv = crypt_random_string(8);
794
+ $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
795
+ $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
796
+ $des = new Crypt_TripleDES();
797
+ $des->setKey($symkey);
798
+ $des->setIV($iv);
799
+ $iv = strtoupper(bin2hex($iv));
800
+ $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
801
+ "Proc-Type: 4,ENCRYPTED\r\n" .
802
+ "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
803
+ "\r\n" .
804
+ chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
805
+ '-----END RSA PRIVATE KEY-----';
806
+ } else {
807
+ $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
808
+ chunk_split(base64_encode($RSAPrivateKey), 64) .
809
+ '-----END RSA PRIVATE KEY-----';
810
+ }
811
+
812
+ return $RSAPrivateKey;
813
+ }
814
+ }
815
+
816
+ /**
817
+ * Convert a public key to the appropriate format
818
+ *
819
+ * @access private
820
+ * @see setPublicKeyFormat()
821
+ * @param String $RSAPrivateKey
822
+ * @return String
823
+ */
824
+ function _convertPublicKey($n, $e)
825
+ {
826
+ $modulus = $n->toBytes(true);
827
+ $publicExponent = $e->toBytes(true);
828
+
829
+ switch ($this->publicKeyFormat) {
830
+ case CRYPT_RSA_PUBLIC_FORMAT_RAW:
831
+ return array('e' => $e->copy(), 'n' => $n->copy());
832
+ case CRYPT_RSA_PUBLIC_FORMAT_XML:
833
+ return "<RSAKeyValue>\r\n" .
834
+ ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
835
+ ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
836
+ '</RSAKeyValue>';
837
+ break;
838
+ case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
839
+ // from <http://tools.ietf.org/html/rfc4253#page-15>:
840
+ // string "ssh-rsa"
841
+ // mpint e
842
+ // mpint n
843
+ $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
844
+ $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
845
+
846
+ return $RSAPublicKey;
847
+ default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
848
+ // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
849
+ // RSAPublicKey ::= SEQUENCE {
850
+ // modulus INTEGER, -- n
851
+ // publicExponent INTEGER -- e
852
+ // }
853
+ $components = array(
854
+ 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
855
+ 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
856
+ );
857
+
858
+ $RSAPublicKey = pack('Ca*a*a*',
859
+ CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
860
+ $components['modulus'], $components['publicExponent']
861
+ );
862
+
863
+ if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1) {
864
+ // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
865
+ $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
866
+ $RSAPublicKey = chr(0) . $RSAPublicKey;
867
+ $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
868
+
869
+ $RSAPublicKey = pack('Ca*a*',
870
+ CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
871
+ );
872
+ }
873
+
874
+ $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
875
+ chunk_split(base64_encode($RSAPublicKey), 64) .
876
+ '-----END PUBLIC KEY-----';
877
+
878
+ return $RSAPublicKey;
879
+ }
880
+ }
881
+
882
+ /**
883
+ * Break a public or private key down into its constituant components
884
+ *
885
+ * @access private
886
+ * @see _convertPublicKey()
887
+ * @see _convertPrivateKey()
888
+ * @param String $key
889
+ * @param Integer $type
890
+ * @return Array
891
+ */
892
+ function _parseKey($key, $type)
893
+ {
894
+ if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
895
+ return false;
896
+ }
897
+
898
+ switch ($type) {
899
+ case CRYPT_RSA_PUBLIC_FORMAT_RAW:
900
+ if (!is_array($key)) {
901
+ return false;
902
+ }
903
+ $components = array();
904
+ switch (true) {
905
+ case isset($key['e']):
906
+ $components['publicExponent'] = $key['e']->copy();
907
+ break;
908
+ case isset($key['exponent']):
909
+ $components['publicExponent'] = $key['exponent']->copy();
910
+ break;
911
+ case isset($key['publicExponent']):
912
+ $components['publicExponent'] = $key['publicExponent']->copy();
913
+ break;
914
+ case isset($key[0]):
915
+ $components['publicExponent'] = $key[0]->copy();
916
+ }
917
+ switch (true) {
918
+ case isset($key['n']):
919
+ $components['modulus'] = $key['n']->copy();
920
+ break;
921
+ case isset($key['modulo']):
922
+ $components['modulus'] = $key['modulo']->copy();
923
+ break;
924
+ case isset($key['modulus']):
925
+ $components['modulus'] = $key['modulus']->copy();
926
+ break;
927
+ case isset($key[1]):
928
+ $components['modulus'] = $key[1]->copy();
929
+ }
930
+ return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
931
+ case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
932
+ case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
933
+ /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
934
+ "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
935
+ protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
936
+ two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
937
+
938
+ http://tools.ietf.org/html/rfc1421#section-4.6.1.1
939
+ http://tools.ietf.org/html/rfc1421#section-4.6.1.3
940
+
941
+ DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
942
+ DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
943
+ function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
944
+ own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
945
+ implementation are part of the standard, as well.
946
+
947
+ * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
948
+ if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
949
+ $iv = pack('H*', trim($matches[2]));
950
+ $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
951
+ $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
952
+ $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-| #s', '', $key);
953
+ $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
954
+ if ($ciphertext === false) {
955
+ $ciphertext = $key;
956
+ }
957
+ switch ($matches[1]) {
958
+ case 'AES-256-CBC':
959
+ $crypto = new Crypt_AES();
960
+ break;
961
+ case 'AES-128-CBC':
962
+ $symkey = substr($symkey, 0, 16);
963
+ $crypto = new Crypt_AES();
964
+ break;
965
+ case 'DES-EDE3-CFB':
966
+ $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
967
+ break;
968
+ case 'DES-EDE3-CBC':
969
+ $symkey = substr($symkey, 0, 24);
970
+ $crypto = new Crypt_TripleDES();
971
+ break;
972
+ case 'DES-CBC':
973
+ $crypto = new Crypt_DES();
974
+ break;
975
+ default:
976
+ return false;
977
+ }
978
+ $crypto->setKey($symkey);
979
+ $crypto->setIV($iv);
980
+ $decoded = $crypto->decrypt($ciphertext);
981
+ } else {
982
+ $decoded = preg_replace('#-.+-|[\r\n]| #', '', $key);
983
+ $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
984
+ }
985
+
986
+ if ($decoded !== false) {
987
+ $key = $decoded;
988
+ }
989
+
990
+ $components = array();
991
+
992
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
993
+ return false;
994
+ }
995
+ if ($this->_decodeLength($key) != strlen($key)) {
996
+ return false;
997
+ }
998
+
999
+ $tag = ord($this->_string_shift($key));
1000
+ /* intended for keys for which OpenSSL's asn1parse returns the following:
1001
+
1002
+ 0:d=0 hl=4 l= 631 cons: SEQUENCE
1003
+ 4:d=1 hl=2 l= 1 prim: INTEGER :00
1004
+ 7:d=1 hl=2 l= 13 cons: SEQUENCE
1005
+ 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
1006
+ 20:d=2 hl=2 l= 0 prim: NULL
1007
+ 22:d=1 hl=4 l= 609 prim: OCTET STRING */
1008
+
1009
+ if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
1010
+ $this->_string_shift($key, 3);
1011
+ $tag = CRYPT_RSA_ASN1_SEQUENCE;
1012
+ }
1013
+
1014
+ if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
1015
+ /* intended for keys for which OpenSSL's asn1parse returns the following:
1016
+
1017
+ 0:d=0 hl=4 l= 290 cons: SEQUENCE
1018
+ 4:d=1 hl=2 l= 13 cons: SEQUENCE
1019
+ 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
1020
+ 17:d=2 hl=2 l= 0 prim: NULL
1021
+ 19:d=1 hl=4 l= 271 prim: BIT STRING */
1022
+ $this->_string_shift($key, $this->_decodeLength($key));
1023
+ $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
1024
+ $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
1025
+ // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
1026
+ // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
1027
+ // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
1028
+ if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
1029
+ $this->_string_shift($key);
1030
+ }
1031
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1032
+ return false;
1033
+ }
1034
+ if ($this->_decodeLength($key) != strlen($key)) {
1035
+ return false;
1036
+ }
1037
+ $tag = ord($this->_string_shift($key));
1038
+ }
1039
+ if ($tag != CRYPT_RSA_ASN1_INTEGER) {
1040
+ return false;
1041
+ }
1042
+
1043
+ $length = $this->_decodeLength($key);
1044
+ $temp = $this->_string_shift($key, $length);
1045
+ if (strlen($temp) != 1 || ord($temp) > 2) {
1046
+ $components['modulus'] = new Math_BigInteger($temp, 256);
1047
+ $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
1048
+ $length = $this->_decodeLength($key);
1049
+ $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1050
+
1051
+ return $components;
1052
+ }
1053
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
1054
+ return false;
1055
+ }
1056
+ $length = $this->_decodeLength($key);
1057
+ $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1058
+ $this->_string_shift($key);
1059
+ $length = $this->_decodeLength($key);
1060
+ $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1061
+ $this->_string_shift($key);
1062
+ $length = $this->_decodeLength($key);
1063
+ $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1064
+ $this->_string_shift($key);
1065
+ $length = $this->_decodeLength($key);
1066
+ $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1067
+ $this->_string_shift($key);
1068
+ $length = $this->_decodeLength($key);
1069
+ $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1070
+ $this->_string_shift($key);
1071
+ $length = $this->_decodeLength($key);
1072
+ $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1073
+ $this->_string_shift($key);
1074
+ $length = $this->_decodeLength($key);
1075
+ $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1076
+ $this->_string_shift($key);
1077
+ $length = $this->_decodeLength($key);
1078
+ $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1079
+
1080
+ if (!empty($key)) {
1081
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1082
+ return false;
1083
+ }
1084
+ $this->_decodeLength($key);
1085
+ while (!empty($key)) {
1086
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1087
+ return false;
1088
+ }
1089
+ $this->_decodeLength($key);
1090
+ $key = substr($key, 1);
1091
+ $length = $this->_decodeLength($key);
1092
+ $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1093
+ $this->_string_shift($key);
1094
+ $length = $this->_decodeLength($key);
1095
+ $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1096
+ $this->_string_shift($key);
1097
+ $length = $this->_decodeLength($key);
1098
+ $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1099
+ }
1100
+ }
1101
+
1102
+ return $components;
1103
+ case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
1104
+ $parts = explode(' ', $key, 3);
1105
+
1106
+ $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
1107
+ if ($key === false) {
1108
+ return false;
1109
+ }
1110
+
1111
+ $comment = isset($parts[2]) ? $parts[2] : false;
1112
+
1113
+ $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
1114
+
1115
+ if (strlen($key) <= 4) {
1116
+ return false;
1117
+ }
1118
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));
1119
+ $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
1120
+ if (strlen($key) <= 4) {
1121
+ return false;
1122
+ }
1123
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));
1124
+ $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
1125
+
1126
+ if ($cleanup && strlen($key)) {
1127
+ if (strlen($key) <= 4) {
1128
+ return false;
1129
+ }
1130
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));
1131
+ $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
1132
+ return strlen($key) ? false : array(
1133
+ 'modulus' => $realModulus,
1134
+ 'publicExponent' => $modulus,
1135
+ 'comment' => $comment
1136
+ );
1137
+ } else {
1138
+ return strlen($key) ? false : array(
1139
+ 'modulus' => $modulus,
1140
+ 'publicExponent' => $publicExponent,
1141
+ 'comment' => $comment
1142
+ );
1143
+ }
1144
+ // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
1145
+ // http://en.wikipedia.org/wiki/XML_Signature
1146
+ case CRYPT_RSA_PRIVATE_FORMAT_XML:
1147
+ case CRYPT_RSA_PUBLIC_FORMAT_XML:
1148
+ $this->components = array();
1149
+
1150
+ $xml = xml_parser_create('UTF-8');
1151
+ xml_set_object($xml, $this);
1152
+ xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
1153
+ xml_set_character_data_handler($xml, '_data_handler');
1154
+ // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
1155
+ if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
1156
+ return false;
1157
+ }
1158
+
1159
+ return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
1160
+ // from PuTTY's SSHPUBK.C
1161
+ case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
1162
+ $components = array();
1163
+ $key = preg_split('#\r\n|\r|\n#', $key);
1164
+ $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
1165
+ if ($type != 'ssh-rsa') {
1166
+ return false;
1167
+ }
1168
+ $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
1169
+ $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
1170
+
1171
+ $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
1172
+ $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
1173
+ $public = substr($public, 11);
1174
+ extract(unpack('Nlength', $this->_string_shift($public, 4)));
1175
+ $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
1176
+ extract(unpack('Nlength', $this->_string_shift($public, 4)));
1177
+ $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
1178
+
1179
+ $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
1180
+ $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
1181
+
1182
+ switch ($encryption) {
1183
+ case 'aes256-cbc':
1184
+ $symkey = '';
1185
+ $sequence = 0;
1186
+ while (strlen($symkey) < 32) {
1187
+ $temp = pack('Na*', $sequence++, $this->password);
1188
+ $symkey.= pack('H*', sha1($temp));
1189
+ }
1190
+ $symkey = substr($symkey, 0, 32);
1191
+ $crypto = new Crypt_AES();
1192
+ }
1193
+
1194
+ if ($encryption != 'none') {
1195
+ $crypto->setKey($symkey);
1196
+ $crypto->disablePadding();
1197
+ $private = $crypto->decrypt($private);
1198
+ if ($private === false) {
1199
+ return false;
1200
+ }
1201
+ }
1202
+
1203
+ extract(unpack('Nlength', $this->_string_shift($private, 4)));
1204
+ if (strlen($private) < $length) {
1205
+ return false;
1206
+ }
1207
+ $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
1208
+ extract(unpack('Nlength', $this->_string_shift($private, 4)));
1209
+ if (strlen($private) < $length) {
1210
+ return false;
1211
+ }
1212
+ $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
1213
+ extract(unpack('Nlength', $this->_string_shift($private, 4)));
1214
+ if (strlen($private) < $length) {
1215
+ return false;
1216
+ }
1217
+ $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
1218
+
1219
+ $temp = $components['primes'][1]->subtract($this->one);
1220
+ $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
1221
+ $temp = $components['primes'][2]->subtract($this->one);
1222
+ $components['exponents'][] = $components['publicExponent']->modInverse($temp);
1223
+
1224
+ extract(unpack('Nlength', $this->_string_shift($private, 4)));
1225
+ if (strlen($private) < $length) {
1226
+ return false;
1227
+ }
1228
+ $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
1229
+
1230
+ return $components;
1231
+ }
1232
+ }
1233
+
1234
+ /**
1235
+ * Returns the key size
1236
+ *
1237
+ * More specifically, this returns the size of the modulo in bits.
1238
+ *
1239
+ * @access public
1240
+ * @return Integer
1241
+ */
1242
+ function getSize()
1243
+ {
1244
+ return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
1245
+ }
1246
+
1247
+ /**
1248
+ * Start Element Handler
1249
+ *
1250
+ * Called by xml_set_element_handler()
1251
+ *
1252
+ * @access private
1253
+ * @param Resource $parser
1254
+ * @param String $name
1255
+ * @param Array $attribs
1256
+ */
1257
+ function _start_element_handler($parser, $name, $attribs)
1258
+ {
1259
+ //$name = strtoupper($name);
1260
+ switch ($name) {
1261
+ case 'MODULUS':
1262
+ $this->current = &$this->components['modulus'];
1263
+ break;
1264
+ case 'EXPONENT':
1265
+ $this->current = &$this->components['publicExponent'];
1266
+ break;
1267
+ case 'P':
1268
+ $this->current = &$this->components['primes'][1];
1269
+ break;
1270
+ case 'Q':
1271
+ $this->current = &$this->components['primes'][2];
1272
+ break;
1273
+ case 'DP':
1274
+ $this->current = &$this->components['exponents'][1];
1275
+ break;
1276
+ case 'DQ':
1277
+ $this->current = &$this->components['exponents'][2];
1278
+ break;
1279
+ case 'INVERSEQ':
1280
+ $this->current = &$this->components['coefficients'][2];
1281
+ break;
1282
+ case 'D':
1283
+ $this->current = &$this->components['privateExponent'];
1284
+ }
1285
+ $this->current = '';
1286
+ }
1287
+
1288
+ /**
1289
+ * Stop Element Handler
1290
+ *
1291
+ * Called by xml_set_element_handler()
1292
+ *
1293
+ * @access private
1294
+ * @param Resource $parser
1295
+ * @param String $name
1296
+ */
1297
+ function _stop_element_handler($parser, $name)
1298
+ {
1299
+ //$name = strtoupper($name);
1300
+ if ($name == 'RSAKEYVALUE') {
1301
+ return;
1302
+ }
1303
+ $this->current = new Math_BigInteger(base64_decode($this->current), 256);
1304
+ unset($this->current);
1305
+ }
1306
+
1307
+ /**
1308
+ * Data Handler
1309
+ *
1310
+ * Called by xml_set_character_data_handler()
1311
+ *
1312
+ * @access private
1313
+ * @param Resource $parser
1314
+ * @param String $data
1315
+ */
1316
+ function _data_handler($parser, $data)
1317
+ {
1318
+ if (!isset($this->current) || is_object($this->current)) {
1319
+ return;
1320
+ }
1321
+ $this->current.= trim($data);
1322
+ }
1323
+
1324
+ /**
1325
+ * Loads a public or private key
1326
+ *
1327
+ * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
1328
+ *
1329
+ * @access public
1330
+ * @param String $key
1331
+ * @param Integer $type optional
1332
+ */
1333
+ function loadKey($key, $type = false)
1334
+ {
1335
+ if ($type === false) {
1336
+ $types = array(
1337
+ CRYPT_RSA_PUBLIC_FORMAT_RAW,
1338
+ CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
1339
+ CRYPT_RSA_PRIVATE_FORMAT_XML,
1340
+ CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
1341
+ CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
1342
+ );
1343
+ foreach ($types as $type) {
1344
+ $components = $this->_parseKey($key, $type);
1345
+ if ($components !== false) {
1346
+ break;
1347
+ }
1348
+ }
1349
+
1350
+ } else {
1351
+ $components = $this->_parseKey($key, $type);
1352
+ }
1353
+
1354
+ if ($components === false) {
1355
+ return false;
1356
+ }
1357
+
1358
+ if (isset($components['comment']) && $components['comment'] !== false) {
1359
+ $this->comment = $components['comment'];
1360
+ }
1361
+ $this->modulus = $components['modulus'];
1362
+ $this->k = strlen($this->modulus->toBytes());
1363
+ $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
1364
+ if (isset($components['primes'])) {
1365
+ $this->primes = $components['primes'];
1366
+ $this->exponents = $components['exponents'];
1367
+ $this->coefficients = $components['coefficients'];
1368
+ $this->publicExponent = $components['publicExponent'];
1369
+ } else {
1370
+ $this->primes = array();
1371
+ $this->exponents = array();
1372
+ $this->coefficients = array();
1373
+ $this->publicExponent = false;
1374
+ }
1375
+
1376
+ return true;
1377
+ }
1378
+
1379
+ /**
1380
+ * Sets the password
1381
+ *
1382
+ * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
1383
+ * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
1384
+ *
1385
+ * @see createKey()
1386
+ * @see loadKey()
1387
+ * @access public
1388
+ * @param String $password
1389
+ */
1390
+ function setPassword($password = false)
1391
+ {
1392
+ $this->password = $password;
1393
+ }
1394
+
1395
+ /**
1396
+ * Defines the public key
1397
+ *
1398
+ * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
1399
+ * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
1400
+ * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
1401
+ * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
1402
+ * exponent this won't work unless you manually add the public exponent.
1403
+ *
1404
+ * Do note that when a new key is loaded the index will be cleared.
1405
+ *
1406
+ * Returns true on success, false on failure
1407
+ *
1408
+ * @see getPublicKey()
1409
+ * @access public
1410
+ * @param String $key optional
1411
+ * @param Integer $type optional
1412
+ * @return Boolean
1413
+ */
1414
+ function setPublicKey($key = false, $type = false)
1415
+ {
1416
+ if ($key === false && !empty($this->modulus)) {
1417
+ $this->publicExponent = $this->exponent;
1418
+ return true;
1419
+ }
1420
+
1421
+ if ($type === false) {
1422
+ $types = array(
1423
+ CRYPT_RSA_PUBLIC_FORMAT_RAW,
1424
+ CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
1425
+ CRYPT_RSA_PUBLIC_FORMAT_XML,
1426
+ CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
1427
+ );
1428
+ foreach ($types as $type) {
1429
+ $components = $this->_parseKey($key, $type);
1430
+ if ($components !== false) {
1431
+ break;
1432
+ }
1433
+ }
1434
+ } else {
1435
+ $components = $this->_parseKey($key, $type);
1436
+ }
1437
+
1438
+ if ($components === false) {
1439
+ return false;
1440
+ }
1441
+
1442
+ if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
1443
+ $this->modulus = $components['modulus'];
1444
+ $this->exponent = $this->publicExponent = $components['publicExponent'];
1445
+ return true;
1446
+ }
1447
+
1448
+ $this->publicExponent = $components['publicExponent'];
1449
+
1450
+ return true;
1451
+ }
1452
+
1453
+ /**
1454
+ * Returns the public key
1455
+ *
1456
+ * The public key is only returned under two circumstances - if the private key had the public key embedded within it
1457
+ * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
1458
+ * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
1459
+ *
1460
+ * @see getPublicKey()
1461
+ * @access public
1462
+ * @param String $key
1463
+ * @param Integer $type optional
1464
+ */
1465
+ function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1466
+ {
1467
+ if (empty($this->modulus) || empty($this->publicExponent)) {
1468
+ return false;
1469
+ }
1470
+
1471
+ $oldFormat = $this->publicKeyFormat;
1472
+ $this->publicKeyFormat = $type;
1473
+ $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
1474
+ $this->publicKeyFormat = $oldFormat;
1475
+ return $temp;
1476
+ }
1477
+
1478
+ /**
1479
+ * Returns the private key
1480
+ *
1481
+ * The private key is only returned if the currently loaded key contains the constituent prime numbers.
1482
+ *
1483
+ * @see getPublicKey()
1484
+ * @access public
1485
+ * @param String $key
1486
+ * @param Integer $type optional
1487
+ */
1488
+ function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1489
+ {
1490
+ if (empty($this->primes)) {
1491
+ return false;
1492
+ }
1493
+
1494
+ $oldFormat = $this->privateKeyFormat;
1495
+ $this->privateKeyFormat = $type;
1496
+ $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
1497
+ $this->privateKeyFormat = $oldFormat;
1498
+ return $temp;
1499
+ }
1500
+
1501
+ /**
1502
+ * Returns a minimalistic private key
1503
+ *
1504
+ * Returns the private key without the prime number constituants. Structurally identical to a public key that
1505
+ * hasn't been set as the public key
1506
+ *
1507
+ * @see getPrivateKey()
1508
+ * @access private
1509
+ * @param String $key
1510
+ * @param Integer $type optional
1511
+ */
1512
+ function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1513
+ {
1514
+ if (empty($this->modulus) || empty($this->exponent)) {
1515
+ return false;
1516
+ }
1517
+
1518
+ $oldFormat = $this->publicKeyFormat;
1519
+ $this->publicKeyFormat = $mode;
1520
+ $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
1521
+ $this->publicKeyFormat = $oldFormat;
1522
+ return $temp;
1523
+ }
1524
+
1525
+ /**
1526
+ * __toString() magic method
1527
+ *
1528
+ * @access public
1529
+ */
1530
+ function __toString()
1531
+ {
1532
+ $key = $this->getPrivateKey($this->privateKeyFormat);
1533
+ if ($key !== false) {
1534
+ return $key;
1535
+ }
1536
+ $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
1537
+ return $key !== false ? $key : '';
1538
+ }
1539
+
1540
+ /**
1541
+ * Generates the smallest and largest numbers requiring $bits bits
1542
+ *
1543
+ * @access private
1544
+ * @param Integer $bits
1545
+ * @return Array
1546
+ */
1547
+ function _generateMinMax($bits)
1548
+ {
1549
+ $bytes = $bits >> 3;
1550
+ $min = str_repeat(chr(0), $bytes);
1551
+ $max = str_repeat(chr(0xFF), $bytes);
1552
+ $msb = $bits & 7;
1553
+ if ($msb) {
1554
+ $min = chr(1 << ($msb - 1)) . $min;
1555
+ $max = chr((1 << $msb) - 1) . $max;
1556
+ } else {
1557
+ $min[0] = chr(0x80);
1558
+ }
1559
+
1560
+ return array(
1561
+ 'min' => new Math_BigInteger($min, 256),
1562
+ 'max' => new Math_BigInteger($max, 256)
1563
+ );
1564
+ }
1565
+
1566
+ /**
1567
+ * DER-decode the length
1568
+ *
1569
+ * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1570
+ * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
1571
+ *
1572
+ * @access private
1573
+ * @param String $string
1574
+ * @return Integer
1575
+ */
1576
+ function _decodeLength(&$string)
1577
+ {
1578
+ $length = ord($this->_string_shift($string));
1579
+ if ( $length & 0x80 ) { // definite length, long form
1580
+ $length&= 0x7F;
1581
+ $temp = $this->_string_shift($string, $length);
1582
+ list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
1583
+ }
1584
+ return $length;
1585
+ }
1586
+
1587
+ /**
1588
+ * DER-encode the length
1589
+ *
1590
+ * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1591
+ * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
1592
+ *
1593
+ * @access private
1594
+ * @param Integer $length
1595
+ * @return String
1596
+ */
1597
+ function _encodeLength($length)
1598
+ {
1599
+ if ($length <= 0x7F) {
1600
+ return chr($length);
1601
+ }
1602
+
1603
+ $temp = ltrim(pack('N', $length), chr(0));
1604
+ return pack('Ca*', 0x80 | strlen($temp), $temp);
1605
+ }
1606
+
1607
+ /**
1608
+ * String Shift
1609
+ *
1610
+ * Inspired by array_shift
1611
+ *
1612
+ * @param String $string
1613
+ * @param optional Integer $index
1614
+ * @return String
1615
+ * @access private
1616
+ */
1617
+ function _string_shift(&$string, $index = 1)
1618
+ {
1619
+ $substr = substr($string, 0, $index);
1620
+ $string = substr($string, $index);
1621
+ return $substr;
1622
+ }
1623
+
1624
+ /**
1625
+ * Determines the private key format
1626
+ *
1627
+ * @see createKey()
1628
+ * @access public
1629
+ * @param Integer $format
1630
+ */
1631
+ function setPrivateKeyFormat($format)
1632
+ {
1633
+ $this->privateKeyFormat = $format;
1634
+ }
1635
+
1636
+ /**
1637
+ * Determines the public key format
1638
+ *
1639
+ * @see createKey()
1640
+ * @access public
1641
+ * @param Integer $format
1642
+ */
1643
+ function setPublicKeyFormat($format)
1644
+ {
1645
+ $this->publicKeyFormat = $format;
1646
+ }
1647
+
1648
+ /**
1649
+ * Determines which hashing function should be used
1650
+ *
1651
+ * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
1652
+ * decryption. If $hash isn't supported, sha1 is used.
1653
+ *
1654
+ * @access public
1655
+ * @param String $hash
1656
+ */
1657
+ function setHash($hash)
1658
+ {
1659
+ // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1660
+ switch ($hash) {
1661
+ case 'md2':
1662
+ case 'md5':
1663
+ case 'sha1':
1664
+ case 'sha256':
1665
+ case 'sha384':
1666
+ case 'sha512':
1667
+ $this->hash = new Crypt_Hash($hash);
1668
+ $this->hashName = $hash;
1669
+ break;
1670
+ default:
1671
+ $this->hash = new Crypt_Hash('sha1');
1672
+ $this->hashName = 'sha1';
1673
+ }
1674
+ $this->hLen = $this->hash->getLength();
1675
+ }
1676
+
1677
+ /**
1678
+ * Determines which hashing function should be used for the mask generation function
1679
+ *
1680
+ * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
1681
+ * best if Hash and MGFHash are set to the same thing this is not a requirement.
1682
+ *
1683
+ * @access public
1684
+ * @param String $hash
1685
+ */
1686
+ function setMGFHash($hash)
1687
+ {
1688
+ // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1689
+ switch ($hash) {
1690
+ case 'md2':
1691
+ case 'md5':
1692
+ case 'sha1':
1693
+ case 'sha256':
1694
+ case 'sha384':
1695
+ case 'sha512':
1696
+ $this->mgfHash = new Crypt_Hash($hash);
1697
+ break;
1698
+ default:
1699
+ $this->mgfHash = new Crypt_Hash('sha1');
1700
+ }
1701
+ $this->mgfHLen = $this->mgfHash->getLength();
1702
+ }
1703
+
1704
+ /**
1705
+ * Determines the salt length
1706
+ *
1707
+ * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
1708
+ *
1709
+ * Typical salt lengths in octets are hLen (the length of the output
1710
+ * of the hash function Hash) and 0.
1711
+ *
1712
+ * @access public
1713
+ * @param Integer $format
1714
+ */
1715
+ function setSaltLength($sLen)
1716
+ {
1717
+ $this->sLen = $sLen;
1718
+ }
1719
+
1720
+ /**
1721
+ * Integer-to-Octet-String primitive
1722
+ *
1723
+ * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
1724
+ *
1725
+ * @access private
1726
+ * @param Math_BigInteger $x
1727
+ * @param Integer $xLen
1728
+ * @return String
1729
+ */
1730
+ function _i2osp($x, $xLen)
1731
+ {
1732
+ $x = $x->toBytes();
1733
+ if (strlen($x) > $xLen) {
1734
+ user_error('Integer too large');
1735
+ return false;
1736
+ }
1737
+ return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
1738
+ }
1739
+
1740
+ /**
1741
+ * Octet-String-to-Integer primitive
1742
+ *
1743
+ * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
1744
+ *
1745
+ * @access private
1746
+ * @param String $x
1747
+ * @return Math_BigInteger
1748
+ */
1749
+ function _os2ip($x)
1750
+ {
1751
+ return new Math_BigInteger($x, 256);
1752
+ }
1753
+
1754
+ /**
1755
+ * Exponentiate with or without Chinese Remainder Theorem
1756
+ *
1757
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
1758
+ *
1759
+ * @access private
1760
+ * @param Math_BigInteger $x
1761
+ * @return Math_BigInteger
1762
+ */
1763
+ function _exponentiate($x)
1764
+ {
1765
+ if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
1766
+ return $x->modPow($this->exponent, $this->modulus);
1767
+ }
1768
+
1769
+ $num_primes = count($this->primes);
1770
+
1771
+ if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
1772
+ $m_i = array(
1773
+ 1 => $x->modPow($this->exponents[1], $this->primes[1]),
1774
+ 2 => $x->modPow($this->exponents[2], $this->primes[2])
1775
+ );
1776
+ $h = $m_i[1]->subtract($m_i[2]);
1777
+ $h = $h->multiply($this->coefficients[2]);
1778
+ list(, $h) = $h->divide($this->primes[1]);
1779
+ $m = $m_i[2]->add($h->multiply($this->primes[2]));
1780
+
1781
+ $r = $this->primes[1];
1782
+ for ($i = 3; $i <= $num_primes; $i++) {
1783
+ $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
1784
+
1785
+ $r = $r->multiply($this->primes[$i - 1]);
1786
+
1787
+ $h = $m_i->subtract($m);
1788
+ $h = $h->multiply($this->coefficients[$i]);
1789
+ list(, $h) = $h->divide($this->primes[$i]);
1790
+
1791
+ $m = $m->add($r->multiply($h));
1792
+ }
1793
+ } else {
1794
+ $smallest = $this->primes[1];
1795
+ for ($i = 2; $i <= $num_primes; $i++) {
1796
+ if ($smallest->compare($this->primes[$i]) > 0) {
1797
+ $smallest = $this->primes[$i];
1798
+ }
1799
+ }
1800
+
1801
+ $one = new Math_BigInteger(1);
1802
+
1803
+ $r = $one->random($one, $smallest->subtract($one));
1804
+
1805
+ $m_i = array(
1806
+ 1 => $this->_blind($x, $r, 1),
1807
+ 2 => $this->_blind($x, $r, 2)
1808
+ );
1809
+ $h = $m_i[1]->subtract($m_i[2]);
1810
+ $h = $h->multiply($this->coefficients[2]);
1811
+ list(, $h) = $h->divide($this->primes[1]);
1812
+ $m = $m_i[2]->add($h->multiply($this->primes[2]));
1813
+
1814
+ $r = $this->primes[1];
1815
+ for ($i = 3; $i <= $num_primes; $i++) {
1816
+ $m_i = $this->_blind($x, $r, $i);
1817
+
1818
+ $r = $r->multiply($this->primes[$i - 1]);
1819
+
1820
+ $h = $m_i->subtract($m);
1821
+ $h = $h->multiply($this->coefficients[$i]);
1822
+ list(, $h) = $h->divide($this->primes[$i]);
1823
+
1824
+ $m = $m->add($r->multiply($h));
1825
+ }
1826
+ }
1827
+
1828
+ return $m;
1829
+ }
1830
+
1831
+ /**
1832
+ * Performs RSA Blinding
1833
+ *
1834
+ * Protects against timing attacks by employing RSA Blinding.
1835
+ * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
1836
+ *
1837
+ * @access private
1838
+ * @param Math_BigInteger $x
1839
+ * @param Math_BigInteger $r
1840
+ * @param Integer $i
1841
+ * @return Math_BigInteger
1842
+ */
1843
+ function _blind($x, $r, $i)
1844
+ {
1845
+ $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
1846
+ $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
1847
+
1848
+ $r = $r->modInverse($this->primes[$i]);
1849
+ $x = $x->multiply($r);
1850
+ list(, $x) = $x->divide($this->primes[$i]);
1851
+
1852
+ return $x;
1853
+ }
1854
+
1855
+ /**
1856
+ * Performs blinded RSA equality testing
1857
+ *
1858
+ * Protects against a particular type of timing attack described.
1859
+ *
1860
+ * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
1861
+ *
1862
+ * Thanks for the heads up singpolyma!
1863
+ *
1864
+ * @access private
1865
+ * @param String $x
1866
+ * @param String $y
1867
+ * @return Boolean
1868
+ */
1869
+ function _equals($x, $y)
1870
+ {
1871
+ if (strlen($x) != strlen($y)) {
1872
+ return false;
1873
+ }
1874
+
1875
+ $result = 0;
1876
+ for ($i = 0; $i < strlen($x); $i++) {
1877
+ $result |= ord($x[$i]) ^ ord($y[$i]);
1878
+ }
1879
+
1880
+ return $result == 0;
1881
+ }
1882
+
1883
+ /**
1884
+ * RSAEP
1885
+ *
1886
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
1887
+ *
1888
+ * @access private
1889
+ * @param Math_BigInteger $m
1890
+ * @return Math_BigInteger
1891
+ */
1892
+ function _rsaep($m)
1893
+ {
1894
+ if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1895
+ user_error('Message representative out of range');
1896
+ return false;
1897
+ }
1898
+ return $this->_exponentiate($m);
1899
+ }
1900
+
1901
+ /**
1902
+ * RSADP
1903
+ *
1904
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
1905
+ *
1906
+ * @access private
1907
+ * @param Math_BigInteger $c
1908
+ * @return Math_BigInteger
1909
+ */
1910
+ function _rsadp($c)
1911
+ {
1912
+ if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
1913
+ user_error('Ciphertext representative out of range');
1914
+ return false;
1915
+ }
1916
+ return $this->_exponentiate($c);
1917
+ }
1918
+
1919
+ /**
1920
+ * RSASP1
1921
+ *
1922
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
1923
+ *
1924
+ * @access private
1925
+ * @param Math_BigInteger $m
1926
+ * @return Math_BigInteger
1927
+ */
1928
+ function _rsasp1($m)
1929
+ {
1930
+ if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1931
+ user_error('Message representative out of range');
1932
+ return false;
1933
+ }
1934
+ return $this->_exponentiate($m);
1935
+ }
1936
+
1937
+ /**
1938
+ * RSAVP1
1939
+ *
1940
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
1941
+ *
1942
+ * @access private
1943
+ * @param Math_BigInteger $s
1944
+ * @return Math_BigInteger
1945
+ */
1946
+ function _rsavp1($s)
1947
+ {
1948
+ if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
1949
+ user_error('Signature representative out of range');
1950
+ return false;
1951
+ }
1952
+ return $this->_exponentiate($s);
1953
+ }
1954
+
1955
+ /**
1956
+ * MGF1
1957
+ *
1958
+ * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
1959
+ *
1960
+ * @access private
1961
+ * @param String $mgfSeed
1962
+ * @param Integer $mgfLen
1963
+ * @return String
1964
+ */
1965
+ function _mgf1($mgfSeed, $maskLen)
1966
+ {
1967
+ // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
1968
+
1969
+ $t = '';
1970
+ $count = ceil($maskLen / $this->mgfHLen);
1971
+ for ($i = 0; $i < $count; $i++) {
1972
+ $c = pack('N', $i);
1973
+ $t.= $this->mgfHash->hash($mgfSeed . $c);
1974
+ }
1975
+
1976
+ return substr($t, 0, $maskLen);
1977
+ }
1978
+
1979
+ /**
1980
+ * RSAES-OAEP-ENCRYPT
1981
+ *
1982
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
1983
+ * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
1984
+ *
1985
+ * @access private
1986
+ * @param String $m
1987
+ * @param String $l
1988
+ * @return String
1989
+ */
1990
+ function _rsaes_oaep_encrypt($m, $l = '')
1991
+ {
1992
+ $mLen = strlen($m);
1993
+
1994
+ // Length checking
1995
+
1996
+ // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
1997
+ // be output.
1998
+
1999
+ if ($mLen > $this->k - 2 * $this->hLen - 2) {
2000
+ user_error('Message too long');
2001
+ return false;
2002
+ }
2003
+
2004
+ // EME-OAEP encoding
2005
+
2006
+ $lHash = $this->hash->hash($l);
2007
+ $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
2008
+ $db = $lHash . $ps . chr(1) . $m;
2009
+ $seed = crypt_random_string($this->hLen);
2010
+ $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
2011
+ $maskedDB = $db ^ $dbMask;
2012
+ $seedMask = $this->_mgf1($maskedDB, $this->hLen);
2013
+ $maskedSeed = $seed ^ $seedMask;
2014
+ $em = chr(0) . $maskedSeed . $maskedDB;
2015
+
2016
+ // RSA encryption
2017
+
2018
+ $m = $this->_os2ip($em);
2019
+ $c = $this->_rsaep($m);
2020
+ $c = $this->_i2osp($c, $this->k);
2021
+
2022
+ // Output the ciphertext C
2023
+
2024
+ return $c;
2025
+ }
2026
+
2027
+ /**
2028
+ * RSAES-OAEP-DECRYPT
2029
+ *
2030
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
2031
+ * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
2032
+ *
2033
+ * Note. Care must be taken to ensure that an opponent cannot
2034
+ * distinguish the different error conditions in Step 3.g, whether by
2035
+ * error message or timing, or, more generally, learn partial
2036
+ * information about the encoded message EM. Otherwise an opponent may
2037
+ * be able to obtain useful information about the decryption of the
2038
+ * ciphertext C, leading to a chosen-ciphertext attack such as the one
2039
+ * observed by Manger [36].
2040
+ *
2041
+ * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
2042
+ *
2043
+ * Both the encryption and the decryption operations of RSAES-OAEP take
2044
+ * the value of a label L as input. In this version of PKCS #1, L is
2045
+ * the empty string; other uses of the label are outside the scope of
2046
+ * this document.
2047
+ *
2048
+ * @access private
2049
+ * @param String $c
2050
+ * @param String $l
2051
+ * @return String
2052
+ */
2053
+ function _rsaes_oaep_decrypt($c, $l = '')
2054
+ {
2055
+ // Length checking
2056
+
2057
+ // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2058
+ // be output.
2059
+
2060
+ if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
2061
+ user_error('Decryption error');
2062
+ return false;
2063
+ }
2064
+
2065
+ // RSA decryption
2066
+
2067
+ $c = $this->_os2ip($c);
2068
+ $m = $this->_rsadp($c);
2069
+ if ($m === false) {
2070
+ user_error('Decryption error');
2071
+ return false;
2072
+ }
2073
+ $em = $this->_i2osp($m, $this->k);
2074
+
2075
+ // EME-OAEP decoding
2076
+
2077
+ $lHash = $this->hash->hash($l);
2078
+ $y = ord($em[0]);
2079
+ $maskedSeed = substr($em, 1, $this->hLen);
2080
+ $maskedDB = substr($em, $this->hLen + 1);
2081
+ $seedMask = $this->_mgf1($maskedDB, $this->hLen);
2082
+ $seed = $maskedSeed ^ $seedMask;
2083
+ $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
2084
+ $db = $maskedDB ^ $dbMask;
2085
+ $lHash2 = substr($db, 0, $this->hLen);
2086
+ $m = substr($db, $this->hLen);
2087
+ if ($lHash != $lHash2) {
2088
+ user_error('Decryption error');
2089
+ return false;
2090
+ }
2091
+ $m = ltrim($m, chr(0));
2092
+ if (ord($m[0]) != 1) {
2093
+ user_error('Decryption error');
2094
+ return false;
2095
+ }
2096
+
2097
+ // Output the message M
2098
+
2099
+ return substr($m, 1);
2100
+ }
2101
+
2102
+ /**
2103
+ * RSAES-PKCS1-V1_5-ENCRYPT
2104
+ *
2105
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
2106
+ *
2107
+ * @access private
2108
+ * @param String $m
2109
+ * @return String
2110
+ */
2111
+ function _rsaes_pkcs1_v1_5_encrypt($m)
2112
+ {
2113
+ $mLen = strlen($m);
2114
+
2115
+ // Length checking
2116
+
2117
+ if ($mLen > $this->k - 11) {
2118
+ user_error('Message too long');
2119
+ return false;
2120
+ }
2121
+
2122
+ // EME-PKCS1-v1_5 encoding
2123
+
2124
+ $psLen = $this->k - $mLen - 3;
2125
+ $ps = '';
2126
+ while (strlen($ps) != $psLen) {
2127
+ $temp = crypt_random_string($psLen - strlen($ps));
2128
+ $temp = str_replace("\x00", '', $temp);
2129
+ $ps.= $temp;
2130
+ }
2131
+ $type = 2;
2132
+ // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
2133
+ if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
2134
+ $type = 1;
2135
+ // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
2136
+ $ps = str_repeat("\xFF", $psLen);
2137
+ }
2138
+ $em = chr(0) . chr($type) . $ps . chr(0) . $m;
2139
+
2140
+ // RSA encryption
2141
+ $m = $this->_os2ip($em);
2142
+ $c = $this->_rsaep($m);
2143
+ $c = $this->_i2osp($c, $this->k);
2144
+
2145
+ // Output the ciphertext C
2146
+
2147
+ return $c;
2148
+ }
2149
+
2150
+ /**
2151
+ * RSAES-PKCS1-V1_5-DECRYPT
2152
+ *
2153
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
2154
+ *
2155
+ * For compatability purposes, this function departs slightly from the description given in RFC3447.
2156
+ * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
2157
+ * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
2158
+ * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
2159
+ * to be 2 regardless of which key is used. For compatability purposes, we'll just check to make sure the
2160
+ * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
2161
+ *
2162
+ * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
2163
+ * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
2164
+ * not private key encrypted ciphertext's.
2165
+ *
2166
+ * @access private
2167
+ * @param String $c
2168
+ * @return String
2169
+ */
2170
+ function _rsaes_pkcs1_v1_5_decrypt($c)
2171
+ {
2172
+ // Length checking
2173
+
2174
+ if (strlen($c) != $this->k) { // or if k < 11
2175
+ user_error('Decryption error');
2176
+ return false;
2177
+ }
2178
+
2179
+ // RSA decryption
2180
+
2181
+ $c = $this->_os2ip($c);
2182
+ $m = $this->_rsadp($c);
2183
+
2184
+ if ($m === false) {
2185
+ user_error('Decryption error');
2186
+ return false;
2187
+ }
2188
+ $em = $this->_i2osp($m, $this->k);
2189
+
2190
+ // EME-PKCS1-v1_5 decoding
2191
+
2192
+ if (ord($em[0]) != 0 || ord($em[1]) > 2) {
2193
+ user_error('Decryption error');
2194
+ return false;
2195
+ }
2196
+
2197
+ $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
2198
+ $m = substr($em, strlen($ps) + 3);
2199
+
2200
+ if (strlen($ps) < 8) {
2201
+ user_error('Decryption error');
2202
+ return false;
2203
+ }
2204
+
2205
+ // Output M
2206
+
2207
+ return $m;
2208
+ }
2209
+
2210
+ /**
2211
+ * EMSA-PSS-ENCODE
2212
+ *
2213
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
2214
+ *
2215
+ * @access private
2216
+ * @param String $m
2217
+ * @param Integer $emBits
2218
+ */
2219
+ function _emsa_pss_encode($m, $emBits)
2220
+ {
2221
+ // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2222
+ // be output.
2223
+
2224
+ $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
2225
+ $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
2226
+
2227
+ $mHash = $this->hash->hash($m);
2228
+ if ($emLen < $this->hLen + $sLen + 2) {
2229
+ user_error('Encoding error');
2230
+ return false;
2231
+ }
2232
+
2233
+ $salt = crypt_random_string($sLen);
2234
+ $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
2235
+ $h = $this->hash->hash($m2);
2236
+ $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
2237
+ $db = $ps . chr(1) . $salt;
2238
+ $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
2239
+ $maskedDB = $db ^ $dbMask;
2240
+ $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
2241
+ $em = $maskedDB . $h . chr(0xBC);
2242
+
2243
+ return $em;
2244
+ }
2245
+
2246
+ /**
2247
+ * EMSA-PSS-VERIFY
2248
+ *
2249
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
2250
+ *
2251
+ * @access private
2252
+ * @param String $m
2253
+ * @param String $em
2254
+ * @param Integer $emBits
2255
+ * @return String
2256
+ */
2257
+ function _emsa_pss_verify($m, $em, $emBits)
2258
+ {
2259
+ // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2260
+ // be output.
2261
+
2262
+ $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
2263
+ $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
2264
+
2265
+ $mHash = $this->hash->hash($m);
2266
+ if ($emLen < $this->hLen + $sLen + 2) {
2267
+ return false;
2268
+ }
2269
+
2270
+ if ($em[strlen($em) - 1] != chr(0xBC)) {
2271
+ return false;
2272
+ }
2273
+
2274
+ $maskedDB = substr($em, 0, -$this->hLen - 1);
2275
+ $h = substr($em, -$this->hLen - 1, $this->hLen);
2276
+ $temp = chr(0xFF << ($emBits & 7));
2277
+ if ((~$maskedDB[0] & $temp) != $temp) {
2278
+ return false;
2279
+ }
2280
+ $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
2281
+ $db = $maskedDB ^ $dbMask;
2282
+ $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
2283
+ $temp = $emLen - $this->hLen - $sLen - 2;
2284
+ if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
2285
+ return false;
2286
+ }
2287
+ $salt = substr($db, $temp + 1); // should be $sLen long
2288
+ $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
2289
+ $h2 = $this->hash->hash($m2);
2290
+ return $this->_equals($h, $h2);
2291
+ }
2292
+
2293
+ /**
2294
+ * RSASSA-PSS-SIGN
2295
+ *
2296
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
2297
+ *
2298
+ * @access private
2299
+ * @param String $m
2300
+ * @return String
2301
+ */
2302
+ function _rsassa_pss_sign($m)
2303
+ {
2304
+ // EMSA-PSS encoding
2305
+
2306
+ $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
2307
+
2308
+ // RSA signature
2309
+
2310
+ $m = $this->_os2ip($em);
2311
+ $s = $this->_rsasp1($m);
2312
+ $s = $this->_i2osp($s, $this->k);
2313
+
2314
+ // Output the signature S
2315
+
2316
+ return $s;
2317
+ }
2318
+
2319
+ /**
2320
+ * RSASSA-PSS-VERIFY
2321
+ *
2322
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
2323
+ *
2324
+ * @access private
2325
+ * @param String $m
2326
+ * @param String $s
2327
+ * @return String
2328
+ */
2329
+ function _rsassa_pss_verify($m, $s)
2330
+ {
2331
+ // Length checking
2332
+
2333
+ if (strlen($s) != $this->k) {
2334
+ user_error('Invalid signature');
2335
+ return false;
2336
+ }
2337
+
2338
+ // RSA verification
2339
+
2340
+ $modBits = 8 * $this->k;
2341
+
2342
+ $s2 = $this->_os2ip($s);
2343
+ $m2 = $this->_rsavp1($s2);
2344
+ if ($m2 === false) {
2345
+ user_error('Invalid signature');
2346
+ return false;
2347
+ }
2348
+ $em = $this->_i2osp($m2, $modBits >> 3);
2349
+ if ($em === false) {
2350
+ user_error('Invalid signature');
2351
+ return false;
2352
+ }
2353
+
2354
+ // EMSA-PSS verification
2355
+
2356
+ return $this->_emsa_pss_verify($m, $em, $modBits - 1);
2357
+ }
2358
+
2359
+ /**
2360
+ * EMSA-PKCS1-V1_5-ENCODE
2361
+ *
2362
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
2363
+ *
2364
+ * @access private
2365
+ * @param String $m
2366
+ * @param Integer $emLen
2367
+ * @return String
2368
+ */
2369
+ function _emsa_pkcs1_v1_5_encode($m, $emLen)
2370
+ {
2371
+ $h = $this->hash->hash($m);
2372
+ if ($h === false) {
2373
+ return false;
2374
+ }
2375
+
2376
+ // see http://tools.ietf.org/html/rfc3447#page-43
2377
+ switch ($this->hashName) {
2378
+ case 'md2':
2379
+ $t = pack('H*', '3020300c06082a864886f70d020205000410');
2380
+ break;
2381
+ case 'md5':
2382
+ $t = pack('H*', '3020300c06082a864886f70d020505000410');
2383
+ break;
2384
+ case 'sha1':
2385
+ $t = pack('H*', '3021300906052b0e03021a05000414');
2386
+ break;
2387
+ case 'sha256':
2388
+ $t = pack('H*', '3031300d060960864801650304020105000420');
2389
+ break;
2390
+ case 'sha384':
2391
+ $t = pack('H*', '3041300d060960864801650304020205000430');
2392
+ break;
2393
+ case 'sha512':
2394
+ $t = pack('H*', '3051300d060960864801650304020305000440');
2395
+ }
2396
+ $t.= $h;
2397
+ $tLen = strlen($t);
2398
+
2399
+ if ($emLen < $tLen + 11) {
2400
+ user_error('Intended encoded message length too short');
2401
+ return false;
2402
+ }
2403
+
2404
+ $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
2405
+
2406
+ $em = "\0\1$ps\0$t";
2407
+
2408
+ return $em;
2409
+ }
2410
+
2411
+ /**
2412
+ * RSASSA-PKCS1-V1_5-SIGN
2413
+ *
2414
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
2415
+ *
2416
+ * @access private
2417
+ * @param String $m
2418
+ * @return String
2419
+ */
2420
+ function _rsassa_pkcs1_v1_5_sign($m)
2421
+ {
2422
+ // EMSA-PKCS1-v1_5 encoding
2423
+
2424
+ $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
2425
+ if ($em === false) {
2426
+ user_error('RSA modulus too short');
2427
+ return false;
2428
+ }
2429
+
2430
+ // RSA signature
2431
+
2432
+ $m = $this->_os2ip($em);
2433
+ $s = $this->_rsasp1($m);
2434
+ $s = $this->_i2osp($s, $this->k);
2435
+
2436
+ // Output the signature S
2437
+
2438
+ return $s;
2439
+ }
2440
+
2441
+ /**
2442
+ * RSASSA-PKCS1-V1_5-VERIFY
2443
+ *
2444
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
2445
+ *
2446
+ * @access private
2447
+ * @param String $m
2448
+ * @return String
2449
+ */
2450
+ function _rsassa_pkcs1_v1_5_verify($m, $s)
2451
+ {
2452
+ // Length checking
2453
+
2454
+ if (strlen($s) != $this->k) {
2455
+ user_error('Invalid signature');
2456
+ return false;
2457
+ }
2458
+
2459
+ // RSA verification
2460
+
2461
+ $s = $this->_os2ip($s);
2462
+ $m2 = $this->_rsavp1($s);
2463
+ if ($m2 === false) {
2464
+ user_error('Invalid signature');
2465
+ return false;
2466
+ }
2467
+ $em = $this->_i2osp($m2, $this->k);
2468
+ if ($em === false) {
2469
+ user_error('Invalid signature');
2470
+ return false;
2471
+ }
2472
+
2473
+ // EMSA-PKCS1-v1_5 encoding
2474
+
2475
+ $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
2476
+ if ($em2 === false) {
2477
+ user_error('RSA modulus too short');
2478
+ return false;
2479
+ }
2480
+
2481
+ // Compare
2482
+ return $this->_equals($em, $em2);
2483
+ }
2484
+
2485
+ /**
2486
+ * Set Encryption Mode
2487
+ *
2488
+ * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
2489
+ *
2490
+ * @access public
2491
+ * @param Integer $mode
2492
+ */
2493
+ function setEncryptionMode($mode)
2494
+ {
2495
+ $this->encryptionMode = $mode;
2496
+ }
2497
+
2498
+ /**
2499
+ * Set Signature Mode
2500
+ *
2501
+ * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
2502
+ *
2503
+ * @access public
2504
+ * @param Integer $mode
2505
+ */
2506
+ function setSignatureMode($mode)
2507
+ {
2508
+ $this->signatureMode = $mode;
2509
+ }
2510
+
2511
+ /**
2512
+ * Set public key comment.
2513
+ *
2514
+ * @access public
2515
+ * @param String $comment
2516
+ */
2517
+ function setComment($comment)
2518
+ {
2519
+ $this->comment = $comment;
2520
+ }
2521
+
2522
+ /**
2523
+ * Get public key comment.
2524
+ *
2525
+ * @access public
2526
+ * @return String
2527
+ */
2528
+ function getComment()
2529
+ {
2530
+ return $this->comment;
2531
+ }
2532
+
2533
+ /**
2534
+ * Encryption
2535
+ *
2536
+ * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
2537
+ * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
2538
+ * be concatenated together.
2539
+ *
2540
+ * @see decrypt()
2541
+ * @access public
2542
+ * @param String $plaintext
2543
+ * @return String
2544
+ */
2545
+ function encrypt($plaintext)
2546
+ {
2547
+ switch ($this->encryptionMode) {
2548
+ case CRYPT_RSA_ENCRYPTION_PKCS1:
2549
+ $length = $this->k - 11;
2550
+ if ($length <= 0) {
2551
+ return false;
2552
+ }
2553
+
2554
+ $plaintext = str_split($plaintext, $length);
2555
+ $ciphertext = '';
2556
+ foreach ($plaintext as $m) {
2557
+ $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
2558
+ }
2559
+ return $ciphertext;
2560
+ //case CRYPT_RSA_ENCRYPTION_OAEP:
2561
+ default:
2562
+ $length = $this->k - 2 * $this->hLen - 2;
2563
+ if ($length <= 0) {
2564
+ return false;
2565
+ }
2566
+
2567
+ $plaintext = str_split($plaintext, $length);
2568
+ $ciphertext = '';
2569
+ foreach ($plaintext as $m) {
2570
+ $ciphertext.= $this->_rsaes_oaep_encrypt($m);
2571
+ }
2572
+ return $ciphertext;
2573
+ }
2574
+ }
2575
+
2576
+ /**
2577
+ * Decryption
2578
+ *
2579
+ * @see encrypt()
2580
+ * @access public
2581
+ * @param String $plaintext
2582
+ * @return String
2583
+ */
2584
+ function decrypt($ciphertext)
2585
+ {
2586
+ if ($this->k <= 0) {
2587
+ return false;
2588
+ }
2589
+
2590
+ $ciphertext = str_split($ciphertext, $this->k);
2591
+ $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
2592
+
2593
+ $plaintext = '';
2594
+
2595
+ switch ($this->encryptionMode) {
2596
+ case CRYPT_RSA_ENCRYPTION_PKCS1:
2597
+ $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
2598
+ break;
2599
+ //case CRYPT_RSA_ENCRYPTION_OAEP:
2600
+ default:
2601
+ $decrypt = '_rsaes_oaep_decrypt';
2602
+ }
2603
+
2604
+ foreach ($ciphertext as $c) {
2605
+ $temp = $this->$decrypt($c);
2606
+ if ($temp === false) {
2607
+ return false;
2608
+ }
2609
+ $plaintext.= $temp;
2610
+ }
2611
+
2612
+ return $plaintext;
2613
+ }
2614
+
2615
+ /**
2616
+ * Create a signature
2617
+ *
2618
+ * @see verify()
2619
+ * @access public
2620
+ * @param String $message
2621
+ * @return String
2622
+ */
2623
+ function sign($message)
2624
+ {
2625
+ if (empty($this->modulus) || empty($this->exponent)) {
2626
+ return false;
2627
+ }
2628
+
2629
+ switch ($this->signatureMode) {
2630
+ case CRYPT_RSA_SIGNATURE_PKCS1:
2631
+ return $this->_rsassa_pkcs1_v1_5_sign($message);
2632
+ //case CRYPT_RSA_SIGNATURE_PSS:
2633
+ default:
2634
+ return $this->_rsassa_pss_sign($message);
2635
+ }
2636
+ }
2637
+
2638
+ /**
2639
+ * Verifies a signature
2640
+ *
2641
+ * @see sign()
2642
+ * @access public
2643
+ * @param String $message
2644
+ * @param String $signature
2645
+ * @return Boolean
2646
+ */
2647
+ function verify($message, $signature)
2648
+ {
2649
+ if (empty($this->modulus) || empty($this->exponent)) {
2650
+ return false;
2651
+ }
2652
+
2653
+ switch ($this->signatureMode) {
2654
+ case CRYPT_RSA_SIGNATURE_PKCS1:
2655
+ return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
2656
+ //case CRYPT_RSA_SIGNATURE_PSS:
2657
+ default:
2658
+ return $this->_rsassa_pss_verify($message, $signature);
2659
+ }
2660
+ }
2661
+ }
lib/LivrariOnline/Random.php ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Random Number Generator
6
+ *
7
+ * PHP versions 4 and 5
8
+ *
9
+ * Here's a short example of how to use this library:
10
+ * <code>
11
+ * <?php
12
+ * include('Crypt/Random.php');
13
+ *
14
+ * echo bin2hex(crypt_random_string(8));
15
+ * ?>
16
+ * </code>
17
+ *
18
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
19
+ * of this software and associated documentation files (the "Software"), to deal
20
+ * in the Software without restriction, including without limitation the rights
21
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
+ * copies of the Software, and to permit persons to whom the Software is
23
+ * furnished to do so, subject to the following conditions:
24
+ *
25
+ * The above copyright notice and this permission notice shall be included in
26
+ * all copies or substantial portions of the Software.
27
+ *
28
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34
+ * THE SOFTWARE.
35
+ *
36
+ * @category Crypt
37
+ * @package Crypt_Random
38
+ * @author Jim Wigginton <terrafrost@php.net>
39
+ * @copyright MMVII Jim Wigginton
40
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
41
+ * @link http://phpseclib.sourceforge.net
42
+ */
43
+
44
+ /**
45
+ * "Is Windows" test
46
+ *
47
+ * @access private
48
+ */
49
+ define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
50
+
51
+ /**
52
+ * Generate a random string.
53
+ *
54
+ * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
55
+ * microoptimizations because this function has the potential of being called a huge number of times.
56
+ * eg. for RSA key generation.
57
+ *
58
+ * @param Integer $length
59
+ * @return String
60
+ * @access public
61
+ */
62
+ function crypt_random_string($length)
63
+ {
64
+ if (CRYPT_RANDOM_IS_WINDOWS) {
65
+ // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
66
+ // ie. class_alias is a function that was introduced in PHP 5.3
67
+ if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
68
+ return mcrypt_create_iv($length);
69
+ }
70
+ // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
71
+ // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
72
+ // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
73
+ // call php_win32_get_random_bytes():
74
+ //
75
+ // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
76
+ // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
77
+ //
78
+ // php_win32_get_random_bytes() is defined thusly:
79
+ //
80
+ // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
81
+ //
82
+ // we're calling it, all the same, in the off chance that the mcrypt extension is not available
83
+ if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
84
+ return openssl_random_pseudo_bytes($length);
85
+ }
86
+ } else {
87
+ // method 1. the fastest
88
+ if (function_exists('openssl_random_pseudo_bytes')) {
89
+ return openssl_random_pseudo_bytes($length);
90
+ }
91
+ // method 2
92
+ static $fp = true;
93
+ if ($fp === true) {
94
+ // warning's will be output unles the error suppression operator is used. errors such as
95
+ // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
96
+ $fp = @fopen('/dev/urandom', 'rb');
97
+ }
98
+ if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
99
+ return fread($fp, $length);
100
+ }
101
+ // method 3. pretty much does the same thing as method 2 per the following url:
102
+ // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
103
+ // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
104
+ // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
105
+ // restrictions or some such
106
+ if (function_exists('mcrypt_create_iv')) {
107
+ return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
108
+ }
109
+ }
110
+ // at this point we have no choice but to use a pure-PHP CSPRNG
111
+
112
+ // cascade entropy across multiple PHP instances by fixing the session and collecting all
113
+ // environmental variables, including the previous session data and the current session
114
+ // data.
115
+ //
116
+ // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
117
+ // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
118
+ // PHP isn't low level to be able to use those as sources and on a web server there's not likely
119
+ // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
120
+ // however. a ton of people visiting the website. obviously you don't want to base your seeding
121
+ // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
122
+ // by the user and (2) this isn't just looking at the data sent by the current user - it's based
123
+ // on the data sent by all users. one user requests the page and a hash of their info is saved.
124
+ // another user visits the page and the serialization of their data is utilized along with the
125
+ // server envirnment stuff and a hash of the previous http request data (which itself utilizes
126
+ // a hash of the session data before that). certainly an attacker should be assumed to have
127
+ // full control over his own http requests. he, however, is not going to have control over
128
+ // everyone's http requests.
129
+ static $crypto = false, $v;
130
+ if ($crypto === false) {
131
+ // save old session data
132
+ $old_session_id = session_id();
133
+ $old_use_cookies = ini_get('session.use_cookies');
134
+ $old_session_cache_limiter = session_cache_limiter();
135
+ if (isset($_SESSION)) {
136
+ $_OLD_SESSION = $_SESSION;
137
+ }
138
+ if ($old_session_id != '') {
139
+ session_write_close();
140
+ }
141
+
142
+ session_id(1);
143
+ ini_set('session.use_cookies', 0);
144
+ session_cache_limiter('');
145
+ session_start();
146
+
147
+ $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
148
+ serialize($_SERVER) .
149
+ serialize($_POST) .
150
+ serialize($_GET) .
151
+ serialize($_COOKIE) .
152
+ serialize($GLOBALS) .
153
+ serialize($_SESSION) .
154
+ serialize($_OLD_SESSION)
155
+ ));
156
+ if (!isset($_SESSION['count'])) {
157
+ $_SESSION['count'] = 0;
158
+ }
159
+ $_SESSION['count']++;
160
+
161
+ session_write_close();
162
+
163
+ // restore old session data
164
+ if ($old_session_id != '') {
165
+ session_id($old_session_id);
166
+ session_start();
167
+ ini_set('session.use_cookies', $old_use_cookies);
168
+ session_cache_limiter($old_session_cache_limiter);
169
+ } else {
170
+ if (isset($_OLD_SESSION)) {
171
+ $_SESSION = $_OLD_SESSION;
172
+ unset($_OLD_SESSION);
173
+ } else {
174
+ unset($_SESSION);
175
+ }
176
+ }
177
+
178
+ // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
179
+ // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
180
+ // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
181
+ // original hash and the current hash. we'll be emulating that. for more info see the following URL:
182
+ //
183
+ // http://tools.ietf.org/html/rfc4253#section-7.2
184
+ //
185
+ // see the is_string($crypto) part for an example of how to expand the keys
186
+ $key = pack('H*', sha1($seed . 'A'));
187
+ $iv = pack('H*', sha1($seed . 'C'));
188
+
189
+ // ciphers are used as per the nist.gov link below. also, see this link:
190
+ //
191
+ // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
192
+ switch (true) {
193
+ case class_exists('Crypt_AES'):
194
+ $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
195
+ break;
196
+ case class_exists('Crypt_TripleDES'):
197
+ $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
198
+ break;
199
+ case class_exists('Crypt_DES'):
200
+ $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
201
+ break;
202
+ case class_exists('Crypt_RC4'):
203
+ $crypto = new Crypt_RC4();
204
+ break;
205
+ default:
206
+ $crypto = $seed;
207
+ return crypt_random_string($length);
208
+ }
209
+
210
+ $crypto->setKey($key);
211
+ $crypto->setIV($iv);
212
+ $crypto->enableContinuousBuffer();
213
+ }
214
+
215
+ if (is_string($crypto)) {
216
+ // the following is based off of ANSI X9.31:
217
+ //
218
+ // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
219
+ //
220
+ // OpenSSL uses that same standard for it's random numbers:
221
+ //
222
+ // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
223
+ // (do a search for "ANS X9.31 A.2.4")
224
+ //
225
+ // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see
226
+ // later on in the code) but if they're not we'll use sha1
227
+ $result = '';
228
+ while (strlen($result) < $length) { // each loop adds 20 bytes
229
+ // microtime() isn't packed as "densely" as it could be but then neither is that the idea.
230
+ // the idea is simply to ensure that each "block" has a unique element to it.
231
+ $i = pack('H*', sha1(microtime()));
232
+ $r = pack('H*', sha1($i ^ $v));
233
+ $v = pack('H*', sha1($r ^ $i));
234
+ $result.= $r;
235
+ }
236
+ return substr($result, 0, $length);
237
+ }
238
+
239
+ //return $crypto->encrypt(str_repeat("\0", $length));
240
+
241
+ $result = '';
242
+ while (strlen($result) < $length) {
243
+ $i = $crypto->encrypt(microtime());
244
+ $r = $crypto->encrypt($i ^ $v);
245
+ $v = $crypto->encrypt($r ^ $i);
246
+ $result.= $r;
247
+ }
248
+ return substr($result, 0, $length);
249
+ }
lib/LivrariOnline/Rijndael.php ADDED
@@ -0,0 +1,1370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of Rijndael.
5
+ *
6
+ * Uses mcrypt, if available/possible, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * If {@link Crypt_Rijndael::setBlockLength() setBlockLength()} isn't called, it'll be assumed to be 128 bits. If
11
+ * {@link Crypt_Rijndael::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
12
+ * {@link Crypt_Rijndael::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's
13
+ * 136-bits it'll be null-padded to 192-bits and 192 bits will be the key length until
14
+ * {@link Crypt_Rijndael::setKey() setKey()} is called, again, at which point, it'll be recalculated.
15
+ *
16
+ * Not all Rijndael implementations may support 160-bits or 224-bits as the block length / key length. mcrypt, for example,
17
+ * does not. AES, itself, only supports block lengths of 128 and key lengths of 128, 192, and 256.
18
+ * {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=10 Rijndael-ammended.pdf#page=10} defines the
19
+ * algorithm for block lengths of 192 and 256 but not for block lengths / key lengths of 160 and 224. Indeed, 160 and 224
20
+ * are first defined as valid key / block lengths in
21
+ * {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=44 Rijndael-ammended.pdf#page=44}:
22
+ * Extensions: Other block and Cipher Key lengths.
23
+ * Note: Use of 160/224-bit Keys must be explicitly set by setKeyLength(160) respectively setKeyLength(224).
24
+ *
25
+ * {@internal The variable names are the same as those in
26
+ * {@link http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf#page=10 fips-197.pdf#page=10}.}}
27
+ *
28
+ * Here's a short example of how to use this library:
29
+ * <code>
30
+ * <?php
31
+ * include('Crypt/Rijndael.php');
32
+ *
33
+ * $rijndael = new Crypt_Rijndael();
34
+ *
35
+ * $rijndael->setKey('abcdefghijklmnop');
36
+ *
37
+ * $size = 10 * 1024;
38
+ * $plaintext = '';
39
+ * for ($i = 0; $i < $size; $i++) {
40
+ * $plaintext.= 'a';
41
+ * }
42
+ *
43
+ * echo $rijndael->decrypt($rijndael->encrypt($plaintext));
44
+ * ?>
45
+ * </code>
46
+ *
47
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
48
+ * of this software and associated documentation files (the "Software"), to deal
49
+ * in the Software without restriction, including without limitation the rights
50
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
+ * copies of the Software, and to permit persons to whom the Software is
52
+ * furnished to do so, subject to the following conditions:
53
+ *
54
+ * The above copyright notice and this permission notice shall be included in
55
+ * all copies or substantial portions of the Software.
56
+ *
57
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
63
+ * THE SOFTWARE.
64
+ *
65
+ * @category Crypt
66
+ * @package Crypt_Rijndael
67
+ * @author Jim Wigginton <terrafrost@php.net>
68
+ * @copyright MMVIII Jim Wigginton
69
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
70
+ * @link http://phpseclib.sourceforge.net
71
+ */
72
+
73
+ /**
74
+ * Include Crypt_Base
75
+ *
76
+ * Base cipher class
77
+ */
78
+ require_once('Base.php');
79
+
80
+ /**#@+
81
+ * @access public
82
+ * @see Crypt_Rijndael::encrypt()
83
+ * @see Crypt_Rijndael::decrypt()
84
+ */
85
+ /**
86
+ * Encrypt / decrypt using the Counter mode.
87
+ *
88
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
89
+ *
90
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
91
+ */
92
+ define('CRYPT_RIJNDAEL_MODE_CTR', CRYPT_MODE_CTR);
93
+ /**
94
+ * Encrypt / decrypt using the Electronic Code Book mode.
95
+ *
96
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
97
+ */
98
+ define('CRYPT_RIJNDAEL_MODE_ECB', CRYPT_MODE_ECB);
99
+ /**
100
+ * Encrypt / decrypt using the Code Book Chaining mode.
101
+ *
102
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
103
+ */
104
+ define('CRYPT_RIJNDAEL_MODE_CBC', CRYPT_MODE_CBC);
105
+ /**
106
+ * Encrypt / decrypt using the Cipher Feedback mode.
107
+ *
108
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
109
+ */
110
+ define('CRYPT_RIJNDAEL_MODE_CFB', CRYPT_MODE_CFB);
111
+ /**
112
+ * Encrypt / decrypt using the Cipher Feedback mode.
113
+ *
114
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
115
+ */
116
+ define('CRYPT_RIJNDAEL_MODE_OFB', CRYPT_MODE_OFB);
117
+ /**#@-*/
118
+
119
+ /**#@+
120
+ * @access private
121
+ * @see Crypt_Rijndael::Crypt_Rijndael()
122
+ */
123
+ /**
124
+ * Toggles the internal implementation
125
+ */
126
+ define('CRYPT_RIJNDAEL_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
127
+ /**
128
+ * Toggles the mcrypt implementation
129
+ */
130
+ define('CRYPT_RIJNDAEL_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
131
+ /**#@-*/
132
+
133
+ /**
134
+ * Pure-PHP implementation of Rijndael.
135
+ *
136
+ * @package Crypt_Rijndael
137
+ * @author Jim Wigginton <terrafrost@php.net>
138
+ * @version 0.1.0
139
+ * @access public
140
+ */
141
+ class Crypt_Rijndael extends Crypt_Base
142
+ {
143
+ /**
144
+ * The default password key_size used by setPassword()
145
+ *
146
+ * @see Crypt_Base::password_key_size
147
+ * @see Crypt_Base::setPassword()
148
+ * @var Integer
149
+ * @access private
150
+ */
151
+ var $password_key_size = 16;
152
+
153
+ /**
154
+ * The namespace used by the cipher for its constants.
155
+ *
156
+ * @see Crypt_Base::const_namespace
157
+ * @var String
158
+ * @access private
159
+ */
160
+ var $const_namespace = 'RIJNDAEL';
161
+
162
+ /**
163
+ * The mcrypt specific name of the cipher
164
+ *
165
+ * Mcrypt is useable for 128/192/256-bit $block_size/$key_size. For 160/224 not.
166
+ * Crypt_Rijndael determines automatically whether mcrypt is useable
167
+ * or not for the current $block_size/$key_size.
168
+ * In case of, $cipher_name_mcrypt will be set dynamicaly at run time accordingly.
169
+ *
170
+ * @see Crypt_Base::cipher_name_mcrypt
171
+ * @see Crypt_Base::engine
172
+ * @see _setupEngine()
173
+ * @var String
174
+ * @access private
175
+ */
176
+ var $cipher_name_mcrypt = 'rijndael-128';
177
+
178
+ /**
179
+ * The default salt used by setPassword()
180
+ *
181
+ * @see Crypt_Base::password_default_salt
182
+ * @see Crypt_Base::setPassword()
183
+ * @var String
184
+ * @access private
185
+ */
186
+ var $password_default_salt = 'phpseclib';
187
+
188
+ /**
189
+ * Has the key length explicitly been set or should it be derived from the key, itself?
190
+ *
191
+ * @see setKeyLength()
192
+ * @var Boolean
193
+ * @access private
194
+ */
195
+ var $explicit_key_length = false;
196
+
197
+ /**
198
+ * The Key Schedule
199
+ *
200
+ * @see _setup()
201
+ * @var Array
202
+ * @access private
203
+ */
204
+ var $w;
205
+
206
+ /**
207
+ * The Inverse Key Schedule
208
+ *
209
+ * @see _setup()
210
+ * @var Array
211
+ * @access private
212
+ */
213
+ var $dw;
214
+
215
+ /**
216
+ * The Block Length divided by 32
217
+ *
218
+ * @see setBlockLength()
219
+ * @var Integer
220
+ * @access private
221
+ * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size
222
+ * because the encryption / decryption / key schedule creation requires this number and not $block_size. We could
223
+ * derive this from $block_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
224
+ * of that, we'll just precompute it once.
225
+ *
226
+ */
227
+ var $Nb = 4;
228
+
229
+ /**
230
+ * The Key Length
231
+ *
232
+ * @see setKeyLength()
233
+ * @var Integer
234
+ * @access private
235
+ * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk
236
+ * because the encryption / decryption / key schedule creation requires this number and not $key_size. We could
237
+ * derive this from $key_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
238
+ * of that, we'll just precompute it once.
239
+ */
240
+ var $key_size = 16;
241
+
242
+ /**
243
+ * The Key Length divided by 32
244
+ *
245
+ * @see setKeyLength()
246
+ * @var Integer
247
+ * @access private
248
+ * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4
249
+ */
250
+ var $Nk = 4;
251
+
252
+ /**
253
+ * The Number of Rounds
254
+ *
255
+ * @var Integer
256
+ * @access private
257
+ * @internal The max value is 14, the min value is 10.
258
+ */
259
+ var $Nr;
260
+
261
+ /**
262
+ * Shift offsets
263
+ *
264
+ * @var Array
265
+ * @access private
266
+ */
267
+ var $c;
268
+
269
+ /**
270
+ * Holds the last used key- and block_size information
271
+ *
272
+ * @var Array
273
+ * @access private
274
+ */
275
+ var $kl;
276
+
277
+ /**
278
+ * Precomputed mixColumns table
279
+ *
280
+ * According to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=19> (section 5.2.1),
281
+ * precomputed tables can be used in the mixColumns phase. in that example, they're assigned t0...t3, so
282
+ * those are the names we'll use.
283
+ *
284
+ * @see Crypt_Rijndael:_encryptBlock()
285
+ * @see Crypt_Rijndael:_decryptBlock()
286
+ * @var Array
287
+ * @access private
288
+ */
289
+ var $t0 = array(
290
+ 0xC66363A5, 0xF87C7C84, 0xEE777799, 0xF67B7B8D, 0xFFF2F20D, 0xD66B6BBD, 0xDE6F6FB1, 0x91C5C554,
291
+ 0x60303050, 0x02010103, 0xCE6767A9, 0x562B2B7D, 0xE7FEFE19, 0xB5D7D762, 0x4DABABE6, 0xEC76769A,
292
+ 0x8FCACA45, 0x1F82829D, 0x89C9C940, 0xFA7D7D87, 0xEFFAFA15, 0xB25959EB, 0x8E4747C9, 0xFBF0F00B,
293
+ 0x41ADADEC, 0xB3D4D467, 0x5FA2A2FD, 0x45AFAFEA, 0x239C9CBF, 0x53A4A4F7, 0xE4727296, 0x9BC0C05B,
294
+ 0x75B7B7C2, 0xE1FDFD1C, 0x3D9393AE, 0x4C26266A, 0x6C36365A, 0x7E3F3F41, 0xF5F7F702, 0x83CCCC4F,
295
+ 0x6834345C, 0x51A5A5F4, 0xD1E5E534, 0xF9F1F108, 0xE2717193, 0xABD8D873, 0x62313153, 0x2A15153F,
296
+ 0x0804040C, 0x95C7C752, 0x46232365, 0x9DC3C35E, 0x30181828, 0x379696A1, 0x0A05050F, 0x2F9A9AB5,
297
+ 0x0E070709, 0x24121236, 0x1B80809B, 0xDFE2E23D, 0xCDEBEB26, 0x4E272769, 0x7FB2B2CD, 0xEA75759F,
298
+ 0x1209091B, 0x1D83839E, 0x582C2C74, 0x341A1A2E, 0x361B1B2D, 0xDC6E6EB2, 0xB45A5AEE, 0x5BA0A0FB,
299
+ 0xA45252F6, 0x763B3B4D, 0xB7D6D661, 0x7DB3B3CE, 0x5229297B, 0xDDE3E33E, 0x5E2F2F71, 0x13848497,
300
+ 0xA65353F5, 0xB9D1D168, 0x00000000, 0xC1EDED2C, 0x40202060, 0xE3FCFC1F, 0x79B1B1C8, 0xB65B5BED,
301
+ 0xD46A6ABE, 0x8DCBCB46, 0x67BEBED9, 0x7239394B, 0x944A4ADE, 0x984C4CD4, 0xB05858E8, 0x85CFCF4A,
302
+ 0xBBD0D06B, 0xC5EFEF2A, 0x4FAAAAE5, 0xEDFBFB16, 0x864343C5, 0x9A4D4DD7, 0x66333355, 0x11858594,
303
+ 0x8A4545CF, 0xE9F9F910, 0x04020206, 0xFE7F7F81, 0xA05050F0, 0x783C3C44, 0x259F9FBA, 0x4BA8A8E3,
304
+ 0xA25151F3, 0x5DA3A3FE, 0x804040C0, 0x058F8F8A, 0x3F9292AD, 0x219D9DBC, 0x70383848, 0xF1F5F504,
305
+ 0x63BCBCDF, 0x77B6B6C1, 0xAFDADA75, 0x42212163, 0x20101030, 0xE5FFFF1A, 0xFDF3F30E, 0xBFD2D26D,
306
+ 0x81CDCD4C, 0x180C0C14, 0x26131335, 0xC3ECEC2F, 0xBE5F5FE1, 0x359797A2, 0x884444CC, 0x2E171739,
307
+ 0x93C4C457, 0x55A7A7F2, 0xFC7E7E82, 0x7A3D3D47, 0xC86464AC, 0xBA5D5DE7, 0x3219192B, 0xE6737395,
308
+ 0xC06060A0, 0x19818198, 0x9E4F4FD1, 0xA3DCDC7F, 0x44222266, 0x542A2A7E, 0x3B9090AB, 0x0B888883,
309
+ 0x8C4646CA, 0xC7EEEE29, 0x6BB8B8D3, 0x2814143C, 0xA7DEDE79, 0xBC5E5EE2, 0x160B0B1D, 0xADDBDB76,
310
+ 0xDBE0E03B, 0x64323256, 0x743A3A4E, 0x140A0A1E, 0x924949DB, 0x0C06060A, 0x4824246C, 0xB85C5CE4,
311
+ 0x9FC2C25D, 0xBDD3D36E, 0x43ACACEF, 0xC46262A6, 0x399191A8, 0x319595A4, 0xD3E4E437, 0xF279798B,
312
+ 0xD5E7E732, 0x8BC8C843, 0x6E373759, 0xDA6D6DB7, 0x018D8D8C, 0xB1D5D564, 0x9C4E4ED2, 0x49A9A9E0,
313
+ 0xD86C6CB4, 0xAC5656FA, 0xF3F4F407, 0xCFEAEA25, 0xCA6565AF, 0xF47A7A8E, 0x47AEAEE9, 0x10080818,
314
+ 0x6FBABAD5, 0xF0787888, 0x4A25256F, 0x5C2E2E72, 0x381C1C24, 0x57A6A6F1, 0x73B4B4C7, 0x97C6C651,
315
+ 0xCBE8E823, 0xA1DDDD7C, 0xE874749C, 0x3E1F1F21, 0x964B4BDD, 0x61BDBDDC, 0x0D8B8B86, 0x0F8A8A85,
316
+ 0xE0707090, 0x7C3E3E42, 0x71B5B5C4, 0xCC6666AA, 0x904848D8, 0x06030305, 0xF7F6F601, 0x1C0E0E12,
317
+ 0xC26161A3, 0x6A35355F, 0xAE5757F9, 0x69B9B9D0, 0x17868691, 0x99C1C158, 0x3A1D1D27, 0x279E9EB9,
318
+ 0xD9E1E138, 0xEBF8F813, 0x2B9898B3, 0x22111133, 0xD26969BB, 0xA9D9D970, 0x078E8E89, 0x339494A7,
319
+ 0x2D9B9BB6, 0x3C1E1E22, 0x15878792, 0xC9E9E920, 0x87CECE49, 0xAA5555FF, 0x50282878, 0xA5DFDF7A,
320
+ 0x038C8C8F, 0x59A1A1F8, 0x09898980, 0x1A0D0D17, 0x65BFBFDA, 0xD7E6E631, 0x844242C6, 0xD06868B8,
321
+ 0x824141C3, 0x299999B0, 0x5A2D2D77, 0x1E0F0F11, 0x7BB0B0CB, 0xA85454FC, 0x6DBBBBD6, 0x2C16163A
322
+ );
323
+
324
+ /**
325
+ * Precomputed mixColumns table
326
+ *
327
+ * @see Crypt_Rijndael:_encryptBlock()
328
+ * @see Crypt_Rijndael:_decryptBlock()
329
+ * @var Array
330
+ * @access private
331
+ */
332
+ var $t1 = array(
333
+ 0xA5C66363, 0x84F87C7C, 0x99EE7777, 0x8DF67B7B, 0x0DFFF2F2, 0xBDD66B6B, 0xB1DE6F6F, 0x5491C5C5,
334
+ 0x50603030, 0x03020101, 0xA9CE6767, 0x7D562B2B, 0x19E7FEFE, 0x62B5D7D7, 0xE64DABAB, 0x9AEC7676,
335
+ 0x458FCACA, 0x9D1F8282, 0x4089C9C9, 0x87FA7D7D, 0x15EFFAFA, 0xEBB25959, 0xC98E4747, 0x0BFBF0F0,
336
+ 0xEC41ADAD, 0x67B3D4D4, 0xFD5FA2A2, 0xEA45AFAF, 0xBF239C9C, 0xF753A4A4, 0x96E47272, 0x5B9BC0C0,
337
+ 0xC275B7B7, 0x1CE1FDFD, 0xAE3D9393, 0x6A4C2626, 0x5A6C3636, 0x417E3F3F, 0x02F5F7F7, 0x4F83CCCC,
338
+ 0x5C683434, 0xF451A5A5, 0x34D1E5E5, 0x08F9F1F1, 0x93E27171, 0x73ABD8D8, 0x53623131, 0x3F2A1515,
339
+ 0x0C080404, 0x5295C7C7, 0x65462323, 0x5E9DC3C3, 0x28301818, 0xA1379696, 0x0F0A0505, 0xB52F9A9A,
340
+ 0x090E0707, 0x36241212, 0x9B1B8080, 0x3DDFE2E2, 0x26CDEBEB, 0x694E2727, 0xCD7FB2B2, 0x9FEA7575,
341
+ 0x1B120909, 0x9E1D8383, 0x74582C2C, 0x2E341A1A, 0x2D361B1B, 0xB2DC6E6E, 0xEEB45A5A, 0xFB5BA0A0,
342
+ 0xF6A45252, 0x4D763B3B, 0x61B7D6D6, 0xCE7DB3B3, 0x7B522929, 0x3EDDE3E3, 0x715E2F2F, 0x97138484,
343
+ 0xF5A65353, 0x68B9D1D1, 0x00000000, 0x2CC1EDED, 0x60402020, 0x1FE3FCFC, 0xC879B1B1, 0xEDB65B5B,
344
+ 0xBED46A6A, 0x468DCBCB, 0xD967BEBE, 0x4B723939, 0xDE944A4A, 0xD4984C4C, 0xE8B05858, 0x4A85CFCF,
345
+ 0x6BBBD0D0, 0x2AC5EFEF, 0xE54FAAAA, 0x16EDFBFB, 0xC5864343, 0xD79A4D4D, 0x55663333, 0x94118585,
346
+ 0xCF8A4545, 0x10E9F9F9, 0x06040202, 0x81FE7F7F, 0xF0A05050, 0x44783C3C, 0xBA259F9F, 0xE34BA8A8,
347
+ 0xF3A25151, 0xFE5DA3A3, 0xC0804040, 0x8A058F8F, 0xAD3F9292, 0xBC219D9D, 0x48703838, 0x04F1F5F5,
348
+ 0xDF63BCBC, 0xC177B6B6, 0x75AFDADA, 0x63422121, 0x30201010, 0x1AE5FFFF, 0x0EFDF3F3, 0x6DBFD2D2,
349
+ 0x4C81CDCD, 0x14180C0C, 0x35261313, 0x2FC3ECEC, 0xE1BE5F5F, 0xA2359797, 0xCC884444, 0x392E1717,
350
+ 0x5793C4C4, 0xF255A7A7, 0x82FC7E7E, 0x477A3D3D, 0xACC86464, 0xE7BA5D5D, 0x2B321919, 0x95E67373,
351
+ 0xA0C06060, 0x98198181, 0xD19E4F4F, 0x7FA3DCDC, 0x66442222, 0x7E542A2A, 0xAB3B9090, 0x830B8888,
352
+ 0xCA8C4646, 0x29C7EEEE, 0xD36BB8B8, 0x3C281414, 0x79A7DEDE, 0xE2BC5E5E, 0x1D160B0B, 0x76ADDBDB,
353
+ 0x3BDBE0E0, 0x56643232, 0x4E743A3A, 0x1E140A0A, 0xDB924949, 0x0A0C0606, 0x6C482424, 0xE4B85C5C,
354
+ 0x5D9FC2C2, 0x6EBDD3D3, 0xEF43ACAC, 0xA6C46262, 0xA8399191, 0xA4319595, 0x37D3E4E4, 0x8BF27979,
355
+ 0x32D5E7E7, 0x438BC8C8, 0x596E3737, 0xB7DA6D6D, 0x8C018D8D, 0x64B1D5D5, 0xD29C4E4E, 0xE049A9A9,
356
+ 0xB4D86C6C, 0xFAAC5656, 0x07F3F4F4, 0x25CFEAEA, 0xAFCA6565, 0x8EF47A7A, 0xE947AEAE, 0x18100808,
357
+ 0xD56FBABA, 0x88F07878, 0x6F4A2525, 0x725C2E2E, 0x24381C1C, 0xF157A6A6, 0xC773B4B4, 0x5197C6C6,
358
+ 0x23CBE8E8, 0x7CA1DDDD, 0x9CE87474, 0x213E1F1F, 0xDD964B4B, 0xDC61BDBD, 0x860D8B8B, 0x850F8A8A,
359
+ 0x90E07070, 0x427C3E3E, 0xC471B5B5, 0xAACC6666, 0xD8904848, 0x05060303, 0x01F7F6F6, 0x121C0E0E,
360
+ 0xA3C26161, 0x5F6A3535, 0xF9AE5757, 0xD069B9B9, 0x91178686, 0x5899C1C1, 0x273A1D1D, 0xB9279E9E,
361
+ 0x38D9E1E1, 0x13EBF8F8, 0xB32B9898, 0x33221111, 0xBBD26969, 0x70A9D9D9, 0x89078E8E, 0xA7339494,
362
+ 0xB62D9B9B, 0x223C1E1E, 0x92158787, 0x20C9E9E9, 0x4987CECE, 0xFFAA5555, 0x78502828, 0x7AA5DFDF,
363
+ 0x8F038C8C, 0xF859A1A1, 0x80098989, 0x171A0D0D, 0xDA65BFBF, 0x31D7E6E6, 0xC6844242, 0xB8D06868,
364
+ 0xC3824141, 0xB0299999, 0x775A2D2D, 0x111E0F0F, 0xCB7BB0B0, 0xFCA85454, 0xD66DBBBB, 0x3A2C1616
365
+ );
366
+
367
+ /**
368
+ * Precomputed mixColumns table
369
+ *
370
+ * @see Crypt_Rijndael:_encryptBlock()
371
+ * @see Crypt_Rijndael:_decryptBlock()
372
+ * @var Array
373
+ * @access private
374
+ */
375
+ var $t2 = array(
376
+ 0x63A5C663, 0x7C84F87C, 0x7799EE77, 0x7B8DF67B, 0xF20DFFF2, 0x6BBDD66B, 0x6FB1DE6F, 0xC55491C5,
377
+ 0x30506030, 0x01030201, 0x67A9CE67, 0x2B7D562B, 0xFE19E7FE, 0xD762B5D7, 0xABE64DAB, 0x769AEC76,
378
+ 0xCA458FCA, 0x829D1F82, 0xC94089C9, 0x7D87FA7D, 0xFA15EFFA, 0x59EBB259, 0x47C98E47, 0xF00BFBF0,
379
+ 0xADEC41AD, 0xD467B3D4, 0xA2FD5FA2, 0xAFEA45AF, 0x9CBF239C, 0xA4F753A4, 0x7296E472, 0xC05B9BC0,
380
+ 0xB7C275B7, 0xFD1CE1FD, 0x93AE3D93, 0x266A4C26, 0x365A6C36, 0x3F417E3F, 0xF702F5F7, 0xCC4F83CC,
381
+ 0x345C6834, 0xA5F451A5, 0xE534D1E5, 0xF108F9F1, 0x7193E271, 0xD873ABD8, 0x31536231, 0x153F2A15,
382
+ 0x040C0804, 0xC75295C7, 0x23654623, 0xC35E9DC3, 0x18283018, 0x96A13796, 0x050F0A05, 0x9AB52F9A,
383
+ 0x07090E07, 0x12362412, 0x809B1B80, 0xE23DDFE2, 0xEB26CDEB, 0x27694E27, 0xB2CD7FB2, 0x759FEA75,
384
+ 0x091B1209, 0x839E1D83, 0x2C74582C, 0x1A2E341A, 0x1B2D361B, 0x6EB2DC6E, 0x5AEEB45A, 0xA0FB5BA0,
385
+ 0x52F6A452, 0x3B4D763B, 0xD661B7D6, 0xB3CE7DB3, 0x297B5229, 0xE33EDDE3, 0x2F715E2F, 0x84971384,
386
+ 0x53F5A653, 0xD168B9D1, 0x00000000, 0xED2CC1ED, 0x20604020, 0xFC1FE3FC, 0xB1C879B1, 0x5BEDB65B,
387
+ 0x6ABED46A, 0xCB468DCB, 0xBED967BE, 0x394B7239, 0x4ADE944A, 0x4CD4984C, 0x58E8B058, 0xCF4A85CF,
388
+ 0xD06BBBD0, 0xEF2AC5EF, 0xAAE54FAA, 0xFB16EDFB, 0x43C58643, 0x4DD79A4D, 0x33556633, 0x85941185,
389
+ 0x45CF8A45, 0xF910E9F9, 0x02060402, 0x7F81FE7F, 0x50F0A050, 0x3C44783C, 0x9FBA259F, 0xA8E34BA8,
390
+ 0x51F3A251, 0xA3FE5DA3, 0x40C08040, 0x8F8A058F, 0x92AD3F92, 0x9DBC219D, 0x38487038, 0xF504F1F5,
391
+ 0xBCDF63BC, 0xB6C177B6, 0xDA75AFDA, 0x21634221, 0x10302010, 0xFF1AE5FF, 0xF30EFDF3, 0xD26DBFD2,
392
+ 0xCD4C81CD, 0x0C14180C, 0x13352613, 0xEC2FC3EC, 0x5FE1BE5F, 0x97A23597, 0x44CC8844, 0x17392E17,
393
+ 0xC45793C4, 0xA7F255A7, 0x7E82FC7E, 0x3D477A3D, 0x64ACC864, 0x5DE7BA5D, 0x192B3219, 0x7395E673,
394
+ 0x60A0C060, 0x81981981, 0x4FD19E4F, 0xDC7FA3DC, 0x22664422, 0x2A7E542A, 0x90AB3B90, 0x88830B88,
395
+ 0x46CA8C46, 0xEE29C7EE, 0xB8D36BB8, 0x143C2814, 0xDE79A7DE, 0x5EE2BC5E, 0x0B1D160B, 0xDB76ADDB,
396
+ 0xE03BDBE0, 0x32566432, 0x3A4E743A, 0x0A1E140A, 0x49DB9249, 0x060A0C06, 0x246C4824, 0x5CE4B85C,
397
+ 0xC25D9FC2, 0xD36EBDD3, 0xACEF43AC, 0x62A6C462, 0x91A83991, 0x95A43195, 0xE437D3E4, 0x798BF279,
398
+ 0xE732D5E7, 0xC8438BC8, 0x37596E37, 0x6DB7DA6D, 0x8D8C018D, 0xD564B1D5, 0x4ED29C4E, 0xA9E049A9,
399
+ 0x6CB4D86C, 0x56FAAC56, 0xF407F3F4, 0xEA25CFEA, 0x65AFCA65, 0x7A8EF47A, 0xAEE947AE, 0x08181008,
400
+ 0xBAD56FBA, 0x7888F078, 0x256F4A25, 0x2E725C2E, 0x1C24381C, 0xA6F157A6, 0xB4C773B4, 0xC65197C6,
401
+ 0xE823CBE8, 0xDD7CA1DD, 0x749CE874, 0x1F213E1F, 0x4BDD964B, 0xBDDC61BD, 0x8B860D8B, 0x8A850F8A,
402
+ 0x7090E070, 0x3E427C3E, 0xB5C471B5, 0x66AACC66, 0x48D89048, 0x03050603, 0xF601F7F6, 0x0E121C0E,
403
+ 0x61A3C261, 0x355F6A35, 0x57F9AE57, 0xB9D069B9, 0x86911786, 0xC15899C1, 0x1D273A1D, 0x9EB9279E,
404
+ 0xE138D9E1, 0xF813EBF8, 0x98B32B98, 0x11332211, 0x69BBD269, 0xD970A9D9, 0x8E89078E, 0x94A73394,
405
+ 0x9BB62D9B, 0x1E223C1E, 0x87921587, 0xE920C9E9, 0xCE4987CE, 0x55FFAA55, 0x28785028, 0xDF7AA5DF,
406
+ 0x8C8F038C, 0xA1F859A1, 0x89800989, 0x0D171A0D, 0xBFDA65BF, 0xE631D7E6, 0x42C68442, 0x68B8D068,
407
+ 0x41C38241, 0x99B02999, 0x2D775A2D, 0x0F111E0F, 0xB0CB7BB0, 0x54FCA854, 0xBBD66DBB, 0x163A2C16
408
+ );
409
+
410
+ /**
411
+ * Precomputed mixColumns table
412
+ *
413
+ * @see Crypt_Rijndael:_encryptBlock()
414
+ * @see Crypt_Rijndael:_decryptBlock()
415
+ * @var Array
416
+ * @access private
417
+ */
418
+ var $t3 = array(
419
+ 0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491,
420
+ 0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC,
421
+ 0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB,
422
+ 0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B,
423
+ 0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83,
424
+ 0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A,
425
+ 0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F,
426
+ 0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA,
427
+ 0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B,
428
+ 0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713,
429
+ 0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6,
430
+ 0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85,
431
+ 0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411,
432
+ 0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B,
433
+ 0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1,
434
+ 0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF,
435
+ 0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E,
436
+ 0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6,
437
+ 0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B,
438
+ 0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD,
439
+ 0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8,
440
+ 0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2,
441
+ 0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049,
442
+ 0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810,
443
+ 0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197,
444
+ 0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F,
445
+ 0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C,
446
+ 0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927,
447
+ 0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733,
448
+ 0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5,
449
+ 0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0,
450
+ 0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C
451
+ );
452
+
453
+ /**
454
+ * Precomputed invMixColumns table
455
+ *
456
+ * @see Crypt_Rijndael:_encryptBlock()
457
+ * @see Crypt_Rijndael:_decryptBlock()
458
+ * @var Array
459
+ * @access private
460
+ */
461
+ var $dt0 = array(
462
+ 0x51F4A750, 0x7E416553, 0x1A17A4C3, 0x3A275E96, 0x3BAB6BCB, 0x1F9D45F1, 0xACFA58AB, 0x4BE30393,
463
+ 0x2030FA55, 0xAD766DF6, 0x88CC7691, 0xF5024C25, 0x4FE5D7FC, 0xC52ACBD7, 0x26354480, 0xB562A38F,
464
+ 0xDEB15A49, 0x25BA1B67, 0x45EA0E98, 0x5DFEC0E1, 0xC32F7502, 0x814CF012, 0x8D4697A3, 0x6BD3F9C6,
465
+ 0x038F5FE7, 0x15929C95, 0xBF6D7AEB, 0x955259DA, 0xD4BE832D, 0x587421D3, 0x49E06929, 0x8EC9C844,
466
+ 0x75C2896A, 0xF48E7978, 0x99583E6B, 0x27B971DD, 0xBEE14FB6, 0xF088AD17, 0xC920AC66, 0x7DCE3AB4,
467
+ 0x63DF4A18, 0xE51A3182, 0x97513360, 0x62537F45, 0xB16477E0, 0xBB6BAE84, 0xFE81A01C, 0xF9082B94,
468
+ 0x70486858, 0x8F45FD19, 0x94DE6C87, 0x527BF8B7, 0xAB73D323, 0x724B02E2, 0xE31F8F57, 0x6655AB2A,
469
+ 0xB2EB2807, 0x2FB5C203, 0x86C57B9A, 0xD33708A5, 0x302887F2, 0x23BFA5B2, 0x02036ABA, 0xED16825C,
470
+ 0x8ACF1C2B, 0xA779B492, 0xF307F2F0, 0x4E69E2A1, 0x65DAF4CD, 0x0605BED5, 0xD134621F, 0xC4A6FE8A,
471
+ 0x342E539D, 0xA2F355A0, 0x058AE132, 0xA4F6EB75, 0x0B83EC39, 0x4060EFAA, 0x5E719F06, 0xBD6E1051,
472
+ 0x3E218AF9, 0x96DD063D, 0xDD3E05AE, 0x4DE6BD46, 0x91548DB5, 0x71C45D05, 0x0406D46F, 0x605015FF,
473
+ 0x1998FB24, 0xD6BDE997, 0x894043CC, 0x67D99E77, 0xB0E842BD, 0x07898B88, 0xE7195B38, 0x79C8EEDB,
474
+ 0xA17C0A47, 0x7C420FE9, 0xF8841EC9, 0x00000000, 0x09808683, 0x322BED48, 0x1E1170AC, 0x6C5A724E,
475
+ 0xFD0EFFFB, 0x0F853856, 0x3DAED51E, 0x362D3927, 0x0A0FD964, 0x685CA621, 0x9B5B54D1, 0x24362E3A,
476
+ 0x0C0A67B1, 0x9357E70F, 0xB4EE96D2, 0x1B9B919E, 0x80C0C54F, 0x61DC20A2, 0x5A774B69, 0x1C121A16,
477
+ 0xE293BA0A, 0xC0A02AE5, 0x3C22E043, 0x121B171D, 0x0E090D0B, 0xF28BC7AD, 0x2DB6A8B9, 0x141EA9C8,
478
+ 0x57F11985, 0xAF75074C, 0xEE99DDBB, 0xA37F60FD, 0xF701269F, 0x5C72F5BC, 0x44663BC5, 0x5BFB7E34,
479
+ 0x8B432976, 0xCB23C6DC, 0xB6EDFC68, 0xB8E4F163, 0xD731DCCA, 0x42638510, 0x13972240, 0x84C61120,
480
+ 0x854A247D, 0xD2BB3DF8, 0xAEF93211, 0xC729A16D, 0x1D9E2F4B, 0xDCB230F3, 0x0D8652EC, 0x77C1E3D0,
481
+ 0x2BB3166C, 0xA970B999, 0x119448FA, 0x47E96422, 0xA8FC8CC4, 0xA0F03F1A, 0x567D2CD8, 0x223390EF,
482
+ 0x87494EC7, 0xD938D1C1, 0x8CCAA2FE, 0x98D40B36, 0xA6F581CF, 0xA57ADE28, 0xDAB78E26, 0x3FADBFA4,
483
+ 0x2C3A9DE4, 0x5078920D, 0x6A5FCC9B, 0x547E4662, 0xF68D13C2, 0x90D8B8E8, 0x2E39F75E, 0x82C3AFF5,
484
+ 0x9F5D80BE, 0x69D0937C, 0x6FD52DA9, 0xCF2512B3, 0xC8AC993B, 0x10187DA7, 0xE89C636E, 0xDB3BBB7B,
485
+ 0xCD267809, 0x6E5918F4, 0xEC9AB701, 0x834F9AA8, 0xE6956E65, 0xAAFFE67E, 0x21BCCF08, 0xEF15E8E6,
486
+ 0xBAE79BD9, 0x4A6F36CE, 0xEA9F09D4, 0x29B07CD6, 0x31A4B2AF, 0x2A3F2331, 0xC6A59430, 0x35A266C0,
487
+ 0x744EBC37, 0xFC82CAA6, 0xE090D0B0, 0x33A7D815, 0xF104984A, 0x41ECDAF7, 0x7FCD500E, 0x1791F62F,
488
+ 0x764DD68D, 0x43EFB04D, 0xCCAA4D54, 0xE49604DF, 0x9ED1B5E3, 0x4C6A881B, 0xC12C1FB8, 0x4665517F,
489
+ 0x9D5EEA04, 0x018C355D, 0xFA877473, 0xFB0B412E, 0xB3671D5A, 0x92DBD252, 0xE9105633, 0x6DD64713,
490
+ 0x9AD7618C, 0x37A10C7A, 0x59F8148E, 0xEB133C89, 0xCEA927EE, 0xB761C935, 0xE11CE5ED, 0x7A47B13C,
491
+ 0x9CD2DF59, 0x55F2733F, 0x1814CE79, 0x73C737BF, 0x53F7CDEA, 0x5FFDAA5B, 0xDF3D6F14, 0x7844DB86,
492
+ 0xCAAFF381, 0xB968C43E, 0x3824342C, 0xC2A3405F, 0x161DC372, 0xBCE2250C, 0x283C498B, 0xFF0D9541,
493
+ 0x39A80171, 0x080CB3DE, 0xD8B4E49C, 0x6456C190, 0x7BCB8461, 0xD532B670, 0x486C5C74, 0xD0B85742
494
+ );
495
+
496
+ /**
497
+ * Precomputed invMixColumns table
498
+ *
499
+ * @see Crypt_Rijndael:_encryptBlock()
500
+ * @see Crypt_Rijndael:_decryptBlock()
501
+ * @var Array
502
+ * @access private
503
+ */
504
+ var $dt1 = array(
505
+ 0x5051F4A7, 0x537E4165, 0xC31A17A4, 0x963A275E, 0xCB3BAB6B, 0xF11F9D45, 0xABACFA58, 0x934BE303,
506
+ 0x552030FA, 0xF6AD766D, 0x9188CC76, 0x25F5024C, 0xFC4FE5D7, 0xD7C52ACB, 0x80263544, 0x8FB562A3,
507
+ 0x49DEB15A, 0x6725BA1B, 0x9845EA0E, 0xE15DFEC0, 0x02C32F75, 0x12814CF0, 0xA38D4697, 0xC66BD3F9,
508
+ 0xE7038F5F, 0x9515929C, 0xEBBF6D7A, 0xDA955259, 0x2DD4BE83, 0xD3587421, 0x2949E069, 0x448EC9C8,
509
+ 0x6A75C289, 0x78F48E79, 0x6B99583E, 0xDD27B971, 0xB6BEE14F, 0x17F088AD, 0x66C920AC, 0xB47DCE3A,
510
+ 0x1863DF4A, 0x82E51A31, 0x60975133, 0x4562537F, 0xE0B16477, 0x84BB6BAE, 0x1CFE81A0, 0x94F9082B,
511
+ 0x58704868, 0x198F45FD, 0x8794DE6C, 0xB7527BF8, 0x23AB73D3, 0xE2724B02, 0x57E31F8F, 0x2A6655AB,
512
+ 0x07B2EB28, 0x032FB5C2, 0x9A86C57B, 0xA5D33708, 0xF2302887, 0xB223BFA5, 0xBA02036A, 0x5CED1682,
513
+ 0x2B8ACF1C, 0x92A779B4, 0xF0F307F2, 0xA14E69E2, 0xCD65DAF4, 0xD50605BE, 0x1FD13462, 0x8AC4A6FE,
514
+ 0x9D342E53, 0xA0A2F355, 0x32058AE1, 0x75A4F6EB, 0x390B83EC, 0xAA4060EF, 0x065E719F, 0x51BD6E10,
515
+ 0xF93E218A, 0x3D96DD06, 0xAEDD3E05, 0x464DE6BD, 0xB591548D, 0x0571C45D, 0x6F0406D4, 0xFF605015,
516
+ 0x241998FB, 0x97D6BDE9, 0xCC894043, 0x7767D99E, 0xBDB0E842, 0x8807898B, 0x38E7195B, 0xDB79C8EE,
517
+ 0x47A17C0A, 0xE97C420F, 0xC9F8841E, 0x00000000, 0x83098086, 0x48322BED, 0xAC1E1170, 0x4E6C5A72,
518
+ 0xFBFD0EFF, 0x560F8538, 0x1E3DAED5, 0x27362D39, 0x640A0FD9, 0x21685CA6, 0xD19B5B54, 0x3A24362E,
519
+ 0xB10C0A67, 0x0F9357E7, 0xD2B4EE96, 0x9E1B9B91, 0x4F80C0C5, 0xA261DC20, 0x695A774B, 0x161C121A,
520
+ 0x0AE293BA, 0xE5C0A02A, 0x433C22E0, 0x1D121B17, 0x0B0E090D, 0xADF28BC7, 0xB92DB6A8, 0xC8141EA9,
521
+ 0x8557F119, 0x4CAF7507, 0xBBEE99DD, 0xFDA37F60, 0x9FF70126, 0xBC5C72F5, 0xC544663B, 0x345BFB7E,
522
+ 0x768B4329, 0xDCCB23C6, 0x68B6EDFC, 0x63B8E4F1, 0xCAD731DC, 0x10426385, 0x40139722, 0x2084C611,
523
+ 0x7D854A24, 0xF8D2BB3D, 0x11AEF932, 0x6DC729A1, 0x4B1D9E2F, 0xF3DCB230, 0xEC0D8652, 0xD077C1E3,
524
+ 0x6C2BB316, 0x99A970B9, 0xFA119448, 0x2247E964, 0xC4A8FC8C, 0x1AA0F03F, 0xD8567D2C, 0xEF223390,
525
+ 0xC787494E, 0xC1D938D1, 0xFE8CCAA2, 0x3698D40B, 0xCFA6F581, 0x28A57ADE, 0x26DAB78E, 0xA43FADBF,
526
+ 0xE42C3A9D, 0x0D507892, 0x9B6A5FCC, 0x62547E46, 0xC2F68D13, 0xE890D8B8, 0x5E2E39F7, 0xF582C3AF,
527
+ 0xBE9F5D80, 0x7C69D093, 0xA96FD52D, 0xB3CF2512, 0x3BC8AC99, 0xA710187D, 0x6EE89C63, 0x7BDB3BBB,
528
+ 0x09CD2678, 0xF46E5918, 0x01EC9AB7, 0xA8834F9A, 0x65E6956E, 0x7EAAFFE6, 0x0821BCCF, 0xE6EF15E8,
529
+ 0xD9BAE79B, 0xCE4A6F36, 0xD4EA9F09, 0xD629B07C, 0xAF31A4B2, 0x312A3F23, 0x30C6A594, 0xC035A266,
530
+ 0x37744EBC, 0xA6FC82CA, 0xB0E090D0, 0x1533A7D8, 0x4AF10498, 0xF741ECDA, 0x0E7FCD50, 0x2F1791F6,
531
+ 0x8D764DD6, 0x4D43EFB0, 0x54CCAA4D, 0xDFE49604, 0xE39ED1B5, 0x1B4C6A88, 0xB8C12C1F, 0x7F466551,
532
+ 0x049D5EEA, 0x5D018C35, 0x73FA8774, 0x2EFB0B41, 0x5AB3671D, 0x5292DBD2, 0x33E91056, 0x136DD647,
533
+ 0x8C9AD761, 0x7A37A10C, 0x8E59F814, 0x89EB133C, 0xEECEA927, 0x35B761C9, 0xEDE11CE5, 0x3C7A47B1,
534
+ 0x599CD2DF, 0x3F55F273, 0x791814CE, 0xBF73C737, 0xEA53F7CD, 0x5B5FFDAA, 0x14DF3D6F, 0x867844DB,
535
+ 0x81CAAFF3, 0x3EB968C4, 0x2C382434, 0x5FC2A340, 0x72161DC3, 0x0CBCE225, 0x8B283C49, 0x41FF0D95,
536
+ 0x7139A801, 0xDE080CB3, 0x9CD8B4E4, 0x906456C1, 0x617BCB84, 0x70D532B6, 0x74486C5C, 0x42D0B857
537
+ );
538
+
539
+ /**
540
+ * Precomputed invMixColumns table
541
+ *
542
+ * @see Crypt_Rijndael:_encryptBlock()
543
+ * @see Crypt_Rijndael:_decryptBlock()
544
+ * @var Array
545
+ * @access private
546
+ */
547
+ var $dt2 = array(
548
+ 0xA75051F4, 0x65537E41, 0xA4C31A17, 0x5E963A27, 0x6BCB3BAB, 0x45F11F9D, 0x58ABACFA, 0x03934BE3,
549
+ 0xFA552030, 0x6DF6AD76, 0x769188CC, 0x4C25F502, 0xD7FC4FE5, 0xCBD7C52A, 0x44802635, 0xA38FB562,
550
+ 0x5A49DEB1, 0x1B6725BA, 0x0E9845EA, 0xC0E15DFE, 0x7502C32F, 0xF012814C, 0x97A38D46, 0xF9C66BD3,
551
+ 0x5FE7038F, 0x9C951592, 0x7AEBBF6D, 0x59DA9552, 0x832DD4BE, 0x21D35874, 0x692949E0, 0xC8448EC9,
552
+ 0x896A75C2, 0x7978F48E, 0x3E6B9958, 0x71DD27B9, 0x4FB6BEE1, 0xAD17F088, 0xAC66C920, 0x3AB47DCE,
553
+ 0x4A1863DF, 0x3182E51A, 0x33609751, 0x7F456253, 0x77E0B164, 0xAE84BB6B, 0xA01CFE81, 0x2B94F908,
554
+ 0x68587048, 0xFD198F45, 0x6C8794DE, 0xF8B7527B, 0xD323AB73, 0x02E2724B, 0x8F57E31F, 0xAB2A6655,
555
+ 0x2807B2EB, 0xC2032FB5, 0x7B9A86C5, 0x08A5D337, 0x87F23028, 0xA5B223BF, 0x6ABA0203, 0x825CED16,
556
+ 0x1C2B8ACF, 0xB492A779, 0xF2F0F307, 0xE2A14E69, 0xF4CD65DA, 0xBED50605, 0x621FD134, 0xFE8AC4A6,
557
+ 0x539D342E, 0x55A0A2F3, 0xE132058A, 0xEB75A4F6, 0xEC390B83, 0xEFAA4060, 0x9F065E71, 0x1051BD6E,
558
+ 0x8AF93E21, 0x063D96DD, 0x05AEDD3E, 0xBD464DE6, 0x8DB59154, 0x5D0571C4, 0xD46F0406, 0x15FF6050,
559
+ 0xFB241998, 0xE997D6BD, 0x43CC8940, 0x9E7767D9, 0x42BDB0E8, 0x8B880789, 0x5B38E719, 0xEEDB79C8,
560
+ 0x0A47A17C, 0x0FE97C42, 0x1EC9F884, 0x00000000, 0x86830980, 0xED48322B, 0x70AC1E11, 0x724E6C5A,
561
+ 0xFFFBFD0E, 0x38560F85, 0xD51E3DAE, 0x3927362D, 0xD9640A0F, 0xA621685C, 0x54D19B5B, 0x2E3A2436,
562
+ 0x67B10C0A, 0xE70F9357, 0x96D2B4EE, 0x919E1B9B, 0xC54F80C0, 0x20A261DC, 0x4B695A77, 0x1A161C12,
563
+ 0xBA0AE293, 0x2AE5C0A0, 0xE0433C22, 0x171D121B, 0x0D0B0E09, 0xC7ADF28B, 0xA8B92DB6, 0xA9C8141E,
564
+ 0x198557F1, 0x074CAF75, 0xDDBBEE99, 0x60FDA37F, 0x269FF701, 0xF5BC5C72, 0x3BC54466, 0x7E345BFB,
565
+ 0x29768B43, 0xC6DCCB23, 0xFC68B6ED, 0xF163B8E4, 0xDCCAD731, 0x85104263, 0x22401397, 0x112084C6,
566
+ 0x247D854A, 0x3DF8D2BB, 0x3211AEF9, 0xA16DC729, 0x2F4B1D9E, 0x30F3DCB2, 0x52EC0D86, 0xE3D077C1,
567
+ 0x166C2BB3, 0xB999A970, 0x48FA1194, 0x642247E9, 0x8CC4A8FC, 0x3F1AA0F0, 0x2CD8567D, 0x90EF2233,
568
+ 0x4EC78749, 0xD1C1D938, 0xA2FE8CCA, 0x0B3698D4, 0x81CFA6F5, 0xDE28A57A, 0x8E26DAB7, 0xBFA43FAD,
569
+ 0x9DE42C3A, 0x920D5078, 0xCC9B6A5F, 0x4662547E, 0x13C2F68D, 0xB8E890D8, 0xF75E2E39, 0xAFF582C3,
570
+ 0x80BE9F5D, 0x937C69D0, 0x2DA96FD5, 0x12B3CF25, 0x993BC8AC, 0x7DA71018, 0x636EE89C, 0xBB7BDB3B,
571
+ 0x7809CD26, 0x18F46E59, 0xB701EC9A, 0x9AA8834F, 0x6E65E695, 0xE67EAAFF, 0xCF0821BC, 0xE8E6EF15,
572
+ 0x9BD9BAE7, 0x36CE4A6F, 0x09D4EA9F, 0x7CD629B0, 0xB2AF31A4, 0x23312A3F, 0x9430C6A5, 0x66C035A2,
573
+ 0xBC37744E, 0xCAA6FC82, 0xD0B0E090, 0xD81533A7, 0x984AF104, 0xDAF741EC, 0x500E7FCD, 0xF62F1791,
574
+ 0xD68D764D, 0xB04D43EF, 0x4D54CCAA, 0x04DFE496, 0xB5E39ED1, 0x881B4C6A, 0x1FB8C12C, 0x517F4665,
575
+ 0xEA049D5E, 0x355D018C, 0x7473FA87, 0x412EFB0B, 0x1D5AB367, 0xD25292DB, 0x5633E910, 0x47136DD6,
576
+ 0x618C9AD7, 0x0C7A37A1, 0x148E59F8, 0x3C89EB13, 0x27EECEA9, 0xC935B761, 0xE5EDE11C, 0xB13C7A47,
577
+ 0xDF599CD2, 0x733F55F2, 0xCE791814, 0x37BF73C7, 0xCDEA53F7, 0xAA5B5FFD, 0x6F14DF3D, 0xDB867844,
578
+ 0xF381CAAF, 0xC43EB968, 0x342C3824, 0x405FC2A3, 0xC372161D, 0x250CBCE2, 0x498B283C, 0x9541FF0D,
579
+ 0x017139A8, 0xB3DE080C, 0xE49CD8B4, 0xC1906456, 0x84617BCB, 0xB670D532, 0x5C74486C, 0x5742D0B8
580
+ );
581
+
582
+ /**
583
+ * Precomputed invMixColumns table
584
+ *
585
+ * @see Crypt_Rijndael:_encryptBlock()
586
+ * @see Crypt_Rijndael:_decryptBlock()
587
+ * @var Array
588
+ * @access private
589
+ */
590
+ var $dt3 = array(
591
+ 0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B,
592
+ 0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5,
593
+ 0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B,
594
+ 0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E,
595
+ 0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D,
596
+ 0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9,
597
+ 0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66,
598
+ 0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED,
599
+ 0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4,
600
+ 0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD,
601
+ 0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60,
602
+ 0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79,
603
+ 0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C,
604
+ 0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24,
605
+ 0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C,
606
+ 0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814,
607
+ 0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B,
608
+ 0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084,
609
+ 0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077,
610
+ 0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22,
611
+ 0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F,
612
+ 0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582,
613
+ 0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB,
614
+ 0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF,
615
+ 0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035,
616
+ 0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17,
617
+ 0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46,
618
+ 0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D,
619
+ 0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A,
620
+ 0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678,
621
+ 0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF,
622
+ 0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0
623
+ );
624
+
625
+ /**
626
+ * The SubByte S-Box
627
+ *
628
+ * @see Crypt_Rijndael::_encryptBlock()
629
+ * @var Array
630
+ * @access private
631
+ */
632
+ var $sbox = array(
633
+ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
634
+ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
635
+ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
636
+ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
637
+ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
638
+ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
639
+ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
640
+ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
641
+ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
642
+ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
643
+ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
644
+ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
645
+ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
646
+ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
647
+ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
648
+ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
649
+ );
650
+
651
+ /**
652
+ * The inverse SubByte S-Box
653
+ *
654
+ * @see Crypt_Rijndael::_decryptBlock()
655
+ * @var Array
656
+ * @access private
657
+ */
658
+ var $isbox = array(
659
+ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
660
+ 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
661
+ 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
662
+ 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
663
+ 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
664
+ 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
665
+ 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
666
+ 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
667
+ 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
668
+ 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
669
+ 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
670
+ 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
671
+ 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
672
+ 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
673
+ 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
674
+ 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
675
+ );
676
+
677
+ /**
678
+ * Default Constructor.
679
+ *
680
+ * Determines whether or not the mcrypt extension should be used.
681
+ *
682
+ * $mode could be:
683
+ *
684
+ * - CRYPT_RIJNDAEL_MODE_ECB
685
+ *
686
+ * - CRYPT_RIJNDAEL_MODE_CBC
687
+ *
688
+ * - CRYPT_RIJNDAEL_MODE_CTR
689
+ *
690
+ * - CRYPT_RIJNDAEL_MODE_CFB
691
+ *
692
+ * - CRYPT_RIJNDAEL_MODE_OFB
693
+ *
694
+ * If not explictly set, CRYPT_RIJNDAEL_MODE_CBC will be used.
695
+ *
696
+ * @see Crypt_Base::Crypt_Base()
697
+ * @param optional Integer $mode
698
+ * @access public
699
+ */
700
+ function Crypt_Rijndael($mode = CRYPT_RIJNDAEL_MODE_CBC)
701
+ {
702
+ parent::Crypt_Base($mode);
703
+ }
704
+
705
+ /**
706
+ * Sets the key.
707
+ *
708
+ * Keys can be of any length. Rijndael, itself, requires the use of a key that's between 128-bits and 256-bits long and
709
+ * whose length is a multiple of 32. If the key is less than 256-bits and the key length isn't set, we round the length
710
+ * up to the closest valid key length, padding $key with null bytes. If the key is more than 256-bits, we trim the
711
+ * excess bits.
712
+ *
713
+ * If the key is not explicitly set, it'll be assumed to be all null bytes.
714
+ *
715
+ * Note: 160/224-bit keys must explicitly set by setKeyLength(), otherwise they will be round/pad up to 192/256 bits.
716
+ *
717
+ * @see Crypt_Base:setKey()
718
+ * @see setKeyLength()
719
+ * @access public
720
+ * @param String $key
721
+ */
722
+ function setKey($key)
723
+ {
724
+ parent::setKey($key);
725
+
726
+ if (!$this->explicit_key_length) {
727
+ $length = strlen($key);
728
+ switch (true) {
729
+ case $length <= 16:
730
+ $this->key_size = 16;
731
+ break;
732
+ case $length <= 24:
733
+ $this->key_size = 24;
734
+ break;
735
+ default:
736
+ $this->key_size = 32;
737
+ }
738
+ $this->_setupEngine();
739
+ }
740
+ }
741
+
742
+ /**
743
+ * Sets the key length
744
+ *
745
+ * Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
746
+ * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
747
+ *
748
+ * Note: phpseclib extends Rijndael (and AES) for using 160- and 224-bit keys but they are officially not defined
749
+ * and the most (if not all) implementations are not able using 160/224-bit keys but round/pad them up to
750
+ * 192/256 bits as, for example, mcrypt will do.
751
+ *
752
+ * That said, if you want be compatible with other Rijndael and AES implementations,
753
+ * you should not setKeyLength(160) or setKeyLength(224).
754
+ *
755
+ * Additional: In case of 160- and 224-bit keys, phpseclib will/can, for that reason, not use
756
+ * the mcrypt php extention, even if available.
757
+ * This results then in slower encryption.
758
+ *
759
+ * @access public
760
+ * @param Integer $length
761
+ */
762
+ function setKeyLength($length)
763
+ {
764
+ switch (true) {
765
+ case $length == 160:
766
+ $this->key_size = 20;
767
+ break;
768
+ case $length == 224:
769
+ $this->key_size = 28;
770
+ break;
771
+ case $length <= 128:
772
+ $this->key_size = 16;
773
+ break;
774
+ case $length <= 192:
775
+ $this->key_size = 24;
776
+ break;
777
+ default:
778
+ $this->key_size = 32;
779
+ }
780
+
781
+ $this->explicit_key_length = true;
782
+ $this->changed = true;
783
+ $this->_setupEngine();
784
+ }
785
+
786
+ /**
787
+ * Sets the block length
788
+ *
789
+ * Valid block lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
790
+ * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
791
+ *
792
+ * @access public
793
+ * @param Integer $length
794
+ */
795
+ function setBlockLength($length)
796
+ {
797
+ $length >>= 5;
798
+ if ($length > 8) {
799
+ $length = 8;
800
+ } else if ($length < 4) {
801
+ $length = 4;
802
+ }
803
+ $this->Nb = $length;
804
+ $this->block_size = $length << 2;
805
+ $this->changed = true;
806
+ $this->_setupEngine();
807
+ }
808
+
809
+ /**
810
+ * Setup the fastest possible $engine
811
+ *
812
+ * Determines if the mcrypt (MODE_MCRYPT) $engine available
813
+ * and usable for the current $block_size and $key_size.
814
+ *
815
+ * If not, the slower MODE_INTERNAL $engine will be set.
816
+ *
817
+ * @see setKey()
818
+ * @see setKeyLength()
819
+ * @see setBlockLength()
820
+ * @access private
821
+ */
822
+ function _setupEngine()
823
+ {
824
+ if (constant('CRYPT_' . $this->const_namespace . '_MODE') == CRYPT_MODE_INTERNAL) {
825
+ // No mcrypt support at all for rijndael
826
+ return;
827
+ }
828
+
829
+ // The required mcrypt module name for the current $block_size of rijndael
830
+ $cipher_name_mcrypt = 'rijndael-' . ($this->block_size << 3);
831
+
832
+ // Determining the availibility/usability of $cipher_name_mcrypt
833
+ switch (true) {
834
+ case $this->key_size % 8: // mcrypt is not usable for 160/224-bit keys, only for 128/192/256-bit keys
835
+ case !in_array($cipher_name_mcrypt, mcrypt_list_algorithms()): // $cipher_name_mcrypt is not available for the current $block_size
836
+ $engine = CRYPT_MODE_INTERNAL;
837
+ break;
838
+ default:
839
+ $engine = CRYPT_MODE_MCRYPT;
840
+ }
841
+
842
+ if ($this->engine == $engine && $this->cipher_name_mcrypt == $cipher_name_mcrypt) {
843
+ // allready set, so we not unnecessary close $this->enmcrypt/demcrypt/ecb
844
+ return;
845
+ }
846
+
847
+ // Set the $engine
848
+ $this->engine = $engine;
849
+ $this->cipher_name_mcrypt = $cipher_name_mcrypt;
850
+
851
+ if ($this->enmcrypt) {
852
+ // Closing the current mcrypt resource(s). _mcryptSetup() will, if needed,
853
+ // (re)open them with the module named in $this->cipher_name_mcrypt
854
+ mcrypt_module_close($this->enmcrypt);
855
+ mcrypt_module_close($this->demcrypt);
856
+ $this->enmcrypt = null;
857
+ $this->demcrypt = null;
858
+
859
+ if ($this->ecb) {
860
+ mcrypt_module_close($this->ecb);
861
+ $this->ecb = null;
862
+ }
863
+ }
864
+ }
865
+
866
+ /**
867
+ * Setup the CRYPT_MODE_MCRYPT $engine
868
+ *
869
+ * @see Crypt_Base::_setupMcrypt()
870
+ * @access private
871
+ */
872
+ function _setupMcrypt()
873
+ {
874
+ $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0");
875
+ parent::_setupMcrypt();
876
+ }
877
+
878
+ /**
879
+ * Encrypts a block
880
+ *
881
+ * @access private
882
+ * @param String $in
883
+ * @return String
884
+ */
885
+ function _encryptBlock($in)
886
+ {
887
+ static $t0, $t1, $t2, $t3, $sbox;
888
+ if (!$t0) {
889
+ for ($i = 0; $i < 256; ++$i) {
890
+ $t0[] = (int)$this->t0[$i];
891
+ $t1[] = (int)$this->t1[$i];
892
+ $t2[] = (int)$this->t2[$i];
893
+ $t3[] = (int)$this->t3[$i];
894
+ $sbox[] = (int)$this->sbox[$i];
895
+ }
896
+ }
897
+
898
+ $state = array();
899
+ $words = unpack('N*', $in);
900
+
901
+ $c = $this->c;
902
+ $w = $this->w;
903
+ $Nb = $this->Nb;
904
+ $Nr = $this->Nr;
905
+
906
+ // addRoundKey
907
+ $i = -1;
908
+ foreach ($words as $word) {
909
+ $state[] = $word ^ $w[0][++$i];
910
+ }
911
+
912
+ // fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components -
913
+ // subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding
914
+ // Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf.
915
+ // Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization.
916
+ // Unfortunately, the description given there is not quite correct. Per aes.spec.v316.pdf#page=19 [1],
917
+ // equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well.
918
+
919
+ // [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf
920
+ $temp = array();
921
+ for ($round = 1; $round < $Nr; ++$round) {
922
+ $i = 0; // $c[0] == 0
923
+ $j = $c[1];
924
+ $k = $c[2];
925
+ $l = $c[3];
926
+
927
+ while ($i < $Nb) {
928
+ $temp[$i] = $t0[$state[$i] >> 24 & 0x000000FF] ^
929
+ $t1[$state[$j] >> 16 & 0x000000FF] ^
930
+ $t2[$state[$k] >> 8 & 0x000000FF] ^
931
+ $t3[$state[$l] & 0x000000FF] ^
932
+ $w[$round][$i];
933
+ ++$i;
934
+ $j = ($j + 1) % $Nb;
935
+ $k = ($k + 1) % $Nb;
936
+ $l = ($l + 1) % $Nb;
937
+ }
938
+ $state = $temp;
939
+ }
940
+
941
+ // subWord
942
+ for ($i = 0; $i < $Nb; ++$i) {
943
+ $state[$i] = $sbox[$state[$i] & 0x000000FF] |
944
+ ($sbox[$state[$i] >> 8 & 0x000000FF] << 8) |
945
+ ($sbox[$state[$i] >> 16 & 0x000000FF] << 16) |
946
+ ($sbox[$state[$i] >> 24 & 0x000000FF] << 24);
947
+ }
948
+
949
+ // shiftRows + addRoundKey
950
+ $i = 0; // $c[0] == 0
951
+ $j = $c[1];
952
+ $k = $c[2];
953
+ $l = $c[3];
954
+ while ($i < $Nb) {
955
+ $temp[$i] = ($state[$i] & 0xFF000000) ^
956
+ ($state[$j] & 0x00FF0000) ^
957
+ ($state[$k] & 0x0000FF00) ^
958
+ ($state[$l] & 0x000000FF) ^
959
+ $w[$Nr][$i];
960
+ ++$i;
961
+ $j = ($j + 1) % $Nb;
962
+ $k = ($k + 1) % $Nb;
963
+ $l = ($l + 1) % $Nb;
964
+ }
965
+
966
+ switch ($Nb) {
967
+ case 8:
968
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
969
+ case 7:
970
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
971
+ case 6:
972
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
973
+ case 5:
974
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
975
+ default:
976
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
977
+ }
978
+ }
979
+
980
+ /**
981
+ * Decrypts a block
982
+ *
983
+ * @access private
984
+ * @param String $in
985
+ * @return String
986
+ */
987
+ function _decryptBlock($in)
988
+ {
989
+ static $dt0, $dt1, $dt2, $dt3, $isbox;
990
+ if (!$dt0) {
991
+ for ($i = 0; $i < 256; ++$i) {
992
+ $dt0[] = (int)$this->dt0[$i];
993
+ $dt1[] = (int)$this->dt1[$i];
994
+ $dt2[] = (int)$this->dt2[$i];
995
+ $dt3[] = (int)$this->dt3[$i];
996
+ $isbox[] = (int)$this->isbox[$i];
997
+ }
998
+ }
999
+
1000
+ $state = array();
1001
+ $words = unpack('N*', $in);
1002
+
1003
+ $c = $this->c;
1004
+ $dw = $this->dw;
1005
+ $Nb = $this->Nb;
1006
+ $Nr = $this->Nr;
1007
+
1008
+ // addRoundKey
1009
+ $i = -1;
1010
+ foreach ($words as $word) {
1011
+ $state[] = $word ^ $dw[$Nr][++$i];
1012
+ }
1013
+
1014
+ $temp = array();
1015
+ for ($round = $Nr - 1; $round > 0; --$round) {
1016
+ $i = 0; // $c[0] == 0
1017
+ $j = $Nb - $c[1];
1018
+ $k = $Nb - $c[2];
1019
+ $l = $Nb - $c[3];
1020
+
1021
+ while ($i < $Nb) {
1022
+ $temp[$i] = $dt0[$state[$i] >> 24 & 0x000000FF] ^
1023
+ $dt1[$state[$j] >> 16 & 0x000000FF] ^
1024
+ $dt2[$state[$k] >> 8 & 0x000000FF] ^
1025
+ $dt3[$state[$l] & 0x000000FF] ^
1026
+ $dw[$round][$i];
1027
+ ++$i;
1028
+ $j = ($j + 1) % $Nb;
1029
+ $k = ($k + 1) % $Nb;
1030
+ $l = ($l + 1) % $Nb;
1031
+ }
1032
+ $state = $temp;
1033
+ }
1034
+
1035
+ // invShiftRows + invSubWord + addRoundKey
1036
+ $i = 0; // $c[0] == 0
1037
+ $j = $Nb - $c[1];
1038
+ $k = $Nb - $c[2];
1039
+ $l = $Nb - $c[3];
1040
+
1041
+ while ($i < $Nb) {
1042
+ $word = ($state[$i] & 0xFF000000) |
1043
+ ($state[$j] & 0x00FF0000) |
1044
+ ($state[$k] & 0x0000FF00) |
1045
+ ($state[$l] & 0x000000FF);
1046
+
1047
+ $temp[$i] = $dw[0][$i] ^ ($isbox[$word & 0x000000FF] |
1048
+ ($isbox[$word >> 8 & 0x000000FF] << 8) |
1049
+ ($isbox[$word >> 16 & 0x000000FF] << 16) |
1050
+ ($isbox[$word >> 24 & 0x000000FF] << 24));
1051
+ ++$i;
1052
+ $j = ($j + 1) % $Nb;
1053
+ $k = ($k + 1) % $Nb;
1054
+ $l = ($l + 1) % $Nb;
1055
+ }
1056
+
1057
+ switch ($Nb) {
1058
+ case 8:
1059
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
1060
+ case 7:
1061
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
1062
+ case 6:
1063
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
1064
+ case 5:
1065
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
1066
+ default:
1067
+ return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * Setup the key (expansion)
1073
+ *
1074
+ * @see Crypt_Base::_setupKey()
1075
+ * @access private
1076
+ */
1077
+ function _setupKey()
1078
+ {
1079
+ // Each number in $rcon is equal to the previous number multiplied by two in Rijndael's finite field.
1080
+ // See http://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplicative_inverse
1081
+ static $rcon = array(0,
1082
+ 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
1083
+ 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000,
1084
+ 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000,
1085
+ 0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000,
1086
+ 0x97000000, 0x35000000, 0x6A000000, 0xD4000000, 0xB3000000,
1087
+ 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000
1088
+ );
1089
+
1090
+ $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0");
1091
+
1092
+ if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_size === $this->kl['key_size'] && $this->block_size === $this->kl['block_size']) {
1093
+ // already expanded
1094
+ return;
1095
+ }
1096
+ $this->kl = array('key' => $this->key, 'key_size' => $this->key_size, 'block_size' => $this->block_size);
1097
+
1098
+ $this->Nk = $this->key_size >> 2;
1099
+ // see Rijndael-ammended.pdf#page=44
1100
+ $this->Nr = max($this->Nk, $this->Nb) + 6;
1101
+
1102
+ // shift offsets for Nb = 5, 7 are defined in Rijndael-ammended.pdf#page=44,
1103
+ // "Table 8: Shift offsets in Shiftrow for the alternative block lengths"
1104
+ // shift offsets for Nb = 4, 6, 8 are defined in Rijndael-ammended.pdf#page=14,
1105
+ // "Table 2: Shift offsets for different block lengths"
1106
+ switch ($this->Nb) {
1107
+ case 4:
1108
+ case 5:
1109
+ case 6:
1110
+ $this->c = array(0, 1, 2, 3);
1111
+ break;
1112
+ case 7:
1113
+ $this->c = array(0, 1, 2, 4);
1114
+ break;
1115
+ case 8:
1116
+ $this->c = array(0, 1, 3, 4);
1117
+ }
1118
+
1119
+ $w = array_values(unpack('N*words', $this->key));
1120
+
1121
+ $length = $this->Nb * ($this->Nr + 1);
1122
+ for ($i = $this->Nk; $i < $length; $i++) {
1123
+ $temp = $w[$i - 1];
1124
+ if ($i % $this->Nk == 0) {
1125
+ // according to <http://php.net/language.types.integer>, "the size of an integer is platform-dependent".
1126
+ // on a 32-bit machine, it's 32-bits, and on a 64-bit machine, it's 64-bits. on a 32-bit machine,
1127
+ // 0xFFFFFFFF << 8 == 0xFFFFFF00, but on a 64-bit machine, it equals 0xFFFFFFFF00. as such, doing 'and'
1128
+ // with 0xFFFFFFFF (or 0xFFFFFF00) on a 32-bit machine is unnecessary, but on a 64-bit machine, it is.
1129
+ $temp = (($temp << 8) & 0xFFFFFF00) | (($temp >> 24) & 0x000000FF); // rotWord
1130
+ $temp = $this->_subWord($temp) ^ $rcon[$i / $this->Nk];
1131
+ } else if ($this->Nk > 6 && $i % $this->Nk == 4) {
1132
+ $temp = $this->_subWord($temp);
1133
+ }
1134
+ $w[$i] = $w[$i - $this->Nk] ^ $temp;
1135
+ }
1136
+
1137
+ // convert the key schedule from a vector of $Nb * ($Nr + 1) length to a matrix with $Nr + 1 rows and $Nb columns
1138
+ // and generate the inverse key schedule. more specifically,
1139
+ // according to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=23> (section 5.3.3),
1140
+ // "The key expansion for the Inverse Cipher is defined as follows:
1141
+ // 1. Apply the Key Expansion.
1142
+ // 2. Apply InvMixColumn to all Round Keys except the first and the last one."
1143
+ // also, see fips-197.pdf#page=27, "5.3.5 Equivalent Inverse Cipher"
1144
+ $temp = $this->w = $this->dw = array();
1145
+ for ($i = $row = $col = 0; $i < $length; $i++, $col++) {
1146
+ if ($col == $this->Nb) {
1147
+ if ($row == 0) {
1148
+ $this->dw[0] = $this->w[0];
1149
+ } else {
1150
+ // subWord + invMixColumn + invSubWord = invMixColumn
1151
+ $j = 0;
1152
+ while ($j < $this->Nb) {
1153
+ $dw = $this->_subWord($this->w[$row][$j]);
1154
+ $temp[$j] = $this->dt0[$dw >> 24 & 0x000000FF] ^
1155
+ $this->dt1[$dw >> 16 & 0x000000FF] ^
1156
+ $this->dt2[$dw >> 8 & 0x000000FF] ^
1157
+ $this->dt3[$dw & 0x000000FF];
1158
+ $j++;
1159
+ }
1160
+ $this->dw[$row] = $temp;
1161
+ }
1162
+
1163
+ $col = 0;
1164
+ $row++;
1165
+ }
1166
+ $this->w[$row][$col] = $w[$i];
1167
+ }
1168
+
1169
+ $this->dw[$row] = $this->w[$row];
1170
+
1171
+ // In case of $this->use_inline_crypt === true we have to use 1-dim key arrays (both ascending)
1172
+ if ($this->use_inline_crypt) {
1173
+ $this->dw = array_reverse($this->dw);
1174
+ $w = array_pop($this->w);
1175
+ $dw = array_pop($this->dw);
1176
+ foreach ($this->w as $r => $wr) {
1177
+ foreach ($wr as $c => $wc) {
1178
+ $w[] = $wc;
1179
+ $dw[] = $this->dw[$r][$c];
1180
+ }
1181
+ }
1182
+ $this->w = $w;
1183
+ $this->dw = $dw;
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * Performs S-Box substitutions
1189
+ *
1190
+ * @access private
1191
+ * @param Integer $word
1192
+ */
1193
+ function _subWord($word)
1194
+ {
1195
+ $sbox = $this->sbox;
1196
+
1197
+ return $sbox[$word & 0x000000FF] |
1198
+ ($sbox[$word >> 8 & 0x000000FF] << 8) |
1199
+ ($sbox[$word >> 16 & 0x000000FF] << 16) |
1200
+ ($sbox[$word >> 24 & 0x000000FF] << 24);
1201
+ }
1202
+
1203
+ /**
1204
+ * Setup the performance-optimized function for de/encrypt()
1205
+ *
1206
+ * @see Crypt_Base::_setupInlineCrypt()
1207
+ * @access private
1208
+ */
1209
+ function _setupInlineCrypt()
1210
+ {
1211
+ // Note: _setupInlineCrypt() will be called only if $this->changed === true
1212
+ // So here we are'nt under the same heavy timing-stress as we are in _de/encryptBlock() or de/encrypt().
1213
+ // However...the here generated function- $code, stored as php callback in $this->inline_crypt, must work as fast as even possible.
1214
+
1215
+ $lambda_functions =& Crypt_Rijndael::_getLambdaFunctions();
1216
+
1217
+ // The first 10 generated $lambda_functions will use the key-words hardcoded for better performance.
1218
+ // For memory reason we limit those ultra-optimized functions.
1219
+ // After that, we use pure (extracted) integer vars for the key-words which is faster than accessing them via array.
1220
+ if (count($lambda_functions) < 10) {
1221
+ $w = $this->w;
1222
+ $dw = $this->dw;
1223
+ $init_encrypt = '';
1224
+ $init_decrypt = '';
1225
+ } else {
1226
+ for ($i = 0, $cw = count($this->w); $i < $cw; ++$i) {
1227
+ $w[] = '$w[' . $i . ']';
1228
+ $dw[] = '$dw[' . $i . ']';
1229
+ }
1230
+ $init_encrypt = '$w = $self->w;';
1231
+ $init_decrypt = '$dw = $self->dw;';
1232
+ }
1233
+
1234
+ $code_hash = md5(str_pad("Crypt_Rijndael, {$this->mode}, {$this->block_size}, ", 32, "\0") . implode(',', $w));
1235
+
1236
+ if (!isset($lambda_functions[$code_hash])) {
1237
+ $Nr = $this->Nr;
1238
+ $Nb = $this->Nb;
1239
+ $c = $this->c;
1240
+
1241
+ // Generating encrypt code:
1242
+ $init_encrypt.= '
1243
+ static $t0, $t1, $t2, $t3, $sbox;
1244
+ if (!$t0) {
1245
+ for ($i = 0; $i < 256; ++$i) {
1246
+ $t0[$i] = (int)$self->t0[$i];
1247
+ $t1[$i] = (int)$self->t1[$i];
1248
+ $t2[$i] = (int)$self->t2[$i];
1249
+ $t3[$i] = (int)$self->t3[$i];
1250
+ $sbox[$i] = (int)$self->sbox[$i];
1251
+ }
1252
+ }
1253
+ ';
1254
+
1255
+ $s = 'e';
1256
+ $e = 's';
1257
+ $wc = $Nb - 1;
1258
+
1259
+ // Preround: addRoundKey
1260
+ $encrypt_block = '$in = unpack("N*", $in);'."\n";
1261
+ for ($i = 0; $i < $Nb; ++$i) {
1262
+ $encrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n";
1263
+ }
1264
+
1265
+ // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
1266
+ for ($round = 1; $round < $Nr; ++$round) {
1267
+ list($s, $e) = array($e, $s);
1268
+ for ($i = 0; $i < $Nb; ++$i) {
1269
+ $encrypt_block.=
1270
+ '$'.$e.$i.' =
1271
+ $t0[($'.$s.$i .' >> 24) & 0xff] ^
1272
+ $t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^
1273
+ $t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^
1274
+ $t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^
1275
+ '.$w[++$wc].";\n";
1276
+ }
1277
+ }
1278
+
1279
+ // Finalround: subWord + shiftRows + addRoundKey
1280
+ for ($i = 0; $i < $Nb; ++$i) {
1281
+ $encrypt_block.=
1282
+ '$'.$e.$i.' =
1283
+ $sbox[ $'.$e.$i.' & 0xff] |
1284
+ ($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
1285
+ ($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
1286
+ ($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
1287
+ }
1288
+ $encrypt_block .= '$in = pack("N*"'."\n";
1289
+ for ($i = 0; $i < $Nb; ++$i) {
1290
+ $encrypt_block.= ',
1291
+ ($'.$e.$i .' & 0xFF000000) ^
1292
+ ($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000) ^
1293
+ ($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00) ^
1294
+ ($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF) ^
1295
+ '.$w[$i]."\n";
1296
+ }
1297
+ $encrypt_block .= ');';
1298
+
1299
+ // Generating decrypt code:
1300
+ $init_decrypt.= '
1301
+ static $dt0, $dt1, $dt2, $dt3, $isbox;
1302
+ if (!$dt0) {
1303
+ for ($i = 0; $i < 256; ++$i) {
1304
+ $dt0[$i] = (int)$self->dt0[$i];
1305
+ $dt1[$i] = (int)$self->dt1[$i];
1306
+ $dt2[$i] = (int)$self->dt2[$i];
1307
+ $dt3[$i] = (int)$self->dt3[$i];
1308
+ $isbox[$i] = (int)$self->isbox[$i];
1309
+ }
1310
+ }
1311
+ ';
1312
+
1313
+ $s = 'e';
1314
+ $e = 's';
1315
+ $wc = $Nb - 1;
1316
+
1317
+ // Preround: addRoundKey
1318
+ $decrypt_block = '$in = unpack("N*", $in);'."\n";
1319
+ for ($i = 0; $i < $Nb; ++$i) {
1320
+ $decrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n";
1321
+ }
1322
+
1323
+ // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
1324
+ for ($round = 1; $round < $Nr; ++$round) {
1325
+ list($s, $e) = array($e, $s);
1326
+ for ($i = 0; $i < $Nb; ++$i) {
1327
+ $decrypt_block.=
1328
+ '$'.$e.$i.' =
1329
+ $dt0[($'.$s.$i .' >> 24) & 0xff] ^
1330
+ $dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^
1331
+ $dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^
1332
+ $dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^
1333
+ '.$dw[++$wc].";\n";
1334
+ }
1335
+ }
1336
+
1337
+ // Finalround: subWord + shiftRows + addRoundKey
1338
+ for ($i = 0; $i < $Nb; ++$i) {
1339
+ $decrypt_block.=
1340
+ '$'.$e.$i.' =
1341
+ $isbox[ $'.$e.$i.' & 0xff] |
1342
+ ($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
1343
+ ($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
1344
+ ($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
1345
+ }
1346
+ $decrypt_block .= '$in = pack("N*"'."\n";
1347
+ for ($i = 0; $i < $Nb; ++$i) {
1348
+ $decrypt_block.= ',
1349
+ ($'.$e.$i. ' & 0xFF000000) ^
1350
+ ($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000) ^
1351
+ ($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00) ^
1352
+ ($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF) ^
1353
+ '.$dw[$i]."\n";
1354
+ }
1355
+ $decrypt_block .= ');';
1356
+
1357
+ $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
1358
+ array(
1359
+ 'init_crypt' => '',
1360
+ 'init_encrypt' => $init_encrypt,
1361
+ 'init_decrypt' => $init_decrypt,
1362
+ 'encrypt_block' => $encrypt_block,
1363
+ 'decrypt_block' => $decrypt_block
1364
+ )
1365
+ );
1366
+ }
1367
+ $this->inline_crypt = $lambda_functions[$code_hash];
1368
+ }
1369
+ }
1370
+
lib/LivrariOnline/TripleDES.php ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of Triple DES.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Here's a short example of how to use this library:
11
+ * <code>
12
+ * <?php
13
+ * include('Crypt/TripleDES.php');
14
+ *
15
+ * $des = new Crypt_TripleDES();
16
+ *
17
+ * $des->setKey('abcdefghijklmnopqrstuvwx');
18
+ *
19
+ * $size = 10 * 1024;
20
+ * $plaintext = '';
21
+ * for ($i = 0; $i < $size; $i++) {
22
+ * $plaintext.= 'a';
23
+ * }
24
+ *
25
+ * echo $des->decrypt($des->encrypt($plaintext));
26
+ * ?>
27
+ * </code>
28
+ *
29
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ * of this software and associated documentation files (the "Software"), to deal
31
+ * in the Software without restriction, including without limitation the rights
32
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ * copies of the Software, and to permit persons to whom the Software is
34
+ * furnished to do so, subject to the following conditions:
35
+ *
36
+ * The above copyright notice and this permission notice shall be included in
37
+ * all copies or substantial portions of the Software.
38
+ *
39
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ * THE SOFTWARE.
46
+ *
47
+ * @category Crypt
48
+ * @package Crypt_TripleDES
49
+ * @author Jim Wigginton <terrafrost@php.net>
50
+ * @copyright MMVII Jim Wigginton
51
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
52
+ * @link http://phpseclib.sourceforge.net
53
+ */
54
+
55
+ /**
56
+ * Include Crypt_DES
57
+ */
58
+ require_once('DES.php');
59
+
60
+ /**
61
+ * Encrypt / decrypt using inner chaining
62
+ *
63
+ * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
64
+ */
65
+ define('CRYPT_DES_MODE_3CBC', -2);
66
+
67
+ /**
68
+ * Encrypt / decrypt using outer chaining
69
+ *
70
+ * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
71
+ */
72
+ define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
73
+
74
+ /**
75
+ * Pure-PHP implementation of Triple DES.
76
+ *
77
+ * @package Crypt_TripleDES
78
+ * @author Jim Wigginton <terrafrost@php.net>
79
+ * @version 0.1.0
80
+ * @access public
81
+ */
82
+ class Crypt_TripleDES extends Crypt_DES
83
+ {
84
+ /**
85
+ * The default password key_size used by setPassword()
86
+ *
87
+ * @see Crypt_DES::password_key_size
88
+ * @see Crypt_Base::password_key_size
89
+ * @see Crypt_Base::setPassword()
90
+ * @var Integer
91
+ * @access private
92
+ */
93
+ var $password_key_size = 24;
94
+
95
+ /**
96
+ * The default salt used by setPassword()
97
+ *
98
+ * @see Crypt_Base::password_default_salt
99
+ * @see Crypt_Base::setPassword()
100
+ * @var String
101
+ * @access private
102
+ */
103
+ var $password_default_salt = 'phpseclib';
104
+
105
+ /**
106
+ * The namespace used by the cipher for its constants.
107
+ *
108
+ * @see Crypt_DES::const_namespace
109
+ * @see Crypt_Base::const_namespace
110
+ * @var String
111
+ * @access private
112
+ */
113
+ var $const_namespace = 'DES';
114
+
115
+ /**
116
+ * The mcrypt specific name of the cipher
117
+ *
118
+ * @see Crypt_DES::cipher_name_mcrypt
119
+ * @see Crypt_Base::cipher_name_mcrypt
120
+ * @var String
121
+ * @access private
122
+ */
123
+ var $cipher_name_mcrypt = 'tripledes';
124
+
125
+ /**
126
+ * Optimizing value while CFB-encrypting
127
+ *
128
+ * @see Crypt_Base::cfb_init_len
129
+ * @var Integer
130
+ * @access private
131
+ */
132
+ var $cfb_init_len = 750;
133
+
134
+ /**
135
+ * max possible size of $key
136
+ *
137
+ * @see Crypt_TripleDES::setKey()
138
+ * @see Crypt_DES::setKey()
139
+ * @var String
140
+ * @access private
141
+ */
142
+ var $key_size_max = 24;
143
+
144
+ /**
145
+ * Internal flag whether using CRYPT_DES_MODE_3CBC or not
146
+ *
147
+ * @var Boolean
148
+ * @access private
149
+ */
150
+ var $mode_3cbc;
151
+
152
+ /**
153
+ * The Crypt_DES objects
154
+ *
155
+ * Used only if $mode_3cbc === true
156
+ *
157
+ * @var Array
158
+ * @access private
159
+ */
160
+ var $des;
161
+
162
+ /**
163
+ * Default Constructor.
164
+ *
165
+ * Determines whether or not the mcrypt extension should be used.
166
+ *
167
+ * $mode could be:
168
+ *
169
+ * - CRYPT_DES_MODE_ECB
170
+ *
171
+ * - CRYPT_DES_MODE_CBC
172
+ *
173
+ * - CRYPT_DES_MODE_CTR
174
+ *
175
+ * - CRYPT_DES_MODE_CFB
176
+ *
177
+ * - CRYPT_DES_MODE_OFB
178
+ *
179
+ * - CRYPT_DES_MODE_3CBC
180
+ *
181
+ * If not explictly set, CRYPT_DES_MODE_CBC will be used.
182
+ *
183
+ * @see Crypt_DES::Crypt_DES()
184
+ * @see Crypt_Base::Crypt_Base()
185
+ * @param optional Integer $mode
186
+ * @access public
187
+ */
188
+ function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
189
+ {
190
+ switch ($mode) {
191
+ // In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC
192
+ // and additional flag us internally as 3CBC
193
+ case CRYPT_DES_MODE_3CBC:
194
+ parent::Crypt_DES(CRYPT_DES_MODE_CBC);
195
+ $this->mode_3cbc = true;
196
+
197
+ // This three $des'es will do the 3CBC work (if $key > 64bits)
198
+ $this->des = array(
199
+ new Crypt_DES(CRYPT_DES_MODE_CBC),
200
+ new Crypt_DES(CRYPT_DES_MODE_CBC),
201
+ new Crypt_DES(CRYPT_DES_MODE_CBC),
202
+ );
203
+
204
+ // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
205
+ $this->des[0]->disablePadding();
206
+ $this->des[1]->disablePadding();
207
+ $this->des[2]->disablePadding();
208
+ break;
209
+ // If not 3CBC, we init as usual
210
+ default:
211
+ parent::Crypt_DES($mode);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Sets the initialization vector. (optional)
217
+ *
218
+ * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
219
+ * to be all zero's.
220
+ *
221
+ * @see Crypt_Base::setIV()
222
+ * @access public
223
+ * @param String $iv
224
+ */
225
+ function setIV($iv)
226
+ {
227
+ parent::setIV($iv);
228
+ if ($this->mode_3cbc) {
229
+ $this->des[0]->setIV($iv);
230
+ $this->des[1]->setIV($iv);
231
+ $this->des[2]->setIV($iv);
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Sets the key.
237
+ *
238
+ * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
239
+ * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
240
+ *
241
+ * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
242
+ *
243
+ * If the key is not explicitly set, it'll be assumed to be all null bytes.
244
+ *
245
+ * @access public
246
+ * @see Crypt_DES::setKey()
247
+ * @see Crypt_Base::setKey()
248
+ * @param String $key
249
+ */
250
+ function setKey($key)
251
+ {
252
+ $length = strlen($key);
253
+ if ($length > 8) {
254
+ $key = str_pad(substr($key, 0, 24), 24, chr(0));
255
+ // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
256
+ // http://php.net/function.mcrypt-encrypt#47973
257
+ //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
258
+ } else {
259
+ $key = str_pad($key, 8, chr(0));
260
+ }
261
+ parent::setKey($key);
262
+
263
+ // And in case of CRYPT_DES_MODE_3CBC:
264
+ // if key <= 64bits we not need the 3 $des to work,
265
+ // because we will then act as regular DES-CBC with just a <= 64bit key.
266
+ // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
267
+ if ($this->mode_3cbc && $length > 8) {
268
+ $this->des[0]->setKey(substr($key, 0, 8));
269
+ $this->des[1]->setKey(substr($key, 8, 8));
270
+ $this->des[2]->setKey(substr($key, 16, 8));
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Encrypts a message.
276
+ *
277
+ * @see Crypt_Base::encrypt()
278
+ * @access public
279
+ * @param String $plaintext
280
+ * @return String $cipertext
281
+ */
282
+ function encrypt($plaintext)
283
+ {
284
+ // parent::en/decrypt() is able to do all the work for all modes and keylengths,
285
+ // except for: CRYPT_DES_MODE_3CBC (inner chaining CBC) with a key > 64bits
286
+
287
+ // if the key is smaller then 8, do what we'd normally do
288
+ if ($this->mode_3cbc && strlen($this->key) > 8) {
289
+ return $this->des[2]->encrypt(
290
+ $this->des[1]->decrypt(
291
+ $this->des[0]->encrypt($this->_pad($plaintext))));
292
+ }
293
+
294
+ return parent::encrypt($plaintext);
295
+ }
296
+
297
+ /**
298
+ * Decrypts a message.
299
+ *
300
+ * @see Crypt_Base::decrypt()
301
+ * @access public
302
+ * @param String $ciphertext
303
+ * @return String $plaintext
304
+ */
305
+ function decrypt($ciphertext)
306
+ {
307
+ if ($this->mode_3cbc && strlen($this->key) > 8) {
308
+ return $this->_unpad($this->des[0]->decrypt(
309
+ $this->des[1]->encrypt(
310
+ $this->des[2]->decrypt(str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0")))));
311
+ }
312
+
313
+ return parent::decrypt($ciphertext);
314
+ }
315
+
316
+ /**
317
+ * Treat consecutive "packets" as if they are a continuous buffer.
318
+ *
319
+ * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
320
+ * will yield different outputs:
321
+ *
322
+ * <code>
323
+ * echo $des->encrypt(substr($plaintext, 0, 8));
324
+ * echo $des->encrypt(substr($plaintext, 8, 8));
325
+ * </code>
326
+ * <code>
327
+ * echo $des->encrypt($plaintext);
328
+ * </code>
329
+ *
330
+ * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
331
+ * another, as demonstrated with the following:
332
+ *
333
+ * <code>
334
+ * $des->encrypt(substr($plaintext, 0, 8));
335
+ * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
336
+ * </code>
337
+ * <code>
338
+ * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
339
+ * </code>
340
+ *
341
+ * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
342
+ * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
343
+ * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
344
+ *
345
+ * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
346
+ * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
347
+ * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
348
+ * however, they are also less intuitive and more likely to cause you problems.
349
+ *
350
+ * @see Crypt_Base::enableContinuousBuffer()
351
+ * @see Crypt_TripleDES::disableContinuousBuffer()
352
+ * @access public
353
+ */
354
+ function enableContinuousBuffer()
355
+ {
356
+ parent::enableContinuousBuffer();
357
+ if ($this->mode_3cbc) {
358
+ $this->des[0]->enableContinuousBuffer();
359
+ $this->des[1]->enableContinuousBuffer();
360
+ $this->des[2]->enableContinuousBuffer();
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Treat consecutive packets as if they are a discontinuous buffer.
366
+ *
367
+ * The default behavior.
368
+ *
369
+ * @see Crypt_Base::disableContinuousBuffer()
370
+ * @see Crypt_TripleDES::enableContinuousBuffer()
371
+ * @access public
372
+ */
373
+ function disableContinuousBuffer()
374
+ {
375
+ parent::disableContinuousBuffer();
376
+ if ($this->mode_3cbc) {
377
+ $this->des[0]->disableContinuousBuffer();
378
+ $this->des[1]->disableContinuousBuffer();
379
+ $this->des[2]->disableContinuousBuffer();
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Creates the key schedule
385
+ *
386
+ * @see Crypt_DES::_setupKey()
387
+ * @see Crypt_Base::_setupKey()
388
+ * @access private
389
+ */
390
+ function _setupKey()
391
+ {
392
+ switch (true) {
393
+ // if $key <= 64bits we configure our internal pure-php cipher engine
394
+ // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same.
395
+ case strlen($this->key) <= 8:
396
+ $this->des_rounds = 1;
397
+ break;
398
+
399
+ // otherwise, if $key > 64bits, we configure our engine to work as 3DES.
400
+ default:
401
+ $this->des_rounds = 3;
402
+
403
+ // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately.
404
+ if ($this->mode_3cbc) {
405
+ $this->des[0]->_setupKey();
406
+ $this->des[1]->_setupKey();
407
+ $this->des[2]->_setupKey();
408
+
409
+ // because $des[0-2] will, now, do all the work we can return here
410
+ // not need unnecessary stress parent::_setupKey() with our, now unused, $key.
411
+ return;
412
+ }
413
+ }
414
+ // setup our key
415
+ parent::_setupKey();
416
+ }
417
+ }
418
+
lib/LivrariOnline/Twofish.php ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Pure-PHP implementation of Twofish.
5
+ *
6
+ * Uses mcrypt, if available, and an internal implementation, otherwise.
7
+ *
8
+ * PHP versions 4 and 5
9
+ *
10
+ * Useful resources are as follows:
11
+ *
12
+ * - {@link http://en.wikipedia.org/wiki/Twofish Wikipedia description of Twofish}
13
+ *
14
+ * Here's a short example of how to use this library:
15
+ * <code>
16
+ * <?php
17
+ * include('Crypt/Twofish.php');
18
+ *
19
+ * $twofish = new Crypt_Twofish();
20
+ *
21
+ * $twofish->setKey('12345678901234567890123456789012');
22
+ *
23
+ * $plaintext = str_repeat('a', 1024);
24
+ *
25
+ * echo $twofish->decrypt($twofish->encrypt($plaintext));
26
+ * ?>
27
+ * </code>
28
+ *
29
+ * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ * of this software and associated documentation files (the "Software"), to deal
31
+ * in the Software without restriction, including without limitation the rights
32
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ * copies of the Software, and to permit persons to whom the Software is
34
+ * furnished to do so, subject to the following conditions:
35
+ *
36
+ * The above copyright notice and this permission notice shall be included in
37
+ * all copies or substantial portions of the Software.
38
+ *
39
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ * THE SOFTWARE.
46
+ *
47
+ * @category Crypt
48
+ * @package Crypt_Twofish
49
+ * @author Jim Wigginton <terrafrost@php.net>
50
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
51
+ * @copyright MMVII Jim Wigginton
52
+ * @license http://www.opensource.org/licenses/mit-license.html MIT License
53
+ * @version 1.0
54
+ * @link http://phpseclib.sourceforge.net
55
+ */
56
+
57
+ /**
58
+ * Include Crypt_Base
59
+ *
60
+ * Base cipher class
61
+ */
62
+ require_once('Base.php');
63
+
64
+ /**#@+
65
+ * @access public
66
+ * @see Crypt_Twofish::encrypt()
67
+ * @see Crypt_Twofish::decrypt()
68
+ */
69
+ /**
70
+ * Encrypt / decrypt using the Counter mode.
71
+ *
72
+ * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
73
+ *
74
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
75
+ */
76
+ define('CRYPT_TWOFISH_MODE_CTR', CRYPT_MODE_CTR);
77
+ /**
78
+ * Encrypt / decrypt using the Electronic Code Book mode.
79
+ *
80
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
81
+ */
82
+ define('CRYPT_TWOFISH_MODE_ECB', CRYPT_MODE_ECB);
83
+ /**
84
+ * Encrypt / decrypt using the Code Book Chaining mode.
85
+ *
86
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
87
+ */
88
+ define('CRYPT_TWOFISH_MODE_CBC', CRYPT_MODE_CBC);
89
+ /**
90
+ * Encrypt / decrypt using the Cipher Feedback mode.
91
+ *
92
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
93
+ */
94
+ define('CRYPT_TWOFISH_MODE_CFB', CRYPT_MODE_CFB);
95
+ /**
96
+ * Encrypt / decrypt using the Cipher Feedback mode.
97
+ *
98
+ * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
99
+ */
100
+ define('CRYPT_TWOFISH_MODE_OFB', CRYPT_MODE_OFB);
101
+ /**#@-*/
102
+
103
+ /**#@+
104
+ * @access private
105
+ * @see Crypt_Twofish::Crypt_Twofish()
106
+ */
107
+ /**
108
+ * Toggles the internal implementation
109
+ */
110
+ define('CRYPT_TWOFISH_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
111
+ /**
112
+ * Toggles the mcrypt implementation
113
+ */
114
+ define('CRYPT_TWOFISH_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
115
+ /**#@-*/
116
+
117
+ /**
118
+ * Pure-PHP implementation of Twofish.
119
+ *
120
+ * @package Crypt_Twofish
121
+ * @author Jim Wigginton <terrafrost@php.net>
122
+ * @author Hans-Juergen Petrich <petrich@tronic-media.com>
123
+ * @version 1.0
124
+ * @access public
125
+ */
126
+ class Crypt_Twofish extends Crypt_Base
127
+ {
128
+ /**
129
+ * The namespace used by the cipher for its constants.
130
+ *
131
+ * @see Crypt_Base::const_namespace
132
+ * @var String
133
+ * @access private
134
+ */
135
+ var $const_namespace = 'TWOFISH';
136
+
137
+ /**
138
+ * The mcrypt specific name of the cipher
139
+ *
140
+ * @see Crypt_Base::cipher_name_mcrypt
141
+ * @var String
142
+ * @access private
143
+ */
144
+ var $cipher_name_mcrypt = 'twofish';
145
+
146
+ /**
147
+ * Optimizing value while CFB-encrypting
148
+ *
149
+ * @see Crypt_Base::cfb_init_len
150
+ * @var Integer
151
+ * @access private
152
+ */
153
+ var $cfb_init_len = 800;
154
+
155
+ /**
156
+ * Q-Table
157
+ *
158
+ * @var Array
159
+ * @access private
160
+ */
161
+ var $q0 = array (
162
+ 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76,
163
+ 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38,
164
+ 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C,
165
+ 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48,
166
+ 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23,
167
+ 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82,
168
+ 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C,
169
+ 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61,
170
+ 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B,
171
+ 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1,
172
+ 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66,
173
+ 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7,
174
+ 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA,
175
+ 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71,
176
+ 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8,
177
+ 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7,
178
+ 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2,
179
+ 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90,
180
+ 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB,
181
+ 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF,
182
+ 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B,
183
+ 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64,
184
+ 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A,
185
+ 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A,
186
+ 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02,
187
+ 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D,
188
+ 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72,
189
+ 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34,
190
+ 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8,
191
+ 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4,
192
+ 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00,
193
+ 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0
194
+ );
195
+
196
+ /**
197
+ * Q-Table
198
+ *
199
+ * @var Array
200
+ * @access private
201
+ */
202
+ var $q1 = array (
203
+ 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8,
204
+ 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B,
205
+ 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1,
206
+ 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F,
207
+ 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D,
208
+ 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5,
209
+ 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3,
210
+ 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51,
211
+ 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96,
212
+ 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C,
213
+ 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70,
214
+ 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8,
215
+ 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC,
216
+ 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2,
217
+ 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9,
218
+ 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17,
219
+ 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3,
220
+ 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E,
221
+ 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49,
222
+ 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9,
223
+ 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01,
224
+ 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48,
225
+ 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19,
226
+ 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64,
227
+ 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5,
228
+ 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69,
229
+ 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E,
230
+ 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC,
231
+ 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB,
232
+ 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9,
233
+ 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2,
234
+ 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91
235
+ );
236
+
237
+ /**
238
+ * M-Table
239
+ *
240
+ * @var Array
241
+ * @access private
242
+ */
243
+ var $m0 = array (
244
+ 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8,
245
+ 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B,
246
+ 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1,
247
+ 0x24243C30, 0x5151E20F, 0xBABAC6F8, 0x4A4AF31B, 0xBFBF4887, 0x0D0D70FA, 0xB0B0B306, 0x7575DE3F,
248
+ 0xD2D2FD5E, 0x7D7D20BA, 0x666631AE, 0x3A3AA35B, 0x59591C8A, 0x00000000, 0xCDCD93BC, 0x1A1AE09D,
249
+ 0xAEAE2C6D, 0x7F7FABC1, 0x2B2BC7B1, 0xBEBEB90E, 0xE0E0A080, 0x8A8A105D, 0x3B3B52D2, 0x6464BAD5,
250
+ 0xD8D888A0, 0xE7E7A584, 0x5F5FE807, 0x1B1B1114, 0x2C2CC2B5, 0xFCFCB490, 0x3131272C, 0x808065A3,
251
+ 0x73732AB2, 0x0C0C8173, 0x79795F4C, 0x6B6B4154, 0x4B4B0292, 0x53536974, 0x94948F36, 0x83831F51,
252
+ 0x2A2A3638, 0xC4C49CB0, 0x2222C8BD, 0xD5D5F85A, 0xBDBDC3FC, 0x48487860, 0xFFFFCE62, 0x4C4C0796,
253
+ 0x4141776C, 0xC7C7E642, 0xEBEB24F7, 0x1C1C1410, 0x5D5D637C, 0x36362228, 0x6767C027, 0xE9E9AF8C,
254
+ 0x4444F913, 0x1414EA95, 0xF5F5BB9C, 0xCFCF18C7, 0x3F3F2D24, 0xC0C0E346, 0x7272DB3B, 0x54546C70,
255
+ 0x29294CCA, 0xF0F035E3, 0x0808FE85, 0xC6C617CB, 0xF3F34F11, 0x8C8CE4D0, 0xA4A45993, 0xCACA96B8,
256
+ 0x68683BA6, 0xB8B84D83, 0x38382820, 0xE5E52EFF, 0xADAD569F, 0x0B0B8477, 0xC8C81DC3, 0x9999FFCC,
257
+ 0x5858ED03, 0x19199A6F, 0x0E0E0A08, 0x95957EBF, 0x70705040, 0xF7F730E7, 0x6E6ECF2B, 0x1F1F6EE2,
258
+ 0xB5B53D79, 0x09090F0C, 0x616134AA, 0x57571682, 0x9F9F0B41, 0x9D9D803A, 0x111164EA, 0x2525CDB9,
259
+ 0xAFAFDDE4, 0x4545089A, 0xDFDF8DA4, 0xA3A35C97, 0xEAEAD57E, 0x353558DA, 0xEDEDD07A, 0x4343FC17,
260
+ 0xF8F8CB66, 0xFBFBB194, 0x3737D3A1, 0xFAFA401D, 0xC2C2683D, 0xB4B4CCF0, 0x32325DDE, 0x9C9C71B3,
261
+ 0x5656E70B, 0xE3E3DA72, 0x878760A7, 0x15151B1C, 0xF9F93AEF, 0x6363BFD1, 0x3434A953, 0x9A9A853E,
262
+ 0xB1B1428F, 0x7C7CD133, 0x88889B26, 0x3D3DA65F, 0xA1A1D7EC, 0xE4E4DF76, 0x8181942A, 0x91910149,
263
+ 0x0F0FFB81, 0xEEEEAA88, 0x161661EE, 0xD7D77321, 0x9797F5C4, 0xA5A5A81A, 0xFEFE3FEB, 0x6D6DB5D9,
264
+ 0x7878AEC5, 0xC5C56D39, 0x1D1DE599, 0x7676A4CD, 0x3E3EDCAD, 0xCBCB6731, 0xB6B6478B, 0xEFEF5B01,
265
+ 0x12121E18, 0x6060C523, 0x6A6AB0DD, 0x4D4DF61F, 0xCECEE94E, 0xDEDE7C2D, 0x55559DF9, 0x7E7E5A48,
266
+ 0x2121B24F, 0x03037AF2, 0xA0A02665, 0x5E5E198E, 0x5A5A6678, 0x65654B5C, 0x62624E58, 0xFDFD4519,
267
+ 0x0606F48D, 0x404086E5, 0xF2F2BE98, 0x3333AC57, 0x17179067, 0x05058E7F, 0xE8E85E05, 0x4F4F7D64,
268
+ 0x89896AAF, 0x10109563, 0x74742FB6, 0x0A0A75FE, 0x5C5C92F5, 0x9B9B74B7, 0x2D2D333C, 0x3030D6A5,
269
+ 0x2E2E49CE, 0x494989E9, 0x46467268, 0x77775544, 0xA8A8D8E0, 0x9696044D, 0x2828BD43, 0xA9A92969,
270
+ 0xD9D97929, 0x8686912E, 0xD1D187AC, 0xF4F44A15, 0x8D8D1559, 0xD6D682A8, 0xB9B9BC0A, 0x42420D9E,
271
+ 0xF6F6C16E, 0x2F2FB847, 0xDDDD06DF, 0x23233934, 0xCCCC6235, 0xF1F1C46A, 0xC1C112CF, 0x8585EBDC,
272
+ 0x8F8F9E22, 0x7171A1C9, 0x9090F0C0, 0xAAAA539B, 0x0101F189, 0x8B8BE1D4, 0x4E4E8CED, 0x8E8E6FAB,
273
+ 0xABABA212, 0x6F6F3EA2, 0xE6E6540D, 0xDBDBF252, 0x92927BBB, 0xB7B7B602, 0x6969CA2F, 0x3939D9A9,
274
+ 0xD3D30CD7, 0xA7A72361, 0xA2A2AD1E, 0xC3C399B4, 0x6C6C4450, 0x07070504, 0x04047FF6, 0x272746C2,
275
+ 0xACACA716, 0xD0D07625, 0x50501386, 0xDCDCF756, 0x84841A55, 0xE1E15109, 0x7A7A25BE, 0x1313EF91
276
+ );
277
+
278
+ /**
279
+ * M-Table
280
+ *
281
+ * @var Array
282
+ * @access private
283
+ */
284
+ var $m1 = array (
285
+ 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4,
286
+ 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A,
287
+ 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141,
288
+ 0x43BD2828, 0x7532BCBC, 0x37D47B7B, 0x269B8888, 0xFA700D0D, 0x13F94444, 0x94B1FBFB, 0x485A7E7E,
289
+ 0xF27A0303, 0xD0E48C8C, 0x8B47B6B6, 0x303C2424, 0x84A5E7E7, 0x54416B6B, 0xDF06DDDD, 0x23C56060,
290
+ 0x1945FDFD, 0x5BA33A3A, 0x3D68C2C2, 0x59158D8D, 0xF321ECEC, 0xAE316666, 0xA23E6F6F, 0x82165757,
291
+ 0x63951010, 0x015BEFEF, 0x834DB8B8, 0x2E918686, 0xD9B56D6D, 0x511F8383, 0x9B53AAAA, 0x7C635D5D,
292
+ 0xA63B6868, 0xEB3FFEFE, 0xA5D63030, 0xBE257A7A, 0x16A7ACAC, 0x0C0F0909, 0xE335F0F0, 0x6123A7A7,
293
+ 0xC0F09090, 0x8CAFE9E9, 0x3A809D9D, 0xF5925C5C, 0x73810C0C, 0x2C273131, 0x2576D0D0, 0x0BE75656,
294
+ 0xBB7B9292, 0x4EE9CECE, 0x89F10101, 0x6B9F1E1E, 0x53A93434, 0x6AC4F1F1, 0xB499C3C3, 0xF1975B5B,
295
+ 0xE1834747, 0xE66B1818, 0xBDC82222, 0x450E9898, 0xE26E1F1F, 0xF4C9B3B3, 0xB62F7474, 0x66CBF8F8,
296
+ 0xCCFF9999, 0x95EA1414, 0x03ED5858, 0x56F7DCDC, 0xD4E18B8B, 0x1C1B1515, 0x1EADA2A2, 0xD70CD3D3,
297
+ 0xFB2BE2E2, 0xC31DC8C8, 0x8E195E5E, 0xB5C22C2C, 0xE9894949, 0xCF12C1C1, 0xBF7E9595, 0xBA207D7D,
298
+ 0xEA641111, 0x77840B0B, 0x396DC5C5, 0xAF6A8989, 0x33D17C7C, 0xC9A17171, 0x62CEFFFF, 0x7137BBBB,
299
+ 0x81FB0F0F, 0x793DB5B5, 0x0951E1E1, 0xADDC3E3E, 0x242D3F3F, 0xCDA47676, 0xF99D5555, 0xD8EE8282,
300
+ 0xE5864040, 0xC5AE7878, 0xB9CD2525, 0x4D049696, 0x44557777, 0x080A0E0E, 0x86135050, 0xE730F7F7,
301
+ 0xA1D33737, 0x1D40FAFA, 0xAA346161, 0xED8C4E4E, 0x06B3B0B0, 0x706C5454, 0xB22A7373, 0xD2523B3B,
302
+ 0x410B9F9F, 0x7B8B0202, 0xA088D8D8, 0x114FF3F3, 0x3167CBCB, 0xC2462727, 0x27C06767, 0x90B4FCFC,
303
+ 0x20283838, 0xF67F0404, 0x60784848, 0xFF2EE5E5, 0x96074C4C, 0x5C4B6565, 0xB1C72B2B, 0xAB6F8E8E,
304
+ 0x9E0D4242, 0x9CBBF5F5, 0x52F2DBDB, 0x1BF34A4A, 0x5FA63D3D, 0x9359A4A4, 0x0ABCB9B9, 0xEF3AF9F9,
305
+ 0x91EF1313, 0x85FE0808, 0x49019191, 0xEE611616, 0x2D7CDEDE, 0x4FB22121, 0x8F42B1B1, 0x3BDB7272,
306
+ 0x47B82F2F, 0x8748BFBF, 0x6D2CAEAE, 0x46E3C0C0, 0xD6573C3C, 0x3E859A9A, 0x6929A9A9, 0x647D4F4F,
307
+ 0x2A948181, 0xCE492E2E, 0xCB17C6C6, 0x2FCA6969, 0xFCC3BDBD, 0x975CA3A3, 0x055EE8E8, 0x7AD0EDED,
308
+ 0xAC87D1D1, 0x7F8E0505, 0xD5BA6464, 0x1AA8A5A5, 0x4BB72626, 0x0EB9BEBE, 0xA7608787, 0x5AF8D5D5,
309
+ 0x28223636, 0x14111B1B, 0x3FDE7575, 0x2979D9D9, 0x88AAEEEE, 0x3C332D2D, 0x4C5F7979, 0x02B6B7B7,
310
+ 0xB896CACA, 0xDA583535, 0xB09CC4C4, 0x17FC4343, 0x551A8484, 0x1FF64D4D, 0x8A1C5959, 0x7D38B2B2,
311
+ 0x57AC3333, 0xC718CFCF, 0x8DF40606, 0x74695353, 0xB7749B9B, 0xC4F59797, 0x9F56ADAD, 0x72DAE3E3,
312
+ 0x7ED5EAEA, 0x154AF4F4, 0x229E8F8F, 0x12A2ABAB, 0x584E6262, 0x07E85F5F, 0x99E51D1D, 0x34392323,
313
+ 0x6EC1F6F6, 0x50446C6C, 0xDE5D3232, 0x68724646, 0x6526A0A0, 0xBC93CDCD, 0xDB03DADA, 0xF8C6BABA,
314
+ 0xC8FA9E9E, 0xA882D6D6, 0x2BCF6E6E, 0x40507070, 0xDCEB8585, 0xFE750A0A, 0x328A9393, 0xA48DDFDF,
315
+ 0xCA4C2929, 0x10141C1C, 0x2173D7D7, 0xF0CCB4B4, 0xD309D4D4, 0x5D108A8A, 0x0FE25151, 0x00000000,
316
+ 0x6F9A1919, 0x9DE01A1A, 0x368F9494, 0x42E6C7C7, 0x4AECC9C9, 0x5EFDD2D2, 0xC1AB7F7F, 0xE0D8A8A8
317
+ );
318
+
319
+ /**
320
+ * M-Table
321
+ *
322
+ * @var Array
323
+ * @access private
324
+ */
325
+ var $m2 = array (
326
+ 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA,
327
+ 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7,
328
+ 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783,
329
+ 0x2430243C, 0x510F51E2, 0xBAF8BAC6, 0x4A1B4AF3, 0xBF87BF48, 0x0DFA0D70, 0xB006B0B3, 0x753F75DE,
330
+ 0xD25ED2FD, 0x7DBA7D20, 0x66AE6631, 0x3A5B3AA3, 0x598A591C, 0x00000000, 0xCDBCCD93, 0x1A9D1AE0,
331
+ 0xAE6DAE2C, 0x7FC17FAB, 0x2BB12BC7, 0xBE0EBEB9, 0xE080E0A0, 0x8A5D8A10, 0x3BD23B52, 0x64D564BA,
332
+ 0xD8A0D888, 0xE784E7A5, 0x5F075FE8, 0x1B141B11, 0x2CB52CC2, 0xFC90FCB4, 0x312C3127, 0x80A38065,
333
+ 0x73B2732A, 0x0C730C81, 0x794C795F, 0x6B546B41, 0x4B924B02, 0x53745369, 0x9436948F, 0x8351831F,
334
+ 0x2A382A36, 0xC4B0C49C, 0x22BD22C8, 0xD55AD5F8, 0xBDFCBDC3, 0x48604878, 0xFF62FFCE, 0x4C964C07,
335
+ 0x416C4177, 0xC742C7E6, 0xEBF7EB24, 0x1C101C14, 0x5D7C5D63, 0x36283622, 0x672767C0, 0xE98CE9AF,
336
+ 0x441344F9, 0x149514EA, 0xF59CF5BB, 0xCFC7CF18, 0x3F243F2D, 0xC046C0E3, 0x723B72DB, 0x5470546C,
337
+ 0x29CA294C, 0xF0E3F035, 0x088508FE, 0xC6CBC617, 0xF311F34F, 0x8CD08CE4, 0xA493A459, 0xCAB8CA96,
338
+ 0x68A6683B, 0xB883B84D, 0x38203828, 0xE5FFE52E, 0xAD9FAD56, 0x0B770B84, 0xC8C3C81D, 0x99CC99FF,
339
+ 0x580358ED, 0x196F199A, 0x0E080E0A, 0x95BF957E, 0x70407050, 0xF7E7F730, 0x6E2B6ECF, 0x1FE21F6E,
340
+ 0xB579B53D, 0x090C090F, 0x61AA6134, 0x57825716, 0x9F419F0B, 0x9D3A9D80, 0x11EA1164, 0x25B925CD,
341
+ 0xAFE4AFDD, 0x459A4508, 0xDFA4DF8D, 0xA397A35C, 0xEA7EEAD5, 0x35DA3558, 0xED7AEDD0, 0x431743FC,
342
+ 0xF866F8CB, 0xFB94FBB1, 0x37A137D3, 0xFA1DFA40, 0xC23DC268, 0xB4F0B4CC, 0x32DE325D, 0x9CB39C71,
343
+ 0x560B56E7, 0xE372E3DA, 0x87A78760, 0x151C151B, 0xF9EFF93A, 0x63D163BF, 0x345334A9, 0x9A3E9A85,
344
+ 0xB18FB142, 0x7C337CD1, 0x8826889B, 0x3D5F3DA6, 0xA1ECA1D7, 0xE476E4DF, 0x812A8194, 0x91499101,
345
+ 0x0F810FFB, 0xEE88EEAA, 0x16EE1661, 0xD721D773, 0x97C497F5, 0xA51AA5A8, 0xFEEBFE3F, 0x6DD96DB5,
346
+ 0x78C578AE, 0xC539C56D, 0x1D991DE5, 0x76CD76A4, 0x3EAD3EDC, 0xCB31CB67, 0xB68BB647, 0xEF01EF5B,
347
+ 0x1218121E, 0x602360C5, 0x6ADD6AB0, 0x4D1F4DF6, 0xCE4ECEE9, 0xDE2DDE7C, 0x55F9559D, 0x7E487E5A,
348
+ 0x214F21B2, 0x03F2037A, 0xA065A026, 0x5E8E5E19, 0x5A785A66, 0x655C654B, 0x6258624E, 0xFD19FD45,
349
+ 0x068D06F4, 0x40E54086, 0xF298F2BE, 0x335733AC, 0x17671790, 0x057F058E, 0xE805E85E, 0x4F644F7D,
350
+ 0x89AF896A, 0x10631095, 0x74B6742F, 0x0AFE0A75, 0x5CF55C92, 0x9BB79B74, 0x2D3C2D33, 0x30A530D6,
351
+ 0x2ECE2E49, 0x49E94989, 0x46684672, 0x77447755, 0xA8E0A8D8, 0x964D9604, 0x284328BD, 0xA969A929,
352
+ 0xD929D979, 0x862E8691, 0xD1ACD187, 0xF415F44A, 0x8D598D15, 0xD6A8D682, 0xB90AB9BC, 0x429E420D,
353
+ 0xF66EF6C1, 0x2F472FB8, 0xDDDFDD06, 0x23342339, 0xCC35CC62, 0xF16AF1C4, 0xC1CFC112, 0x85DC85EB,
354
+ 0x8F228F9E, 0x71C971A1, 0x90C090F0, 0xAA9BAA53, 0x018901F1, 0x8BD48BE1, 0x4EED4E8C, 0x8EAB8E6F,
355
+ 0xAB12ABA2, 0x6FA26F3E, 0xE60DE654, 0xDB52DBF2, 0x92BB927B, 0xB702B7B6, 0x692F69CA, 0x39A939D9,
356
+ 0xD3D7D30C, 0xA761A723, 0xA21EA2AD, 0xC3B4C399, 0x6C506C44, 0x07040705, 0x04F6047F, 0x27C22746,
357
+ 0xAC16ACA7, 0xD025D076, 0x50865013, 0xDC56DCF7, 0x8455841A, 0xE109E151, 0x7ABE7A25, 0x139113EF
358
+ );
359
+
360
+ /**
361
+ * M-Table
362
+ *
363
+ * @var Array
364
+ * @access private
365
+ */
366
+ var $m3 = array (
367
+ 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF,
368
+ 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836,
369
+ 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77,
370
+ 0xBD2843BD, 0x32BC7532, 0xD47B37D4, 0x9B88269B, 0x700DFA70, 0xF94413F9, 0xB1FB94B1, 0x5A7E485A,
371
+ 0x7A03F27A, 0xE48CD0E4, 0x47B68B47, 0x3C24303C, 0xA5E784A5, 0x416B5441, 0x06DDDF06, 0xC56023C5,
372
+ 0x45FD1945, 0xA33A5BA3, 0x68C23D68, 0x158D5915, 0x21ECF321, 0x3166AE31, 0x3E6FA23E, 0x16578216,
373
+ 0x95106395, 0x5BEF015B, 0x4DB8834D, 0x91862E91, 0xB56DD9B5, 0x1F83511F, 0x53AA9B53, 0x635D7C63,
374
+ 0x3B68A63B, 0x3FFEEB3F, 0xD630A5D6, 0x257ABE25, 0xA7AC16A7, 0x0F090C0F, 0x35F0E335, 0x23A76123,
375
+ 0xF090C0F0, 0xAFE98CAF, 0x809D3A80, 0x925CF592, 0x810C7381, 0x27312C27, 0x76D02576, 0xE7560BE7,
376
+ 0x7B92BB7B, 0xE9CE4EE9, 0xF10189F1, 0x9F1E6B9F, 0xA93453A9, 0xC4F16AC4, 0x99C3B499, 0x975BF197,
377
+ 0x8347E183, 0x6B18E66B, 0xC822BDC8, 0x0E98450E, 0x6E1FE26E, 0xC9B3F4C9, 0x2F74B62F, 0xCBF866CB,
378
+ 0xFF99CCFF, 0xEA1495EA, 0xED5803ED, 0xF7DC56F7, 0xE18BD4E1, 0x1B151C1B, 0xADA21EAD, 0x0CD3D70C,
379
+ 0x2BE2FB2B, 0x1DC8C31D, 0x195E8E19, 0xC22CB5C2, 0x8949E989, 0x12C1CF12, 0x7E95BF7E, 0x207DBA20,
380
+ 0x6411EA64, 0x840B7784, 0x6DC5396D, 0x6A89AF6A, 0xD17C33D1, 0xA171C9A1, 0xCEFF62CE, 0x37BB7137,
381
+ 0xFB0F81FB, 0x3DB5793D, 0x51E10951, 0xDC3EADDC, 0x2D3F242D, 0xA476CDA4, 0x9D55F99D, 0xEE82D8EE,
382
+ 0x8640E586, 0xAE78C5AE, 0xCD25B9CD, 0x04964D04, 0x55774455, 0x0A0E080A, 0x13508613, 0x30F7E730,
383
+ 0xD337A1D3, 0x40FA1D40, 0x3461AA34, 0x8C4EED8C, 0xB3B006B3, 0x6C54706C, 0x2A73B22A, 0x523BD252,
384
+ 0x0B9F410B, 0x8B027B8B, 0x88D8A088, 0x4FF3114F, 0x67CB3167, 0x4627C246, 0xC06727C0, 0xB4FC90B4,
385
+ 0x28382028, 0x7F04F67F, 0x78486078, 0x2EE5FF2E, 0x074C9607, 0x4B655C4B, 0xC72BB1C7, 0x6F8EAB6F,
386
+ 0x0D429E0D, 0xBBF59CBB, 0xF2DB52F2, 0xF34A1BF3, 0xA63D5FA6, 0x59A49359, 0xBCB90ABC, 0x3AF9EF3A,
387
+ 0xEF1391EF, 0xFE0885FE, 0x01914901, 0x6116EE61, 0x7CDE2D7C, 0xB2214FB2, 0x42B18F42, 0xDB723BDB,
388
+ 0xB82F47B8, 0x48BF8748, 0x2CAE6D2C, 0xE3C046E3, 0x573CD657, 0x859A3E85, 0x29A96929, 0x7D4F647D,
389
+ 0x94812A94, 0x492ECE49, 0x17C6CB17, 0xCA692FCA, 0xC3BDFCC3, 0x5CA3975C, 0x5EE8055E, 0xD0ED7AD0,
390
+ 0x87D1AC87, 0x8E057F8E, 0xBA64D5BA, 0xA8A51AA8, 0xB7264BB7, 0xB9BE0EB9, 0x6087A760, 0xF8D55AF8,
391
+ 0x22362822, 0x111B1411, 0xDE753FDE, 0x79D92979, 0xAAEE88AA, 0x332D3C33, 0x5F794C5F, 0xB6B702B6,
392
+ 0x96CAB896, 0x5835DA58, 0x9CC4B09C, 0xFC4317FC, 0x1A84551A, 0xF64D1FF6, 0x1C598A1C, 0x38B27D38,
393
+ 0xAC3357AC, 0x18CFC718, 0xF4068DF4, 0x69537469, 0x749BB774, 0xF597C4F5, 0x56AD9F56, 0xDAE372DA,
394
+ 0xD5EA7ED5, 0x4AF4154A, 0x9E8F229E, 0xA2AB12A2, 0x4E62584E, 0xE85F07E8, 0xE51D99E5, 0x39233439,
395
+ 0xC1F66EC1, 0x446C5044, 0x5D32DE5D, 0x72466872, 0x26A06526, 0x93CDBC93, 0x03DADB03, 0xC6BAF8C6,
396
+ 0xFA9EC8FA, 0x82D6A882, 0xCF6E2BCF, 0x50704050, 0xEB85DCEB, 0x750AFE75, 0x8A93328A, 0x8DDFA48D,
397
+ 0x4C29CA4C, 0x141C1014, 0x73D72173, 0xCCB4F0CC, 0x09D4D309, 0x108A5D10, 0xE2510FE2, 0x00000000,
398
+ 0x9A196F9A, 0xE01A9DE0, 0x8F94368F, 0xE6C742E6, 0xECC94AEC, 0xFDD25EFD, 0xAB7FC1AB, 0xD8A8E0D8
399
+ );
400
+
401
+ /**
402
+ * The Key Schedule Array
403
+ *
404
+ * @var Array
405
+ * @access private
406
+ */
407
+ var $K = array();
408
+
409
+ /**
410
+ * The Key depended S-Table 0
411
+ *
412
+ * @var Array
413
+ * @access private
414
+ */
415
+ var $S0 = array();
416
+
417
+ /**
418
+ * The Key depended S-Table 1
419
+ *
420
+ * @var Array
421
+ * @access private
422
+ */
423
+ var $S1 = array();
424
+
425
+ /**
426
+ * The Key depended S-Table 2
427
+ *
428
+ * @var Array
429
+ * @access private
430
+ */
431
+ var $S2 = array();
432
+
433
+ /**
434
+ * The Key depended S-Table 3
435
+ *
436
+ * @var Array
437
+ * @access private
438
+ */
439
+ var $S3 = array();
440
+
441
+ /**
442
+ * Holds the last used key
443
+ *
444
+ * @var Array
445
+ * @access private
446
+ */
447
+ var $kl;
448
+
449
+ /**
450
+ * Default Constructor.
451
+ *
452
+ * Determines whether or not the mcrypt extension should be used.
453
+ *
454
+ * $mode could be:
455
+ *
456
+ * - CRYPT_TWOFISH_MODE_ECB
457
+ *
458
+ * - CRYPT_TWOFISH_MODE_CBC
459
+ *
460
+ * - CRYPT_TWOFISH_MODE_CTR
461
+ *
462
+ * - CRYPT_TWOFISH_MODE_CFB
463
+ *
464
+ * - CRYPT_TWOFISH_MODE_OFB
465
+ *
466
+ * If not explictly set, CRYPT_TWOFISH_MODE_CBC will be used.
467
+ *
468
+ * @see Crypt_Base::Crypt_Base()
469
+ * @param optional Integer $mode
470
+ * @access public
471
+ */
472
+ function Crypt_Twofish($mode = CRYPT_TWOFISH_MODE_CBC)
473
+ {
474
+ parent::Crypt_Base($mode);
475
+ }
476
+
477
+ /**
478
+ * Sets the key.
479
+ *
480
+ * Keys can be of any length. Twofish, itself, requires the use of a key that's 128, 192 or 256-bits long.
481
+ * If the key is less than 256-bits we round the length up to the closest valid key length,
482
+ * padding $key with null bytes. If the key is more than 256-bits, we trim the excess bits.
483
+ *
484
+ * If the key is not explicitly set, it'll be assumed a 128 bits key to be all null bytes.
485
+ *
486
+ * @access public
487
+ * @see Crypt_Base::setKey()
488
+ * @param String $key
489
+ */
490
+ function setKey($key)
491
+ {
492
+ $keylength = strlen($key);
493
+ switch (true) {
494
+ case $keylength <= 16:
495
+ $key = str_pad($key, 16, "\0");
496
+ break;
497
+ case $keylength <= 24:
498
+ $key = str_pad($key, 24, "\0");
499
+ break;
500
+ case $keylength < 32:
501
+ $key = str_pad($key, 32, "\0");
502
+ break;
503
+ case $keylength > 32:
504
+ $key = substr($key, 0, 32);
505
+ }
506
+ parent::setKey($key);
507
+ }
508
+
509
+ /**
510
+ * Setup the key (expansion)
511
+ *
512
+ * @see Crypt_Base::_setupKey()
513
+ * @access private
514
+ */
515
+ function _setupKey()
516
+ {
517
+ if (isset($this->kl['key']) && $this->key === $this->kl['key']) {
518
+ // already expanded
519
+ return;
520
+ }
521
+ $this->kl = array('key' => $this->key);
522
+
523
+ /* Key expanding and generating the key-depended s-boxes */
524
+ $le_longs = unpack('V*', $this->key);
525
+ $key = unpack('C*', $this->key);
526
+ $m0 = $this->m0;
527
+ $m1 = $this->m1;
528
+ $m2 = $this->m2;
529
+ $m3 = $this->m3;
530
+ $q0 = $this->q0;
531
+ $q1 = $this->q1;
532
+
533
+ $K = $S0 = $S1 = $S2 = $S3 = array();
534
+
535
+ switch (strlen($this->key)) {
536
+ case 16:
537
+ list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]);
538
+ list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]);
539
+ for ($i = 0, $j = 1; $i < 40; $i+= 2,$j+= 2) {
540
+ $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^
541
+ $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^
542
+ $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^
543
+ $m3[$q1[$q1[$i] ^ $key[12]] ^ $key[4]];
544
+ $B = $m0[$q0[$q0[$j] ^ $key[13]] ^ $key[5]] ^
545
+ $m1[$q0[$q1[$j] ^ $key[14]] ^ $key[6]] ^
546
+ $m2[$q1[$q0[$j] ^ $key[15]] ^ $key[7]] ^
547
+ $m3[$q1[$q1[$j] ^ $key[16]] ^ $key[8]];
548
+ $B = ($B << 8) | ($B >> 24 & 0xff);
549
+ $K[] = $A+= $B;
550
+ $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
551
+ }
552
+ for ($i = 0; $i < 256; ++$i) {
553
+ $S0[$i] = $m0[$q0[$q0[$i] ^ $s4] ^ $s0];
554
+ $S1[$i] = $m1[$q0[$q1[$i] ^ $s5] ^ $s1];
555
+ $S2[$i] = $m2[$q1[$q0[$i] ^ $s6] ^ $s2];
556
+ $S3[$i] = $m3[$q1[$q1[$i] ^ $s7] ^ $s3];
557
+ }
558
+ break;
559
+ case 24:
560
+ list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]);
561
+ list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]);
562
+ list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]);
563
+ for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
564
+ $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
565
+ $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
566
+ $m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
567
+ $m3[$q1[$q1[$q0[$i] ^ $key[20]] ^ $key[12]] ^ $key[4]];
568
+ $B = $m0[$q0[$q0[$q1[$j] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^
569
+ $m1[$q0[$q1[$q1[$j] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^
570
+ $m2[$q1[$q0[$q0[$j] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^
571
+ $m3[$q1[$q1[$q0[$j] ^ $key[24]] ^ $key[16]] ^ $key[8]];
572
+ $B = ($B << 8) | ($B >> 24 & 0xff);
573
+ $K[] = $A+= $B;
574
+ $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
575
+ }
576
+ for ($i = 0; $i < 256; ++$i) {
577
+ $S0[$i] = $m0[$q0[$q0[$q1[$i] ^ $s8] ^ $s4] ^ $s0];
578
+ $S1[$i] = $m1[$q0[$q1[$q1[$i] ^ $s9] ^ $s5] ^ $s1];
579
+ $S2[$i] = $m2[$q1[$q0[$q0[$i] ^ $sa] ^ $s6] ^ $s2];
580
+ $S3[$i] = $m3[$q1[$q1[$q0[$i] ^ $sb] ^ $s7] ^ $s3];
581
+ }
582
+ break;
583
+ default: // 32
584
+ list ($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]);
585
+ list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]);
586
+ list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]);
587
+ list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]);
588
+ for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
589
+ $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
590
+ $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
591
+ $m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
592
+ $m3[$q1[$q1[$q0[$q1[$i] ^ $key[28]] ^ $key[20]] ^ $key[12]] ^ $key[4]];
593
+ $B = $m0[$q0[$q0[$q1[$q1[$j] ^ $key[29]] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^
594
+ $m1[$q0[$q1[$q1[$q0[$j] ^ $key[30]] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^
595
+ $m2[$q1[$q0[$q0[$q0[$j] ^ $key[31]] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^
596
+ $m3[$q1[$q1[$q0[$q1[$j] ^ $key[32]] ^ $key[24]] ^ $key[16]] ^ $key[8]];
597
+ $B = ($B << 8) | ($B >> 24 & 0xff);
598
+ $K[] = $A+= $B;
599
+ $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
600
+ }
601
+ for ($i = 0; $i < 256; ++$i) {
602
+ $S0[$i] = $m0[$q0[$q0[$q1[$q1[$i] ^ $sc] ^ $s8] ^ $s4] ^ $s0];
603
+ $S1[$i] = $m1[$q0[$q1[$q1[$q0[$i] ^ $sd] ^ $s9] ^ $s5] ^ $s1];
604
+ $S2[$i] = $m2[$q1[$q0[$q0[$q0[$i] ^ $se] ^ $sa] ^ $s6] ^ $s2];
605
+ $S3[$i] = $m3[$q1[$q1[$q0[$q1[$i] ^ $sf] ^ $sb] ^ $s7] ^ $s3];
606
+ }
607
+ }
608
+
609
+ $this->K = $K;
610
+ $this->S0 = $S0;
611
+ $this->S1 = $S1;
612
+ $this->S2 = $S2;
613
+ $this->S3 = $S3;
614
+ }
615
+
616
+ /**
617
+ * _mdsrem function using by the twofish cipher algorithm
618
+ *
619
+ * @access private
620
+ * @param String $A
621
+ * @param String $B
622
+ * @return Array
623
+ */
624
+ function _mdsrem($A, $B)
625
+ {
626
+ // No gain by unrolling this loop.
627
+ for ($i = 0; $i < 8; ++$i) {
628
+ // Get most significant coefficient.
629
+ $t = 0xff & ($B >> 24);
630
+
631
+ // Shift the others up.
632
+ $B = ($B << 8) | (0xff & ($A >> 24));
633
+ $A<<= 8;
634
+
635
+ $u = $t << 1;
636
+
637
+ // Subtract the modular polynomial on overflow.
638
+ if ($t & 0x80) {
639
+ $u^= 0x14d;
640
+ }
641
+
642
+ // Remove t * (a * x^2 + 1).
643
+ $B ^= $t ^ ($u << 16);
644
+
645
+ // Form u = a*t + t/a = t*(a + 1/a).
646
+ $u^= 0x7fffffff & ($t >> 1);
647
+
648
+ // Add the modular polynomial on underflow.
649
+ if ($t & 0x01) $u^= 0xa6 ;
650
+
651
+ // Remove t * (a + 1/a) * (x^3 + x).
652
+ $B^= ($u << 24) | ($u << 8);
653
+ }
654
+
655
+ return array(
656
+ 0xff & $B >> 24,
657
+ 0xff & $B >> 16,
658
+ 0xff & $B >> 8,
659
+ 0xff & $B);
660
+ }
661
+
662
+ /**
663
+ * Encrypts a block
664
+ *
665
+ * @access private
666
+ * @param String $in
667
+ * @return String
668
+ */
669
+ function _encryptBlock($in)
670
+ {
671
+ $S0 = $this->S0;
672
+ $S1 = $this->S1;
673
+ $S2 = $this->S2;
674
+ $S3 = $this->S3;
675
+ $K = $this->K;
676
+
677
+ $in = unpack("V4", $in);
678
+ $R0 = $K[0] ^ $in[1];
679
+ $R1 = $K[1] ^ $in[2];
680
+ $R2 = $K[2] ^ $in[3];
681
+ $R3 = $K[3] ^ $in[4];
682
+
683
+ $ki = 7;
684
+ while ($ki < 39) {
685
+ $t0 = $S0[ $R0 & 0xff] ^
686
+ $S1[($R0 >> 8) & 0xff] ^
687
+ $S2[($R0 >> 16) & 0xff] ^
688
+ $S3[($R0 >> 24) & 0xff];
689
+ $t1 = $S0[($R1 >> 24) & 0xff] ^
690
+ $S1[ $R1 & 0xff] ^
691
+ $S2[($R1 >> 8) & 0xff] ^
692
+ $S3[($R1 >> 16) & 0xff];
693
+ $R2^= $t0 + $t1 + $K[++$ki];
694
+ $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31);
695
+ $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]);
696
+
697
+ $t0 = $S0[ $R2 & 0xff] ^
698
+ $S1[($R2 >> 8) & 0xff] ^
699
+ $S2[($R2 >> 16) & 0xff] ^
700
+ $S3[($R2 >> 24) & 0xff];
701
+ $t1 = $S0[($R3 >> 24) & 0xff] ^
702
+ $S1[ $R3 & 0xff] ^
703
+ $S2[($R3 >> 8) & 0xff] ^
704
+ $S3[($R3 >> 16) & 0xff];
705
+ $R0^= ($t0 + $t1 + $K[++$ki]);
706
+ $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31);
707
+ $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]);
708
+ }
709
+
710
+ return pack("V4", $K[4] ^ $R2,
711
+ $K[5] ^ $R3,
712
+ $K[6] ^ $R0,
713
+ $K[7] ^ $R1);
714
+ }
715
+
716
+ /**
717
+ * Decrypts a block
718
+ *
719
+ * @access private
720
+ * @param String $in
721
+ * @return String
722
+ */
723
+ function _decryptBlock($in)
724
+ {
725
+ $S0 = $this->S0;
726
+ $S1 = $this->S1;
727
+ $S2 = $this->S2;
728
+ $S3 = $this->S3;
729
+ $K = $this->K;
730
+
731
+ $in = unpack("V4", $in);
732
+ $R0 = $K[4] ^ $in[1];
733
+ $R1 = $K[5] ^ $in[2];
734
+ $R2 = $K[6] ^ $in[3];
735
+ $R3 = $K[7] ^ $in[4];
736
+
737
+ $ki = 40;
738
+ while ($ki > 8) {
739
+ $t0 = $S0[$R0 & 0xff] ^
740
+ $S1[$R0 >> 8 & 0xff] ^
741
+ $S2[$R0 >> 16 & 0xff] ^
742
+ $S3[$R0 >> 24 & 0xff];
743
+ $t1 = $S0[$R1 >> 24 & 0xff] ^
744
+ $S1[$R1 & 0xff] ^
745
+ $S2[$R1 >> 8 & 0xff] ^
746
+ $S3[$R1 >> 16 & 0xff];
747
+ $R3^= $t0 + ($t1 << 1) + $K[--$ki];
748
+ $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
749
+ $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + $K[--$ki]);
750
+
751
+ $t0 = $S0[$R2 & 0xff] ^
752
+ $S1[$R2 >> 8 & 0xff] ^
753
+ $S2[$R2 >> 16 & 0xff] ^
754
+ $S3[$R2 >> 24 & 0xff];
755
+ $t1 = $S0[$R3 >> 24 & 0xff] ^
756
+ $S1[$R3 & 0xff] ^
757
+ $S2[$R3 >> 8 & 0xff] ^
758
+ $S3[$R3 >> 16 & 0xff];
759
+ $R1^= $t0 + ($t1 << 1) + $K[--$ki];
760
+ $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
761
+ $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + $K[--$ki]);
762
+ }
763
+
764
+ return pack("V4", $K[0] ^ $R2,
765
+ $K[1] ^ $R3,
766
+ $K[2] ^ $R0,
767
+ $K[3] ^ $R1);
768
+ }
769
+
770
+ /**
771
+ * Setup the performance-optimized function for de/encrypt()
772
+ *
773
+ * @see Crypt_Base::_setupInlineCrypt()
774
+ * @access private
775
+ */
776
+ function _setupInlineCrypt()
777
+ {
778
+ $lambda_functions =& Crypt_Twofish::_getLambdaFunctions();
779
+
780
+ // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one.
781
+ $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 );
782
+
783
+ switch (true) {
784
+ case $gen_hi_opt_code:
785
+ $code_hash = md5(str_pad("Crypt_Twofish, {$this->mode}, ", 32, "\0") . $this->key);
786
+ break;
787
+ default:
788
+ $code_hash = "Crypt_Twofish, {$this->mode}";
789
+ }
790
+
791
+ if (!isset($lambda_functions[$code_hash])) {
792
+ switch (true) {
793
+ case $gen_hi_opt_code:
794
+ $K = $this->K;
795
+
796
+ $init_crypt = '
797
+ static $S0, $S1, $S2, $S3;
798
+ if (!$S0) {
799
+ for ($i = 0; $i < 256; ++$i) {
800
+ $S0[] = (int)$self->S0[$i];
801
+ $S1[] = (int)$self->S1[$i];
802
+ $S2[] = (int)$self->S2[$i];
803
+ $S3[] = (int)$self->S3[$i];
804
+ }
805
+ }
806
+ ';
807
+ break;
808
+ default:
809
+ $K = array();
810
+ for ($i = 0; $i < 40; ++$i) {
811
+ $K[] = '$K_' . $i;
812
+ }
813
+
814
+ $init_crypt = '
815
+ $S0 = $self->S0;
816
+ $S1 = $self->S1;
817
+ $S2 = $self->S2;
818
+ $S3 = $self->S3;
819
+ list(' . implode(',', $K) . ') = $self->K;
820
+ ';
821
+ }
822
+
823
+ // Generating encrypt code:
824
+ $encrypt_block = '
825
+ $in = unpack("V4", $in);
826
+ $R0 = '.$K[0].' ^ $in[1];
827
+ $R1 = '.$K[1].' ^ $in[2];
828
+ $R2 = '.$K[2].' ^ $in[3];
829
+ $R3 = '.$K[3].' ^ $in[4];
830
+ ';
831
+ for ($ki = 7, $i = 0; $i < 8; ++$i) {
832
+ $encrypt_block.= '
833
+ $t0 = $S0[ $R0 & 0xff] ^
834
+ $S1[($R0 >> 8) & 0xff] ^
835
+ $S2[($R0 >> 16) & 0xff] ^
836
+ $S3[($R0 >> 24) & 0xff];
837
+ $t1 = $S0[($R1 >> 24) & 0xff] ^
838
+ $S1[ $R1 & 0xff] ^
839
+ $S2[($R1 >> 8) & 0xff] ^
840
+ $S3[($R1 >> 16) & 0xff];
841
+ $R2^= ($t0 + $t1 + '.$K[++$ki].');
842
+ $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31);
843
+ $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].');
844
+
845
+ $t0 = $S0[ $R2 & 0xff] ^
846
+ $S1[($R2 >> 8) & 0xff] ^
847
+ $S2[($R2 >> 16) & 0xff] ^
848
+ $S3[($R2 >> 24) & 0xff];
849
+ $t1 = $S0[($R3 >> 24) & 0xff] ^
850
+ $S1[ $R3 & 0xff] ^
851
+ $S2[($R3 >> 8) & 0xff] ^
852
+ $S3[($R3 >> 16) & 0xff];
853
+ $R0^= ($t0 + $t1 + '.$K[++$ki].');
854
+ $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31);
855
+ $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].');
856
+ ';
857
+ }
858
+ $encrypt_block.= '
859
+ $in = pack("V4", '.$K[4].' ^ $R2,
860
+ '.$K[5].' ^ $R3,
861
+ '.$K[6].' ^ $R0,
862
+ '.$K[7].' ^ $R1);
863
+ ';
864
+
865
+ // Generating decrypt code:
866
+ $decrypt_block = '
867
+ $in = unpack("V4", $in);
868
+ $R0 = '.$K[4].' ^ $in[1];
869
+ $R1 = '.$K[5].' ^ $in[2];
870
+ $R2 = '.$K[6].' ^ $in[3];
871
+ $R3 = '.$K[7].' ^ $in[4];
872
+ ';
873
+ for ($ki = 40, $i = 0; $i < 8; ++$i) {
874
+ $decrypt_block.= '
875
+ $t0 = $S0[$R0 & 0xff] ^
876
+ $S1[$R0 >> 8 & 0xff] ^
877
+ $S2[$R0 >> 16 & 0xff] ^
878
+ $S3[$R0 >> 24 & 0xff];
879
+ $t1 = $S0[$R1 >> 24 & 0xff] ^
880
+ $S1[$R1 & 0xff] ^
881
+ $S2[$R1 >> 8 & 0xff] ^
882
+ $S3[$R1 >> 16 & 0xff];
883
+ $R3^= $t0 + ($t1 << 1) + '.$K[--$ki].';
884
+ $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
885
+ $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + '.$K[--$ki].');
886
+
887
+ $t0 = $S0[$R2 & 0xff] ^
888
+ $S1[$R2 >> 8 & 0xff] ^
889
+ $S2[$R2 >> 16 & 0xff] ^
890
+ $S3[$R2 >> 24 & 0xff];
891
+ $t1 = $S0[$R3 >> 24 & 0xff] ^
892
+ $S1[$R3 & 0xff] ^
893
+ $S2[$R3 >> 8 & 0xff] ^
894
+ $S3[$R3 >> 16 & 0xff];
895
+ $R1^= $t0 + ($t1 << 1) + '.$K[--$ki].';
896
+ $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
897
+ $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + '.$K[--$ki].');
898
+ ';
899
+ }
900
+ $decrypt_block.= '
901
+ $in = pack("V4", '.$K[0].' ^ $R2,
902
+ '.$K[1].' ^ $R3,
903
+ '.$K[2].' ^ $R0,
904
+ '.$K[3].' ^ $R1);
905
+ ';
906
+
907
+ $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
908
+ array(
909
+ 'init_crypt' => $init_crypt,
910
+ 'init_encrypt' => '',
911
+ 'init_decrypt' => '',
912
+ 'encrypt_block' => $encrypt_block,
913
+ 'decrypt_block' => $decrypt_block
914
+ )
915
+ );
916
+ }
917
+ $this->inline_crypt = $lambda_functions[$code_hash];
918
+ }
919
+ }
920
+
lib/LivrariOnline/curl.php ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class cURL {
4
+ var $headers;
5
+ var $user_agent;
6
+ var $compression;
7
+ var $cookie_file;
8
+ var $proxy;
9
+
10
+ function cURL($cookies=FALSE,$cookie='cookies.txt',$compression='gzip',$proxy='') {
11
+ $lo = new LO();
12
+ $this->headers[] = 'Accept: text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8';
13
+ //$this->headers[] = 'Connection: Keep-Alive';
14
+ $this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
15
+ $this->user_agent = 'Mozilla/4.0 (LivrariOnline.ro '.$lo->version.')';
16
+ $this->compression = $compression;
17
+ $this->proxy = $proxy;
18
+ $this->cookies = $cookies;
19
+ if ($this->cookies == TRUE) $this->cookie($cookie);
20
+ }
21
+
22
+ function cookie($cookie_file) {
23
+ if (file_exists($cookie_file)) {
24
+ $this->cookie_file=$cookie_file;
25
+ } else {
26
+ fopen($cookie_file,'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
27
+ $this->cookie_file=$cookie_file;
28
+ fclose($this->cookie_file);
29
+ }
30
+ }
31
+
32
+ function get($url) {
33
+ $process = curl_init($url);
34
+ curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
35
+ curl_setopt($process, CURLOPT_HEADER, 0);
36
+ curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
37
+ if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
38
+ if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
39
+ curl_setopt($process,CURLOPT_ENCODING , $this->compression);
40
+ curl_setopt($process, CURLOPT_TIMEOUT, 30);
41
+ if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
42
+ curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
43
+ curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
44
+ curl_setopt($process, CURLOPT_CONNECTTIMEOUT ,5); //timeout pe conexiune
45
+ curl_setopt($process, CURLOPT_TIMEOUT, 10); //timeout pe executie
46
+ $return = curl_exec($process);
47
+ $error = curl_error($process);
48
+ curl_close($process);
49
+
50
+ if( !empty( $error )) {
51
+ return false;
52
+ } else {
53
+ return $return;
54
+ }
55
+ }
56
+
57
+ function post($url,$data) {
58
+ $process = curl_init($url);
59
+ curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
60
+ curl_setopt($process, CURLOPT_HEADER, 0);
61
+ curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
62
+ if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
63
+ if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
64
+ curl_setopt($process, CURLOPT_ENCODING , $this->compression);
65
+ curl_setopt($process, CURLOPT_TIMEOUT, 30);
66
+ if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
67
+ curl_setopt($process, CURLOPT_POSTFIELDS, $data);
68
+ curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
69
+ //curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
70
+ curl_setopt($process, CURLOPT_POST, 1);
71
+ $return = curl_exec($process);
72
+ $error = curl_error($process);
73
+ curl_close($process);
74
+ error_log("lo url: ".$url);
75
+ error_log("lo data: ".$data);
76
+ if( !empty( $error )) {
77
+ return false;
78
+ } else {
79
+ return $return;
80
+ }
81
+ }
82
+
83
+ function error($error) {
84
+ echo "<center><div style='width:500px;border: 3px solid #FFEEFF; padding: 3px; background-color: #FFDDFF;font-family: verdana; font-size: 10px'><b>cURL Error</b><br>$error</div></center>";
85
+ die;
86
+ }
87
+ }
88
+
89
+ ?>
lib/LivrariOnline/lo.php ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ require_once('AES_Encryption.php');
3
+ require_once('padCrypt.php');
4
+ require_once('RSA.php');
5
+ require_once('curl.php');
6
+
7
+ class LO
8
+ {
9
+ //private
10
+ private $f_request = NULL;
11
+ private $f_secure = NULL;
12
+ private $aes_key = NULL;
13
+ private $iv = NULL;
14
+ private $rsa_key = NULL;
15
+
16
+ //definesc erorile standard: nu am putut comunica cu serverul, raspunsul de la server nu este de tip JSON. Restul de erori vin de la server
17
+ private $error = array('server' => 'Nu am putut comunica cu serverul', 'notJSON' => 'Raspunsul primit de la server nu este formatat corect');
18
+
19
+ //public
20
+ public $f_login = NULL;
21
+ public $version = NULL;
22
+
23
+
24
+ //////////////////////////////////////////////////////////////
25
+ // METODE PUBLICE //
26
+ //////////////////////////////////////////////////////////////
27
+
28
+ //setez versiunea de kit
29
+ public function LO(){
30
+ $this->version = "0.1b";
31
+ }
32
+
33
+ //setez cheia RSA
34
+ public function setRSAKey($rsa_key)
35
+ {
36
+ $this->rsa_key = $rsa_key;
37
+ }
38
+
39
+ //////////////////////////////////////////////////////////////
40
+ // METODE COMUNICARE CU SERVER //
41
+ //////////////////////////////////////////////////////////////
42
+
43
+ public function CancelLivrare($f_request)
44
+ {
45
+ return $this->LOCommunicate($f_request, 'http://api.livrarionline.ro/Lobackend.asmx/CancelLivrare');
46
+ }
47
+
48
+ public function GenerateAwb($f_request)
49
+ {
50
+ return $this->LOCommunicate($f_request, 'http://api.livrarionline.ro/Lobackend.asmx/GenerateAwb');
51
+ }
52
+
53
+ public function PrintAwb($f_request,$class,$style)
54
+ {
55
+ return '<a style="'.$style.'" class="'.$class.'" id="print-awb" href="http://api.livrarionline.ro/Lobackend_print/PrintAwb.aspx?f_login='.$this->f_login.'&awb='.$f_request['awb'].'" target="_blank">Click pentru print AWB</a>';
56
+ }
57
+
58
+ public function Tracking($f_request)
59
+ {
60
+ return $this->LOCommunicate($f_request, 'http://api.livrarionline.ro/Lobackend.asmx/Tracking');
61
+ }
62
+
63
+ public function EstimeazaPret($f_request)
64
+ {
65
+ return $this->LOCommunicate($f_request, 'http://estimare.livrarionline.ro/EstimarePret.asmx/EstimeazaPret');
66
+ }
67
+
68
+
69
+ //////////////////////////////////////////////////////////////
70
+ // END METODE COMUNICARE CU SERVER //
71
+ //////////////////////////////////////////////////////////////
72
+
73
+ //helper pentru validarea bifarii unui checkbox si trimiterea de valori boolean catre server
74
+ public function checkboxSelected($value)
75
+ {
76
+ if ($value) return true;
77
+ return false;
78
+ }
79
+
80
+ //////////////////////////////////////////////////////////////
81
+ // END METODE PUBLICE //
82
+ //////////////////////////////////////////////////////////////
83
+
84
+ //////////////////////////////////////////////////////////////
85
+ // METODE PRIVATE //
86
+ //////////////////////////////////////////////////////////////
87
+
88
+ //criptez f_request cu AES
89
+ private function AESEnc()
90
+ {
91
+
92
+ $this->aes_key = md5(uniqid());
93
+ $this->iv = '285c02831e028bff';
94
+ $aes = new AES_Encryption($this->aes_key, $this->iv, "PKCS7", "cbc");
95
+ $this->f_request = bin2hex(base64_encode($aes->encrypt($this->f_request)));
96
+ }
97
+
98
+ //criptez cheia AES cu RSA
99
+ private function RSAEnc()
100
+ {
101
+ $rsa = new Crypt_RSA();
102
+ $rsa->loadKey($this->rsa_key);
103
+ $rsa->setPublicKey();
104
+ $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
105
+ $this->f_secure = base64_encode($rsa->encrypt($this->aes_key));
106
+ }
107
+
108
+ //setez f_request, criptez f_request cu AES si cheia AES cu RSA
109
+ private function setFRequest($f_request)
110
+ {
111
+ $this->f_request = json_encode($f_request);
112
+ $this->AESEnc();
113
+ $this->RSAEnc();
114
+ }
115
+
116
+ //construiesc JSON ce va fi trimis catre server
117
+ private function createJSON()
118
+ {
119
+ $request = array();
120
+
121
+ $request['f_login'] = $this->f_login;
122
+ $request['f_request'] = $this->f_request;
123
+ $request['f_secure'] = $this->f_secure;
124
+
125
+ return json_encode(array('loapi' => $request));
126
+ }
127
+
128
+ //metoda pentru verificarea daca un string este JSON - folosit la primirea raspunsului de la server
129
+ private function isJSON($string) {
130
+ if (is_object(json_decode($string)))
131
+ return true;
132
+ return false;
133
+ }
134
+
135
+ //metoda pentru verificarea raspunsului obtinut de la server. O voi apela cand primesc raspunsul de la server
136
+ private function processResponse($response)
137
+ {
138
+ //daca nu primesc raspuns de la server
139
+ if ($response == FALSE)
140
+ return (object)array('status' => 'error','message' => $this->error['server']);
141
+ else
142
+ {
143
+ //verific daca raspunsul este de tip JSON
144
+ if ($this->isJSON($response))
145
+ {
146
+ $response = json_decode($response);
147
+ return $response->loapi;
148
+ }
149
+ else
150
+ return (object)array('status' => 'error','message' => $response);
151
+ }
152
+ }
153
+
154
+ //metoda comunicare cu server LO
155
+ private function LOCommunicate($f_request, $urltopost)
156
+ {
157
+ $cc = new cURL();
158
+ $this->setFRequest($f_request);
159
+ error_log(urlencode($this->createJSON()));
160
+ $response = $cc->post($urltopost,'loapijson='.urlencode($this->createJSON()));
161
+ return $this->processResponse($response);
162
+ }
163
+
164
+ //////////////////////////////////////////////////////////////
165
+ // END METODE PRIVATE //
166
+ //////////////////////////////////////////////////////////////
167
+ }
168
+ ?>
lib/LivrariOnline/padCrypt.php ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * padCrypt.php
5
+ *
6
+ * This class can be used to pad strings with the following methods:
7
+ * ANSI X.923, ISO 10126, PKCS7, Zero Padding, and Bit Padding
8
+ *
9
+ * The methods are implemented as documented at:
10
+ * http://en.wikipedia.org/wiki/Padding_(cryptography)
11
+ *
12
+ * @author Strategy Star Inc.
13
+ * @website http://www.strategystar.net
14
+ */
15
+
16
+ class padCrypt
17
+ {
18
+ public static function pad_ISO_10126($data, $block_size)
19
+ {
20
+ $padding = $block_size - (strlen($data) % $block_size);
21
+
22
+ for($x=1; $x<$padding; $x++)
23
+ {
24
+ mt_srand();
25
+ $data .= chr(mt_rand(0,255));
26
+ }
27
+
28
+ return $data . chr($padding);
29
+ }
30
+
31
+ public static function unpad_ISO_10126($data)
32
+ {
33
+ $length = ord(substr($data, -1));
34
+ return substr($data, 0, strlen($data)-$length);
35
+ }
36
+
37
+ public static function pad_ANSI_X923($data, $block_size)
38
+ {
39
+ $padding = $block_size - (strlen($data) % $block_size);
40
+ return $data . str_repeat(chr(0), $padding - 1) . chr($padding);
41
+ }
42
+
43
+ public static function unpad_ANSI_X923($data)
44
+ {
45
+ $length = ord(substr($data, -1));
46
+ $padding_position = strlen($data) - $length;
47
+ $padding = substr($data, $padding_position, -1);
48
+
49
+ for($x=0; $x<$length; $x++)
50
+ {
51
+ if(ord(substr($padding, $x, 1)) != 0)
52
+ {
53
+ return $data;
54
+ }
55
+ }
56
+
57
+ return substr($data, 0, $padding_position);
58
+ }
59
+
60
+ public static function pad_PKCS7($data, $block_size)
61
+ {
62
+ $padding = $block_size - (strlen($data) % $block_size);
63
+ $pattern = chr($padding);
64
+ return $data . str_repeat($pattern, $padding);
65
+ }
66
+
67
+ public static function unpad_PKCS7($data)
68
+ {
69
+ $pattern = substr($data, -1);
70
+ $length = ord($pattern);
71
+ $padding = str_repeat($pattern, $length);
72
+ $pattern_pos = strlen($data) - $length;
73
+
74
+ if(substr($data, $pattern_pos) == $padding)
75
+ {
76
+ return substr($data, 0, $pattern_pos);
77
+ }
78
+
79
+ return $data;
80
+ }
81
+
82
+ public static function pad_BIT($data, $block_size)
83
+ {
84
+ $length = $block_size - (strlen($data) % $block_size) - 1;
85
+ return $data . "\x80" . str_repeat("\x00", $length);
86
+ }
87
+
88
+ public static function unpad_BIT($data)
89
+ {
90
+ if(substr(rtrim($data, "\x00"), -1) == "\x80")
91
+ {
92
+ return substr(rtrim($data, "\x00"), 0, -1);
93
+ }
94
+
95
+ return $data;
96
+ }
97
+
98
+ public static function pad_ZERO($data, $block_size)
99
+ {
100
+ $length = $block_size - (strlen($data) % $block_size);
101
+ return $data . str_repeat("\x00", $length);
102
+ }
103
+
104
+ public static function unpad_ZERO($data)
105
+ {
106
+ return rtrim($data, "\x00");
107
+ }
108
+ }
109
+
110
+ ?>
package.xml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package>
3
+ <name>Xtreme_Livrarionline</name>
4
+ <version>1.0.1</version>
5
+ <stability>stable</stability>
6
+ <license>AFL</license>
7
+ <channel>community</channel>
8
+ <extends/>
9
+ <summary>Livrarionline Shipping Module</summary>
10
+ <description>Livrarionline Shipping Module</description>
11
+ <notes>Release 1.0.1</notes>
12
+ <authors><author><name>Michael Mussulis</name><user>mpgjunky</user><email>michael@xtreme-vision.net</email></author></authors>
13
+ <date>2014-06-22</date>
14
+ <time>14:09:39</time>
15
+ <contents><target name="magelocal"><dir name="Xtreme"><dir name="Livrarionline"><dir name="Block"><dir name="Adminhtml"><file name="Awb.php" hash="9d2d4cfc6234d28d2edd1a1ff6358aab"/><dir name="Livrarionline"><dir name="Edit"><file name="Form.php" hash="fed435ef52f3163314fe6cfa7403adc1"/><dir name="Tab"><file name="Form.php" hash="4773539b05a65b97826c9691413f4245"/></dir><file name="Tabs.php" hash="e4ae4f673b0f52d4971c31f93cc13ce1"/></dir><file name="Edit.php" hash="95acb7075f12d585c286e167fa1e885c"/><file name="Grid.php" hash="209f8bd6cbf46e1d19c731e64c3e7916"/></dir><file name="Livrarionline.php" hash="9eda429609e65c0d0d80d54058f50fa0"/><dir name="Manageawb"><dir name="Edit"><file name="Form.php" hash="8fa5b897bea24b00038167a505a98a95"/><dir name="Tab"><file name="Form.php" hash="38ad835938c854f4abe293cb6a5afb47"/></dir><file name="Tabs.php" hash="cff04c9f6b112142eb7e1aa89d0a3f0b"/></dir><file name="Edit.php" hash="a0f548bfaaf8fcc11162a498de94cd2c"/><file name="Grid.php" hash="90c27e079c0005a4988e977e4324a1a1"/></dir><file name="Manageawb.php" hash="f60a4880954ad6ba8dfcdd67c0bb2524"/><dir name="Managecarriers"><dir name="Edit"><file name="Form.php" hash="41d2ad5d5e8a40a936bb18fd33937554"/><dir name="Tab"><file name="Form.php" hash="14b4cd2ff87a09ce7b07617560d770fa"/></dir><file name="Tabs.php" hash="b81c9dece587eabcbcd0d1d68c5ef54e"/></dir><file name="Edit.php" hash="aff65206eed9c258d88deadf89ee259c"/><file name="Grid.php" hash="ae3dd07c521b0104181a9b2f2a2710c6"/></dir><file name="Managecarriers.php" hash="9d5133e3b152a637b579e1f8c4b009dd"/><dir name="Managestores"><dir name="Edit"><file name="Form.php" hash="5a791afbaa1f5b4e48a303b203ccdea1"/><dir name="Tab"><file name="Form.php" hash="e250545876e728336f065956fee16ec2"/></dir><file name="Tabs.php" hash="ca6fd50a89122bbd45385f3f4b9748c0"/></dir><file name="Edit.php" hash="16e33bfa34331a52b3640271b6d75b96"/><file name="Grid.php" hash="582095e1428fee02febec372ff6208b1"/></dir><file name="Managestores.php" hash="67a1b7ef9e0a521083cc7a9f28b2e622"/><dir name="Sales"><dir name="Order"><dir name="View"><dir name="Tab"><file name="Loawb.php" hash="9e545a4a4ce88e15c82db856a87aec22"/></dir></dir><file name="View.php" hash="4a0ae6997cb0298e8014edfb60dd9570"/></dir></dir></dir><file name="Livrarionline.php" hash="e53390b99af3a055f1ef7823c41a9c88"/></dir><dir name="Helper"><file name="Data.php" hash="739b377b4c3cbd472f847237c8a6dcf6"/></dir><dir name="Model"><dir name="Awb"><file name="Parcels.php" hash="0704d7f1c015118bcef206f2487dcd74"/></dir><file name="Awb.php" hash="d15234238a4cf15d9f8811a76b4471e9"/><dir name="Carrier"><file name="Livrarionline.php" hash="b16394add816e3ad1937dfb185296786"/></dir><file name="Carriers.php" hash="1178ea1257801b9acdf17cea64a35c31"/><file name="Livrarionline.php" hash="abbb447eca2b951e6b9d5374becaa286"/><dir name="Mysql4"><dir name="Awb"><file name="Collection.php" hash="c82f68e46b8f3e88615a1ee42d566207"/><dir name="Parcels"><file name="Collection.php" hash="aaad8936e0ed7d0db5359fcdad4cc769"/></dir><file name="Parcels.php" hash="917aa1999a7a932df1d9464297e2ca46"/></dir><file name="Awb.php" hash="c91e1669113296c4d1a6a47a190757d6"/><dir name="Carriers"><file name="Collection.php" hash="e0a8fa7d4c4c01df245c55b198c1e01d"/></dir><file name="Carriers.php" hash="bfb2c975a7360b9e843cf2b619fb6bd7"/><dir name="Livrarionline"><file name="Collection.php" hash="69a03535117e4f503837dfdf1df17701"/></dir><file name="Livrarionline.php" hash="a734b219d52e9104c735092d85451ff2"/><dir name="Stores"><file name="Collection.php" hash="e22d4b45ded32b256347edcc1c0d71d8"/></dir><file name="Stores.php" hash="8fe740e7b14868e9e5d940676530251e"/></dir><file name="Payee.php" hash="19bd933b29a0e5e9ca98061fa8140fae"/><file name="Status.php" hash="fae197ad04c91f5358f2f3633a39e91d"/><file name="Stores.php" hash="36fe8bb37ea66982cc014282dbe3d288"/></dir><dir name="controllers"><dir name="Adminhtml"><file name="AwbController.php" hash="3574d705b941ad7e642375d730d17bb5"/><file name="LivrarionlineController.php" hash="2a68a6dd408f4055e18e13c79cb7e464"/><file name="ManageawbController.php" hash="b058bf0bfc58175a4e90775189c7e6d7"/><file name="ManagecarriersController.php" hash="567a5d5ca374ad4222a6d74499f1d59e"/><file name="ManagestoresController.php" hash="d9864145b3236dd528aa7be7eab5c564"/></dir><file name="IndexController.php" hash="e12312e570bcd609192b7bbf8cfc2f56"/></dir><dir name="etc"><file name="config.xml" hash="183cbafc765524f1ee41c1c8a3f3374b"/><file name="system.xml" hash="bf47955d6c6f11507d85be989319eacb"/></dir><dir name="sql"><dir name="livrarionline_setup"><file name="mysql4-install-0.1.0.php" hash="32a1bdb1003cf070a02206680d93dc0d"/></dir></dir></dir></dir></target><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="layout"><file name="livrarionline.xml" hash="9d33c282fd0e0af9c282431eb8d80e80"/></dir><dir name="template"><dir name="livrarionline"><file name="awb.phtml" hash="bcc4c6f547812c083454a9de591bd773"/><dir name="order"><dir name="view"><dir name="tab"><file name="info.phtml" hash="73d7d9641f299b84a52416cc9ea9cc30"/></dir></dir></dir><dir name="sales"><dir name="order"><dir name="view"><file name="loawb.phtml" hash="5d41402abc4b2a76b9719d911017c592"/></dir></dir></dir></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Xtreme_Livrarionline.xml" hash="709a231ce665b518e80d639e1bbb36bd"/></dir></target><target name="magelib"><dir name="LivrariOnline"><file name="AES.php" hash="785bce6a6f16a78257982888eef38c3f"/><file name="AES_Encryption.php" hash="2379c56d7fead575e314a729eb08c45a"/><file name="Base.php" hash="8414fe454de0aa9bb687d7be5ebc1a1d"/><file name="BigInteger.php" hash="282833739198737256f5daa5a4980344"/><file name="Blowfish.php" hash="75b9feccd3f0d730c585eedc39f7c562"/><file name="DES.php" hash="f8ea721c854715e12c402557c9bcbc65"/><file name="Hash.php" hash="27610ff89b06ea1cf65dc4df11f8b151"/><file name="RC2.php" hash="8524a6ef91d36a6d66b480b2ec35912b"/><file name="RC4.php" hash="3071a0f1750888c542727abf7c5efa0a"/><file name="RSA.php" hash="386f427d09844d490e5e2fe9c2cb02c1"/><file name="Random.php" hash="49d2afb2e4b5e0b74810841c8c1358d9"/><file name="Rijndael.php" hash="563223c4317a65524cd835139a95fe51"/><file name="TripleDES.php" hash="6db830eb88670893fc0b2bc45383b9ee"/><file name="Twofish.php" hash="144f4213aae9f769d5a9e0e769ca1c7f"/><file name="curl.php" hash="b16cd9067b84c48faf7b8bc787d92a5b"/><file name="lo.php" hash="d956c94099d41c190d474e23c92b0bc5"/><file name="padCrypt.php" hash="6d8f31d865a5011abbc02206df45f165"/></dir></target><target name="mage"><dir name="js"><dir name="livrarionline"><file name="jquery-1.11.1.min.js" hash="8101d596b2b8fa35fe3a634ea342d7c3"/><file name="jquery.noconflict.js" hash="10bdc1b7f2effa529e5baae786007688"/></dir></dir></target></contents>
16
+ <compatible/>
17
+ <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
18
+ </package>