ImageRecycle_image_pdf_optimize - Version 2.0.0

Version Notes

Background optimization
Account creation in plugin

Download this release

Release Info

Developer ImageRecycle
Extension ImageRecycle_image_pdf_optimize
Version 2.0.0
Comparing to
See all releases


Code changes from version 1.0.6 to 2.0.0

Files changed (59) hide show
  1. app/code/community/Imagerecycle/Imagerecycle/Block/Images.php +338 -274
  2. app/code/community/Imagerecycle/Imagerecycle/Block/Notifications.php +18 -0
  3. app/code/community/Imagerecycle/Imagerecycle/Block/Settings.php +66 -0
  4. app/code/community/Imagerecycle/Imagerecycle/Helper/Data.php +114 -23
  5. app/code/community/Imagerecycle/Imagerecycle/Model/Notification.php +21 -0
  6. app/code/community/Imagerecycle/Imagerecycle/Model/Observer.php +196 -69
  7. app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Images.php +5 -5
  8. app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Images/Collection.php +0 -6
  9. app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Setup.php +4 -4
  10. app/code/community/Imagerecycle/Imagerecycle/classes/ioa.class.php +270 -220
  11. app/code/community/Imagerecycle/Imagerecycle/controllers/ImageAllController.php +381 -0
  12. app/code/community/Imagerecycle/Imagerecycle/controllers/IndexController.php +317 -166
  13. app/code/community/Imagerecycle/Imagerecycle/etc/adminhtml.xml +14 -14
  14. app/code/community/Imagerecycle/Imagerecycle/etc/config.xml +44 -0
  15. app/code/community/Imagerecycle/Imagerecycle/sql/imagerecycle_setup/mysql4-install-1.0.0.php +20 -18
  16. app/design/adminhtml/default/default/layout/imagerecycle_imagerecycle.xml +40 -12
  17. app/design/adminhtml/default/default/template/imagerecycle/imagerecycle/connect.phtml +70 -0
  18. app/design/adminhtml/default/default/template/imagerecycle/imagerecycle/images.phtml +322 -371
  19. app/design/adminhtml/default/default/template/imagerecycle/imagerecycle/listing.phtml +325 -0
  20. app/design/adminhtml/default/default/template/imagerecycle/imagerecycle/settings.phtml +389 -0
  21. app/etc/modules/Imagerecycle_ImageRecycle.xml +9 -9
  22. js/imagerecycle/imagerecycle/bluebox.js +0 -263
  23. js/imagerecycle/imagerecycle/config.js +199 -0
  24. js/imagerecycle/imagerecycle/jaofiletree.js +210 -0
  25. js/imagerecycle/imagerecycle/jquery.min.js +2 -4
  26. js/imagerecycle/imagerecycle/jquery.reveal.js +160 -0
  27. js/imagerecycle/imagerecycle/script.js +423 -217
  28. js/imagerecycle/imagerecycle/thickbox.js +334 -0
  29. package.xml +14 -12
  30. skin/adminhtml/default/default/imagerecycle/imagerecycle/imagerecycle.css +434 -448
  31. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/application.png +0 -0
  32. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/code.png +0 -0
  33. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/css.png +0 -0
  34. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/db.png +0 -0
  35. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/directory.png +0 -0
  36. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/doc.png +0 -0
  37. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/drive.png +0 -0
  38. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/file.png +0 -0
  39. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/film.png +0 -0
  40. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/flash.png +0 -0
  41. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/folder_open.png +0 -0
  42. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/html.png +0 -0
  43. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/java.png +0 -0
  44. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/linux.png +0 -0
  45. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/loadingAnimation.gif +0 -0
  46. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/music.png +0 -0
  47. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/php.png +0 -0
  48. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/picture.png +0 -0
  49. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/ppt.png +0 -0
  50. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/psd.png +0 -0
  51. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/ruby.png +0 -0
  52. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/script.png +0 -0
  53. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/spinner.gif +0 -0
  54. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/txt.png +0 -0
  55. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/xls.png +0 -0
  56. skin/adminhtml/default/default/imagerecycle/imagerecycle/images/zip.png +0 -0
  57. skin/adminhtml/default/default/imagerecycle/imagerecycle/jaofiletree.css +168 -0
  58. skin/adminhtml/default/default/imagerecycle/imagerecycle/reveal.css +38 -0
  59. skin/adminhtml/default/default/imagerecycle/imagerecycle/thickbox.css +143 -0
app/code/community/Imagerecycle/Imagerecycle/Block/Images.php CHANGED
@@ -1,274 +1,338 @@
1
- <?php
2
-
3
- Class Imagerecycle_Imagerecycle_Block_Images extends Mage_Page_Block_Html {
4
-
5
- private $allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
6
- private $ignoredPath = array('app', 'var', 'cache', 'adminhtml', '.', '..');
7
- protected $totalImages = 0;
8
- protected $totalFile = 0;
9
- protected $time_elapsed_secs = 0;
10
- protected $totalOptimizedImages = 0;
11
- protected $limit = 30;
12
- protected $page_show = 10;
13
- protected $order_by = '';
14
- protected $order_dir = 'asc';
15
-
16
- public function __construct() {
17
- parent::__construct();
18
- //Include ioaphp class once
19
- include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
20
- //Get settings
21
- $this->settings = array(
22
- 'api_key' => Mage::getStoreConfig('mageio_api_key'),
23
- 'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
24
- 'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
25
- 'exclude_folders' => Mage::getStoreConfig('mageio_exclude_folders'),
26
- 'resize_auto' => Mage::getStoreConfig('mageio_resize_auto'),
27
- 'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
28
- 'min_size' => Mage::getStoreConfig('mageio_min_size'),
29
- 'max_size' => Mage::getStoreConfig('mageio_max_size'),
30
- 'compression_type_pdf' => Mage::getStoreConfig('mageio_compression_type_pdf'),
31
- 'compression_type_png' => Mage::getStoreConfig('mageio_compression_type_png'),
32
- 'compression_type_jpg' => Mage::getStoreConfig('mageio_compression_type_jpg'),
33
- 'compression_type_gif' => Mage::getStoreConfig('mageio_compression_type_gif'),
34
- 'compression_type' => Mage::getStoreConfig('mageio_compression_type'),
35
- );
36
-
37
- if(empty($this->settings['compression_type']) ) { $this->settings['compression_type'] = 'lossy'; }
38
- if (!empty($this->settings['exclude_folders'])) {
39
- $this->ignoredPath = explode(',',$this->settings['exclude_folders']);
40
- array_unshift($this->ignoredPath, '.');
41
- array_unshift($this->ignoredPath, './');
42
- }else {
43
- $this->settings['exclude_folders'] = "app,var,cache,adminhtml";
44
- }
45
-
46
- for($i=0;$i<count($this->allowed_ext); $i++) {
47
- $compression_type = $this->settings['compression_type_'.$this->allowed_ext[$i]];
48
- if($compression_type=="none") {
49
- unset($this->allowed_ext[$i]);
50
- }
51
- }
52
- $this->allowed_ext = array_values($this->allowed_ext);
53
-
54
- //Get current page
55
- $requestParams = $this->getRequest()->getParams();
56
- $page = !empty($requestParams['page']) ? abs((int) $requestParams['page']) : 1;
57
- $this->page = $page;
58
- }
59
-
60
- public function getImages() {
61
-
62
- $images = $this->_getLocalImages();
63
- $numberOfPage = $this->totalImages / $this->limit;
64
- $totalPages = is_int($numberOfPage) ? $numberOfPage : (floor($numberOfPage) + 1);
65
- if ($this->page > $totalPages)
66
- $this->page = $totalPages;
67
- $this->pagination = $this->buildPager($this->totalImages);
68
-
69
- $images = $this->prepareLocalImages($images);
70
-
71
- return $images;
72
- }
73
-
74
- public function prepareLocalImages($images) {
75
- //process data before display
76
- $requestParams = $this->getRequest()->getParams();
77
- $filter_fields = array('filename','size', 'status');
78
- if( !empty($requestParams['order_by']) && in_array($requestParams['order_by'], $filter_fields)) {
79
- $order_by = $requestParams['order_by'];
80
- if(isset($requestParams['dir']) && $requestParams['dir']=='desc') {
81
- $this->order_dir = 'desc';
82
- }else {
83
- $this->order_dir = 'asc';
84
- }
85
- } else {
86
- $order_by = '' ;//default - image path
87
- }
88
- $this->order_by = $order_by;
89
-
90
- if($order_by == 'size') {
91
- usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpSize") );
92
- }else if($order_by == 'status') {
93
- usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpStatus"));
94
- }else if($order_by == 'filename' && $this->order_dir == 'desc') {
95
- usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpNameDesc"));
96
- }
97
-
98
- $start = ($this->page - 1) * $this->limit;
99
- $result = array_slice($images, $start, $this->limit);
100
-
101
- return $result;
102
- }
103
-
104
- public function _getLocalImages() {
105
-
106
- $optimizedFiles = array();
107
- $resourceR = $this->getCoreRead('imagerecycle/images');
108
- $sql = "SELECT file,size_before FROM `{$resourceR->tableName}`";
109
- $optimizedFiles = $resourceR->fetchAssoc($sql);
110
-
111
- $this->totalOptimizedImages = count($optimizedFiles);
112
- $min_size = isset($this->settings['min_size']) ? (int)$this->settings['min_size']*1024 : 1* 1024;
113
- $max_size = !empty($this->settings['max_size']) ? (int)$this->settings['max_size'] * 1024 : 10000 * 1024;
114
- $images = array();
115
-
116
- $base_dir = Mage::getBaseDir();
117
- // Set a flag to prevent scanning over and over again by request
118
- Mage::getSingleton('core/session')->setData('scanning_local_images', true);
119
- $start = microtime(true);
120
- clearstatcache(); $counter = 0;
121
- foreach (new RecursiveIteratorIterator(new IgnorantRecursiveDirectoryIterator($base_dir)) as $filename) {
122
- $continue = false;
123
- $this->totalFile++;
124
- // if( $counter > 100 ) break;
125
- foreach ($this->ignoredPath as $ignore_path) {
126
- $ignore_path = DIRECTORY_SEPARATOR . $ignore_path . DIRECTORY_SEPARATOR;
127
- if (strpos(substr($filename, strlen($base_dir)), $ignore_path) === 0 || strpos(substr($filename, strlen($base_dir)), DIRECTORY_SEPARATOR . 'adminhtml' . DIRECTORY_SEPARATOR) !== FALSE) {
128
- $continue = true;
129
- continue;
130
- }
131
- }
132
- if ($continue === true) {
133
- continue;
134
- }
135
-
136
- if (!in_array(strtolower(pathinfo($filename, PATHINFO_EXTENSION)), $this->allowed_ext)) {
137
- continue;
138
- }
139
-
140
- if(filesize($filename) < $min_size || filesize($filename) > $max_size ) {
141
- continue;
142
- }
143
- $data = array();
144
- $data['filename'] = str_replace('\\', '/', substr($filename, strlen($base_dir) + 1));
145
- $data['size'] = filesize($filename);
146
- $data['filetype'] = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
147
- if (isset($optimizedFiles[$data['filename']]) ) {
148
- $data['optimized'] = true;
149
- $data['optimized_datas'] = $optimizedFiles[$data['filename']];
150
- } else {
151
- $data['optimized'] = false;
152
- }
153
- $this->totalImages++;
154
-
155
- $images[] = $data; $counter++;
156
- }
157
- $this->time_elapsed_secs = microtime(true) - $start;
158
- //Unset image scanning in local flag
159
- Mage::getSingleton('core/session')->unsetData('scanning_local_images');
160
-
161
- return $images;
162
- }
163
-
164
- private function cmpStatus($a, $b)
165
- {
166
- if ($a['optimized'] == $b['optimized']) {
167
- return strcmp($a['filename'], $b['filename']);
168
- }
169
-
170
- if( $this->order_dir=='asc') {
171
- return strcmp($a['optimized'], $b['optimized']);
172
- }else {
173
- return strcmp($b['optimized'], $a['optimized']);
174
- }
175
- }
176
-
177
- private function cmpSize($a, $b)
178
- {
179
- if ($a['size'] == $b['size']) {
180
- return strcmp($a['filename'], $b['filename']);
181
- }
182
- if( $this->order_dir=='asc') {
183
- return ($a['size'] < $b['size']) ? -1 : 1;
184
- }else {
185
- return ($a['size'] < $b['size']) ? 1 : -1;
186
- }
187
- }
188
- private function cmpNameDesc($a, $b)
189
- {
190
- return strcmp($b['filename'], $a['filename']);
191
- }
192
-
193
- public function getTotalImages() {
194
- return $this->totalImages;
195
- }
196
-
197
- public function getTotalOptimizedImages() {
198
- return $this->totalOptimizedImages;
199
- }
200
-
201
- protected function buildPager($total) {
202
- $pagination = new stdClass();
203
-
204
- $numb = $total / $this->limit;
205
- if ($numb > 1) {
206
- if (!is_float($numb)) {
207
- $total_page = $numb;
208
- } else {
209
- $total_page = ceil($numb);
210
- }
211
- } else {
212
- $total_page = 1;
213
- }
214
-
215
- if ($total_page > $this->page_show) {
216
- $t_floor = floor($total_page / $this->page_show) + 1;
217
- $p_floor = floor($this->page / $this->page_show) + ($this->page % $this->page_show == 0 ? 0 : 1);
218
-
219
- if ($p_floor < $t_floor) {
220
- $pagination->range = range($p_floor * $this->page_show - ($this->page_show - 1), $p_floor * $this->page_show);
221
- } elseif ($p_floor = $t_floor) {
222
- $pagination->range = range(($p_floor - 1) * $this->page_show, $total_page);
223
- }
224
- } else {
225
- $pagination->range = range(1, $total_page);
226
- }
227
-
228
- $pagination->start = 1;
229
- $pagination->prev = $this->page > 1 ? $this->page - 1 : 1;
230
- $pagination->next = $this->page < $total_page ? $this->page + 1 : $total_page;
231
- $pagination->end = $total_page;
232
- $pagination->current = $this->page;
233
-
234
- #debug($pagination);
235
- return (int) $total_page > 1 ? $pagination : 0;
236
- }
237
-
238
- public function getCoreRead($entityId) {
239
- $resource = Mage::getSingleton('core/resource');
240
- $resourceR = $resource->getConnection('core_read');
241
- $tableName = $resource->getTableName($entityId);
242
- $resourceR->tableName = $tableName;
243
- return $resourceR;
244
- }
245
-
246
- public function getCoreWrite($entityId) {
247
- $resource = Mage::getSingleton('core/resource');
248
- $resourceW = $resource->getConnection('core_write');
249
- $tableName = $resource->getTableName($entityId);
250
- $resourceW->tableName = $tableName;
251
- return $resourceW;
252
- }
253
-
254
- public function getDataIgnore($key, $default = null) {
255
- return isset($this->{$key}) ? $this->{$key} : $default;
256
- }
257
-
258
- protected function trimToLower(&$string) {
259
- return strtolower(trim($string));
260
- }
261
-
262
- }
263
-
264
- class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
265
-
266
- function getChildren() {
267
- try {
268
- return new IgnorantRecursiveDirectoryIterator($this->getPathname());
269
- } catch (UnexpectedValueException $e) {
270
- return new RecursiveArrayIterator(array());
271
- }
272
- }
273
-
274
- }
1
+ <?php
2
+
3
+ Class Imagerecycle_Imagerecycle_Block_Images extends Mage_Page_Block_Html {
4
+
5
+ private $allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
6
+ private $ignoredPath = array('app', 'var', 'cache', 'adminhtml', '.', '..');
7
+ private $allowedPath = "";
8
+ protected $totalImages = 0;
9
+ protected $totalFile = 0;
10
+ protected $time_elapsed_secs = 0;
11
+ protected $totalOptimizedImages = 0;
12
+ protected $limit = 30;
13
+ protected $page_show = 10;
14
+ protected $order_by = '';
15
+ protected $order_dir = 'asc';
16
+
17
+ public function __construct() {
18
+ parent::__construct();
19
+ //Include ioaphp class once
20
+ include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
21
+ //Get settings
22
+ $this->settings = array(
23
+ 'api_key' => Mage::getStoreConfig('mageio_api_key'),
24
+ 'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
25
+ 'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
26
+ 'include_folders' => Mage::getStoreConfig('mageio_include_folders'),
27
+ 'saving_auto' => Mage::getStoreConfig('mageio_saving_auto'),
28
+ 'compress_auto' => Mage::getStoreConfig('mageio_compress_auto'),
29
+ 'resize_auto' => Mage::getStoreConfig('mageio_resize_auto'),
30
+ 'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
31
+ 'min_size' => Mage::getStoreConfig('mageio_min_size'),
32
+ 'max_size' => Mage::getStoreConfig('mageio_max_size'),
33
+ 'compression_type_pdf' => Mage::getStoreConfig('mageio_compression_type_pdf'),
34
+ 'compression_type_png' => Mage::getStoreConfig('mageio_compression_type_png'),
35
+ 'compression_type_jpg' => Mage::getStoreConfig('mageio_compression_type_jpg'),
36
+ 'compression_type_jpeg' => Mage::getStoreConfig('mageio_compression_type_jpeg'),
37
+ 'compression_type_gif' => Mage::getStoreConfig('mageio_compression_type_gif'),
38
+ 'compression_type' => Mage::getStoreConfig('mageio_compression_type'),
39
+ );
40
+
41
+ $this->allowedPath = explode(',',$this->settings['include_folders']);
42
+
43
+ for($i=0;$i<count($this->allowed_ext); $i++) {
44
+ $compression_type = $this->settings['compression_type_'.$this->allowed_ext[$i]];
45
+ if($compression_type=="none") {
46
+ unset($this->allowed_ext[$i]);
47
+ }
48
+ }
49
+ $this->allowed_ext = array_values($this->allowed_ext);
50
+ //Get current page
51
+ $requestParams = $this->getRequest()->getParams();
52
+ $page = !empty($requestParams['page']) ? abs((int) $requestParams['page']) : 1;
53
+ $this->page = $page;
54
+ }
55
+ /*Load Image from Database
56
+ *@ Return Loaded and searched images
57
+ */
58
+ public function loadImage($name,$type,$size,$status){
59
+ $images = array();
60
+ $resourceR = $this->getCoreRead('imagerecycle/images');
61
+ $where = "";
62
+ //Path condition
63
+
64
+ if(count($this->allowedPath) != 0){
65
+ $i = 0;
66
+ foreach($this->allowedPath as $path){
67
+ if(!$path) return $images;
68
+ $i++;
69
+ $where .= ($i == 1)? " WHERE file LIKE CONCAT(".$resourceR->quote($path).",'%')" :" OR file LIKE CONCAT(".$resourceR->quote($path).",'%')";
70
+ }
71
+ $sql = "(SELECT * FROM `{$resourceR->tableName}`".$where.") AS tbl";
72
+ }
73
+ $where1 = " WHERE tbl.id > 0";
74
+
75
+ if($name){
76
+ $where1 .= " AND tbl.file LIKE CONCAT('%',".$resourceR->quote($name).",'%')";
77
+ }
78
+ if($type){
79
+ $where1 .= " AND tbl.ext LIKE CONCAT('%',".$resourceR->quote($type).")";
80
+ }
81
+
82
+ if($status == "opt") $where1 .= " AND tbl.extension = '1'";
83
+ else if($status == "unopt") $where1 .= " AND tbl.extension = ''";
84
+ $sqll = "SELECT * FROM ".$sql .$where1;
85
+ $images = $resourceR->fetchAssoc($sqll);
86
+ $this->totalImages = count($images);
87
+ $numberOfPage = $this->totalImages / $this->limit;
88
+ $totalPages = is_int($numberOfPage) ? $numberOfPage : (floor($numberOfPage) + 1);
89
+ if ($this->page > $totalPages)
90
+ $this->page = $totalPages;
91
+ $this->pagination = $this->buildPager($this->totalImages);
92
+ $images = $this->prepareLocalImages($images);
93
+ return $images;
94
+ }
95
+
96
+ public function alterversion(){
97
+
98
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
99
+ //be careful if file exist
100
+ $dbname = Mage::getConfig()->getResourceConnectionConfig('default_setup')->dbname;
101
+ $sql = "SELECT IF ( EXISTS (SELECT * FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = '".$dbname. "' AND `TABLE_NAME` = '".$resourceW->tableName."' AND `COLUMN_NAME` = 'name' ),1, 0)";
102
+ $record7 = $resourceW->fetchOne($sql);
103
+
104
+ if(!$record7) // if table alreday exist and the table is old version
105
+ {
106
+ $resourceW->query("ALTER TABLE `{$resourceW->tableName}` ADD (`name` VARCHAR(250) NOT NULL,`ext` VARCHAR(250) NOT NULL)");
107
+ $images = $resourceW->fetchAssoc("SELECT * FROM `{$resourceW->tableName}`");
108
+ foreach($images as $image){
109
+ $filetype = strtolower(pathinfo($image['file'], PATHINFO_EXTENSION));
110
+ $name = substr($image['file'], strrpos($image['file'], "/")+1);
111
+ $name = substr($name, 0, strrpos($name, '.'));
112
+
113
+ $resourceW->query("UPDATE `{$resourceW->tableName}` SET `extension` ='1', `name` =".$resourceW->quote($name).", `ext` =".$resourceW->quote($filetype)." WHERE `id` = " .$resourceW->quote($image['id']));
114
+ }
115
+
116
+ }
117
+
118
+ }
119
+
120
+ public function prepareLocalImages($images) {
121
+ //process data before display
122
+ $requestParams = $this->getRequest()->getParams();
123
+ $filter_fields = array('filename','size', 'status');
124
+ if( !empty($requestParams['order_by']) && in_array($requestParams['order_by'], $filter_fields)) {
125
+ $order_by = $requestParams['order_by'];
126
+ if(isset($requestParams['dir']) && $requestParams['dir']=='desc') {
127
+ $this->order_dir = 'desc';
128
+ }else {
129
+ $this->order_dir = 'asc';
130
+ }
131
+ } else {
132
+ $order_by = '' ;
133
+ }
134
+ $this->order_by = $order_by;
135
+
136
+ if($order_by == 'size') {
137
+ usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpSize") );
138
+ }else if($order_by == 'status') {
139
+ usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpStatus"));
140
+ }else if($order_by == 'filename' && $this->order_dir == 'desc') {
141
+ usort($images, array("Imagerecycle_Imagerecycle_Block_Images","cmpNameDesc"));
142
+ }
143
+
144
+ $start = ($this->page - 1) * $this->limit;
145
+ $result = array_slice($images, $start, $this->limit);
146
+
147
+ return $result;
148
+ }
149
+
150
+ public function _getLocalImages() {
151
+
152
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
153
+
154
+ $min_size = isset($this->settings['min_size']) ? (int)$this->settings['min_size']*1024 : 1* 1024;
155
+ $max_size = !empty($this->settings['max_size']) ? (int)$this->settings['max_size'] * 1024 : 10000 * 1024;
156
+ $images = array();
157
+
158
+ if(Mage::getStoreConfig('mageio_include_folders') == '')
159
+ $base_dir = Mage::getBaseDir();
160
+ else
161
+ $base_dir = Mage::getBaseDir().DIRECTORY_SEPARATOR;
162
+
163
+ // Set a flag to prevent scanning over and over again by request
164
+ Mage::getSingleton('core/session')->setData('scanning_local_images', true);
165
+ $start = microtime(true);
166
+ clearstatcache(); $counter = 0;
167
+ foreach($this->allowedPath as $base){
168
+ $base = $base_dir . $base;
169
+
170
+ if (!file_exists($base)) {
171
+ continue;
172
+ }
173
+ foreach (new RecursiveIteratorIterator(new IgnorantRecursiveDirectoryIterator($base)) as $filename) {
174
+ $continue = false;
175
+ $this->totalFile++;
176
+ foreach ($this->ignoredPath as $ignore_path) {
177
+ $ignore_path = DIRECTORY_SEPARATOR . $ignore_path . DIRECTORY_SEPARATOR;
178
+ if (strpos(substr($filename, strlen($base)), $ignore_path) === 0 || strpos(substr($filename, strlen($base)), DIRECTORY_SEPARATOR . 'adminhtml' . DIRECTORY_SEPARATOR) !== FALSE) {
179
+ $continue = true;
180
+ continue;
181
+ }
182
+ }
183
+ if ($continue === true) {
184
+ continue;
185
+ }
186
+ if (!in_array(strtolower(pathinfo($filename, PATHINFO_EXTENSION)), $this->allowed_ext)) {
187
+ continue;
188
+ }
189
+
190
+ if(filesize($filename) < $min_size || filesize($filename) > $max_size ) {
191
+ continue;
192
+ }
193
+
194
+ $data = array();
195
+ if(Mage::getStoreConfig('mageio_include_folders') == ''){
196
+ $data['filename'] = str_replace('\\', '/', substr($filename, strlen($base_dir) + 1));
197
+ }
198
+ else{
199
+ $data['filename'] = str_replace('\\', '/', substr($filename, strlen($base_dir)));
200
+ }
201
+
202
+ $data['size'] = filesize($filename);
203
+ $data['filetype'] = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
204
+
205
+ $this->totalImages++;
206
+ $images[] = $data; $counter++;
207
+
208
+ $id = $resourceW->fetchOne("SELECT id FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($data['filename']));
209
+ if (!$id) {
210
+ $name = substr($data['filename'], strrpos($data['filename'], "/")+1);
211
+ $name = substr($name, 0, strrpos($name, '.'));
212
+ $resourceW->query("INSERT INTO `{$resourceW->tableName}` (`file`, `size_before`, `name`, `ext`) VALUES ("
213
+ . $resourceW->quote($data['filename']) .",". $resourceW->quote($data['size']).",". $resourceW->quote($name). ",".$resourceW->quote($data['filetype']).")");
214
+ }
215
+ }
216
+
217
+ }
218
+ $this->time_elapsed_secs = microtime(true) - $start;
219
+
220
+ $coreConfig = Mage::getConfig();
221
+ $coreConfig->saveConfig('mageio_loadimage', Mage::helper('core')->escapeHtml('on'))->cleanCache();
222
+ //Unset image scanning in local flag
223
+ Mage::getSingleton('core/session')->unsetData('scanning_local_images');
224
+ return $images;
225
+ }
226
+
227
+ private function cmpStatus($a, $b)
228
+ {
229
+ if ($a['optimized'] == $b['optimized']) {
230
+ return strcmp($a['filename'], $b['filename']);
231
+ }
232
+
233
+ if( $this->order_dir=='asc') {
234
+ return strcmp($a['optimized'], $b['optimized']);
235
+ }else {
236
+ return strcmp($b['optimized'], $a['optimized']);
237
+ }
238
+ }
239
+
240
+ private function cmpSize($a, $b)
241
+ {
242
+ if ($a['size'] == $b['size']) {
243
+ return strcmp($a['filename'], $b['filename']);
244
+ }
245
+ if( $this->order_dir=='asc') {
246
+ return ($a['size'] < $b['size']) ? -1 : 1;
247
+ }else {
248
+ return ($a['size'] < $b['size']) ? 1 : -1;
249
+ }
250
+ }
251
+ private function cmpNameDesc($a, $b)
252
+ {
253
+ return strcmp($b['filename'], $a['filename']);
254
+ }
255
+
256
+ public function getTotalImages() {
257
+ return $this->totalImages;
258
+ }
259
+
260
+ public function getTotalOptimizedImages() {
261
+ return $this->totalOptimizedImages;
262
+ }
263
+
264
+ protected function buildPager($total) {
265
+ $pagination = new stdClass();
266
+
267
+ $numb = $total / $this->limit;
268
+ if ($numb > 1) {
269
+ if (!is_float($numb)) {
270
+ $total_page = $numb;
271
+ } else {
272
+ $total_page = ceil($numb);
273
+ }
274
+ } else {
275
+ $total_page = 1;
276
+ }
277
+
278
+ if ($total_page > $this->page_show) {
279
+ $t_floor = floor($total_page / $this->page_show) + 1;
280
+ $p_floor = floor($this->page / $this->page_show) + ($this->page % $this->page_show == 0 ? 0 : 1);
281
+
282
+ if ($p_floor < $t_floor) {
283
+ $pagination->range = range($p_floor * $this->page_show - ($this->page_show - 1), $p_floor * $this->page_show);
284
+ } elseif ($p_floor = $t_floor) {
285
+ $pagination->range = range(($p_floor - 1) * $this->page_show, $total_page);
286
+ }
287
+ } else {
288
+ $pagination->range = range(1, $total_page);
289
+ }
290
+ $pagination->start = 1;
291
+ $pagination->prev = $this->page > 1 ? $this->page - 1 : 1;
292
+ $pagination->next = $this->page < $total_page ? $this->page + 1 : $total_page;
293
+ $pagination->end = $total_page;
294
+ $pagination->current = $this->page;
295
+ return (int) $total_page > 1 ? $pagination : 0;
296
+ }
297
+ public function getCoreRead($entityId) {
298
+ $resource = Mage::getSingleton('core/resource');
299
+ $resourceR = $resource->getConnection('core_read');
300
+ $tableName = $resource->getTableName($entityId);
301
+ $resourceR->tableName = $tableName;
302
+ return $resourceR;
303
+ }
304
+ public function getCoreWrite($entityId) {
305
+ $resource = Mage::getSingleton('core/resource');
306
+ $resourceW = $resource->getConnection('core_write');
307
+ $tableName = $resource->getTableName($entityId);
308
+ $resourceW->tableName = $tableName;
309
+ return $resourceW;
310
+ }
311
+ public function getDataIgnore($key, $default = null) {
312
+ return isset($this->{$key}) ? $this->{$key} : $default;
313
+ }
314
+ protected function trimToLower(&$string) {
315
+ return strtolower(trim($string));
316
+ }
317
+
318
+ public function getOptimizedImages(){
319
+
320
+ $resourceR = $this->getCoreRead('imagerecycle/images');
321
+ $sql = "SELECT COUNT(*) AS `num` FROM `{$resourceR->tableName}` where `extension` = '1'";
322
+ $optimizedCount = $resourceR->fetchOne($sql);
323
+ return $optimizedCount;
324
+
325
+ }
326
+ }
327
+
328
+ class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
329
+
330
+ function getChildren() {
331
+ try {
332
+ return new IgnorantRecursiveDirectoryIterator($this->getPathname());
333
+ } catch (UnexpectedValueException $e) {
334
+ return new RecursiveArrayIterator(array());
335
+ }
336
+ }
337
+
338
+ }
app/code/community/Imagerecycle/Imagerecycle/Block/Notifications.php ADDED
@@ -0,0 +1,18 @@
1
+ <?php
2
+
3
+ Class Imagerecycle_Imagerecycle_Block_Notifications extends Mage_Adminhtml_Block_Template
4
+ {
5
+ public function _toHtml($className = "notification-global")
6
+ {
7
+ // Let other extensions add messages
8
+ Mage::dispatchEvent('imagerecycle_notifications_before');
9
+ // Get the global notification object
10
+ $messages = Mage::getSingleton('imagerecycle/notification')->getMessages();
11
+ $html = null;
12
+ foreach ($messages as $message) {
13
+ $html .= "<div class='$className'>" . $message . "</div>";
14
+ } /* */
15
+ return $html;
16
+ }
17
+ }
18
+
app/code/community/Imagerecycle/Imagerecycle/Block/Settings.php ADDED
@@ -0,0 +1,66 @@
1
+ <?php
2
+
3
+ Class Imagerecycle_Imagerecycle_Block_Settings extends Mage_Page_Block_Html {
4
+
5
+ private $allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
6
+ private $ignoredPath = array('app', 'var', 'cache', 'adminhtml', '.', '..');
7
+ private $allowedPath = "";
8
+
9
+ public function __construct() {
10
+ parent::__construct();
11
+ //Get settings
12
+ $this->settings = array(
13
+ 'api_key' => Mage::getStoreConfig('mageio_api_key'),
14
+ 'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
15
+ 'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
16
+ 'include_folders' => Mage::getStoreConfig('mageio_include_folders'),
17
+ 'reindex_init' => Mage::getStoreConfig('mageio_reindex_init'),
18
+ 'saving_auto' => Mage::getStoreConfig('mageio_saving_auto'),
19
+ 'compress_auto' => Mage::getStoreConfig('mageio_compress_auto'),
20
+ 'cron_periodicity' => Mage::getStoreConfig('mageio_cron_periodicity'),
21
+ 'resize_auto' => Mage::getStoreConfig('mageio_resize_auto'),
22
+ 'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
23
+ 'min_size' => Mage::getStoreConfig('mageio_min_size'),
24
+ 'max_size' => Mage::getStoreConfig('mageio_max_size'),
25
+ 'compression_type_pdf' => Mage::getStoreConfig('mageio_compression_type_pdf'),
26
+ 'compression_type_png' => Mage::getStoreConfig('mageio_compression_type_png'),
27
+ 'compression_type_jpg' => Mage::getStoreConfig('mageio_compression_type_jpg'),
28
+ 'compression_type_jpeg' => Mage::getStoreConfig('mageio_compression_type_jpeg'),
29
+ 'compression_type_gif' => Mage::getStoreConfig('mageio_compression_type_gif'),
30
+ 'compression_type' => Mage::getStoreConfig('mageio_compression_type'),
31
+ );
32
+
33
+ $this->allowedPath = explode(',',$this->settings['include_folders']);
34
+
35
+ for($i=0;$i<count($this->allowed_ext); $i++) {
36
+ $compression_type = $this->settings['compression_type_'.$this->allowed_ext[$i]];
37
+ if($compression_type=="none") {
38
+ unset($this->allowed_ext[$i]);
39
+ }
40
+ }
41
+ $this->allowed_ext = array_values($this->allowed_ext);
42
+
43
+ }
44
+
45
+ public function formateBytes($data)
46
+ {
47
+ if($data < 1024)
48
+ return round($data, 2).'Bytes';
49
+ $data = $data/1024;
50
+ if($data < 1024)
51
+ return round($data, 2).'KB';
52
+ $data = $data/1024;
53
+ if($data < 1024)
54
+ return round($data, 2).'MB';
55
+
56
+ $data = $data/1024;
57
+ return round($data, 2).'GB';
58
+
59
+ }
60
+
61
+ public function senddata()
62
+ {
63
+ return 'hi';
64
+ }
65
+ }
66
+
app/code/community/Imagerecycle/Imagerecycle/Helper/Data.php CHANGED
@@ -3,13 +3,13 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
3
4
private $allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
5
public $settings = null;
6
-
7
public function getSettings() {
8
return array(
9
'api_key' => Mage::getStoreConfig('mageio_api_key'),
10
'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
11
'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
12
- 'exclude_folders' => Mage::getStoreConfig('mageio_exclude_folders'),
13
'resize_auto' => Mage::getStoreConfig('mageio_resize_auto'),
14
'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
15
'min_size' => Mage::getStoreConfig('mageio_min_size'),
@@ -21,8 +21,14 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
21
'compression_type' => Mage::getStoreConfig('mageio_compression_type'),
22
);
23
}
24
- public function optimize($image, $savePath='') {
25
-
26
$response = new stdClass();
27
$response->status = false;
28
$response->msg = Mage::helper('imagerecycle')->__('Not be optimized yet');
@@ -31,7 +37,6 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
31
$response->msg = Mage::helper('imagerecycle')->__('This image type is not allowed');
32
return $response;
33
}
34
-
35
if (!file_exists($file)) {
36
$response->msg = Mage::helper('imagerecycle')->__('File not found');
37
return $response;
@@ -42,13 +47,12 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
42
if(!$this->settings) {
43
$this->settings = $this->getSettings();
44
}
45
- $ext = array_pop( explode('.',$file));
46
$compressionType= $this->settings['compression_type_'.$ext];
47
if($compressionType=='none') return $response;
48
-
49
if (!$this->settings['api_key'] || !$this->settings['api_secret'] )
50
{
51
-
52
$response->msg = Mage::helper('imagerecycle')->__("You haven't configured Image recycle setting correctly yet.");
53
return $response;
54
}
@@ -62,16 +66,22 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
62
$fparams['resize'] = array("width"=> $resize_image);
63
}
64
}
65
-
66
include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
67
$ioa = new ioaphp($this->settings['api_key'], $this->settings['api_secret']);
68
$return = $ioa->uploadFile($file,$fparams);
69
- Mage::log($return);
70
71
if ($return === false || $return === null || is_string($return)) {
72
$response->msg = $ioa->getLastError();
73
return $response;
74
}
75
$md5 = md5_file($file);
76
clearstatcache();
77
$sizebefore = filesize($file);
@@ -88,29 +98,96 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
88
}
89
clearstatcache();
90
$size_after = filesize($file);
91
-
92
- if($savePath=='') { $savePath = $image;}
93
- $id = $resourceW->fetchOne("SELECT id FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($savePath));
94
if (!$id) {
95
- $resourceW->query("INSERT INTO `{$resourceW->tableName}` (`file`,`md5`,`api_id`,`size_before`, `size_after`,`date`) VALUES ("
96
- . $resourceW->quote($savePath) . "," . $resourceW->quote($md5) . "," . $return->id . "," . (int) $sizebefore . "," . (int) $size_after . ", '" . date('Y-m-d H:i:s') . "' )");
97
} else {
98
- $resourceW->query("UPDATE `{$resourceW->tableName}` SET `size_after` = " . (int) $size_after . " WHERE `id` = " . $id);
99
- }
100
-
101
- $response->status = true;
102
-
103
$response->msg = 'Optimized at '. round(($sizebefore-$size_after)/$sizebefore*100,2).'%';
104
$response->newSize = number_format($size_after/1000, 2, '.', '') ;
105
return $response;
106
}
107
108
public function checkOptimize($image) {
109
$resourceW = $this->getCoreWrite('imagerecycle/images');
110
- $id = $resourceW->fetchOne("SELECT id FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($image));
111
return $id;
112
}
113
-
114
/**
115
* Get content of specified resource via curl or file_get_content() function
116
*/
@@ -156,5 +233,19 @@ Class Imagerecycle_Imagerecycle_Helper_Data extends Mage_Core_Helper_Abstract{
156
$resourceW->tableName = $tableName;
157
return $resourceW;
158
}
159
-
160
}
3
4
private $allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
5
public $settings = null;
6
+ private $allowedPath = "";
7
public function getSettings() {
8
return array(
9
'api_key' => Mage::getStoreConfig('mageio_api_key'),
10
'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
11
'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
12
+ 'include_folders' => Mage::getStoreConfig('mageio_include_folders'),
13
'resize_auto' => Mage::getStoreConfig('mageio_resize_auto'),
14
'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
15
'min_size' => Mage::getStoreConfig('mageio_min_size'),
21
'compression_type' => Mage::getStoreConfig('mageio_compression_type'),
22
);
23
}
24
+
25
+ public function getCurImages(){
26
+ $resourceR = $this->getCoreRead('imagerecycle/images');
27
+ $sql = "SELECT COUNT(*) AS `num` FROM `{$resourceR->tableName}` LIMIT 1";
28
+ $optimizedCount = $resourceR->fetchOne($sql);
29
+ return $optimizedCount;
30
+ }
31
+ public function optimize($image) {
32
$response = new stdClass();
33
$response->status = false;
34
$response->msg = Mage::helper('imagerecycle')->__('Not be optimized yet');
37
$response->msg = Mage::helper('imagerecycle')->__('This image type is not allowed');
38
return $response;
39
}
40
if (!file_exists($file)) {
41
$response->msg = Mage::helper('imagerecycle')->__('File not found');
42
return $response;
47
if(!$this->settings) {
48
$this->settings = $this->getSettings();
49
}
50
+ $ext = substr($file, strrpos($file, '.')+1);
51
$compressionType= $this->settings['compression_type_'.$ext];
52
if($compressionType=='none') return $response;
53
+
54
if (!$this->settings['api_key'] || !$this->settings['api_secret'] )
55
{
56
$response->msg = Mage::helper('imagerecycle')->__("You haven't configured Image recycle setting correctly yet.");
57
return $response;
58
}
66
$fparams['resize'] = array("width"=> $resize_image);
67
}
68
}
69
include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
70
$ioa = new ioaphp($this->settings['api_key'], $this->settings['api_secret']);
71
$return = $ioa->uploadFile($file,$fparams);
72
73
if ($return === false || $return === null || is_string($return)) {
74
+
75
+ // patch the event that there is the error
76
+ $event_data_array = array('type' => $ioa->getLastError());
77
+ $this->checkError($response);
78
$response->msg = $ioa->getLastError();
79
return $response;
80
}
81
+ $coreConfig = Mage::getConfig();
82
+ $coreConfig->saveConfig("mageio_errormessage", Mage::helper('core')->escapeHtml(null))->cleanCache();
83
+
84
+ Mage::dispatchEvent('imagerecycle_notifications_before');
85
$md5 = md5_file($file);
86
clearstatcache();
87
$sizebefore = filesize($file);
98
}
99
clearstatcache();
100
$size_after = filesize($file);
101
+
102
+ $id = $resourceW->fetchOne("SELECT id FROM `{$resourceW->tableName}` WHERE `file` = " . $resourceW->quote($image));
103
if (!$id) {
104
+ $resourceW->query("INSERT INTO `{$resourceW->tableName}` (`file`,`md5`,`api_id`,`size_before`, `size_after`,`date`, `extension`) VALUES ("
105
+ . $resourceW->quote($image) . "," . $resourceW->quote($md5) . "," . $resourceW->quote($return->id) . "," . (int) $sizebefore . "," . (int) $size_after . ", '" . date('Y-m-d H:i:s') . "', '1')");
106
} else {
107
+ $resourceW->query("UPDATE `{$resourceW->tableName}` SET `extension` ='1',`api_id` =".$resourceW->quote($return->id) .", `md5` =".$resourceW->quote($md5)." , `size_after` = " . (int) $size_after . " WHERE `id` = " . $resourceW->quote($id));
108
+ }
109
+
110
+ $response->status = true;
111
$response->msg = 'Optimized at '. round(($sizebefore-$size_after)/$sizebefore*100,2).'%';
112
$response->newSize = number_format($size_after/1000, 2, '.', '') ;
113
return $response;
114
}
115
+
116
+ protected function checkError($response){
117
+ $coreConfig = Mage::getConfig();
118
+ $count = Mage::getStoreConfig('mageio_lasterror');
119
+ $count++;
120
+ if($count >= 3){
121
+ $coreConfig->saveConfig("mageio_saving_auto", Mage::helper('core')->escapeHtml('0'));
122
+ $coreConfig->saveConfig("mageio_compress_auto", Mage::helper('core')->escapeHtml('0'));
123
+ $response->error = 'The automatic optimization options of ImageRecycle have been deactivated due to too many consecutive errors. Please check your account on https://www.imagerecycle.com/my-account';
124
+
125
+ $coreConfig->saveConfig("mageio_errormessage", Mage::helper('core')->escapeHtml('on'));
126
+ Mage::dispatchEvent('imagerecycle_notifications_before');
127
+ $count = 0;
128
+ }
129
+ $coreConfig->saveConfig("mageio_lasterror", Mage::helper('core')->escapeHtml($count));
130
+ $coreConfig->cleanCache();
131
+ }
132
+
133
+ public function _revert($image) {
134
+ $response = new stdClass();
135
+ $response->status = false;
136
+ $response->msg = Mage::helper('imagerecycle')->__('Not be reverted yet');
137
+ $resourceR = $this->getCoreRead('imagerecycle/images');
138
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
139
+ $api_id = $resourceR->fetchOne("SELECT api_id FROM {$resourceR->tableName} WHERE `file` = " . $resourceR->quote($image));
140
+ if ($api_id) {
141
+ if(!$this->settings) {
142
+ $this->settings = $this->getSettings();
143
+ }
144
+ $ioa = new ioaphp($this->settings['api_key'], $this->settings['api_secret']);
145
+ $return = $ioa->getImage($api_id);
146
+ if (!isset($return->id)) {
147
+ $response->msg = Mage::helper('imagerecycle')->__('api id is not correct');
148
+ return $response;
149
+ }
150
+ $fileContent = file_get_contents($return->origin_url);
151
+ if ($fileContent === false) {
152
+ $response->msg = Mage::helper('imagerecycle')->__('Image not found');
153
+ return $response;
154
+ }
155
+ $file = realpath($image);
156
+ if (file_put_contents($file, $fileContent) === false) {
157
+ $response->msg = Mage::helper('imagerecycle')->__("Can't write file");
158
+ return $response;
159
+ }
160
+ clearstatcache();
161
+ $size_after = filesize($file);
162
+ $resourceW->query("UPDATE `{$resourceW->tableName}` SET `date` = '' ,`api_id` = '' ,`extension` = '' ,`md5` = '' , `size_after` ='' WHERE api_id = " . $resourceW->quote($api_id));
163
+ $response->newSize = number_format($size_after/1000, 2, '.', '') ;
164
+ $response->status = true;
165
+ $response->msg = Mage::helper('imagerecycle')->__('Reverted');
166
+ }
167
+ return $response;
168
+ }
169
170
public function checkOptimize($image) {
171
+
172
+ // ??? is it possible after the product has been upload but the data is not optimiexe
173
$resourceW = $this->getCoreWrite('imagerecycle/images');
174
+ $id = $resourceW->fetchOne("SELECT `extension` FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($image));
175
return $id;
176
}
177
+
178
+ public function checkOptimizeTmp($image) {
179
+
180
+ // ??? is it possible after the product has been upload but the data is not optimiexe
181
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
182
+ $id = $resourceW->fetchOne("SELECT `id` FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($image));
183
+ return $id;
184
+ }
185
+
186
+ public function updateOptdata($src, $dst){
187
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
188
+ $id = $resourceW->fetchOne("SELECT id FROM `{$resourceW->tableName}` WHERE `file` = " . $resourceW->quote($src));
189
+ $resourceW->query("UPDATE `{$resourceW->tableName}` SET `file` =".$resourceW->quote($dst)." WHERE `id` = " . $resourceW->quote($id));
190
+ }
191
/**
192
* Get content of specified resource via curl or file_get_content() function
193
*/
233
$resourceW->tableName = $tableName;
234
return $resourceW;
235
}
236
+
237
+ public function getLastTime(){
238
+ return Mage::getStoreConfig('mageio_ao_lastRun');
239
+ }
240
+
241
+ public function setLastTime($time){
242
+ $coreConfig = Mage::getConfig();
243
+ $coreConfig->saveConfig("mageio_ao_lastRun", Mage::helper('core')->escapeHtml($time))->cleanCache();
244
+ }
245
+
246
+ public function getStatus(){
247
+ return Mage::getStoreConfig('optimizeall_flag');
248
+ }
249
}
250
+
251
+
app/code/community/Imagerecycle/Imagerecycle/Model/Notification.php ADDED
@@ -0,0 +1,21 @@
1
+ <?php
2
+ class Imagerecycle_Imagerecycle_Model_Notification extends Varien_object{
3
+ protected $messages = [ ];
4
+
5
+ public function getMessages()
6
+ {
7
+ return $this->messages;
8
+ }
9
+
10
+ public function setMessages($messages)
11
+ {
12
+ $this->messages = $messages;
13
+ return $this;
14
+ }
15
+
16
+ public function addMessage($message)
17
+ {
18
+ $this->messages[] = $message;
19
+ return $this;
20
+ }
21
+ }
app/code/community/Imagerecycle/Imagerecycle/Model/Observer.php CHANGED
@@ -1,70 +1,197 @@
1
- <?php
2
- class Imagerecycle_Imagerecycle_Model_Observer {
3
-
4
- public function imageuploaded($observer) {
5
- //$observer contains data passed from when the event was triggered.
6
- //You can use this data to manipulate the order data before it's saved.
7
- //Uncomment the line below to log what is contained here:
8
- $data = $observer->getEvent()->getData();
9
- $picture = $data['result'];
10
- Mage::log($picture);
11
- if(!$picture['error']) {
12
- include_once(__DIR__.'/../Helper/Data.php');
13
- $helper = new Imagerecycle_Imagerecycle_Helper_Data();
14
- $baseMedia = 'media';
15
- $return = $helper->optimize( $baseMedia . '/tmp/catalog/product' .$picture['file'], $baseMedia . '/catalog/product' .$picture['file']);
16
- Mage::log($return);
17
- }
18
- }
19
-
20
- public function productsaved($observer) {
21
- Mage::log('product after saved!');
22
- $productId = $observer->getProduct()->getId();
23
- $model = Mage::getModel('catalog/product');
24
- $_product = $model->load($productId);
25
-
26
- include_once(__DIR__.'/../Helper/Data.php');
27
- $helper = new Imagerecycle_Imagerecycle_Helper_Data();
28
- $baseMedia = 'media';
29
- foreach ($_product->getMediaGalleryImages() as $image) {
30
- $file = $baseMedia . '/catalog/product'. $image['file'];
31
- if(!$helper->checkOptimize($file)) {
32
- $return = $helper->optimize($file);
33
- Mage::log($return);
34
- }
35
- }
36
-
37
- }
38
-
39
- public function categorySaved($observer) {
40
- Mage::log('category after saved!');
41
-
42
- $categoryId = $observer->getEvent()->getCategory()->getId();
43
- $model = Mage::getModel('catalog/category');
44
- $category = $model->load($categoryId);
45
- $image = $category->getImage();
46
- $thumbnail = $category->getThumbnail();
47
-
48
- include_once(__DIR__.'/../Helper/Data.php');
49
- $helper = new Imagerecycle_Imagerecycle_Helper_Data();
50
- $baseMedia = 'media';
51
- if($image!='') {
52
- $file = $baseMedia .'/catalog/category/'. $image;
53
- if(!$helper->checkOptimize($file)) {
54
- $return = $helper->optimize($file);
55
- Mage::log($return);
56
- }
57
- }
58
-
59
- if($thumbnail!='') {
60
- $file = $baseMedia .'/catalog/category/'. $thumbnail;
61
- if(!$helper->checkOptimize($file)) {
62
- $return = $helper->optimize($file);
63
- Mage::log($return);
64
- }
65
- }
66
-
67
- }
68
-
69
- }
70
?>
1
+ <?php
2
+ class Imagerecycle_Imagerecycle_Model_Observer {
3
+
4
+ public function cronexec($observer){
5
+
6
+ //preprocessing
7
+ //count the time 5 mins 10 mins 20mins 30min 1h 2h 6h 12h 24h 48h mageio_compress_auto
8
+ if( Mage::getStoreConfig('mageio_compress_auto') == '2')
9
+ {
10
+ $now = time();
11
+ $ao_lastRun = Mage::getStoreConfig('mageio_crontime');
12
+ $diff= $now - $ao_lastRun;
13
+ $cron_periodiciy = $this->getCronPeriodicity() * 60;
14
+ if($diff < $cron_periodiciy)
15
+ return;
16
+ $this->cronoptall();
17
+ $coreConfig = Mage::getConfig();
18
+ $coreConfig->saveConfig('mageio_crontime', Mage::helper('core')->escapeHtml($now))->cleanCache();
19
+ }
20
+ }
21
+
22
+ public function checkResponse($observer){
23
+ if( Mage::getStoreConfig('mageio_compress_auto') == '1')
24
+ {
25
+ $now = time();
26
+ $ao_lastRun = Mage::getStoreConfig('mageio_runtime_ajax');
27
+ if($now - $ao_lastRun < 3000 ) {
28
+ return;
29
+ }
30
+ $coreConfig = Mage::getConfig();
31
+ $coreConfig->saveConfig('mageio_runtime_ajax', Mage::helper('core')->escapeHtml($now))->cleanCache();
32
+ $this->cronoptall();
33
+ }
34
+ }
35
+ public function imageuploaded($observer) {
36
+
37
+ //$observer contains data passed from when the event was triggered.
38
+ //You can use this data to manipulate the order data before it's saved.
39
+ //Uncomment the line below to log what is contained here:
40
+
41
+ $flag = Mage::getStoreConfig('mageio_saving_auto');
42
+ if(!$flag) return;
43
+
44
+ $data = $observer->getEvent()->getData();
45
+ $picture = $data['result'];
46
+ Mage::log($picture);
47
+ if(!$picture['error']) {
48
+ include_once(__DIR__.'/../Helper/Data.php');
49
+ $helper = new Imagerecycle_Imagerecycle_Helper_Data();
50
+ $baseMedia = 'media';
51
+ $return = $helper->optimize( $baseMedia . '/tmp/catalog/product' .$picture['file'], $baseMedia . '/catalog/product' .$picture['file']);
52
+ Mage::log($return);
53
+ }
54
+
55
+ }
56
+
57
+ public function cronoptall(){
58
+ $now = time();
59
+ $ao_lastRun = Mage::getStoreConfig('mageio_runtime');
60
+ $diff = $now - $ao_lastRun;
61
+ if(Mage::getStoreConfig('mageio_autosettig') == 'On')
62
+ {
63
+ if($now - $ao_lastRun < 1000 ) {
64
+ return;
65
+ }
66
+ }
67
+ $coreConfig = Mage::getConfig();
68
+ $coreConfig->saveConfig("mageio_autosettig", Mage::helper('core')->escapeHtml('On'));
69
+ $coreConfig->saveConfig("mageio_OptResponse", Mage::helper('core')->escapeHtml('On'));
70
+ $coreConfig->saveConfig("mageio_runtime", Mage::helper('core')->escapeHtml($now));
71
+ $coreConfig->cleanCache();
72
+ $this->headRequest();
73
+ /**/
74
+ }
75
+
76
+ public function checkMessages($observer)
77
+ {
78
+ if(Mage::getStoreConfig('mageio_errormessage') == 'on'){
79
+ $notifications = Mage::getSingleton('imagerecycle/notification');
80
+ $notifications->addMessage('The automatic optimization options of ImageRecycle have been deactivated due to too many consecutive errors. Please check your account on <a href = "https://www.imagerecycle.com/my-account">https://www.imagerecycle.com/my-account</a><br/>To remove this message please got to the settings page and save the settings');
81
+ }
82
+ return $observer;
83
+ }
84
+
85
+ public function checkError($observer){
86
+
87
+ $coreConfig = Mage::getConfig();
88
+ $count = Mage::getStoreConfig('mageio_lasterror');
89
+ $count++;
90
+ $coreConfig->saveConfig("mageio_lasterror", Mage::helper('core')->escapeHtml($count))->cleanCache();
91
+ }
92
+
93
+ protected function headRequest(){
94
+ if( function_exists('curl_version')) {
95
+ $ch = curl_init();
96
+ $url = Mage::getBaseUrl().'imagerecycle/ImageAll/index';
97
+ curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
98
+ curl_setopt ($ch, CURLOPT_URL, $url);
99
+ curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
100
+ curl_setopt ($ch, CURLOPT_TIMEOUT_MS, 1000);
101
+ // Only calling the head
102
+ curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output
103
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
104
+ $content = curl_exec ($ch);
105
+ curl_close ($ch);
106
+ }else {
107
+ return;
108
+ }
109
+ }
110
+
111
+ public function productsaved($observer) {
112
+
113
+ $flag = Mage::getStoreConfig('mageio_saving_auto');
114
+ if(!$flag) return;
115
+ $productId = $observer->getProduct()->getId();
116
+ $model = Mage::getModel('catalog/product');
117
+ $_product = $model->load($productId);
118
+
119
+ include_once(__DIR__.'/../Helper/Data.php');
120
+ $helper = new Imagerecycle_Imagerecycle_Helper_Data();
121
+ $baseMedia = 'media';
122
+ foreach ($_product->getMediaGalleryImages() as $image) {
123
+
124
+ $tmpfile = $baseMedia . '/tmp/catalog/product'. $image['file'];
125
+ $file = $baseMedia . '/catalog/product'. $image['file'];
126
+ if($helper->checkOptimizeTmp($tmpfile)) {
127
+ //it may be change
128
+ $helper->updateOptdata($tmpfile,$file);
129
+ }
130
+
131
+ if(!$helper->checkOptimize($file)) {
132
+ $return = $helper->optimize($file);
133
+ Mage::log($return);
134
+ }
135
+ }
136
+
137
+ }
138
+
139
+ public function getCronPeriodicity(){
140
+ $real_timedata = array(5, 10, 20, 30, 60, 120, 360, 720, 1440, 2880);
141
+ $period_data = array('5mins','10mins','20mins', '30min','1h','2h','6h','12h','24h','48h');
142
+ $i = 0;
143
+ $temp = Mage::getStoreConfig('mageio_cron_periodicity');
144
+ foreach($period_data as $period){
145
+ if($temp == $period)
146
+ return $real_timedata[$i];
147
+ $i++;
148
+ }
149
+ }
150
+ public function printdata($data){
151
+
152
+ $fp = fopen('d:/asd.txt', 'a');
153
+ fwrite($fp, $data);
154
+ fclose($fp);
155
+ }
156
+ public function onBackCheckOutAfter($observer){
157
+
158
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
159
+ echo $cutomer_email = $customer->getEmail();
160
+ $orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
161
+ exit;
162
+
163
+ }
164
+
165
+ public function categorySaved($observer) {
166
+
167
+ $flag = Mage::getStoreConfig('mageio_saving_auto');
168
+ if(!$flag) return;
169
+
170
+ $categoryId = $observer->getEvent()->getCategory()->getId();
171
+ $model = Mage::getModel('catalog/category');
172
+ $category = $model->load($categoryId);
173
+ $image = $category->getImage();
174
+ $thumbnail = $category->getThumbnail();
175
+
176
+ include_once(__DIR__.'/../Helper/Data.php');
177
+ $helper = new Imagerecycle_Imagerecycle_Helper_Data();
178
+ $baseMedia = 'media';
179
+ if($image!='') {
180
+ $file = $baseMedia .'/catalog/category/'. $image;
181
+ if(!$helper->checkOptimize($file)) {
182
+ $return = $helper->optimize($file);
183
+ Mage::log($return);
184
+ }
185
+ }
186
+ if($thumbnail!='') {
187
+ $file = $baseMedia .'/catalog/category/'. $thumbnail;
188
+ if(!$helper->checkOptimize($file)) {
189
+ $return = $helper->optimize($file);
190
+ Mage::log($return);
191
+ }
192
+ }
193
+ }
194
+
195
+
196
+ }
197
?>
app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Images.php CHANGED
@@ -1,6 +1,6 @@
1
- <?php
2
- Class Imagerecycle_Imagerecycle_Model_Resource_Images extends Mage_Core_Model_Resource_Db_Abstract{
3
- protected function _construct(){
4
- $this->_init('imagerecycle/images', 'id');
5
- }
6
}
1
+ <?php
2
+ Class Imagerecycle_Imagerecycle_Model_Resource_Images extends Mage_Core_Model_Resource_Db_Abstract{
3
+ protected function _construct(){
4
+ $this->_init('imagerecycle/images', 'id');
5
+ }
6
}
app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Images/Collection.php DELETED
@@ -1,6 +0,0 @@
1
- <?php
2
- Class Imagerecycle_Weblog_Model_Resource_Blogpost_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract{
3
- protected function _construct(){
4
- $this->_init('weblog/blogpost');
5
- }
6
- }
app/code/community/Imagerecycle/Imagerecycle/Model/Resource/Setup.php CHANGED
@@ -1,4 +1,4 @@
1
- <?php
2
- Class Imagerecycle_Imagerecycle_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup{
3
-
4
- }
1
+ <?php
2
+ Class Imagerecycle_Imagerecycle_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup{
3
+
4
+ }
app/code/community/Imagerecycle/Imagerecycle/classes/ioa.class.php CHANGED
@@ -1,221 +1,271 @@
1
- <?php
2
- class ioaphp {
3
- /**
4
- * Authentication values array
5
- * @var array
6
- */
7
- protected $auth = array();
8
-
9
- /**
10
- * Image Optimize API Url
11
- * @var string api url
12
- */
13
- protected $apiUrl = 'https://api.imagerecycle.com/v1/';
14
-
15
- /**
16
- * Last Error message
17
- * @var string
18
- */
19
- protected $lastError = null;
20
-
21
-
22
- /**
23
- *
24
- * @param string $key
25
- * @param string $secret
26
- */
27
- public function __construct($key,$secret){
28
- $this->auth = array('key'=>$key, 'secret'=>$secret);
29
- }
30
-
31
- /**
32
- * Change the API URL
33
- * @param string $url
34
- */
35
- public function setAPIUrl($url){
36
- $this->apiUrl = $url;
37
- }
38
-
39
- /**
40
- * Upload a file sent through an html post form
41
- * @param $_FILES $file posted file
42
- */
43
- public function uploadFile($file,$params=array()){
44
- if(class_exists('CURLFile')){
45
- $curlFile = new CURLFile($file);
46
- }else{
47
- $curlFile = '@'.$file;
48
- }
49
-
50
- $params = array(
51
- 'auth' => json_encode($this->auth),
52
- 'file' => $curlFile,
53
- 'params' => json_encode( $params)
54
- );
55
-
56
- try {
57
- $result = $this->callAPI($this->apiUrl.'images/','POST',$params);
58
-
59
- } catch (Exception $exc) {
60
- $this->lastError = $exc->getMessage();
61
- return $this->lastError;// false;
62
- }
63
-
64
- return $result;
65
- }
66
-
67
- /**
68
- * Upload a file from an url
69
- * @param string $url
70
- * @return Object
71
- */
72
- public function uploadUrl($url,$params=array()){
73
- $params = array(
74
- 'auth' => json_encode($this->auth),
75
- 'url' => $url,
76
- 'params' => json_encode($params)
77
- );
78
- try {
79
- $result = $this->callAPI($this->apiUrl.'images/','POST',$params);
80
- } catch (Exception $exc) {
81
- $this->lastError = $exc->getMessage();
82
- return false;
83
- }
84
- return $result;
85
- }
86
-
87
- /**
88
- * Call the API with curl
89
- * @param string $url
90
- * @param string $type HTTP method
91
- * @param array $datas
92
- * @return type
93
- */
94
- protected function callAPI($url,$type,$datas){
95
- $curl = curl_init();
96
- curl_setopt($curl, CURLOPT_HEADER, 0);
97
- curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 100);
98
- curl_setopt($curl, CURLOPT_TIMEOUT, 100);
99
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
100
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $type);
101
- //fix windows localhost ssl problem
102
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
103
-
104
- if($type==='POST'){
105
- curl_setopt($curl, CURLOPT_POSTFIELDS, $datas);
106
- }else{
107
- $url .= '?'.http_build_query($datas);
108
- }
109
-
110
- curl_setopt($curl, CURLOPT_URL, $url);
111
- $content = curl_exec($curl);
112
- $infos = curl_getinfo($curl);
113
- $infos['http_code'] = (String)$infos['http_code'];
114
-
115
- if($infos['http_code'][0]!=='2'){
116
- $error = json_decode($content);
117
- if(isset($error->errCode)){
118
- $errCode = $error->errCode;
119
- }else{
120
- $errCode = 0;
121
- }
122
- if(isset($error->errMessage)){
123
- $errMessage = $error->errMessage;
124
- }else{
125
- $errMessage = 'An error occurs';
126
- }
127
- throw new Exception($errMessage,$errCode);
128
- }
129
- curl_close($curl);
130
- return json_decode($content);
131
- }
132
-
133
- /**
134
- * Get all the images
135
- * @return type
136
- */
137
- public function getImagesList($offset=0, $limit=30){
138
- $params = array(
139
- 'auth' => json_encode($this->auth),
140
- 'params' => '',
141
- 'offset' => $offset,
142
- 'limit' => $limit
143
- );
144
-
145
- try {
146
- $result = $this->callAPI($this->apiUrl.'images/','GET',$params);
147
- } catch (Exception $exc) {
148
- $this->lastError = $exc->getMessage();
149
- return false;
150
- }
151
- return $result;
152
- }
153
-
154
- /**
155
- * Get one image
156
- * @param int $id
157
- * @return type
158
- */
159
- public function getImage($id){
160
- $params = array(
161
- 'auth' => json_encode($this->auth),
162
- 'params' => ''
163
- );
164
-
165
- try {
166
- $result = $this->callAPI($this->apiUrl.'images/'.(int)$id,'GET',$params);
167
- } catch (Exception $exc) {
168
- $this->lastError = $exc->getMessage();
169
- return false;
170
- }
171
- return $result;
172
- }
173
-
174
- /**
175
- * Delete an image
176
- * @param int $id
177
- * @return type
178
- */
179
- public function deleteImage($id){
180
- $params = array(
181
- 'auth' => json_encode($this->auth),
182
- 'params' => ''
183
- );
184
-
185
- try {
186
- $result = $this->callAPI($this->apiUrl.'images/'.(int)$id,'DELETE',$params);
187
- } catch (Exception $exc) {
188
- $this->lastError = $exc->getMessage();
189
- return false;
190
- }
191
- return $result;
192
- }
193
-
194
- /**
195
- * Get account information
196
- * @return type
197
- */
198
- public function getAccountInfos(){
199
- $params = array(
200
- 'auth' => json_encode($this->auth),
201
- 'params' => ''
202
- );
203
-
204
- try {
205
- $result = $this->callAPI($this->apiUrl.'accounts/mine','GET',$params);
206
- } catch (Exception $exc) {
207
- $this->lastError = $exc->getMessage();
208
- return false;
209
- }
210
- return $result;
211
- }
212
-
213
- /**
214
- * Get last error message
215
- * @return string
216
- */
217
- public function getLastError(){
218
- return $this->lastError;
219
- }
220
- }
221
?>
1
+ <?php
2
+ class ioaphp {
3
+ /**
4
+ * Authentication values array
5
+ * @var array
6
+ */
7
+ protected $auth = array();
8
+
9
+ /**
10
+ * Image Optimize API Url
11
+ * @var string api url
12
+ */
13
+ protected $apiUrl = 'https://api.imagerecycle.com/v1/';
14
+
15
+ /**
16
+ * Last Error message
17
+ * @var string
18
+ */
19
+ protected $lastError = null;
20
+
21
+
22
+ /**
23
+ *
24
+ * @param string $key
25
+ * @param string $secret
26
+ */
27
+ public function __construct($key,$secret){
28
+
29
+ $this->auth = array('key'=>$key, 'secret'=>$secret);
30
+ }
31
+
32
+ /**
33
+ * Change the API URL
34
+ * @param string $url
35
+ */
36
+ public function setAPIUrl($url){
37
+ $this->apiUrl = $url;
38
+ }
39
+
40
+ /**
41
+ * Upload a file sent through an html post form
42
+ * @param $_FILES $file posted file
43
+ */
44
+ public function uploadFile($file,$params=array()){
45
+ if(class_exists('CURLFile')){
46
+ $curlFile = new CURLFile($file);
47
+ }else{
48
+ $curlFile = '@'.$file;
49
+ }
50
+
51
+ $params = array(
52
+ 'auth' => json_encode($this->auth),
53
+ 'file' => $curlFile,
54
+ 'params' => json_encode( $params)
55
+ );
56
+
57
+ try {
58
+ $result = $this->callAPI($this->apiUrl.'images/','POST',$params);
59
+
60
+ } catch (Exception $exc) {
61
+ $this->lastError = $exc->getMessage();
62
+ return $this->lastError;// false;
63
+ }
64
+
65
+ return $result;
66
+ }
67
+
68
+ /**
69
+ * Upload a file from an url
70
+ * @param string $url
71
+ * @return Object
72
+ */
73
+ public function uploadUrl($url,$params=array()){
74
+ $params = array(
75
+ 'auth' => json_encode($this->auth),
76
+ 'url' => $url,
77
+ 'params' => json_encode($params)
78
+ );
79
+ try {
80
+ $result = $this->callAPI($this->apiUrl.'images/','POST',$params);
81
+ } catch (Exception $exc) {
82
+ $this->lastError = $exc->getMessage();
83
+ return false;
84
+ }
85
+ return $result;
86
+ }
87
+
88
+ public function headRequest($url,$data) {
89
+
90
+ if( function_exists('curl_version')) {
91
+
92
+ $ch = curl_init();
93
+ curl_setopt ($ch, CURLOPT_URL, $url);
94
+ curl_setopt($ch, CURLOPT_POST, 1);
95
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //send the dat
96
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
97
+ curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
98
+ curl_setopt ($ch, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init().
99
+ curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);//The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
100
+ curl_setopt ($ch, CURLOPT_TIMEOUT_MS, 1000); //The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second.
101
+ curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // The contents of the "User-Agent: " header to be used in a HTTP request.
102
+
103
+ $content = curl_exec ($ch);
104
+ curl_close ($ch);
105
+ return $content;
106
+ }else {
107
+
108
+ $ctx = stream_context_create(
109
+ array('http'=>
110
+ array(
111
+ 'timeout' => 1,
112
+ )
113
+ )
114
+ );
115
+ echo file_get_contents($url, false, $ctx);
116
+ }
117
+ }
118
+
119
+
120
+ /**
121
+ * Call the API with curl
122
+ * @param string $url
123
+ * @param string $type HTTP method
124
+ * @param array $datas
125
+ * @return type
126
+ */
127
+ protected function callAPI($url,$type,$datas){
128
+ $curl = curl_init();
129
+ curl_setopt($curl, CURLOPT_HEADER, 0);
130
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 100);
131
+ curl_setopt($curl, CURLOPT_TIMEOUT, 100);
132
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
133
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $type);
134
+ //fix windows localhost ssl problem
135
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
136
+
137
+ if($type==='POST'){
138
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $datas);
139
+ }else{
140
+ $url .= '?'.http_build_query($datas);
141
+ }
142
+
143
+ curl_setopt($curl, CURLOPT_URL, $url);
144
+ $content = curl_exec($curl);
145
+ $infos = curl_getinfo($curl);
146
+ $infos['http_code'] = (String)$infos['http_code'];
147
+
148
+ if($infos['http_code'][0]!=='2'){
149
+ $error = json_decode($content);
150
+ if(isset($error->errCode)){
151
+ $errCode = $error->errCode;
152
+ }else{
153
+ $errCode = 0;
154
+ }
155
+ if(isset($error->errMessage)){
156
+ $errMessage = $error->errMessage;
157
+ }else{
158
+ $errMessage = 'An error occurs';
159
+ }
160
+ throw new Exception($errMessage,$errCode);
161
+ }
162
+ curl_close($curl);
163
+ return json_decode($content);
164
+ }
165
+
166
+ /**
167
+ * Get all the images
168
+ * @return type
169
+ */
170
+ public function getImagesList($offset=0, $limit=30){
171
+ $params = array(
172
+ 'auth' => json_encode($this->auth),
173
+ 'params' => '',
174
+ 'offset' => $offset,
175
+ 'limit' => $limit
176
+ );
177
+
178
+ try {
179
+ $result = $this->callAPI($this->apiUrl.'images/','GET',$params);
180
+ } catch (Exception $exc) {
181
+ $this->lastError = $exc->getMessage();
182
+ return false;
183
+ }
184
+ return $result;
185
+ }
186
+
187
+ /**
188
+ * Get one image
189
+ * @param int $id
190
+ * @return type
191
+ */
192
+ public function getImage($id){
193
+ $params = array(
194
+ 'auth' => json_encode($this->auth),
195
+ 'params' => ''
196
+ );
197
+
198
+ try {
199
+ $result = $this->callAPI($this->apiUrl.'images/'.(int)$id,'GET',$params);
200
+ } catch (Exception $exc) {
201
+ $this->lastError = $exc->getMessage();
202
+ return false;
203
+ }
204
+ return $result;
205
+ }
206
+
207
+ /**
208
+ * Delete an image
209
+ * @param int $id
210
+ * @return type
211
+ */
212
+ public function deleteImage($id){
213
+ $params = array(
214
+ 'auth' => json_encode($this->auth),
215
+ 'params' => ''
216
+ );
217
+
218
+ try {
219
+ $result = $this->callAPI($this->apiUrl.'images/'.(int)$id,'DELETE',$params);
220
+ } catch (Exception $exc) {
221
+ $this->lastError = $exc->getMessage();
222
+ return false;
223
+ }
224
+ return $result;
225
+ }
226
+
227
+ /**
228
+ * Get account information
229
+ * @return type
230
+ */
231
+ public function getAccountInfos(){
232
+
233
+ $params = array(
234
+ 'auth' => json_encode($this->auth),
235
+ 'params' => ''
236
+ );
237
+ try {
238
+ $result = $this->callAPI($this->apiUrl.'accounts/mine','GET',$params);
239
+ } catch (Exception $exc) {
240
+
241
+ $this->lastError = $exc->getMessage();
242
+ return false;
243
+ }
244
+ return $result;
245
+ }
246
+
247
+ /**
248
+ * Get last error message
249
+ * @return string
250
+ */
251
+ public function getLastError(){
252
+ return $this->lastError;
253
+ }
254
+
255
+ /*test the database*/
256
+ public function getData(){
257
+ /**
258
+ * Get the table name
259
+ */
260
+ $resourceR = Mage::getSingleton('core/resource')->getConnection('core_read');
261
+ $tableName = $resourceR->getTableName('a/imagerecycle');
262
+
263
+ var_dump($tableName);
264
+ exit(1);
265
+
266
+ }
267
+ }
268
+
269
+
270
+
271
?>
app/code/community/Imagerecycle/Imagerecycle/controllers/ImageAllController.php ADDED
@@ -0,0 +1,381 @@
1
+ <?php
2
+ class Imagerecycle_Imagerecycle_ImageAllController extends Mage_Core_Controller_Front_Action {
3
+
4
+ public function indexAction() {
5
+ $id = $this->getRequest()->getParam('id');
6
+ if($id == 'cronurl')
7
+ {
8
+ if( Mage::getStoreConfig('mageio_compress_auto')){
9
+ $now = time();
10
+ if(Mage::getStoreConfig('mageio_autosettig') == 'On')
11
+ {
12
+ $ao_lastRun = Mage::getStoreConfig('mageio_runtime');
13
+ $diff = $now - $ao_lastRun;
14
+ if($now - $ao_lastRun < 8000 ) {
15
+ exit;
16
+ }
17
+ }
18
+ $coreConfig = Mage::getConfig();
19
+ $coreConfig->saveConfig("mageio_autosettig", Mage::helper('core')->escapeHtml('On'));
20
+ $coreConfig->saveConfig("mageio_runtime", Mage::helper('core')->escapeHtml($now));
21
+ $coreConfig->cleanCache();
22
+ }
23
+
24
+ }
25
+ else{
26
+ if(Mage::getstoreConfig('mageio_OptResponse') != 'On'){
27
+ echo 'You cannot access!!!';
28
+ exit;
29
+ }
30
+ $this->setStatus('mageio_OptResponse', 'Off');
31
+ }
32
+ $this->initsetting();
33
+ $this->image_auto_optimize();
34
+ }
35
+
36
+ public function initsetting(){
37
+ $this->allowed_ext = array('jpg', 'jpeg', 'png', 'gif','pdf');
38
+ $this->ignoredPath = array('app', 'var', 'cache', 'adminhtml', '.', '..');
39
+ $this->allowedPath = "";
40
+
41
+ $this->totalImages = 0;//
42
+ $this->totalFile = 0;//
43
+ $this->time_elapsed_secs = 0;//
44
+ $this->totalOptimizedImages = 0; //
45
+
46
+ $resource = Mage::getSingleton('core/resource');
47
+ $this->settings = array(
48
+ 'api_key' =>Mage::getStoreConfig('mageio_api_key'),
49
+ 'api_secret' => Mage::getStoreConfig('mageio_api_secret'),
50
+ 'installed_time' => Mage::getStoreConfig('mageio_installed_time'),
51
+ 'include_folders' => Mage::getStoreConfig('mageio_include_folders'),
52
+ 'resize_auto' =>Mage::getStoreConfig('mageio_resize_auto'),
53
+ 'resize_image' => Mage::getStoreConfig('mageio_resize_image'),
54
+ 'min_size' => Mage::getStoreConfig('mageio_min_size'),
55
+ 'max_size' => Mage::getStoreConfig('mageio_max_size'),
56
+ 'compression_type_pdf' =>Mage::getStoreConfig('mageio_compression_type_pdf'),
57
+ 'compression_type_png' => Mage::getStoreConfig('mageio_compression_type_png'),
58
+ 'compression_type_jpg' => Mage::getStoreConfig('mageio_compression_type_jpg'),
59
+ 'compression_type_jpeg' => Mage::getStoreConfig('mageio_compression_type_jpeg'),
60
+ 'compression_type_gif' => Mage::getStoreConfig('mageio_compression_type_gif')
61
+ );
62
+
63
+ if(empty($this->settings['compression_type']) ) { $this->settings['compression_type'] = 'lossy'; }
64
+
65
+ $this->allowedPath = explode(',',$this->settings['include_folders']);
66
+
67
+
68
+ for($i=0;$i<count($this->allowed_ext); $i++) {
69
+ $compression_type = $this->settings['compression_type_'.$this->allowed_ext[$i]];
70
+ if($compression_type=="none") {
71
+ unset($this->allowed_ext[$i]);
72
+ }
73
+ }
74
+ $this->allowed_ext = array_values($this->allowed_ext);
75
+
76
+ }
77
+
78
+ /*
79
+ Get the local images
80
+ @magento database name
81
+ @magento table name
82
+ */
83
+ public function _getLocalImages() {
84
+ $optimizedFiles = array();
85
+ $resourceR = $this->getCoreRead('imagerecycle/images');
86
+
87
+ $sql = "SELECT file,size_before FROM `{$resourceR->tableName}` where `extension` = '1'";
88
+ $optimizedFiles = $resourceR->fetchAssoc($sql);
89
+ $this->totalOptimizedImages = count($optimizedFiles);
90
+
91
+ $min_size = isset($this->settings['min_size']) ? (int)$this->settings['min_size']*1024 : 1* 1024;
92
+ $max_size = !empty($this->settings['max_size']) ? (int)$this->settings['max_size'] * 1024 : 10000 * 1024;
93
+ $images = array();
94
+
95
+ if(Mage::getStoreConfig('mageio_include_folders') == '')
96
+ $base_dir = Mage::getBaseDir();
97
+ else
98
+ $base_dir = Mage::getBaseDir().DIRECTORY_SEPARATOR;
99
+ $start = microtime(true);
100
+ clearstatcache(); $counter = 0;
101
+ foreach($this->allowedPath as $base){
102
+ $base = $base_dir . $base;
103
+
104
+ if (!file_exists($base)) {
105
+ continue;
106
+ }
107
+ foreach (new RecursiveIteratorIterator(new IgnorantRecursiveDirectoryIterator($base)) as $filename) {
108
+ $continue = false;
109
+ $this->totalFile++;
110
+
111
+ foreach ($this->ignoredPath as $ignore_path) {// must customize
112
+ $ignore_path = DIRECTORY_SEPARATOR . $ignore_path . DIRECTORY_SEPARATOR;
113
+ if (strpos(substr($filename, strlen($base)), $ignore_path) === 0 || strpos(substr($filename, strlen($base)), DIRECTORY_SEPARATOR . 'adminhtml' . DIRECTORY_SEPARATOR) !== FALSE) {
114
+ $continue = true;
115
+ continue;
116
+ }
117
+ }
118
+
119
+ if ($continue === true) {
120
+ continue;
121
+ }
122
+ if (!in_array(strtolower(pathinfo($filename, PATHINFO_EXTENSION)), $this->allowed_ext)) {
123
+ continue;
124
+ }
125
+ if(filesize($filename) < $min_size || filesize($filename) > $max_size ) {
126
+ continue;
127
+ }
128
+
129
+ $data = array();
130
+
131
+ if(Mage::getStoreConfig('mageio_include_folders') == ''){
132
+ $data['filename'] = str_replace('\\', '/', substr($filename, strlen($base_dir) + 1));
133
+ }
134
+ else{
135
+ $data['filename'] = str_replace('\\', '/', substr($filename, strlen($base_dir)));
136
+ }
137
+
138
+ $data['size'] = filesize($filename);
139
+ $data['filetype'] = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
140
+
141
+ $filter_name = Mage::getStoreConfig('mageio_all_filter_name');
142
+ $filter_type = Mage::getStoreConfig('mageio_all_filter_type');
143
+
144
+ if($filter_name || $filter_type)
145
+ {
146
+ $pos = strpos($data['filename'], $filter_name);
147
+ if($pos === false){
148
+ continue;
149
+ }
150
+
151
+ if($filter_type)
152
+ {
153
+ if($data['filetype'] !== $filter_type) continue;
154
+ }
155
+ }
156
+ if (isset($optimizedFiles[$data['filename']]) ) {
157
+
158
+ $data['optimized'] = true;
159
+ $data['optimized_datas'] = $optimizedFiles[$data['filename']];
160
+ }
161
+ else{
162
+ $data['optimized'] = false;
163
+ }
164
+ $this->totalImages++;
165
+ $images[] = $data; $counter++;
166
+ }
167
+ }
168
+
169
+ $this->time_elapsed_secs = microtime(true) - $start;
170
+ return $images;
171
+ }
172
+
173
+ /**
174
+ * image auto optimize
175
+ * @param void
176
+ */
177
+ public function image_auto_optimize()
178
+ {
179
+ ignore_user_abort(true);
180
+ $returned = -1;
181
+ $images = $this->_getLocalImages();
182
+ if(empty($images)) {
183
+ $this->setStatus('mageio_autosettig', 'Off');
184
+ $this->setStatus('mageio_runtime', null);
185
+ $this->setStatus('mageio_optfailure', '8');
186
+
187
+ $this->setStatus('filter_type', Mage::getStoreConfig('mageio_all_filter_type'));
188
+ $this->setStatus('filter_name', Mage::getStoreConfig('mageio_all_filter_name'));
189
+ return;
190
+ }
191
+ include_once( Mage::getBaseDir('app').'/code/community/Imagerecycle/Imagerecycle/classes/ioa.class.php');
192
+ foreach ($images as $image) {
193
+ if ($image['optimized'] === false) {
194
+ $now = time();
195
+
196
+ Mage::app()->getConfig()->reinit();
197
+ Mage::app()->getCacheInstance()->cleanType('config');
198
+ Mage::app()->reinitStores();
199
+ if(Mage::getstoreConfig('mageio_autosettig') == 'Off')
200
+ {
201
+ $this->setStatus('mageio_runtime', null);
202
+ break;
203
+ }
204
+ $this->setStatus( 'mageio_runtime' ,$now);
205
+ $returned = $this->optimize($image['filename']);
206
+ if($returned){
207
+
208
+ $this->setStatus('mageio_optfailure', $returned);
209
+ $this->setStatus('mageio_autosettig', 'Off');
210
+ $this->setStatus('mageio_runtime', null);
211
+ return;
212
+ }
213
+ }
214
+ }
215
+ // Now the optimize is ended.
216
+ $this->setStatus('mageio_autosettig', 'Off');
217
+ $this->setStatus('mageio_runtime', null);
218
+ $this->setStatus('mageio_optfailure', $returned);
219
+
220
+ $temp = Mage::getStoreConfig('mageio_all_filter_type');
221
+ $this->setStatus('filter_type',$temp);
222
+
223
+ Mage::app()->getConfig()->reinit();
224
+ Mage::app()->getCacheInstance()->cleanType('config');
225
+ Mage::app()->reinitStores();
226
+
227
+ $temp = Mage::getStoreConfig('mageio_all_filter_name');
228
+ $this->setStatus('filter_name', $temp);
229
+ return;
230
+
231
+ }
232
+
233
+ /***************************************************
234
+ * Optimize the files
235
+ return 1 if success or 0
236
+ *
237
+ ****************************************************/
238
+ public function optimize($image, $savePath='') {
239
+
240
+ $file = realpath($image);
241
+ if (!in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), $this->allowed_ext )) {
242
+ return(6);
243
+ }
244
+ if (!file_exists($file)) {
245
+ //if file is in the database
246
+ return(1);
247
+ }
248
+ $resourceW = $this->getCoreWrite('imagerecycle/images');
249
+ $ext = substr($file, strrpos($file, '.')+1);
250
+ $compressionType= $this->settings['compression_type_'.$ext];
251
+ if($compressionType=='none') return;
252
+
253
+ if (!$this->settings['api_key'] || !$this->settings['api_secret'] )
254
+ {
255
+ return(2);
256
+ }
257
+ $fparams = array("compression_type"=> $compressionType);
258
+ $resize_image = $this->settings['resize_image'];
259
+ $resize_auto = $this->settings['resize_auto'];
260
+ if($resize_image && $resize_auto) {
261
+
262
+ $size = @getimagesize($file);
263
+ if($size && ($size[0]> $resize_image) ) {
264
+ $fparams['resize'] = array("width"=> $resize_image);
265
+ }
266
+ }
267
+ include_once( Mage::getBaseDir('app').'/code/community/Imagerecycle/Imagerecycle/classes/ioa.class.php');
268
+ $ioa = new ioaphp($this->settings['api_key'], $this->settings['api_secret']);
269
+ $return = $ioa->uploadFile($file,$fparams);
270
+
271
+ if ($return === false || $return === null || is_string($return)) {
272
+ $this->checkError();
273
+ return(3);
274
+ }
275
+ $coreConfig = Mage::getConfig();
276
+ $coreConfig->saveConfig("mageio_errormessage", Mage::helper('core')->escapeHtml(null))->cleanCache();
277
+ Mage::dispatchEvent('imagerecycle_notifications_before');
278
+
279
+ $md5 = md5_file($file);
280
+ clearstatcache();
281
+ $sizebefore = filesize($file);
282
+ $optimizedFileContent = $this->getContent($return->optimized_url);
283
+ if ($optimizedFileContent === false) {
284
+ return(4);
285
+ }
286
+
287
+ if (file_put_contents($file, $optimizedFileContent) === false) {
288
+ return(5);
289
+ }
290
+ clearstatcache();
291
+ $size_after = filesize($file);
292
+ if($savePath=='') { $savePath = $image;}
293
+
294
+ $id = $resourceW->fetchOne("SELECT id FROM {$resourceW->tableName} WHERE `file` = " . $resourceW->quote($savePath));
295
+ if (!$id) {
296
+
297
+ $name = substr($file, strrpos($file, "/")+1);
298
+ $ext = substr($name, strrpos($name, ".")+1);
299
+ $name = substr($name, 0, strrpos($name, '.'));
300
+
301
+ $resourceW->query("INSERT INTO `{$resourceW->tableName}` (`file`,`md5`,`api_id`,`size_before`, `size_after`,`date`,`name`, `ext`) VALUES ("
302
+ . $resourceW->quote($savePath) . "," . $resourceW->quote($md5) . "," . $resourceW->quote($return->id) . "," . (int) $sizebefore . "," . (int) $size_after . ",'" . date('Y-m-d H:i:s'). "',". $resourceW->quote($name). ",".$resourceW->quote($ext) .")");
303
+ }
304
+ else {
305
+ $resourceW->query("UPDATE `{$resourceW->tableName}` SET `extension` ='1',`api_id` =". $resourceW->quote($return->id) .", `md5` =".$resourceW->quote($md5)." , `size_after` = " . (int) $size_after .",`date` = '".date('Y-m-d H:i:s') . "' WHERE `id` = " . $resourceW->quote($id));
306
+ }
307
+ return(0);
308
+ }
309
+
310
+ /**
311
+ * Get content of specified resource via curl or file_get_content() function
312
+ */
313
+ protected function checkError(){
314
+ $coreConfig = Mage::getConfig();
315
+ $count = Mage::getStoreConfig('mageio_lasterror');
316
+ $count++;
317
+ if($count >= 3){
318
+ $coreConfig->saveConfig("mageio_saving_auto", Mage::helper('core')->escapeHtml('0'));
319
+ $coreConfig->saveConfig("mageio_compress_auto", Mage::helper('core')->escapeHtml('0'));
320
+ $coreConfig->saveConfig("mageio_errormessage", Mage::helper('core')->escapeHtml('on'));
321
+ Mage::dispatchEvent('imagerecycle_notifications_before');
322
+ $count = 0;
323
+ }
324
+ $coreConfig->saveConfig("mageio_lasterror", Mage::helper('core')->escapeHtml($count));
325
+ $coreConfig->cleanCache();
326
+ }
327
+
328
+ protected function getContent($url) {
329
+ if ($url == '') {
330
+ return '';
331
+ }
332
+ if (!function_exists('curl_version')) {
333
+ if (!$content = @file_get_contents($url)) {
334
+ return '';
335
+ }
336
+ } else {
337
+ $options = array(
338
+ CURLOPT_RETURNTRANSFER => true, // return content
339
+ CURLOPT_FOLLOWLOCATION => true, // follow redirects
340
+ CURLOPT_AUTOREFERER => true, // set referer on redirect
341
+ CURLOPT_CONNECTTIMEOUT => 60, // timeout on connect
342
+ CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
343
+ );
344
+ $ch = curl_init($url);
345
+ curl_setopt_array($ch, $options);
346
+ $content = curl_exec($ch);
347
+ curl_close($ch);
348
+ }
349
+
350
+ return $content;
351
+ }
352
+
353
+ public function setStatus($mage_key, $val){
354
+ $coreConfig = Mage::getConfig();
355
+ $coreConfig->saveConfig($mage_key, Mage::helper('core')->escapeHtml($val))->cleanCache();
356
+ }
357
+ public function getCoreWrite($entityId) {
358
+ $resource = Mage::getSingleton('core/resource');
359
+ $resourceW = $resource->getConnection('core_write');
360
+ $tableName = $resource->getTableName($entityId);
361
+ $resourceW->tableName = $tableName;
362
+ return $resourceW;
363
+ }
364
+ public function getCoreRead($entityId) {
365
+ $resource = Mage::getSingleton('core/resource');
366
+ $resourceR = $resource->getConnection('core_read');
367
+ $tableName = $resource->getTableName($entityId);
368
+ $resourceR->tableName = $tableName;
369
+ return $resourceR;
370
+ }
371
+
372
+ }
373
+ class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
374
+ function getChildren() {
375
+ try {
376
+ return new IgnorantRecursiveDirectoryIterator($this->getPathname());
377
+ } catch (UnexpectedValueException $e) {
378
+ return new RecursiveArrayIterator(array());
379
+ }
380
+ }
381
+ }
app/code/community/Imagerecycle/Imagerecycle/controllers/IndexController.php CHANGED
@@ -1,166 +1,317 @@
1
- <?php
2
-
3
- Class Imagerecycle_Imagerecycle_IndexController extends Mage_Adminhtml_Controller_Action {
4
-
5
- public function indexAction() {
6
- $this->_title($this->__('Image Recycle'));
7
- $this->_initAction()->renderLayout();
8
- return $this;
9
- }
10
-
11
- /**
12
- * Initialize action
13
- *
14
- * @return Mage_Adminhtml_Controller_Action
15
- */
16
- protected function _initAction() {
17
-
18
- $this->loadLayout()->_setActiveMenu('imagerecycle');
19
-
20
- return $this;
21
- }
22
-
23
- public function saveConfigAction() {
24
-
25
- $response = new stdClass();
26
- $response->success = false;
27
- $configKey = array('api_key', 'api_secret','exclude_folders','resize_auto',
28
- 'resize_image','min_size','max_size','compression_type_pdf','compression_type_png','compression_type_jpg','compression_type_gif');
29
- $coreConfig = Mage::getConfig();
30
- $post = $this->getRequest()->getPost();
31
- // var_dump($post);
32
- foreach ($configKey as $key) {
33
- if (isset($post[$key])) {
34
- $coreConfig->saveConfig("mageio_".$key, Mage::helper('core')->escapeHtml($post[$key]));
35
- $response->success = true;
36
- }
37
- }
38
- $installed_time = Mage::getStoreConfig('mageio_installed_time');
39
- if(empty($installed_time)) {
40
- $installed_time = time();
41
- $coreConfig = Mage::getConfig();
42
- $coreConfig->saveConfig('mageio_installed_time', $installed_time);
43
- }
44
-
45
- $cache = Mage::getSingleton('core/cache');
46
- $cache->flush();
47
- $response->msg = "All modifications were saved!";
48
- exit(json_encode($response));
49
- }
50
-
51
- public function revertAction() {
52
- $requestParams = $this->getRequest()->getParams();
53
- $image = isset($requestParams['image']) ? $requestParams['image'] : "";
54
- $return_params = array();
55
- if (isset($requestParams['page'])) {
56
- $return_params['page'] = $requestParams['page'];
57
- }
58
-
59
- //Include ioaphp class once
60
- include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
61
-
62
- $this->blockImages = $this->getLayout()->createBlock('imagerecycle/images');
63
- $returned = $this->_revert($image);
64
- $this->ajaxReponse($returned->status, $returned);
65
-
66
- }
67
-
68
- protected function _revert($image) {
69
-
70
- $response = new stdClass();
71
- $response->status = false;
72
- $response->msg = Mage::helper('imagerecycle')->__('Not be reverted yet');
73
-
74
- $resourceR = $this->blockImages->getCoreRead('imagerecycle/images');
75
- $resourceW = $this->blockImages->getCoreWrite('imagerecycle/images');
76
-
77
- $api_id = $resourceR->fetchOne("SELECT api_id FROM {$resourceR->tableName} WHERE `file` = " . $resourceR->quote($image));
78
- if ($api_id) {
79
-
80
- $ioa = new ioaphp($this->blockImages->settings['api_key'], $this->blockImages->settings['api_secret']);
81
- $return = $ioa->getImage($api_id);
82
-
83
- if (!isset($return->id)) {
84
- $response->msg = Mage::helper('imagerecycle')->__('api id is not correct');
85
- return $response;
86
- }
87
-
88
- $fileContent = file_get_contents($return->origin_url);
89
- if ($fileContent === false) {
90
- $response->msg = Mage::helper('imagerecycle')->__('Image not found');
91
- return $response;
92
- }
93
-
94
- $file = realpath($image);
95
- if (file_put_contents($file, $fileContent) === false) {
96
- $response->msg = Mage::helper('imagerecycle')->__("Can't write file");
97
- return $response;
98
- }
99
- clearstatcache();
100
- $size_after = filesize($file);
101
-
102
- $where = "api_id = " . $api_id;
103
- $result = $resourceW->delete($resourceW->tableName, $where);
104
- if ($result === false) {
105
- $response->msg = Mage::helper('imagerecycle')->__("Can't delete db record");
106
- return $response;
107
- }
108
-
109
- $response->newSize = number_format($size_after/1000, 2, '.', '') ;
110
- $response->status = true;
111
- $response->msg = Mage::helper('imagerecycle')->__('Reverted');
112
- }
113
- return $response;
114
- }
115
-
116
- public function optimizeAction() {
117
- $requestParams = $this->getRequest()->getParams();
118
- $image = isset($requestParams['image']) ? $requestParams['image'] : '';
119
- $return_params = array();
120
- if (isset($requestParams['page'])) {
121
- $return_params['page'] = $requestParams['page'];
122
- }
123
-
124
- //Include ioaphp class once
125
- include_once(Mage::getModuleDir('', 'Imagerecycle_Imagerecycle') . '/classes/ioa.class.php');
126
- $this->blockImages = $this->getLayout()->createBlock('imagerecycle/images');
127
-
128
- include_once(__DIR__.'/../Helper/Data.php');
129
- $helper = new Imagerecycle_Imagerecycle_Helper_Data();
130
- $returned = $helper->optimize($image);
131
- $this->ajaxReponse($returned->status, $returned);
132
- }
133
-
134
- /**
135
- * Be careful of this action if site has a very big amount of images
136
- */
137
- protected function optimizeAllAction() {
138
- $steps = 2;
139
- $this->blockImages = $this->getLayout()->createBlock('imagerecycle/images');
140
- $images = $this->blockImages->_getLocalImages();
141
- include_once(__DIR__.'/../Helper/Data.php');
142
- $helper = new Imagerecycle_Imagerecycle_Helper_Data();
143
-
144
- foreach ($images as $image) {
145
- if ($image['optimized'] === false) {
146
- if ($steps === 0) {
147
- $this->ajaxReponse(true, array('continue' => true, 'totalImages' => $this->blockImages->getTotalImages(), 'totalOptimizedImages' => $this->blockImages->getTotalOptimizedImages()));
148
- }
149
-
150
- $returned = $helper->optimize($image['filename']);
151
- if ($returned === false) {
152
- $this->ajaxReponse(false);
153
- }
154
- $steps--;
155
- }
156
- }
157
- }
158
-
159
- protected function ajaxReponse($status, $datas = null) {
160
- $response = array('status' => $status, 'datas' => $datas);
161
- echo json_encode($response);
162
- die();
163
- }
164
-
165
-
166
- }