Commit ea47d08df4617e8dd6f4aab1b82afbd701f49c85
Merge remote-tracking branch 'origin/master'
Showing
61 changed files
with
2536 additions
and
479 deletions
Show diff stats
.gitignore
.htaccess
@@ -12,7 +12,7 @@ AddDefaultCharset utf-8 | @@ -12,7 +12,7 @@ AddDefaultCharset utf-8 | ||
12 | 12 | ||
13 | RewriteBase / | 13 | RewriteBase / |
14 | # deal with admin first | 14 | # deal with admin first |
15 | - RewriteRule ^storage/(.*)?$ /storage/$1 [L,PT] | 15 | + RewriteRule ^storage/(.*)?$ /storage/$1 [L,PT] |
16 | 16 | ||
17 | RewriteCond %{REQUEST_URI} ^/(admin) | 17 | RewriteCond %{REQUEST_URI} ^/(admin) |
18 | 18 |
backend/.gitignore
backend/components/base/BaseActiveRecord.php
@@ -9,12 +9,16 @@ | @@ -9,12 +9,16 @@ | ||
9 | namespace backend\components\base; | 9 | namespace backend\components\base; |
10 | 10 | ||
11 | 11 | ||
12 | -use yii\base\ErrorException; | 12 | +use common\components\exceptions\OrdinaryActiveRecordException; |
13 | 13 | ||
14 | class BaseActiveRecord extends \yii\db\ActiveRecord { | 14 | class BaseActiveRecord extends \yii\db\ActiveRecord { |
15 | 15 | ||
16 | + /** | ||
17 | + * @param int $row | ||
18 | + * @throws OrdinaryActiveRecordException | ||
19 | + * выбрасывает специальное исключения, наполняя сообщение с массива ошибок модели (после попытки валидации) | ||
20 | + */ | ||
16 | public function throwStringErrorException($row = 0){ | 21 | public function throwStringErrorException($row = 0){ |
17 | - | ||
18 | $errors_str = ''; | 22 | $errors_str = ''; |
19 | if ($row != 0) { | 23 | if ($row != 0) { |
20 | $errors_str = "Ошибка в строке {$row} "; | 24 | $errors_str = "Ошибка в строке {$row} "; |
@@ -22,7 +26,9 @@ class BaseActiveRecord extends \yii\db\ActiveRecord { | @@ -22,7 +26,9 @@ class BaseActiveRecord extends \yii\db\ActiveRecord { | ||
22 | foreach ($this->getErrors() as $error) { | 26 | foreach ($this->getErrors() as $error) { |
23 | $errors_str .= implode( array_values($error) ); | 27 | $errors_str .= implode( array_values($error) ); |
24 | } | 28 | } |
25 | - throw new ErrorException( $errors_str ); | 29 | + $ex = new OrdinaryActiveRecordException( $errors_str ); |
30 | + $ex->active_record_name = static::formName(); | ||
31 | + throw $ex; | ||
26 | } | 32 | } |
27 | 33 | ||
28 | } | 34 | } |
29 | \ No newline at end of file | 35 | \ No newline at end of file |
backend/controllers/BrandsController.php
@@ -9,6 +9,7 @@ use yii\web\Controller; | @@ -9,6 +9,7 @@ use yii\web\Controller; | ||
9 | use yii\web\NotFoundHttpException; | 9 | use yii\web\NotFoundHttpException; |
10 | use yii\filters\VerbFilter; | 10 | use yii\filters\VerbFilter; |
11 | use yii\filters\AccessControl; | 11 | use yii\filters\AccessControl; |
12 | +use yii\web\UploadedFile; | ||
12 | 13 | ||
13 | /** | 14 | /** |
14 | * BrandsController implements the CRUD actions for Brands model. | 15 | * BrandsController implements the CRUD actions for Brands model. |
@@ -27,11 +28,11 @@ class BrandsController extends Controller | @@ -27,11 +28,11 @@ class BrandsController extends Controller | ||
27 | 'class' => AccessControl::className(), | 28 | 'class' => AccessControl::className(), |
28 | 'rules' => [ | 29 | 'rules' => [ |
29 | [ | 30 | [ |
30 | - 'actions' => ['login', 'error', 'download-photo','delete-image' ], | 31 | + 'actions' => ['login', 'error', 'download-photo', 'delete-image'], |
31 | 'allow' => true, | 32 | 'allow' => true, |
32 | ], | 33 | ], |
33 | [ | 34 | [ |
34 | - 'actions' => ['logout', 'index','create','update','view','delete',], | 35 | + 'actions' => ['logout', 'index', 'create', 'update', 'view', 'delete',], |
35 | 'allow' => true, | 36 | 'allow' => true, |
36 | 'roles' => ['@'], | 37 | 'roles' => ['@'], |
37 | ], | 38 | ], |
@@ -81,15 +82,14 @@ class BrandsController extends Controller | @@ -81,15 +82,14 @@ class BrandsController extends Controller | ||
81 | public function actionCreate() | 82 | public function actionCreate() |
82 | { | 83 | { |
83 | $model = new Brands(); | 84 | $model = new Brands(); |
84 | - | ||
85 | - if ($model->load(Yii::$app->request->post()) && $model->save()) { | ||
86 | - //return $this->redirect(['view', 'id' => $model->BRAND]); | ||
87 | - return $this->redirect(['index']); | 85 | + if ($model->load(Yii::$app->request->post())) { |
86 | + return $this->saveModelWithImg($model); | ||
88 | } else { | 87 | } else { |
89 | return $this->render('create', [ | 88 | return $this->render('create', [ |
90 | 'model' => $model, | 89 | 'model' => $model, |
91 | ]); | 90 | ]); |
92 | } | 91 | } |
92 | + | ||
93 | } | 93 | } |
94 | 94 | ||
95 | /** | 95 | /** |
@@ -101,15 +101,21 @@ class BrandsController extends Controller | @@ -101,15 +101,21 @@ class BrandsController extends Controller | ||
101 | public function actionUpdate($id) | 101 | public function actionUpdate($id) |
102 | { | 102 | { |
103 | $model = $this->findModel($id); | 103 | $model = $this->findModel($id); |
104 | + if ($model->load(Yii::$app->request->post())) { | ||
104 | 105 | ||
105 | - if ($model->load(Yii::$app->request->post()) && $model->save()) { | ||
106 | - //return $this->redirect(['view', 'id' => $model->BRAND]); | ||
107 | - return $this->redirect(['index']); | 106 | + if ($model->delete_img) { |
107 | + // удаляем изображение (как из базы так и с сервера), сохраняем модель | ||
108 | + return $this->saveModelWithDeleteImg($model); | ||
109 | + } else { | ||
110 | + // сохраняем модель с сохранением изображения (как в базу так и на сервер) | ||
111 | + return $this->saveModelWithImg($model); | ||
112 | + } | ||
108 | } else { | 113 | } else { |
109 | return $this->render('update', [ | 114 | return $this->render('update', [ |
110 | 'model' => $model, | 115 | 'model' => $model, |
111 | ]); | 116 | ]); |
112 | } | 117 | } |
118 | + | ||
113 | } | 119 | } |
114 | 120 | ||
115 | /** | 121 | /** |
@@ -140,4 +146,49 @@ class BrandsController extends Controller | @@ -140,4 +146,49 @@ class BrandsController extends Controller | ||
140 | throw new NotFoundHttpException('The requested page does not exist.'); | 146 | throw new NotFoundHttpException('The requested page does not exist.'); |
141 | } | 147 | } |
142 | } | 148 | } |
149 | + | ||
150 | + /** | ||
151 | + * @param $model | ||
152 | + * @return string|\yii\web\Response | ||
153 | + * сохраняет картинку и валидирует модель | ||
154 | + * выбрасывает исключение в случае ошибки | ||
155 | + */ | ||
156 | + protected function saveModelWithImg($model) | ||
157 | + { | ||
158 | + $model->file = UploadedFile::getInstance($model, 'file'); | ||
159 | + $model->IMG = $model->file->name; | ||
160 | + // первый проход - валидируем, сохраняем файл, | ||
161 | + if ($model->validate()) { | ||
162 | + // сохраним файл | ||
163 | + $model->file->saveAs(Yii::getAlias('@storage') . '/files/brands/' . $model->IMG); | ||
164 | + if ($model->save()) { | ||
165 | + return $this->redirect(['index']); | ||
166 | + } | ||
167 | + } | ||
168 | + $model->throwStringErrorException(); | ||
169 | + | ||
170 | + } | ||
171 | + | ||
172 | + /** | ||
173 | + * @param $model | ||
174 | + * @return \yii\web\Response | ||
175 | + * сохраняет модель с удалением картинки | ||
176 | + * выбрасывает исключение в случае ошибки | ||
177 | + */ | ||
178 | + protected function saveModelWithDeleteImg($model) | ||
179 | + { | ||
180 | + if ($model->validate()) { | ||
181 | + $img_path = Yii::getAlias('@storage') . '/files/brands/' . $model->IMG; | ||
182 | + // удалим файл | ||
183 | + if(file_exists( $img_path )) | ||
184 | + unlink( $img_path ); | ||
185 | + | ||
186 | + $model->IMG = ''; | ||
187 | + if ($model->save()) { | ||
188 | + return $this->redirect(['index']); | ||
189 | + } | ||
190 | + } | ||
191 | + $model->throwStringErrorException(); | ||
192 | + | ||
193 | + } | ||
143 | } | 194 | } |
backend/controllers/CheckPriceController.php
@@ -10,7 +10,7 @@ use yii\data\ActiveDataProvider; | @@ -10,7 +10,7 @@ use yii\data\ActiveDataProvider; | ||
10 | use yii\filters\AccessControl; | 10 | use yii\filters\AccessControl; |
11 | use backend\components\base\BaseController; | 11 | use backend\components\base\BaseController; |
12 | use yii\filters\VerbFilter; | 12 | use yii\filters\VerbFilter; |
13 | -use backend\models\Details; | 13 | +use common\models\Details; |
14 | use backend\models\ImportersFiles; | 14 | use backend\models\ImportersFiles; |
15 | use backend\models\Importers; | 15 | use backend\models\Importers; |
16 | use yii\base\ErrorException; | 16 | use yii\base\ErrorException; |
backend/controllers/CrossingUploadController.php
@@ -73,7 +73,8 @@ class CrossingUploadController extends BaseController | @@ -73,7 +73,8 @@ class CrossingUploadController extends BaseController | ||
73 | $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; | 73 | $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; |
74 | $model->file->saveAs($model->file_path); | 74 | $model->file->saveAs($model->file_path); |
75 | //запускаем парсинг | 75 | //запускаем парсинг |
76 | - $data = $model->readFile(); | 76 | + $options['mode'] = 'crosses'; |
77 | + $data = $model->readFile($options); | ||
77 | // сохраняем в кеш отпарсенные даные | 78 | // сохраняем в кеш отпарсенные даные |
78 | $this->parserCacheHandler( 1, $data, $model ); | 79 | $this->parserCacheHandler( 1, $data, $model ); |
79 | } else { | 80 | } else { |
@@ -100,7 +101,6 @@ class CrossingUploadController extends BaseController | @@ -100,7 +101,6 @@ class CrossingUploadController extends BaseController | ||
100 | $model = DynamicFormHelper::CreateDynamicModel($arr_attributes); | 101 | $model = DynamicFormHelper::CreateDynamicModel($arr_attributes); |
101 | $crosses_model = new DetailsCrosses(); | 102 | $crosses_model = new DetailsCrosses(); |
102 | $arr_keys = array_keys($this->getBasicColumns()); | 103 | $arr_keys = array_keys($this->getBasicColumns()); |
103 | - | ||
104 | //добавим правила валидации (колонки должны быть те что в модели) | 104 | //добавим правила валидации (колонки должны быть те что в модели) |
105 | foreach ($arr_attributes as $key => $value) { | 105 | foreach ($arr_attributes as $key => $value) { |
106 | $model->addRule($key, 'in', ['range' => $arr_keys]); | 106 | $model->addRule($key, 'in', ['range' => $arr_keys]); |
@@ -171,7 +171,6 @@ class CrossingUploadController extends BaseController | @@ -171,7 +171,6 @@ class CrossingUploadController extends BaseController | ||
171 | 171 | ||
172 | protected function convertDataByConfiguration($data, $configuration) | 172 | protected function convertDataByConfiguration($data, $configuration) |
173 | { | 173 | { |
174 | - | ||
175 | // доп. опции для парсера - удаление префикса в артикулах | 174 | // доп. опции для парсера - удаление префикса в артикулах |
176 | $options['mode'] = 'crosses'; | 175 | $options['mode'] = 'crosses'; |
177 | $fields = []; | 176 | $fields = []; |
@@ -197,7 +196,6 @@ class CrossingUploadController extends BaseController | @@ -197,7 +196,6 @@ class CrossingUploadController extends BaseController | ||
197 | } | 196 | } |
198 | 197 | ||
199 | return $data; | 198 | return $data; |
200 | - | ||
201 | } | 199 | } |
202 | 200 | ||
203 | protected function reverseCrosses($data) | 201 | protected function reverseCrosses($data) |
backend/controllers/DetailsController.php
@@ -105,7 +105,8 @@ class DetailsController extends Controller | @@ -105,7 +105,8 @@ class DetailsController extends Controller | ||
105 | $model = $this->findModel($IMPORT_ID, $BRAND, $ARTICLE); | 105 | $model = $this->findModel($IMPORT_ID, $BRAND, $ARTICLE); |
106 | 106 | ||
107 | if ($model->load(Yii::$app->request->post()) && $model->save()) { | 107 | if ($model->load(Yii::$app->request->post()) && $model->save()) { |
108 | - return $this->redirect(['view', 'IMPORT_ID' => $model->IMPORT_ID, 'BRAND' => $model->BRAND, 'ARTICLE' => $model->ARTICLE]); | 108 | + //return $this->redirect(['view', 'IMPORT_ID' => $model->IMPORT_ID, 'BRAND' => $model->BRAND, 'ARTICLE' => $model->ARTICLE]); |
109 | + return $this->redirect(['index']); | ||
109 | } else { | 110 | } else { |
110 | return $this->render('update', [ | 111 | return $this->render('update', [ |
111 | 'model' => $model, | 112 | 'model' => $model, |
backend/controllers/ParserController.php
1 | <?php | 1 | <?php |
2 | namespace backend\controllers; | 2 | namespace backend\controllers; |
3 | 3 | ||
4 | -use backend\models\Details; | 4 | +use common\components\CustomVarDamp; |
5 | +use common\models\Details; | ||
5 | use common\components\exceptions\CrossParsingException; | 6 | use common\components\exceptions\CrossParsingException; |
7 | +use common\components\exceptions\OrdinaryActiveRecordException; | ||
6 | use common\components\exceptions\PriceParsingException; | 8 | use common\components\exceptions\PriceParsingException; |
7 | use common\components\exceptions\RgParsingException; | 9 | use common\components\exceptions\RgParsingException; |
8 | use common\components\ModelArrayValidator; | 10 | use common\components\ModelArrayValidator; |
9 | use common\components\parsers\MailParser; | 11 | use common\components\parsers\MailParser; |
12 | +use common\components\parsers\Parser; | ||
10 | use Yii; | 13 | use Yii; |
11 | use yii\data\ActiveDataProvider; | 14 | use yii\data\ActiveDataProvider; |
12 | use yii\filters\AccessControl; | 15 | use yii\filters\AccessControl; |
@@ -75,6 +78,10 @@ class ParserController extends BaseController | @@ -75,6 +78,10 @@ class ParserController extends BaseController | ||
75 | $action_name = ['results']; | 78 | $action_name = ['results']; |
76 | }elseif ( $exception instanceof RgParsingException ) { | 79 | }elseif ( $exception instanceof RgParsingException ) { |
77 | $action_name = ['rg-grup/results']; | 80 | $action_name = ['rg-grup/results']; |
81 | + }elseif ( $exception instanceof OrdinaryActiveRecordException ) { | ||
82 | + // для обычной модели возвращаемся в index в качестве контроллера используем имя модели | ||
83 | + $action_name = strtolower($exception->active_record_name); | ||
84 | + $action_name = ["$action_name/index"]; | ||
78 | } | 85 | } |
79 | 86 | ||
80 | if ( $exception !== null ) { | 87 | if ( $exception !== null ) { |
@@ -186,11 +193,14 @@ class ParserController extends BaseController | @@ -186,11 +193,14 @@ class ParserController extends BaseController | ||
186 | public function actionServerFiles () | 193 | public function actionServerFiles () |
187 | { | 194 | { |
188 | $arr_id_files = []; | 195 | $arr_id_files = []; |
196 | + $arr_supported_extension = Parser::supportedExtension(); | ||
189 | 197 | ||
190 | // получим список файлов которые ожидают к загрузке | 198 | // получим список файлов которые ожидают к загрузке |
191 | - foreach ( glob(Yii::getAlias('@temp_upload') . '/*.csv' ) as $server_file ) { | ||
192 | - $file_id = basename($server_file,".csv"); | ||
193 | - $arr_id_files[] = (int) $file_id; | 199 | + foreach ($arr_supported_extension as $ext) { |
200 | + foreach ( glob( Yii::getAlias('@temp_upload') . '/*.' . $ext ) as $server_file ) { | ||
201 | + $file_id = basename($server_file, ".{$ext}"); | ||
202 | + $arr_id_files[] = (int)$file_id; | ||
203 | + } | ||
194 | } | 204 | } |
195 | 205 | ||
196 | $query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy( ['upload_time' => SORT_DESC] ); | 206 | $query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy( ['upload_time' => SORT_DESC] ); |
@@ -215,7 +225,13 @@ class ParserController extends BaseController | @@ -215,7 +225,13 @@ class ParserController extends BaseController | ||
215 | $id = Yii::$app->request->post()['id']; | 225 | $id = Yii::$app->request->post()['id']; |
216 | try { | 226 | try { |
217 | $files_model->delete($id); | 227 | $files_model->delete($id); |
218 | - unlink(Yii::getAlias('@temp_upload') . '/' . $id . '.csv' ); | 228 | + $arr_supported_extension = Parser::supportedExtension(); |
229 | + // получим список файлов которые ожидают к загрузке | ||
230 | + foreach ($arr_supported_extension as $ext) { | ||
231 | + if (file_exists(Yii::getAlias('@temp_upload') . '/' . $id . ".{$ext}")) { | ||
232 | + unlink(Yii::getAlias('@temp_upload') . '/' . $id . ".{$ext}"); | ||
233 | + } | ||
234 | + } | ||
219 | // сообщим скрипту что все ОК | 235 | // сообщим скрипту что все ОК |
220 | echo 1; | 236 | echo 1; |
221 | } catch (ErrorException $e) { | 237 | } catch (ErrorException $e) { |
@@ -230,22 +246,24 @@ class ParserController extends BaseController | @@ -230,22 +246,24 @@ class ParserController extends BaseController | ||
230 | 246 | ||
231 | public function actionLaunchCroneUploads () | 247 | public function actionLaunchCroneUploads () |
232 | { | 248 | { |
233 | - foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) { | 249 | + $arr_supported_extension = Parser::supportedExtension(); |
250 | + // получим список файлов которые ожидают к загрузке | ||
251 | + foreach ($arr_supported_extension as $ext) { | ||
252 | + foreach ( glob( Yii::getAlias('@temp_upload') . '/*.' . $ext ) as $server_file ) { | ||
234 | 253 | ||
235 | - $file_name = basename($server_file,".csv"); | ||
236 | - copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' ); | 254 | + $file_name = basename($server_file, ".{$ext}"); |
255 | + copy($server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . ".{$ext}"); | ||
237 | 256 | ||
257 | + } | ||
238 | } | 258 | } |
239 | - | ||
240 | $controller = new \console\controllers\ParserController( 'parse-prices', $this->module ); | 259 | $controller = new \console\controllers\ParserController( 'parse-prices', $this->module ); |
241 | - $controller->actionSaveMailAttachments(); | 260 | + //$controller->actionSaveMailAttachments(); |
242 | $controller->actionParsePrices(); | 261 | $controller->actionParsePrices(); |
243 | 262 | ||
244 | Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' ); | 263 | Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' ); |
245 | $this->redirect('server-files'); | 264 | $this->redirect('server-files'); |
246 | } | 265 | } |
247 | 266 | ||
248 | - | ||
249 | /** | 267 | /** |
250 | * сохраняет файл на диск и регистрирует в ImportersFiles | 268 | * сохраняет файл на диск и регистрирует в ImportersFiles |
251 | * @param $model - модель с настройками | 269 | * @param $model - модель с настройками |
backend/controllers/RgGrupController.php
@@ -71,7 +71,8 @@ class RgGrupController extends BaseController | @@ -71,7 +71,8 @@ class RgGrupController extends BaseController | ||
71 | $model->file_path = Yii::getAlias('@manual_upload') . '/' . $model->file->name; | 71 | $model->file_path = Yii::getAlias('@manual_upload') . '/' . $model->file->name; |
72 | $model->file->saveAs($model->file_path); | 72 | $model->file->saveAs($model->file_path); |
73 | //запускаем парсинг | 73 | //запускаем парсинг |
74 | - $data = $model->readFile(); | 74 | + $options['mode'] = 'rg'; |
75 | + $data = $model->readFile($options); | ||
75 | // сохраняем в кеш отпарсенные даные | 76 | // сохраняем в кеш отпарсенные даные |
76 | $this->parserCacheHandler(1, $data, $model); | 77 | $this->parserCacheHandler(1, $data, $model); |
77 | } else { | 78 | } else { |
@@ -120,7 +121,7 @@ class RgGrupController extends BaseController | @@ -120,7 +121,7 @@ class RgGrupController extends BaseController | ||
120 | $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); | 121 | $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); |
121 | 122 | ||
122 | // в первой строке у нас заголовки - уберем | 123 | // в первой строке у нас заголовки - уберем |
123 | - unset($data[0]); | 124 | + unset($data[0]); //- закоментировать если в конфиге парсера указано о наличии заголовка |
124 | // подготовим данные для записи в таблицу w_margins_groups | 125 | // подготовим данные для записи в таблицу w_margins_groups |
125 | $data = $this->convertDataByConfiguration($data, $configuration); | 126 | $data = $this->convertDataByConfiguration($data, $configuration); |
126 | 127 |
backend/models/UploadFileCrossingForm.php
@@ -27,7 +27,7 @@ class UploadFileCrossingForm extends Model | @@ -27,7 +27,7 @@ class UploadFileCrossingForm extends Model | ||
27 | { | 27 | { |
28 | return [ | 28 | return [ |
29 | ['file', 'required', 'message' => 'Не выбран файл!' ], | 29 | ['file', 'required', 'message' => 'Не выбран файл!' ], |
30 | - [['file'], 'file', 'extensions' => 'csv', 'checkExtensionByMimeType'=>false ], | 30 | + [['file'], 'file', 'extensions' => ['csv'], 'checkExtensionByMimeType'=>false ], |
31 | [['delete_prefix1', 'delete_prefix2'], 'boolean' ], | 31 | [['delete_prefix1', 'delete_prefix2'], 'boolean' ], |
32 | 32 | ||
33 | ]; | 33 | ]; |
backend/models/UploadFileParsingForm.php
@@ -48,7 +48,7 @@ class UploadFileParsingForm extends Model | @@ -48,7 +48,7 @@ class UploadFileParsingForm extends Model | ||
48 | return [ | 48 | return [ |
49 | ['importer_id', 'required', 'message' => 'Не указан поставщик!' ], | 49 | ['importer_id', 'required', 'message' => 'Не указан поставщик!' ], |
50 | ['file', 'required', 'message' => 'Не выбран файл!' ], | 50 | ['file', 'required', 'message' => 'Не выбран файл!' ], |
51 | - [['file'], 'file', 'extensions' => ['csv', 'xlsx'], 'checkExtensionByMimeType'=>false ], | 51 | + [['file'], 'file', 'extensions' => ['csv', 'xlsx','txt','xls'], 'checkExtensionByMimeType'=>false ], |
52 | ['importer_id', 'integer','max' => 999999, 'min' => 0 ], | 52 | ['importer_id', 'integer','max' => 999999, 'min' => 0 ], |
53 | [['action','delete_prefix', 'delete_price', 'success'], 'boolean', 'except' => 'auto' ], // только для ручной загрузки | 53 | [['action','delete_prefix', 'delete_price', 'success'], 'boolean', 'except' => 'auto' ], // только для ручной загрузки |
54 | ['delimiter', 'string', 'max' => 1], | 54 | ['delimiter', 'string', 'max' => 1], |
backend/views/brands-replace/_form.php
@@ -16,12 +16,9 @@ use yii\widgets\ActiveForm; | @@ -16,12 +16,9 @@ use yii\widgets\ActiveForm; | ||
16 | 16 | ||
17 | <?= $form->field($model, 'to_brand')->textInput(['maxlength' => true]) ?> | 17 | <?= $form->field($model, 'to_brand')->textInput(['maxlength' => true]) ?> |
18 | 18 | ||
19 | - <?= $form->field($model, 'finish')->textInput() ?> | ||
20 | - | ||
21 | - <?= $form->field($model, 'timestamp')->textInput() ?> | ||
22 | 19 | ||
23 | <div class="form-group"> | 20 | <div class="form-group"> |
24 | - <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> | 21 | + <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> |
25 | </div> | 22 | </div> |
26 | 23 | ||
27 | <?php ActiveForm::end(); ?> | 24 | <?php ActiveForm::end(); ?> |
backend/views/brands-replace/create.php
@@ -6,7 +6,7 @@ use yii\helpers\Html; | @@ -6,7 +6,7 @@ use yii\helpers\Html; | ||
6 | /* @var $this yii\web\View */ | 6 | /* @var $this yii\web\View */ |
7 | /* @var $model common\models\BrandsReplace */ | 7 | /* @var $model common\models\BrandsReplace */ |
8 | 8 | ||
9 | -$this->title = 'Добавить Brands Replace'; | 9 | +$this->title = 'Добавить'; |
10 | $this->params['breadcrumbs'][] = ['label' => 'Brands Replaces', 'url' => ['index']]; | 10 | $this->params['breadcrumbs'][] = ['label' => 'Brands Replaces', 'url' => ['index']]; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
backend/views/brands-replace/index.php
@@ -7,7 +7,7 @@ use yii\grid\GridView; | @@ -7,7 +7,7 @@ use yii\grid\GridView; | ||
7 | /* @var $searchModel common\models\BrandsReplaceSearch */ | 7 | /* @var $searchModel common\models\BrandsReplaceSearch */ |
8 | /* @var $dataProvider yii\data\ActiveDataProvider */ | 8 | /* @var $dataProvider yii\data\ActiveDataProvider */ |
9 | 9 | ||
10 | -$this->title = 'Brands Replaces'; | 10 | +$this->title = 'Замена брендов'; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
13 | <div class="brands-replace-index"> | 13 | <div class="brands-replace-index"> |
@@ -16,7 +16,7 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -16,7 +16,7 @@ $this->params['breadcrumbs'][] = $this->title; | ||
16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> | 16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> |
17 | 17 | ||
18 | <p> | 18 | <p> |
19 | - <?= Html::a('Добавить Brands Replace', ['create'], ['class' => 'btn btn-success']) ?> | 19 | + <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?> |
20 | </p> | 20 | </p> |
21 | 21 | ||
22 | <?= GridView::widget([ | 22 | <?= GridView::widget([ |
@@ -28,7 +28,21 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -28,7 +28,21 @@ $this->params['breadcrumbs'][] = $this->title; | ||
28 | 'id', | 28 | 'id', |
29 | 'from_brand', | 29 | 'from_brand', |
30 | 'to_brand', | 30 | 'to_brand', |
31 | - 'finish', | 31 | + ['attribute' => 'finish', |
32 | + 'format' => 'raw', | ||
33 | + 'filter' => [ | ||
34 | + '1'=>'Закончена', | ||
35 | + '0'=>'Не закончена', | ||
36 | + ], | ||
37 | + 'value' => function($data){ | ||
38 | + if($data->finish){ | ||
39 | + $status_img = '<i style="color: #008000" class="glyphicon glyphicon-ok"></i>'; | ||
40 | + } else { | ||
41 | + $status_img = '<i style="color: red" class="glyphicon glyphicon-remove"></i>'; | ||
42 | + } | ||
43 | + return $status_img; | ||
44 | + }, | ||
45 | + ], | ||
32 | 'timestamp', | 46 | 'timestamp', |
33 | 47 | ||
34 | ['class' => 'yii\grid\ActionColumn'], | 48 | ['class' => 'yii\grid\ActionColumn'], |
backend/views/brands-replace/update.php
@@ -5,7 +5,7 @@ use yii\helpers\Html; | @@ -5,7 +5,7 @@ use yii\helpers\Html; | ||
5 | /* @var $this yii\web\View */ | 5 | /* @var $this yii\web\View */ |
6 | /* @var $model common\models\BrandsReplace */ | 6 | /* @var $model common\models\BrandsReplace */ |
7 | 7 | ||
8 | -$this->title = 'Update Brands Replace: ' . ' ' . $model->from_brand; | 8 | +$this->title = 'Редактирование: ' . ' ' . $model->from_brand; |
9 | $this->params['breadcrumbs'][] = ['label' => 'Brands Replaces', 'url' => ['index']]; | 9 | $this->params['breadcrumbs'][] = ['label' => 'Brands Replaces', 'url' => ['index']]; |
10 | $this->params['breadcrumbs'][] = ['label' => $model->from_brand, 'url' => ['view', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand]]; | 10 | $this->params['breadcrumbs'][] = ['label' => $model->from_brand, 'url' => ['view', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand]]; |
11 | $this->params['breadcrumbs'][] = 'Update'; | 11 | $this->params['breadcrumbs'][] = 'Update'; |
backend/views/brands-replace/view.php
@@ -15,8 +15,8 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -15,8 +15,8 @@ $this->params['breadcrumbs'][] = $this->title; | ||
15 | <h1><?= Html::encode($this->title) ?></h1> | 15 | <h1><?= Html::encode($this->title) ?></h1> |
16 | 16 | ||
17 | <p> | 17 | <p> |
18 | - <?= Html::a('Update', ['update', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand], ['class' => 'btn btn-primary']) ?> | ||
19 | - <?= Html::a('Delete', ['delete', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand], [ | 18 | + <?= Html::a('Редактировать', ['update', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand], ['class' => 'btn btn-primary']) ?> |
19 | + <?= Html::a('Удалить', ['delete', 'from_brand' => $model->from_brand, 'to_brand' => $model->to_brand], [ | ||
20 | 'class' => 'btn btn-danger', | 20 | 'class' => 'btn btn-danger', |
21 | 'data' => [ | 21 | 'data' => [ |
22 | 'confirm' => 'Are you sure you want to delete this item?', | 22 | 'confirm' => 'Are you sure you want to delete this item?', |
backend/views/brands/_form.php
@@ -10,27 +10,53 @@ use yii\widgets\ActiveForm; | @@ -10,27 +10,53 @@ use yii\widgets\ActiveForm; | ||
10 | 10 | ||
11 | <div class="brands-form"> | 11 | <div class="brands-form"> |
12 | 12 | ||
13 | - <?php $form = ActiveForm::begin(); ?> | ||
14 | - | ||
15 | - <?= $form->field($model, 'BRAND')->textInput(['maxlength' => true]) ?> | ||
16 | - | ||
17 | - <?= $form->field($model, 'if_tecdoc')->textInput() ?> | ||
18 | - | ||
19 | - <?= $form->field($model, 'tecdoc_logo')->textInput(['maxlength' => true]) ?> | ||
20 | - | ||
21 | - <?= $form->field($model, 'if_oem')->textInput() ?> | 13 | + <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> |
14 | + | ||
15 | + <?php | ||
16 | + if($model->isNewRecord) | ||
17 | + echo $form->field($model, 'BRAND')->textInput(['maxlength' => true])->label('Название') | ||
18 | + ?> | ||
19 | + | ||
20 | + <?= $form->field($model, 'CONTENT')->widget(\mihaildev\ckeditor\CKEditor::className(),[ | ||
21 | + 'editorOptions' => \mihaildev\elfinder\ElFinder::ckeditorOptions('elfinder',[ | ||
22 | + 'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать | ||
23 | + 'inline' => false, //по умолчанию false]), | ||
24 | + // 'filebrowserUploadUrl'=>Yii::$app->getUrlManager()->createUrl('news/images-upload') | ||
25 | + ] | ||
26 | + ) | ||
27 | + ]); ?> | ||
28 | + | ||
29 | + <?= $form->field($model, 'if_oem')->checkbox() ?> | ||
30 | + | ||
31 | +<div class="container-fluid"> | ||
32 | + <fieldset> | ||
33 | + <legend>Изображение</legend> | ||
34 | + <div class="col-md-4"> | ||
35 | + <?= $form->field($model, 'file')->fileInput()->label(false)->hint('имя файла должно иметь только латинские символы и цифры',['tag'=>'span'])?> | ||
36 | + </div> | ||
22 | 37 | ||
23 | - <?= $form->field($model, 'if_checked')->textInput() ?> | 38 | + <div class="col-md-4"> |
39 | + <div> | ||
40 | + <?php | ||
41 | + if(!$model->isNewRecord && $model->IMG) | ||
42 | + echo $form->field($model, 'delete_img')->checkbox(); | ||
43 | + ?> | ||
44 | + </div> | ||
24 | 45 | ||
25 | - <?= $form->field($model, 'CONTENT')->textarea(['rows' => 6]) ?> | 46 | + <?php |
47 | + if(!$model->isNewRecord && $model->IMG) | ||
48 | + echo "Имя файла - $model->IMG"; | ||
49 | + ?> | ||
26 | 50 | ||
27 | - <?= $form->field($model, 'IMG')->textInput(['maxlength' => true]) ?> | 51 | + </div> |
52 | + <fieldset> | ||
28 | 53 | ||
29 | - <?= $form->field($model, 'timestamp')->textInput() ?> | 54 | +</div> |
30 | 55 | ||
31 | <div class="form-group"> | 56 | <div class="form-group"> |
32 | - <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> | 57 | + <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> |
33 | </div> | 58 | </div> |
59 | + <?= Html::a('Вернуться', ['index'], ['class' => 'btn btn-primary']) ?> | ||
34 | 60 | ||
35 | <?php ActiveForm::end(); ?> | 61 | <?php ActiveForm::end(); ?> |
36 | 62 |
backend/views/brands/create.php
@@ -6,7 +6,7 @@ use yii\helpers\Html; | @@ -6,7 +6,7 @@ use yii\helpers\Html; | ||
6 | /* @var $this yii\web\View */ | 6 | /* @var $this yii\web\View */ |
7 | /* @var $model common\models\Brands */ | 7 | /* @var $model common\models\Brands */ |
8 | 8 | ||
9 | -$this->title = 'Добавить Brands'; | 9 | +$this->title = 'Добавить бренд'; |
10 | $this->params['breadcrumbs'][] = ['label' => 'Brands', 'url' => ['index']]; | 10 | $this->params['breadcrumbs'][] = ['label' => 'Brands', 'url' => ['index']]; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
backend/views/brands/index.php
@@ -9,6 +9,8 @@ use yii\grid\GridView; | @@ -9,6 +9,8 @@ use yii\grid\GridView; | ||
9 | 9 | ||
10 | $this->title = 'Бренды'; | 10 | $this->title = 'Бренды'; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | +$img0 = '/storage/checkbox0.gif'; | ||
13 | +$img1 = '/storage/checkbox1.gif'; | ||
12 | ?> | 14 | ?> |
13 | <div class="brands-index"> | 15 | <div class="brands-index"> |
14 | 16 | ||
@@ -16,7 +18,7 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -16,7 +18,7 @@ $this->params['breadcrumbs'][] = $this->title; | ||
16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> | 18 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> |
17 | 19 | ||
18 | <p> | 20 | <p> |
19 | - <?= Html::a('Создать', ['create'], ['class' => 'btn btn-success']) ?> | 21 | + <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?> |
20 | </p> | 22 | </p> |
21 | 23 | ||
22 | <?= GridView::widget([ | 24 | <?= GridView::widget([ |
@@ -27,15 +29,34 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -27,15 +29,34 @@ $this->params['breadcrumbs'][] = $this->title; | ||
27 | 29 | ||
28 | 'ID', | 30 | 'ID', |
29 | 'BRAND', | 31 | 'BRAND', |
30 | - 'if_tecdoc', | ||
31 | - 'tecdoc_logo', | ||
32 | - 'if_oem', | ||
33 | - // 'if_checked', | ||
34 | - // 'CONTENT:ntext', | ||
35 | - // 'IMG', | ||
36 | - // 'timestamp', | ||
37 | - | ||
38 | - ['class' => 'yii\grid\ActionColumn'], | 32 | + ['attribute' => 'if_tecdoc', |
33 | + 'format' => 'raw', | ||
34 | + 'value' => function ( $model ) use ($img0, $img1) { | ||
35 | + if ($model->if_tecdoc == '1') { | ||
36 | + $info = " <img src=$img1>"; | ||
37 | + } | ||
38 | + else { | ||
39 | + $info = " <img src=$img0>"; | ||
40 | + } | ||
41 | + return $info; | ||
42 | + }, | ||
43 | + ], | ||
44 | + | ||
45 | + ['label' => 'ОРИГИНАЛ?', | ||
46 | + 'attribute' => 'if_oem', | ||
47 | + 'format' => 'raw', | ||
48 | + 'value' => function ( $model ) use ($img0, $img1) { | ||
49 | + if ($model->if_oem == '1') { | ||
50 | + $info = " <img src=$img1>"; | ||
51 | + } | ||
52 | + else { | ||
53 | + $info = " <img src=$img0>"; | ||
54 | + } | ||
55 | + return $info; | ||
56 | + }, | ||
57 | + ], | ||
58 | + ['class' => 'yii\grid\ActionColumn', | ||
59 | + 'template' => '{update}'], | ||
39 | ], | 60 | ], |
40 | ]); ?> | 61 | ]); ?> |
41 | 62 |
backend/views/brands/update.php
@@ -5,7 +5,7 @@ use yii\helpers\Html; | @@ -5,7 +5,7 @@ use yii\helpers\Html; | ||
5 | /* @var $this yii\web\View */ | 5 | /* @var $this yii\web\View */ |
6 | /* @var $model common\models\Brands */ | 6 | /* @var $model common\models\Brands */ |
7 | 7 | ||
8 | -$this->title = 'Update Brands: ' . ' ' . $model->BRAND; | 8 | +$this->title = 'Редактирование бренда: ' . ' ' . $model->BRAND; |
9 | $this->params['breadcrumbs'][] = ['label' => 'Brands', 'url' => ['index']]; | 9 | $this->params['breadcrumbs'][] = ['label' => 'Brands', 'url' => ['index']]; |
10 | $this->params['breadcrumbs'][] = ['label' => $model->BRAND, 'url' => ['view', 'id' => $model->BRAND]]; | 10 | $this->params['breadcrumbs'][] = ['label' => $model->BRAND, 'url' => ['view', 'id' => $model->BRAND]]; |
11 | $this->params['breadcrumbs'][] = 'Update'; | 11 | $this->params['breadcrumbs'][] = 'Update'; |
backend/views/details/_form.php
@@ -2,6 +2,8 @@ | @@ -2,6 +2,8 @@ | ||
2 | 2 | ||
3 | use yii\helpers\Html; | 3 | use yii\helpers\Html; |
4 | use yii\widgets\ActiveForm; | 4 | use yii\widgets\ActiveForm; |
5 | +use yii\helpers\ArrayHelper; | ||
6 | +use backend\models\Importers; | ||
5 | 7 | ||
6 | /* @var $this yii\web\View */ | 8 | /* @var $this yii\web\View */ |
7 | /* @var $model common\models\Details */ | 9 | /* @var $model common\models\Details */ |
@@ -10,9 +12,13 @@ use yii\widgets\ActiveForm; | @@ -10,9 +12,13 @@ use yii\widgets\ActiveForm; | ||
10 | 12 | ||
11 | <div class="details-form"> | 13 | <div class="details-form"> |
12 | 14 | ||
13 | - <?php $form = ActiveForm::begin(); ?> | 15 | + <?php $form = ActiveForm::begin(); |
16 | + // первый элемент массива должен быть пустым | ||
17 | + $arr_importers = [ null => '' ]; | ||
18 | + $arr_importers = array_merge( $arr_importers, ArrayHelper::map( Importers::find()->orderBy('name')->all(), 'id','name' ) ); | ||
19 | + ?> | ||
14 | 20 | ||
15 | - <?= $form->field($model, 'IMPORT_ID')->textInput() ?> | 21 | + <?= $form->field($model, 'IMPORT_ID')->dropDownList( $arr_importers ) ?> |
16 | 22 | ||
17 | <?= $form->field($model, 'BRAND')->textInput(['maxlength' => true]) ?> | 23 | <?= $form->field($model, 'BRAND')->textInput(['maxlength' => true]) ?> |
18 | 24 | ||
@@ -30,11 +36,11 @@ use yii\widgets\ActiveForm; | @@ -30,11 +36,11 @@ use yii\widgets\ActiveForm; | ||
30 | 36 | ||
31 | <?= $form->field($model, 'GROUP')->textInput(['maxlength' => true]) ?> | 37 | <?= $form->field($model, 'GROUP')->textInput(['maxlength' => true]) ?> |
32 | 38 | ||
33 | - <?= $form->field($model, 'timestamp')->textInput() ?> | ||
34 | 39 | ||
35 | <div class="form-group"> | 40 | <div class="form-group"> |
36 | - <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> | 41 | + <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> |
37 | </div> | 42 | </div> |
43 | + <?= Html::a('Вернуться', ['index'], ['class' => 'btn btn-primary']) ?> | ||
38 | 44 | ||
39 | <?php ActiveForm::end(); ?> | 45 | <?php ActiveForm::end(); ?> |
40 | 46 |
backend/views/details/index.php
@@ -7,7 +7,7 @@ use yii\grid\GridView; | @@ -7,7 +7,7 @@ use yii\grid\GridView; | ||
7 | /* @var $searchModel common\models\DetailsSearch */ | 7 | /* @var $searchModel common\models\DetailsSearch */ |
8 | /* @var $dataProvider yii\data\ActiveDataProvider */ | 8 | /* @var $dataProvider yii\data\ActiveDataProvider */ |
9 | 9 | ||
10 | -$this->title = 'Список запчастей'; | 10 | +$this->title = 'Товары поставщиков'; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
13 | <div class="details-index"> | 13 | <div class="details-index"> |
@@ -16,7 +16,7 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -16,7 +16,7 @@ $this->params['breadcrumbs'][] = $this->title; | ||
16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> | 16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> |
17 | 17 | ||
18 | <p> | 18 | <p> |
19 | - <?= Html::a('Создать', ['create'], ['class' => 'btn btn-success']) ?> | 19 | + <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?> |
20 | </p> | 20 | </p> |
21 | 21 | ||
22 | <?= GridView::widget([ | 22 | <?= GridView::widget([ |
@@ -27,7 +27,12 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -27,7 +27,12 @@ $this->params['breadcrumbs'][] = $this->title; | ||
27 | ['class' => 'yii\grid\SerialColumn'], | 27 | ['class' => 'yii\grid\SerialColumn'], |
28 | 'ARTICLE', | 28 | 'ARTICLE', |
29 | 'BRAND', | 29 | 'BRAND', |
30 | - 'IMPORT_ID', | 30 | + ['attribute' => 'IMPORT_ID', |
31 | + 'value' => function($model) | ||
32 | + { | ||
33 | + return $model->importer; | ||
34 | + } | ||
35 | + ], | ||
31 | 'DESCR', | 36 | 'DESCR', |
32 | 'BOX', | 37 | 'BOX', |
33 | 'ADD_BOX', | 38 | 'ADD_BOX', |
@@ -35,7 +40,8 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -35,7 +40,8 @@ $this->params['breadcrumbs'][] = $this->title; | ||
35 | 'GROUP', | 40 | 'GROUP', |
36 | // 'timestamp', | 41 | // 'timestamp', |
37 | 42 | ||
38 | - ['class' => 'yii\grid\ActionColumn'], | 43 | + ['class' => 'yii\grid\ActionColumn', |
44 | + 'template' => '{update},{delete}'], | ||
39 | ], | 45 | ], |
40 | ]); ?> | 46 | ]); ?> |
41 | 47 |
backend/views/details/update.php
@@ -5,7 +5,7 @@ use yii\helpers\Html; | @@ -5,7 +5,7 @@ use yii\helpers\Html; | ||
5 | /* @var $this yii\web\View */ | 5 | /* @var $this yii\web\View */ |
6 | /* @var $model common\models\Details */ | 6 | /* @var $model common\models\Details */ |
7 | 7 | ||
8 | -$this->title = 'Update Details: ' . ' ' . $model->IMPORT_ID; | 8 | +$this->title = 'Редактирование записи: ' . ' ' . $model->IMPORT_ID; |
9 | $this->params['breadcrumbs'][] = ['label' => 'Details', 'url' => ['index']]; | 9 | $this->params['breadcrumbs'][] = ['label' => 'Details', 'url' => ['index']]; |
10 | $this->params['breadcrumbs'][] = ['label' => $model->IMPORT_ID, 'url' => ['view', 'IMPORT_ID' => $model->IMPORT_ID, 'BRAND' => $model->BRAND, 'ARTICLE' => $model->ARTICLE]]; | 10 | $this->params['breadcrumbs'][] = ['label' => $model->IMPORT_ID, 'url' => ['view', 'IMPORT_ID' => $model->IMPORT_ID, 'BRAND' => $model->BRAND, 'ARTICLE' => $model->ARTICLE]]; |
11 | $this->params['breadcrumbs'][] = 'Update'; | 11 | $this->params['breadcrumbs'][] = 'Update'; |
backend/views/margins/_form.php
@@ -17,7 +17,7 @@ use yii\widgets\ActiveForm; | @@ -17,7 +17,7 @@ use yii\widgets\ActiveForm; | ||
17 | <?= $form->field($model, 'koef')->textInput() ?> | 17 | <?= $form->field($model, 'koef')->textInput() ?> |
18 | 18 | ||
19 | <div class="form-group"> | 19 | <div class="form-group"> |
20 | - <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> | 20 | + <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> |
21 | </div> | 21 | </div> |
22 | 22 | ||
23 | <?php ActiveForm::end(); ?> | 23 | <?php ActiveForm::end(); ?> |
backend/views/margins/create.php
@@ -6,7 +6,7 @@ use yii\helpers\Html; | @@ -6,7 +6,7 @@ use yii\helpers\Html; | ||
6 | /* @var $this yii\web\View */ | 6 | /* @var $this yii\web\View */ |
7 | /* @var $model common\models\Margins */ | 7 | /* @var $model common\models\Margins */ |
8 | 8 | ||
9 | -$this->title = 'Добавить Margins'; | 9 | +$this->title = 'Добавить тип цен'; |
10 | $this->params['breadcrumbs'][] = ['label' => 'Margins', 'url' => ['index']]; | 10 | $this->params['breadcrumbs'][] = ['label' => 'Margins', 'url' => ['index']]; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
@@ -18,4 +18,6 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -18,4 +18,6 @@ $this->params['breadcrumbs'][] = $this->title; | ||
18 | 'model' => $model, | 18 | 'model' => $model, |
19 | ]) ?> | 19 | ]) ?> |
20 | 20 | ||
21 | + <?= Html::a('Вернуться', ['index'], ['class' => 'btn btn-primary']) ?> | ||
22 | + | ||
21 | </div> | 23 | </div> |
backend/views/margins/index.php
@@ -7,7 +7,7 @@ use yii\grid\GridView; | @@ -7,7 +7,7 @@ use yii\grid\GridView; | ||
7 | /* @var $searchModel common\models\MarginsSearch */ | 7 | /* @var $searchModel common\models\MarginsSearch */ |
8 | /* @var $dataProvider yii\data\ActiveDataProvider */ | 8 | /* @var $dataProvider yii\data\ActiveDataProvider */ |
9 | 9 | ||
10 | -$this->title = 'Margins'; | 10 | +$this->title = 'Типы цен'; |
11 | $this->params['breadcrumbs'][] = $this->title; | 11 | $this->params['breadcrumbs'][] = $this->title; |
12 | ?> | 12 | ?> |
13 | <div class="margins-index"> | 13 | <div class="margins-index"> |
@@ -16,19 +16,17 @@ $this->params['breadcrumbs'][] = $this->title; | @@ -16,19 +16,17 @@ $this->params['breadcrumbs'][] = $this->title; | ||
16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> | 16 | <?php // echo $this->render('_search', ['model' => $searchModel]); ?> |
17 | 17 | ||
18 | <p> | 18 | <p> |
19 | - <?= Html::a('Добавить Margins', ['create'], ['class' => 'btn btn-success']) ?> | 19 | + <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?> |
20 | </p> | 20 | </p> |
21 | 21 | ||
22 | <?= GridView::widget([ | 22 | <?= GridView::widget([ |
23 | 'dataProvider' => $dataProvider, | 23 | 'dataProvider' => $dataProvider, |
24 | - 'filterModel' => $searchModel, | ||
25 | 'columns' => [ | 24 | 'columns' => [ |
26 | ['class' => 'yii\grid\SerialColumn'], | 25 | ['class' => 'yii\grid\SerialColumn'], |
27 | - | ||
28 | 'name', | 26 | 'name', |
29 | 'koef', | 27 | 'koef', |
30 | - | ||
31 | - ['class' => 'yii\grid\ActionColumn'], | 28 | + ['class' => 'yii\grid\ActionColumn', |
29 | + 'template' => '{update}{delete}'], | ||
32 | ], | 30 | ], |
33 | ]); ?> | 31 | ]); ?> |
34 | 32 |
backend/views/margins/update.php
@@ -5,10 +5,10 @@ use yii\helpers\Html; | @@ -5,10 +5,10 @@ use yii\helpers\Html; | ||
5 | /* @var $this yii\web\View */ | 5 | /* @var $this yii\web\View */ |
6 | /* @var $model common\models\Margins */ | 6 | /* @var $model common\models\Margins */ |
7 | 7 | ||
8 | -$this->title = 'Update Margins: ' . ' ' . $model->name; | 8 | +$this->title = 'Редактировать тип цен: ' . ' ' . $model->name; |
9 | $this->params['breadcrumbs'][] = ['label' => 'Margins', 'url' => ['index']]; | 9 | $this->params['breadcrumbs'][] = ['label' => 'Margins', 'url' => ['index']]; |
10 | $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]]; | 10 | $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]]; |
11 | -$this->params['breadcrumbs'][] = 'Update'; | 11 | +$this->params['breadcrumbs'][] = 'Обновить'; |
12 | ?> | 12 | ?> |
13 | <div class="margins-update"> | 13 | <div class="margins-update"> |
14 | 14 | ||
@@ -18,4 +18,6 @@ $this->params['breadcrumbs'][] = 'Update'; | @@ -18,4 +18,6 @@ $this->params['breadcrumbs'][] = 'Update'; | ||
18 | 'model' => $model, | 18 | 'model' => $model, |
19 | ]) ?> | 19 | ]) ?> |
20 | 20 | ||
21 | + <?= Html::a('Вернуться', ['index'], ['class' => 'btn btn-primary']) ?> | ||
22 | + | ||
21 | </div> | 23 | </div> |
backend/views/parser/index.php
@@ -24,7 +24,7 @@ if ( $model->mode ) { | @@ -24,7 +24,7 @@ if ( $model->mode ) { | ||
24 | <h3>Загрузка прайсов поставщиков</h3> | 24 | <h3>Загрузка прайсов поставщиков</h3> |
25 | 25 | ||
26 | 26 | ||
27 | - <?= $form->field($model, 'importer_id')->dropDownList(ArrayHelper::map( Importers::find()->all(), 'id','name' )); ?> | 27 | + <?= $form->field($model, 'importer_id')->dropDownList(ArrayHelper::map( Importers::find()->orderBy('name')->all(), 'id','name' )); ?> |
28 | 28 | ||
29 | <?php if ( !$mode ) { | 29 | <?php if ( !$mode ) { |
30 | echo $form->field($model, 'delete_price')->checkbox(['label' => 'Загрузить с удалением старого прайса']); | 30 | echo $form->field($model, 'delete_price')->checkbox(['label' => 'Загрузить с удалением старого прайса']); |
common/components/PriceWriter.php
@@ -12,7 +12,7 @@ namespace common\components; | @@ -12,7 +12,7 @@ namespace common\components; | ||
12 | use yii\base\ErrorException; | 12 | use yii\base\ErrorException; |
13 | use backend\models\ImportersFiles; | 13 | use backend\models\ImportersFiles; |
14 | use backend\models\Importers; | 14 | use backend\models\Importers; |
15 | -use backend\models\Details; | 15 | +use common\models\Details; |
16 | use common\components\ModelArrayValidator; | 16 | use common\components\ModelArrayValidator; |
17 | 17 | ||
18 | /** | 18 | /** |
common/components/exceptions/OrdinaryActiveRecordException.php
0 → 100644
1 | +<?php | ||
2 | +/** | ||
3 | + * Created by PhpStorm. | ||
4 | + * User: Tsurkanov | ||
5 | + * Date: 30.11.2015 | ||
6 | + * Time: 17:36 | ||
7 | + */ | ||
8 | + | ||
9 | +namespace common\components\exceptions; | ||
10 | + | ||
11 | + | ||
12 | +use yii\base\UserException; | ||
13 | + | ||
14 | +class OrdinaryActiveRecordException extends UserException { | ||
15 | + // для хранения имени AR где произошла ошибка | ||
16 | + // используется для обработки ошибок | ||
17 | + public $active_record_name = ''; | ||
18 | +} | ||
0 | \ No newline at end of file | 19 | \ No newline at end of file |
common/components/parsers/Converter.php
@@ -44,7 +44,7 @@ class Converter implements ConverterInterface | @@ -44,7 +44,7 @@ class Converter implements ConverterInterface | ||
44 | if ($value == '') { | 44 | if ($value == '') { |
45 | return ''; | 45 | return ''; |
46 | } | 46 | } |
47 | - $value = round((int)$value, 2); | 47 | + $value = (int)$value; |
48 | 48 | ||
49 | return $value; | 49 | return $value; |
50 | } | 50 | } |
common/components/parsers/CsvParser.php
@@ -17,7 +17,7 @@ class CsvParser extends TableParser | @@ -17,7 +17,7 @@ class CsvParser extends TableParser | ||
17 | 17 | ||
18 | 18 | ||
19 | /** | 19 | /** |
20 | - * метод устанвливает нужные настройки объекта SplFileObject, для работы с csv | 20 | + * метод устанавливает настройки конвертера |
21 | */ | 21 | */ |
22 | public function setup() | 22 | public function setup() |
23 | { | 23 | { |
@@ -40,33 +40,6 @@ class CsvParser extends TableParser | @@ -40,33 +40,6 @@ class CsvParser extends TableParser | ||
40 | $this->row = fgetcsv( $this->file, 0, $this->delimiter ); | 40 | $this->row = fgetcsv( $this->file, 0, $this->delimiter ); |
41 | } | 41 | } |
42 | 42 | ||
43 | - protected function isEmptyRow(){ | ||
44 | - | ||
45 | - $is_empty = false; | ||
46 | - | ||
47 | - if ($this->row === false || $this->row === NULL ) { | ||
48 | - return true; | ||
49 | - } | ||
50 | - | ||
51 | - $j = 0; | ||
52 | - for ($i = 1; $i <= count( $this->row ); $i++) { | ||
53 | - | ||
54 | - if ( !isset( $this->row[ $i - 1 ] ) ) { | ||
55 | - continue; | ||
56 | - } | ||
57 | - | ||
58 | - if ( $this->isEmptyColumn( $this->row[$i - 1] ) ) { | ||
59 | - $j++; | ||
60 | - } | ||
61 | - | ||
62 | - if ( $j >= $this->min_column_quantity ) { | ||
63 | - $is_empty = true; | ||
64 | - break; | ||
65 | - } | ||
66 | - } | ||
67 | - | ||
68 | - return $is_empty; | ||
69 | - } | ||
70 | 43 | ||
71 | protected function isEmptyColumn( $val ){ | 44 | protected function isEmptyColumn( $val ){ |
72 | return $val == ''; | 45 | return $val == ''; |
common/components/parsers/CustomConverter.php
@@ -3,7 +3,7 @@ namespace common\components\parsers; | @@ -3,7 +3,7 @@ namespace common\components\parsers; | ||
3 | 3 | ||
4 | use common\components\CustomVarDamp; | 4 | use common\components\CustomVarDamp; |
5 | use common\components\parsers\Converter; | 5 | use common\components\parsers\Converter; |
6 | -use backend\models\Details; | 6 | +use common\models\Details; |
7 | use backend\models\DetailsCrosses; | 7 | use backend\models\DetailsCrosses; |
8 | use backend\models\ImportersPrefix; | 8 | use backend\models\ImportersPrefix; |
9 | 9 |
1 | +<?php | ||
2 | +// Test CVS | ||
3 | + | ||
4 | +require_once 'Excel/reader.php'; | ||
5 | + | ||
6 | + | ||
7 | +// ExcelFile($filename, $encoding); | ||
8 | +$data = new Spreadsheet_Excel_Reader(); | ||
9 | + | ||
10 | + | ||
11 | +// Set output Encoding. | ||
12 | +$data->setOutputEncoding('CP1251'); | ||
13 | + | ||
14 | +/*** | ||
15 | +* if you want you can change 'iconv' to mb_convert_encoding: | ||
16 | +* $data->setUTFEncoder('mb'); | ||
17 | +* | ||
18 | +**/ | ||
19 | + | ||
20 | +/*** | ||
21 | +* By default rows & cols indeces start with 1 | ||
22 | +* For change initial index use: | ||
23 | +* $data->setRowColOffset(0); | ||
24 | +* | ||
25 | +**/ | ||
26 | + | ||
27 | + | ||
28 | + | ||
29 | +/*** | ||
30 | +* Some function for formatting output. | ||
31 | +* $data->setDefaultFormat('%.2f'); | ||
32 | +* setDefaultFormat - set format for columns with unknown formatting | ||
33 | +* | ||
34 | +* $data->setColumnFormat(4, '%.3f'); | ||
35 | +* setColumnFormat - set format for column (apply only to number fields) | ||
36 | +* | ||
37 | +**/ | ||
38 | + | ||
39 | +$data->read('jxlrwtest.xls'); | ||
40 | + | ||
41 | +/* | ||
42 | + | ||
43 | + | ||
44 | + $data->sheets[0]['numRows'] - count rows | ||
45 | + $data->sheets[0]['numCols'] - count columns | ||
46 | + $data->sheets[0]['cells'][$i][$j] - data from $i-row $j-column | ||
47 | + | ||
48 | + $data->sheets[0]['cellsInfo'][$i][$j] - extended info about cell | ||
49 | + | ||
50 | + $data->sheets[0]['cellsInfo'][$i][$j]['type'] = "date" | "number" | "unknown" | ||
51 | + if 'type' == "unknown" - use 'raw' value, because cell contain value with format '0.00'; | ||
52 | + $data->sheets[0]['cellsInfo'][$i][$j]['raw'] = value if cell without format | ||
53 | + $data->sheets[0]['cellsInfo'][$i][$j]['colspan'] | ||
54 | + $data->sheets[0]['cellsInfo'][$i][$j]['rowspan'] | ||
55 | +*/ | ||
56 | + | ||
57 | +error_reporting(E_ALL ^ E_NOTICE); | ||
58 | + | ||
59 | +for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { | ||
60 | + for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { | ||
61 | + echo "\"".$data->sheets[0]['cells'][$i][$j]."\","; | ||
62 | + } | ||
63 | + echo "\n"; | ||
64 | + | ||
65 | +} | ||
66 | + | ||
67 | + | ||
68 | +//print_r($data); | ||
69 | +//print_r($data->formatRecords); | ||
70 | +?> |
1 | +<? | ||
2 | +$allow_url_override = 1; // Set to 0 to not allow changed VIA POST or GET | ||
3 | +if(!$allow_url_override || !isset($file_to_include)) | ||
4 | +{ | ||
5 | + $file_to_include = "jxlrwtest.xls"; | ||
6 | +} | ||
7 | +if(!$allow_url_override || !isset($max_rows)) | ||
8 | +{ | ||
9 | + $max_rows = 0; //USE 0 for no max | ||
10 | +} | ||
11 | +if(!$allow_url_override || !isset($max_cols)) | ||
12 | +{ | ||
13 | + $max_cols = 5; //USE 0 for no max | ||
14 | +} | ||
15 | +if(!$allow_url_override || !isset($debug)) | ||
16 | +{ | ||
17 | + $debug = 0; //1 for on 0 for off | ||
18 | +} | ||
19 | +if(!$allow_url_override || !isset($force_nobr)) | ||
20 | +{ | ||
21 | + $force_nobr = 1; //Force the info in cells not to wrap unless stated explicitly (newline) | ||
22 | +} | ||
23 | + | ||
24 | +require_once 'Excel/reader.php'; | ||
25 | +$data = new Spreadsheet_Excel_Reader(); | ||
26 | +$data->setOutputEncoding('CPa25a'); | ||
27 | +$data->read($file_to_include); | ||
28 | +error_reporting(E_ALL ^ E_NOTICE); | ||
29 | +echo " | ||
30 | +<STYLE> | ||
31 | +.table_data | ||
32 | +{ | ||
33 | + border-style:ridge; | ||
34 | + border-width:1; | ||
35 | +} | ||
36 | +.tab_base | ||
37 | +{ | ||
38 | + background:#C5D0DD; | ||
39 | + font-weight:bold; | ||
40 | + border-style:ridge; | ||
41 | + border-width:1; | ||
42 | + cursor:pointer; | ||
43 | +} | ||
44 | +.table_sub_heading | ||
45 | +{ | ||
46 | + background:#CCCCCC; | ||
47 | + font-weight:bold; | ||
48 | + border-style:ridge; | ||
49 | + border-width:1; | ||
50 | +} | ||
51 | +.table_body | ||
52 | +{ | ||
53 | + background:#F0F0F0; | ||
54 | + font-wieght:normal; | ||
55 | + font-size:12; | ||
56 | + font-family:sans-serif; | ||
57 | + border-style:ridge; | ||
58 | + border-width:1; | ||
59 | + border-spacing: 0px; | ||
60 | + border-collapse: collapse; | ||
61 | +} | ||
62 | +.tab_loaded | ||
63 | +{ | ||
64 | + background:#222222; | ||
65 | + color:white; | ||
66 | + font-weight:bold; | ||
67 | + border-style:groove; | ||
68 | + border-width:1; | ||
69 | + cursor:pointer; | ||
70 | +} | ||
71 | +</STYLE> | ||
72 | +"; | ||
73 | +function make_alpha_from_numbers($number) | ||
74 | +{ | ||
75 | + $numeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | ||
76 | + if($number<strlen($numeric)) | ||
77 | + { | ||
78 | + return $numeric[$number]; | ||
79 | + } | ||
80 | + else | ||
81 | + { | ||
82 | + $dev_by = floor($number/strlen($numeric)); | ||
83 | + return "" . make_alpha_from_numbers($dev_by-1) . make_alpha_from_numbers($number-($dev_by*strlen($numeric))); | ||
84 | + } | ||
85 | +} | ||
86 | +echo "<SCRIPT LANGUAGE='JAVASCRIPT'> | ||
87 | +var sheet_HTML = Array();\n"; | ||
88 | +for($sheet=0;$sheet<count($data->sheets);$sheet++) | ||
89 | +{ | ||
90 | + $table_output[$sheet] .= "<TABLE CLASS='table_body'> | ||
91 | + <TR> | ||
92 | + <TD> </TD>"; | ||
93 | + for($i=0;$i<$data->sheets[$sheet]['numCols']&&($i<=$max_cols||$max_cols==0);$i++) | ||
94 | + { | ||
95 | + $table_output[$sheet] .= "<TD CLASS='table_sub_heading' ALIGN=CENTER>" . make_alpha_from_numbers($i) . "</TD>"; | ||
96 | + } | ||
97 | + for($row=1;$row<=$data->sheets[$sheet]['numRows']&&($row<=$max_rows||$max_rows==0);$row++) | ||
98 | + { | ||
99 | + $table_output[$sheet] .= "<TR><TD CLASS='table_sub_heading'>" . $row . "</TD>"; | ||
100 | + for($col=1;$col<=$data->sheets[$sheet]['numCols']&&($col<=$max_cols||$max_cols==0);$col++) | ||
101 | + { | ||
102 | + if($data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan'] >=1 && $data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan'] >=1) | ||
103 | + { | ||
104 | + $this_cell_colspan = " COLSPAN=" . $data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan']; | ||
105 | + $this_cell_rowspan = " ROWSPAN=" . $data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan']; | ||
106 | + for($i=1;$i<$data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan'];$i++) | ||
107 | + { | ||
108 | + $data->sheets[$sheet]['cellsInfo'][$row][$col+$i]['dontprint']=1; | ||
109 | + } | ||
110 | + for($i=1;$i<$data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan'];$i++) | ||
111 | + { | ||
112 | + for($j=0;$j<$data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan'];$j++) | ||
113 | + { | ||
114 | + $data->sheets[$sheet]['cellsInfo'][$row+$i][$col+$j]['dontprint']=1; | ||
115 | + } | ||
116 | + } | ||
117 | + } | ||
118 | + else if($data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan'] >=1) | ||
119 | + { | ||
120 | + $this_cell_colspan = " COLSPAN=" . $data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan']; | ||
121 | + $this_cell_rowspan = ""; | ||
122 | + for($i=1;$i<$data->sheets[$sheet]['cellsInfo'][$row][$col]['colspan'];$i++) | ||
123 | + { | ||
124 | + $data->sheets[$sheet]['cellsInfo'][$row][$col+$i]['dontprint']=1; | ||
125 | + } | ||
126 | + } | ||
127 | + else if($data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan'] >=1) | ||
128 | + { | ||
129 | + $this_cell_colspan = ""; | ||
130 | + $this_cell_rowspan = " ROWSPAN=" . $data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan']; | ||
131 | + for($i=1;$i<$data->sheets[$sheet]['cellsInfo'][$row][$col]['rowspan'];$i++) | ||
132 | + { | ||
133 | + $data->sheets[$sheet]['cellsInfo'][$row+$i][$col]['dontprint']=1; | ||
134 | + } | ||
135 | + } | ||
136 | + else | ||
137 | + { | ||
138 | + $this_cell_colspan = ""; | ||
139 | + $this_cell_rowspan = ""; | ||
140 | + } | ||
141 | + if(!($data->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint'])) | ||
142 | + { | ||
143 | + $table_output[$sheet] .= "<TD CLASS='table_data' $this_cell_colspan $this_cell_rowspan> "; | ||
144 | + if($force_nobr) | ||
145 | + { | ||
146 | + $table_output[$sheet] .= "<NOBR>"; | ||
147 | + } | ||
148 | + $table_output[$sheet] .= nl2br(htmlentities($data->sheets[$sheet]['cells'][$row][$col])); | ||
149 | + if($force_nobr) | ||
150 | + { | ||
151 | + $table_output[$sheet] .= "</NOBR>"; | ||
152 | + } | ||
153 | + $table_output[$sheet] .= "</TD>"; | ||
154 | + } | ||
155 | + } | ||
156 | + $table_output[$sheet] .= "</TR>"; | ||
157 | + } | ||
158 | + $table_output[$sheet] .= "</TABLE>"; | ||
159 | + $table_output[$sheet] = str_replace("\n","",$table_output[$sheet]); | ||
160 | + $table_output[$sheet] = str_replace("\r","",$table_output[$sheet]); | ||
161 | + $table_output[$sheet] = str_replace("\t"," ",$table_output[$sheet]); | ||
162 | + if($debug) | ||
163 | + { | ||
164 | + $debug_output = print_r($data->sheets[$sheet],true); | ||
165 | + $debug_output = str_replace("\n","\\n",$debug_output); | ||
166 | + $debug_output = str_replace("\r","\\r",$debug_output); | ||
167 | + $table_output[$sheet] .= "<PRE>$debug_output</PRE>"; | ||
168 | + } | ||
169 | + echo "sheet_HTML[$sheet] = \"$table_output[$sheet]\";\n"; | ||
170 | +} | ||
171 | +echo " | ||
172 | +function change_tabs(sheet) | ||
173 | +{ | ||
174 | + //alert('sheet_tab_' + sheet); | ||
175 | + for(i=0;i<" , count($data->sheets) , ";i++) | ||
176 | + { | ||
177 | + document.getElementById('sheet_tab_' + i).className = 'tab_base'; | ||
178 | + } | ||
179 | + document.getElementById('table_loader_div').innerHTML=sheet_HTML[sheet]; | ||
180 | + document.getElementById('sheet_tab_' + sheet).className = 'tab_loaded'; | ||
181 | + | ||
182 | +} | ||
183 | +</SCRIPT>"; | ||
184 | +echo " | ||
185 | +<TABLE CLASS='table_body' NAME='tab_table'> | ||
186 | +<TR>"; | ||
187 | +for($sheet=0;$sheet<count($data->sheets);$sheet++) | ||
188 | +{ | ||
189 | + echo "<TD CLASS='tab_base' ID='sheet_tab_$sheet' ALIGN=CENTER | ||
190 | + ONMOUSEDOWN=\"change_tabs($sheet);\">", $data->boundsheets[$sheet]['name'] , "</TD>"; | ||
191 | +} | ||
192 | + | ||
193 | +echo | ||
194 | +"<TR>"; | ||
195 | +echo "</TABLE> | ||
196 | +<DIV ID=table_loader_div></DIV> | ||
197 | +<SCRIPT LANGUAGE='JavaScript'> | ||
198 | +change_tabs(0); | ||
199 | +</SCRIPT>"; | ||
200 | +//echo "<IFRAME NAME=table_loader_iframe SRC='about:blank' WIDTH=100 HEIGHT=100></IFRAME>"; | ||
201 | +/* | ||
202 | +echo "<PRE>"; | ||
203 | +print_r($data); | ||
204 | +echo "</PRE>"; | ||
205 | +*/ | ||
206 | +?> | ||
0 | \ No newline at end of file | 207 | \ No newline at end of file |
1 | +<?php | ||
2 | +define('NUM_BIG_BLOCK_DEPOT_BLOCKS_POS', 0x2c); | ||
3 | +define('SMALL_BLOCK_DEPOT_BLOCK_POS', 0x3c); | ||
4 | +define('ROOT_START_BLOCK_POS', 0x30); | ||
5 | +define('BIG_BLOCK_SIZE', 0x200); | ||
6 | +define('SMALL_BLOCK_SIZE', 0x40); | ||
7 | +define('EXTENSION_BLOCK_POS', 0x44); | ||
8 | +define('NUM_EXTENSION_BLOCK_POS', 0x48); | ||
9 | +define('PROPERTY_STORAGE_BLOCK_SIZE', 0x80); | ||
10 | +define('BIG_BLOCK_DEPOT_BLOCKS_POS', 0x4c); | ||
11 | +define('SMALL_BLOCK_THRESHOLD', 0x1000); | ||
12 | +// property storage offsets | ||
13 | +define('SIZE_OF_NAME_POS', 0x40); | ||
14 | +define('TYPE_POS', 0x42); | ||
15 | +define('START_BLOCK_POS', 0x74); | ||
16 | +define('SIZE_POS', 0x78); | ||
17 | +define('IDENTIFIER_OLE', pack("CCCCCCCC",0xd0,0xcf,0x11,0xe0,0xa1,0xb1,0x1a,0xe1)); | ||
18 | + | ||
19 | +//echo 'ROOT_START_BLOCK_POS = '.ROOT_START_BLOCK_POS."\n"; | ||
20 | + | ||
21 | +//echo bin2hex($data[ROOT_START_BLOCK_POS])."\n"; | ||
22 | +//echo "a="; | ||
23 | +//echo $data[ROOT_START_BLOCK_POS]; | ||
24 | +//function log | ||
25 | + | ||
26 | +function GetInt4d($data, $pos) | ||
27 | +{ | ||
28 | + $value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24); | ||
29 | + if ($value>=4294967294) | ||
30 | + { | ||
31 | + $value=-2; | ||
32 | + } | ||
33 | + return $value; | ||
34 | +} | ||
35 | + | ||
36 | + | ||
37 | +class OLERead { | ||
38 | + var $data = ''; | ||
39 | + | ||
40 | + | ||
41 | + function OLERead(){ | ||
42 | + | ||
43 | + | ||
44 | + } | ||
45 | + | ||
46 | + function read($sFileName){ | ||
47 | + | ||
48 | + // check if file exist and is readable (Darko Miljanovic) | ||
49 | + if(!is_readable($sFileName)) { | ||
50 | + $this->error = 1; | ||
51 | + return false; | ||
52 | + } | ||
53 | + | ||
54 | + $this->data = @file_get_contents($sFileName); | ||
55 | + if (!$this->data) { | ||
56 | + $this->error = 1; | ||
57 | + return false; | ||
58 | + } | ||
59 | + //echo IDENTIFIER_OLE; | ||
60 | + //echo 'start'; | ||
61 | + if (substr($this->data, 0, 8) != IDENTIFIER_OLE) { | ||
62 | + $this->error = 1; | ||
63 | + return false; | ||
64 | + } | ||
65 | + $this->numBigBlockDepotBlocks = GetInt4d($this->data, NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); | ||
66 | + $this->sbdStartBlock = GetInt4d($this->data, SMALL_BLOCK_DEPOT_BLOCK_POS); | ||
67 | + $this->rootStartBlock = GetInt4d($this->data, ROOT_START_BLOCK_POS); | ||
68 | + $this->extensionBlock = GetInt4d($this->data, EXTENSION_BLOCK_POS); | ||
69 | + $this->numExtensionBlocks = GetInt4d($this->data, NUM_EXTENSION_BLOCK_POS); | ||
70 | + | ||
71 | + /* | ||
72 | + echo $this->numBigBlockDepotBlocks." "; | ||
73 | + echo $this->sbdStartBlock." "; | ||
74 | + echo $this->rootStartBlock." "; | ||
75 | + echo $this->extensionBlock." "; | ||
76 | + echo $this->numExtensionBlocks." "; | ||
77 | + */ | ||
78 | + //echo "sbdStartBlock = $this->sbdStartBlock\n"; | ||
79 | + $bigBlockDepotBlocks = array(); | ||
80 | + $pos = BIG_BLOCK_DEPOT_BLOCKS_POS; | ||
81 | + // echo "pos = $pos"; | ||
82 | + $bbdBlocks = $this->numBigBlockDepotBlocks; | ||
83 | + | ||
84 | + if ($this->numExtensionBlocks != 0) { | ||
85 | + $bbdBlocks = (BIG_BLOCK_SIZE - BIG_BLOCK_DEPOT_BLOCKS_POS)/4; | ||
86 | + } | ||
87 | + | ||
88 | + for ($i = 0; $i < $bbdBlocks; $i++) { | ||
89 | + $bigBlockDepotBlocks[$i] = GetInt4d($this->data, $pos); | ||
90 | + $pos += 4; | ||
91 | + } | ||
92 | + | ||
93 | + | ||
94 | + for ($j = 0; $j < $this->numExtensionBlocks; $j++) { | ||
95 | + $pos = ($this->extensionBlock + 1) * BIG_BLOCK_SIZE; | ||
96 | + $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, BIG_BLOCK_SIZE / 4 - 1); | ||
97 | + | ||
98 | + for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i++) { | ||
99 | + $bigBlockDepotBlocks[$i] = GetInt4d($this->data, $pos); | ||
100 | + $pos += 4; | ||
101 | + } | ||
102 | + | ||
103 | + $bbdBlocks += $blocksToRead; | ||
104 | + if ($bbdBlocks < $this->numBigBlockDepotBlocks) { | ||
105 | + $this->extensionBlock = GetInt4d($this->data, $pos); | ||
106 | + } | ||
107 | + } | ||
108 | + | ||
109 | + // var_dump($bigBlockDepotBlocks); | ||
110 | + | ||
111 | + // readBigBlockDepot | ||
112 | + $pos = 0; | ||
113 | + $index = 0; | ||
114 | + $this->bigBlockChain = array(); | ||
115 | + | ||
116 | + for ($i = 0; $i < $this->numBigBlockDepotBlocks; $i++) { | ||
117 | + $pos = ($bigBlockDepotBlocks[$i] + 1) * BIG_BLOCK_SIZE; | ||
118 | + //echo "pos = $pos"; | ||
119 | + for ($j = 0 ; $j < BIG_BLOCK_SIZE / 4; $j++) { | ||
120 | + $this->bigBlockChain[$index] = GetInt4d($this->data, $pos); | ||
121 | + $pos += 4 ; | ||
122 | + $index++; | ||
123 | + } | ||
124 | + } | ||
125 | + | ||
126 | + //var_dump($this->bigBlockChain); | ||
127 | + //echo '=====2'; | ||
128 | + // readSmallBlockDepot(); | ||
129 | + $pos = 0; | ||
130 | + $index = 0; | ||
131 | + $sbdBlock = $this->sbdStartBlock; | ||
132 | + $this->smallBlockChain = array(); | ||
133 | + | ||
134 | + while ($sbdBlock != -2) { | ||
135 | + | ||
136 | + $pos = ($sbdBlock + 1) * BIG_BLOCK_SIZE; | ||
137 | + | ||
138 | + for ($j = 0; $j < BIG_BLOCK_SIZE / 4; $j++) { | ||
139 | + $this->smallBlockChain[$index] = GetInt4d($this->data, $pos); | ||
140 | + $pos += 4; | ||
141 | + $index++; | ||
142 | + } | ||
143 | + | ||
144 | + $sbdBlock = $this->bigBlockChain[$sbdBlock]; | ||
145 | + } | ||
146 | + | ||
147 | + | ||
148 | + // readData(rootStartBlock) | ||
149 | + $block = $this->rootStartBlock; | ||
150 | + $pos = 0; | ||
151 | + $this->entry = $this->__readData($block); | ||
152 | + | ||
153 | + /* | ||
154 | + while ($block != -2) { | ||
155 | + $pos = ($block + 1) * BIG_BLOCK_SIZE; | ||
156 | + $this->entry = $this->entry.substr($this->data, $pos, BIG_BLOCK_SIZE); | ||
157 | + $block = $this->bigBlockChain[$block]; | ||
158 | + } | ||
159 | + */ | ||
160 | + //echo '==='.$this->entry."==="; | ||
161 | + $this->__readPropertySets(); | ||
162 | + | ||
163 | + } | ||
164 | + | ||
165 | + function __readData($bl) { | ||
166 | + $block = $bl; | ||
167 | + $pos = 0; | ||
168 | + $data = ''; | ||
169 | + | ||
170 | + while ($block != -2) { | ||
171 | + $pos = ($block + 1) * BIG_BLOCK_SIZE; | ||
172 | + $data = $data.substr($this->data, $pos, BIG_BLOCK_SIZE); | ||
173 | + //echo "pos = $pos data=$data\n"; | ||
174 | + $block = $this->bigBlockChain[$block]; | ||
175 | + } | ||
176 | + return $data; | ||
177 | + } | ||
178 | + | ||
179 | + function __readPropertySets(){ | ||
180 | + $offset = 0; | ||
181 | + //var_dump($this->entry); | ||
182 | + while ($offset < strlen($this->entry)) { | ||
183 | + $d = substr($this->entry, $offset, PROPERTY_STORAGE_BLOCK_SIZE); | ||
184 | + | ||
185 | + $nameSize = ord($d[SIZE_OF_NAME_POS]) | (ord($d[SIZE_OF_NAME_POS+1]) << 8); | ||
186 | + | ||
187 | + $type = ord($d[TYPE_POS]); | ||
188 | + //$maxBlock = strlen($d) / BIG_BLOCK_SIZE - 1; | ||
189 | + | ||
190 | + $startBlock = GetInt4d($d, START_BLOCK_POS); | ||
191 | + $size = GetInt4d($d, SIZE_POS); | ||
192 | + | ||
193 | + $name = ''; | ||
194 | + for ($i = 0; $i < $nameSize ; $i++) { | ||
195 | + $name .= $d[$i]; | ||
196 | + } | ||
197 | + | ||
198 | + $name = str_replace("\x00", "", $name); | ||
199 | + | ||
200 | + $this->props[] = array ( | ||
201 | + 'name' => $name, | ||
202 | + 'type' => $type, | ||
203 | + 'startBlock' => $startBlock, | ||
204 | + 'size' => $size); | ||
205 | + | ||
206 | + if (($name == "Workbook") || ($name == "Book")) { | ||
207 | + $this->wrkbook = count($this->props) - 1; | ||
208 | + } | ||
209 | + | ||
210 | + if ($name == "Root Entry") { | ||
211 | + $this->rootentry = count($this->props) - 1; | ||
212 | + } | ||
213 | + | ||
214 | + //echo "name ==$name=\n"; | ||
215 | + | ||
216 | + | ||
217 | + $offset += PROPERTY_STORAGE_BLOCK_SIZE; | ||
218 | + } | ||
219 | + | ||
220 | + } | ||
221 | + | ||
222 | + | ||
223 | + function getWorkBook(){ | ||
224 | + if ($this->props[$this->wrkbook]['size'] < SMALL_BLOCK_THRESHOLD){ | ||
225 | +// getSmallBlockStream(PropertyStorage ps) | ||
226 | + | ||
227 | + $rootdata = $this->__readData($this->props[$this->rootentry]['startBlock']); | ||
228 | + | ||
229 | + $streamData = ''; | ||
230 | + $block = $this->props[$this->wrkbook]['startBlock']; | ||
231 | + //$count = 0; | ||
232 | + $pos = 0; | ||
233 | + while ($block != -2) { | ||
234 | + $pos = $block * SMALL_BLOCK_SIZE; | ||
235 | + $streamData .= substr($rootdata, $pos, SMALL_BLOCK_SIZE); | ||
236 | + | ||
237 | + $block = $this->smallBlockChain[$block]; | ||
238 | + } | ||
239 | + | ||
240 | + return $streamData; | ||
241 | + | ||
242 | + | ||
243 | + }else{ | ||
244 | + | ||
245 | + $numBlocks = $this->props[$this->wrkbook]['size'] / BIG_BLOCK_SIZE; | ||
246 | + if ($this->props[$this->wrkbook]['size'] % BIG_BLOCK_SIZE != 0) { | ||
247 | + $numBlocks++; | ||
248 | + } | ||
249 | + | ||
250 | + if ($numBlocks == 0) return ''; | ||
251 | + | ||
252 | + //echo "numBlocks = $numBlocks\n"; | ||
253 | + //byte[] streamData = new byte[numBlocks * BIG_BLOCK_SIZE]; | ||
254 | + //print_r($this->wrkbook); | ||
255 | + $streamData = ''; | ||
256 | + $block = $this->props[$this->wrkbook]['startBlock']; | ||
257 | + //$count = 0; | ||
258 | + $pos = 0; | ||
259 | + //echo "block = $block"; | ||
260 | + while ($block != -2) { | ||
261 | + $pos = ($block + 1) * BIG_BLOCK_SIZE; | ||
262 | + $streamData .= substr($this->data, $pos, BIG_BLOCK_SIZE); | ||
263 | + $block = $this->bigBlockChain[$block]; | ||
264 | + } | ||
265 | + //echo 'stream'.$streamData; | ||
266 | + return $streamData; | ||
267 | + } | ||
268 | + } | ||
269 | + | ||
270 | +} | ||
271 | +?> | ||
0 | \ No newline at end of file | 272 | \ No newline at end of file |
1 | +<?php | ||
2 | +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ | ||
3 | + | ||
4 | +/** | ||
5 | +* A class for reading Microsoft Excel Spreadsheets. | ||
6 | +* | ||
7 | +* Originally developed by Vadim Tkachenko under the name PHPExcelReader. | ||
8 | +* (http://sourceforge.net/projects/phpexcelreader) | ||
9 | +* Based on the Java version by Andy Khan (http://www.andykhan.com). Now | ||
10 | +* maintained by David Sanders. Reads only Biff 7 and Biff 8 formats. | ||
11 | +* | ||
12 | +* PHP versions 4 and 5 | ||
13 | +* | ||
14 | +* LICENSE: This source file is subject to version 3.0 of the PHP license | ||
15 | +* that is available through the world-wide-web at the following URI: | ||
16 | +* http://www.php.net/license/3_0.txt. If you did not receive a copy of | ||
17 | +* the PHP License and are unable to obtain it through the web, please | ||
18 | +* send a note to license@php.net so we can mail you a copy immediately. | ||
19 | +* | ||
20 | +* @category Spreadsheet | ||
21 | +* @package Spreadsheet_Excel_Reader | ||
22 | +* @author Vadim Tkachenko <vt@apachephp.com> | ||
23 | +* @license http://www.php.net/license/3_0.txt PHP License 3.0 | ||
24 | +* @version CVS: $Id: reader.php 19 2007-03-13 12:42:41Z shangxiao $ | ||
25 | +* @link http://pear.php.net/package/Spreadsheet_Excel_Reader | ||
26 | +* @see OLE, Spreadsheet_Excel_Writer | ||
27 | +*/ | ||
28 | + | ||
29 | + | ||
30 | +//require_once 'PEAR.php'; | ||
31 | +//require_once 'Spreadsheet/Excel/Reader/OLERead.php'; | ||
32 | +require_once 'oleread.inc'; | ||
33 | +//require_once 'OLE.php'; | ||
34 | + | ||
35 | +define('SPREADSHEET_EXCEL_READER_BIFF8', 0x600); | ||
36 | +define('SPREADSHEET_EXCEL_READER_BIFF7', 0x500); | ||
37 | +define('SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS', 0x5); | ||
38 | +define('SPREADSHEET_EXCEL_READER_WORKSHEET', 0x10); | ||
39 | + | ||
40 | +define('SPREADSHEET_EXCEL_READER_TYPE_BOF', 0x809); | ||
41 | +define('SPREADSHEET_EXCEL_READER_TYPE_EOF', 0x0a); | ||
42 | +define('SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET', 0x85); | ||
43 | +define('SPREADSHEET_EXCEL_READER_TYPE_DIMENSION', 0x200); | ||
44 | +define('SPREADSHEET_EXCEL_READER_TYPE_ROW', 0x208); | ||
45 | +define('SPREADSHEET_EXCEL_READER_TYPE_DBCELL', 0xd7); | ||
46 | +define('SPREADSHEET_EXCEL_READER_TYPE_FILEPASS', 0x2f); | ||
47 | +define('SPREADSHEET_EXCEL_READER_TYPE_NOTE', 0x1c); | ||
48 | +define('SPREADSHEET_EXCEL_READER_TYPE_TXO', 0x1b6); | ||
49 | +define('SPREADSHEET_EXCEL_READER_TYPE_RK', 0x7e); | ||
50 | +define('SPREADSHEET_EXCEL_READER_TYPE_RK2', 0x27e); | ||
51 | +define('SPREADSHEET_EXCEL_READER_TYPE_MULRK', 0xbd); | ||
52 | +define('SPREADSHEET_EXCEL_READER_TYPE_MULBLANK', 0xbe); | ||
53 | +define('SPREADSHEET_EXCEL_READER_TYPE_INDEX', 0x20b); | ||
54 | +define('SPREADSHEET_EXCEL_READER_TYPE_SST', 0xfc); | ||
55 | +define('SPREADSHEET_EXCEL_READER_TYPE_EXTSST', 0xff); | ||
56 | +define('SPREADSHEET_EXCEL_READER_TYPE_CONTINUE', 0x3c); | ||
57 | +define('SPREADSHEET_EXCEL_READER_TYPE_LABEL', 0x204); | ||
58 | +define('SPREADSHEET_EXCEL_READER_TYPE_LABELSST', 0xfd); | ||
59 | +define('SPREADSHEET_EXCEL_READER_TYPE_NUMBER', 0x203); | ||
60 | +define('SPREADSHEET_EXCEL_READER_TYPE_NAME', 0x18); | ||
61 | +define('SPREADSHEET_EXCEL_READER_TYPE_ARRAY', 0x221); | ||
62 | +define('SPREADSHEET_EXCEL_READER_TYPE_STRING', 0x207); | ||
63 | +define('SPREADSHEET_EXCEL_READER_TYPE_FORMULA', 0x406); | ||
64 | +define('SPREADSHEET_EXCEL_READER_TYPE_FORMULA2', 0x6); | ||
65 | +define('SPREADSHEET_EXCEL_READER_TYPE_FORMAT', 0x41e); | ||
66 | +define('SPREADSHEET_EXCEL_READER_TYPE_XF', 0xe0); | ||
67 | +define('SPREADSHEET_EXCEL_READER_TYPE_BOOLERR', 0x205); | ||
68 | +define('SPREADSHEET_EXCEL_READER_TYPE_UNKNOWN', 0xffff); | ||
69 | +define('SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR', 0x22); | ||
70 | +define('SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS', 0xE5); | ||
71 | + | ||
72 | +define('SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS' , 25569); | ||
73 | +define('SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904', 24107); | ||
74 | +define('SPREADSHEET_EXCEL_READER_MSINADAY', 86400); | ||
75 | +//define('SPREADSHEET_EXCEL_READER_MSINADAY', 24 * 60 * 60); | ||
76 | + | ||
77 | +//define('SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT', "%.2f"); | ||
78 | +define('SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT', "%s"); | ||
79 | + | ||
80 | + | ||
81 | +/* | ||
82 | +* Place includes, constant defines and $_GLOBAL settings here. | ||
83 | +* Make sure they have appropriate docblocks to avoid phpDocumentor | ||
84 | +* construing they are documented by the page-level docblock. | ||
85 | +*/ | ||
86 | + | ||
87 | +/** | ||
88 | +* A class for reading Microsoft Excel Spreadsheets. | ||
89 | +* | ||
90 | +* Originally developed by Vadim Tkachenko under the name PHPExcelReader. | ||
91 | +* (http://sourceforge.net/projects/phpexcelreader) | ||
92 | +* Based on the Java version by Andy Khan (http://www.andykhan.com). Now | ||
93 | +* maintained by David Sanders. Reads only Biff 7 and Biff 8 formats. | ||
94 | +* | ||
95 | +* @category Spreadsheet | ||
96 | +* @package Spreadsheet_Excel_Reader | ||
97 | +* @author Vadim Tkachenko <vt@phpapache.com> | ||
98 | +* @copyright 1997-2005 The PHP Group | ||
99 | +* @license http://www.php.net/license/3_0.txt PHP License 3.0 | ||
100 | +* @version Release: @package_version@ | ||
101 | +* @link http://pear.php.net/package/PackageName | ||
102 | +* @see OLE, Spreadsheet_Excel_Writer | ||
103 | +*/ | ||
104 | +class Spreadsheet_Excel_Reader | ||
105 | +{ | ||
106 | + /** | ||
107 | + * Array of worksheets found | ||
108 | + * | ||
109 | + * @var array | ||
110 | + * @access public | ||
111 | + */ | ||
112 | + var $boundsheets = array(); | ||
113 | + | ||
114 | + /** | ||
115 | + * Array of format records found | ||
116 | + * | ||
117 | + * @var array | ||
118 | + * @access public | ||
119 | + */ | ||
120 | + var $formatRecords = array(); | ||
121 | + | ||
122 | + /** | ||
123 | + * todo | ||
124 | + * | ||
125 | + * @var array | ||
126 | + * @access public | ||
127 | + */ | ||
128 | + var $sst = array(); | ||
129 | + | ||
130 | + /** | ||
131 | + * Array of worksheets | ||
132 | + * | ||
133 | + * The data is stored in 'cells' and the meta-data is stored in an array | ||
134 | + * called 'cellsInfo' | ||
135 | + * | ||
136 | + * Example: | ||
137 | + * | ||
138 | + * $sheets --> 'cells' --> row --> column --> Interpreted value | ||
139 | + * --> 'cellsInfo' --> row --> column --> 'type' - Can be 'date', 'number', or 'unknown' | ||
140 | + * --> 'raw' - The raw data that Excel stores for that data cell | ||
141 | + * | ||
142 | + * @var array | ||
143 | + * @access public | ||
144 | + */ | ||
145 | + var $sheets = array(); | ||
146 | + | ||
147 | + /** | ||
148 | + * The data returned by OLE | ||
149 | + * | ||
150 | + * @var string | ||
151 | + * @access public | ||
152 | + */ | ||
153 | + var $data; | ||
154 | + | ||
155 | + /** | ||
156 | + * OLE object for reading the file | ||
157 | + * | ||
158 | + * @var OLE object | ||
159 | + * @access private | ||
160 | + */ | ||
161 | + var $_ole; | ||
162 | + | ||
163 | + /** | ||
164 | + * Default encoding | ||
165 | + * | ||
166 | + * @var string | ||
167 | + * @access private | ||
168 | + */ | ||
169 | + var $_defaultEncoding; | ||
170 | + | ||
171 | + /** | ||
172 | + * Default number format | ||
173 | + * | ||
174 | + * @var integer | ||
175 | + * @access private | ||
176 | + */ | ||
177 | + var $_defaultFormat = SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT; | ||
178 | + | ||
179 | + /** | ||
180 | + * todo | ||
181 | + * List of formats to use for each column | ||
182 | + * | ||
183 | + * @var array | ||
184 | + * @access private | ||
185 | + */ | ||
186 | + var $_columnsFormat = array(); | ||
187 | + | ||
188 | + /** | ||
189 | + * todo | ||
190 | + * | ||
191 | + * @var integer | ||
192 | + * @access private | ||
193 | + */ | ||
194 | + var $_rowoffset = 1; | ||
195 | + | ||
196 | + /** | ||
197 | + * todo | ||
198 | + * | ||
199 | + * @var integer | ||
200 | + * @access private | ||
201 | + */ | ||
202 | + var $_coloffset = 1; | ||
203 | + | ||
204 | + /** | ||
205 | + * List of default date formats used by Excel | ||
206 | + * | ||
207 | + * @var array | ||
208 | + * @access public | ||
209 | + */ | ||
210 | + var $dateFormats = array ( | ||
211 | + 0xe => "d/m/Y", | ||
212 | + 0xf => "d-M-Y", | ||
213 | + 0x10 => "d-M", | ||
214 | + 0x11 => "M-Y", | ||
215 | + 0x12 => "h:i a", | ||
216 | + 0x13 => "h:i:s a", | ||
217 | + 0x14 => "H:i", | ||
218 | + 0x15 => "H:i:s", | ||
219 | + 0x16 => "d/m/Y H:i", | ||
220 | + 0x2d => "i:s", | ||
221 | + 0x2e => "H:i:s", | ||
222 | + 0x2f => "i:s.S"); | ||
223 | + | ||
224 | + /** | ||
225 | + * Default number formats used by Excel | ||
226 | + * | ||
227 | + * @var array | ||
228 | + * @access public | ||
229 | + */ | ||
230 | + var $numberFormats = array( | ||
231 | + 0x1 => "%1.0f", // "0" | ||
232 | + 0x2 => "%1.2f", // "0.00", | ||
233 | + 0x3 => "%1.0f", //"#,##0", | ||
234 | + 0x4 => "%1.2f", //"#,##0.00", | ||
235 | + 0x5 => "%1.0f", /*"$#,##0;($#,##0)",*/ | ||
236 | + 0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/ | ||
237 | + 0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)", | ||
238 | + 0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)", | ||
239 | + 0x9 => '%1.0f%%', // "0%" | ||
240 | + 0xa => '%1.2f%%', // "0.00%" | ||
241 | + 0xb => '%1.2f', // 0.00E00", | ||
242 | + 0x25 => '%1.0f', // "#,##0;(#,##0)", | ||
243 | + 0x26 => '%1.0f', //"#,##0;(#,##0)", | ||
244 | + 0x27 => '%1.2f', //"#,##0.00;(#,##0.00)", | ||
245 | + 0x28 => '%1.2f', //"#,##0.00;(#,##0.00)", | ||
246 | + 0x29 => '%1.0f', //"#,##0;(#,##0)", | ||
247 | + 0x2a => '$%1.0f', //"$#,##0;($#,##0)", | ||
248 | + 0x2b => '%1.2f', //"#,##0.00;(#,##0.00)", | ||
249 | + 0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)", | ||
250 | + 0x30 => '%1.0f'); //"##0.0E0"; | ||
251 | + | ||
252 | + // }}} | ||
253 | + // {{{ Spreadsheet_Excel_Reader() | ||
254 | + | ||
255 | + /** | ||
256 | + * Constructor | ||
257 | + * | ||
258 | + * Some basic initialisation | ||
259 | + */ | ||
260 | + function Spreadsheet_Excel_Reader() | ||
261 | + { | ||
262 | + $this->_ole =& new OLERead(); | ||
263 | + $this->setUTFEncoder('iconv'); | ||
264 | + } | ||
265 | + | ||
266 | + // }}} | ||
267 | + // {{{ setOutputEncoding() | ||
268 | + | ||
269 | + /** | ||
270 | + * Set the encoding method | ||
271 | + * | ||
272 | + * @param string Encoding to use | ||
273 | + * @access public | ||
274 | + */ | ||
275 | + function setOutputEncoding($encoding) | ||
276 | + { | ||
277 | + $this->_defaultEncoding = $encoding; | ||
278 | + } | ||
279 | + | ||
280 | + // }}} | ||
281 | + // {{{ setUTFEncoder() | ||
282 | + | ||
283 | + /** | ||
284 | + * $encoder = 'iconv' or 'mb' | ||
285 | + * set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding | ||
286 | + * set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding | ||
287 | + * | ||
288 | + * @access public | ||
289 | + * @param string Encoding type to use. Either 'iconv' or 'mb' | ||
290 | + */ | ||
291 | + function setUTFEncoder($encoder = 'iconv') | ||
292 | + { | ||
293 | + $this->_encoderFunction = ''; | ||
294 | + | ||
295 | + if ($encoder == 'iconv') { | ||
296 | + $this->_encoderFunction = function_exists('iconv') ? 'iconv' : ''; | ||
297 | + } elseif ($encoder == 'mb') { | ||
298 | + $this->_encoderFunction = function_exists('mb_convert_encoding') ? | ||
299 | + 'mb_convert_encoding' : | ||
300 | + ''; | ||
301 | + } | ||
302 | + } | ||
303 | + | ||
304 | + // }}} | ||
305 | + // {{{ setRowColOffset() | ||
306 | + | ||
307 | + /** | ||
308 | + * todo | ||
309 | + * | ||
310 | + * @access public | ||
311 | + * @param offset | ||
312 | + */ | ||
313 | + function setRowColOffset($iOffset) | ||
314 | + { | ||
315 | + $this->_rowoffset = $iOffset; | ||
316 | + $this->_coloffset = $iOffset; | ||
317 | + } | ||
318 | + | ||
319 | + // }}} | ||
320 | + // {{{ setDefaultFormat() | ||
321 | + | ||
322 | + /** | ||
323 | + * Set the default number format | ||
324 | + * | ||
325 | + * @access public | ||
326 | + * @param Default format | ||
327 | + */ | ||
328 | + function setDefaultFormat($sFormat) | ||
329 | + { | ||
330 | + $this->_defaultFormat = $sFormat; | ||
331 | + } | ||
332 | + | ||
333 | + // }}} | ||
334 | + // {{{ setColumnFormat() | ||
335 | + | ||
336 | + /** | ||
337 | + * Force a column to use a certain format | ||
338 | + * | ||
339 | + * @access public | ||
340 | + * @param integer Column number | ||
341 | + * @param string Format | ||
342 | + */ | ||
343 | + function setColumnFormat($column, $sFormat) | ||
344 | + { | ||
345 | + $this->_columnsFormat[$column] = $sFormat; | ||
346 | + } | ||
347 | + | ||
348 | + | ||
349 | + // }}} | ||
350 | + // {{{ read() | ||
351 | + | ||
352 | + /** | ||
353 | + * Read the spreadsheet file using OLE, then parse | ||
354 | + * | ||
355 | + * @access public | ||
356 | + * @param filename | ||
357 | + * @todo return a valid value | ||
358 | + */ | ||
359 | + function read($sFileName) | ||
360 | + { | ||
361 | + /* | ||
362 | + require_once 'OLE.php'; | ||
363 | + $ole = new OLE(); | ||
364 | + $ole->read($sFileName); | ||
365 | + | ||
366 | + foreach ($ole->_list as $i => $pps) { | ||
367 | + if (($pps->Name == 'Workbook' || $pps->Name == 'Book') && | ||
368 | + $pps->Size >= SMALL_BLOCK_THRESHOLD) { | ||
369 | + | ||
370 | + $this->data = $ole->getData($i, 0, $ole->getDataLength($i)); | ||
371 | + } elseif ($pps->Name == 'Root Entry') { | ||
372 | + $this->data = $ole->getData($i, 0, $ole->getDataLength($i)); | ||
373 | + } | ||
374 | + //var_dump(strlen($ole->getData($i, 0, $ole->getDataLength($i))), $pps->Name, md5($this->data), $ole->getDataLength($i)); | ||
375 | + } | ||
376 | +//exit; | ||
377 | + $this->_parse(); | ||
378 | + | ||
379 | + return sizeof($this->sheets) > 0; | ||
380 | + */ | ||
381 | + | ||
382 | + $res = $this->_ole->read($sFileName); | ||
383 | + | ||
384 | + // oops, something goes wrong (Darko Miljanovic) | ||
385 | + if($res === false) { | ||
386 | + // check error code | ||
387 | + if($this->_ole->error == 1) { | ||
388 | + // bad file | ||
389 | + die('The filename ' . $sFileName . ' is not readable'); | ||
390 | + } | ||
391 | + // check other error codes here (eg bad fileformat, etc...) | ||
392 | + } | ||
393 | + | ||
394 | + $this->data = $this->_ole->getWorkBook(); | ||
395 | + | ||
396 | + | ||
397 | + /* | ||
398 | + $res = $this->_ole->read($sFileName); | ||
399 | + | ||
400 | + if ($this->isError($res)) { | ||
401 | +// var_dump($res); | ||
402 | + return $this->raiseError($res); | ||
403 | + } | ||
404 | + | ||
405 | + $total = $this->_ole->ppsTotal(); | ||
406 | + for ($i = 0; $i < $total; $i++) { | ||
407 | + if ($this->_ole->isFile($i)) { | ||
408 | + $type = unpack("v", $this->_ole->getData($i, 0, 2)); | ||
409 | + if ($type[''] == 0x0809) { // check if it's a BIFF stream | ||
410 | + $this->_index = $i; | ||
411 | + $this->data = $this->_ole->getData($i, 0, $this->_ole->getDataLength($i)); | ||
412 | + break; | ||
413 | + } | ||
414 | + } | ||
415 | + } | ||
416 | + | ||
417 | + if ($this->_index === null) { | ||
418 | + return $this->raiseError("$file doesn't seem to be an Excel file"); | ||
419 | + } | ||
420 | + | ||
421 | + */ | ||
422 | + | ||
423 | + //echo "data =".$this->data; | ||
424 | + //$this->readRecords(); | ||
425 | + $this->_parse(); | ||
426 | + } | ||
427 | + | ||
428 | + | ||
429 | + // }}} | ||
430 | + // {{{ _parse() | ||
431 | + | ||
432 | + /** | ||
433 | + * Parse a workbook | ||
434 | + * | ||
435 | + * @access private | ||
436 | + * @return bool | ||
437 | + */ | ||
438 | + function _parse() | ||
439 | + { | ||
440 | + $pos = 0; | ||
441 | + | ||
442 | + $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; | ||
443 | + $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; | ||
444 | + | ||
445 | + $version = ord($this->data[$pos + 4]) | ord($this->data[$pos + 5])<<8; | ||
446 | + $substreamType = ord($this->data[$pos + 6]) | ord($this->data[$pos + 7])<<8; | ||
447 | + //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; | ||
448 | + | ||
449 | + if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && | ||
450 | + ($version != SPREADSHEET_EXCEL_READER_BIFF7)) { | ||
451 | + return false; | ||
452 | + } | ||
453 | + | ||
454 | + if ($substreamType != SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS){ | ||
455 | + return false; | ||
456 | + } | ||
457 | + | ||
458 | + //print_r($rec); | ||
459 | + $pos += $length + 4; | ||
460 | + | ||
461 | + $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; | ||
462 | + $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; | ||
463 | + | ||
464 | + while ($code != SPREADSHEET_EXCEL_READER_TYPE_EOF) { | ||
465 | + switch ($code) { | ||
466 | + case SPREADSHEET_EXCEL_READER_TYPE_SST: | ||
467 | + //echo "Type_SST\n"; | ||
468 | + $spos = $pos + 4; | ||
469 | + $limitpos = $spos + $length; | ||
470 | + $uniqueStrings = $this->_GetInt4d($this->data, $spos+4); | ||
471 | + $spos += 8; | ||
472 | + for ($i = 0; $i < $uniqueStrings; $i++) { | ||
473 | + // Read in the number of characters | ||
474 | + if ($spos == $limitpos) { | ||
475 | + $opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
476 | + $conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
477 | + if ($opcode != 0x3c) { | ||
478 | + return -1; | ||
479 | + } | ||
480 | + $spos += 4; | ||
481 | + $limitpos = $spos + $conlength; | ||
482 | + } | ||
483 | + $numChars = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8); | ||
484 | + //echo "i = $i pos = $pos numChars = $numChars "; | ||
485 | + $spos += 2; | ||
486 | + $optionFlags = ord($this->data[$spos]); | ||
487 | + $spos++; | ||
488 | + $asciiEncoding = (($optionFlags & 0x01) == 0) ; | ||
489 | + $extendedString = ( ($optionFlags & 0x04) != 0); | ||
490 | + | ||
491 | + // See if string contains formatting information | ||
492 | + $richString = ( ($optionFlags & 0x08) != 0); | ||
493 | + | ||
494 | + if ($richString) { | ||
495 | + // Read in the crun | ||
496 | + $formattingRuns = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8); | ||
497 | + $spos += 2; | ||
498 | + } | ||
499 | + | ||
500 | + if ($extendedString) { | ||
501 | + // Read in cchExtRst | ||
502 | + $extendedRunLength = $this->_GetInt4d($this->data, $spos); | ||
503 | + $spos += 4; | ||
504 | + } | ||
505 | + | ||
506 | + $len = ($asciiEncoding)? $numChars : $numChars*2; | ||
507 | + if ($spos + $len < $limitpos) { | ||
508 | + $retstr = substr($this->data, $spos, $len); | ||
509 | + $spos += $len; | ||
510 | + }else{ | ||
511 | + // found countinue | ||
512 | + $retstr = substr($this->data, $spos, $limitpos - $spos); | ||
513 | + $bytesRead = $limitpos - $spos; | ||
514 | + $charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2)); | ||
515 | + $spos = $limitpos; | ||
516 | + | ||
517 | + while ($charsLeft > 0){ | ||
518 | + $opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
519 | + $conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
520 | + if ($opcode != 0x3c) { | ||
521 | + return -1; | ||
522 | + } | ||
523 | + $spos += 4; | ||
524 | + $limitpos = $spos + $conlength; | ||
525 | + $option = ord($this->data[$spos]); | ||
526 | + $spos += 1; | ||
527 | + if ($asciiEncoding && ($option == 0)) { | ||
528 | + $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); | ||
529 | + $retstr .= substr($this->data, $spos, $len); | ||
530 | + $charsLeft -= $len; | ||
531 | + $asciiEncoding = true; | ||
532 | + }elseif (!$asciiEncoding && ($option != 0)){ | ||
533 | + $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); | ||
534 | + $retstr .= substr($this->data, $spos, $len); | ||
535 | + $charsLeft -= $len/2; | ||
536 | + $asciiEncoding = false; | ||
537 | + }elseif (!$asciiEncoding && ($option == 0)) { | ||
538 | + // Bummer - the string starts off as Unicode, but after the | ||
539 | + // continuation it is in straightforward ASCII encoding | ||
540 | + $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); | ||
541 | + for ($j = 0; $j < $len; $j++) { | ||
542 | + $retstr .= $this->data[$spos + $j].chr(0); | ||
543 | + } | ||
544 | + $charsLeft -= $len; | ||
545 | + $asciiEncoding = false; | ||
546 | + }else{ | ||
547 | + $newstr = ''; | ||
548 | + for ($j = 0; $j < strlen($retstr); $j++) { | ||
549 | + $newstr = $retstr[$j].chr(0); | ||
550 | + } | ||
551 | + $retstr = $newstr; | ||
552 | + $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); | ||
553 | + $retstr .= substr($this->data, $spos, $len); | ||
554 | + $charsLeft -= $len/2; | ||
555 | + $asciiEncoding = false; | ||
556 | + //echo "Izavrat\n"; | ||
557 | + } | ||
558 | + $spos += $len; | ||
559 | + | ||
560 | + } | ||
561 | + } | ||
562 | + $retstr = ($asciiEncoding) ? $retstr : $this->_encodeUTF16($retstr); | ||
563 | +// echo "Str $i = $retstr\n"; | ||
564 | + if ($richString){ | ||
565 | + $spos += 4 * $formattingRuns; | ||
566 | + } | ||
567 | + | ||
568 | + // For extended strings, skip over the extended string data | ||
569 | + if ($extendedString) { | ||
570 | + $spos += $extendedRunLength; | ||
571 | + } | ||
572 | + //if ($retstr == 'Derby'){ | ||
573 | + // echo "bb\n"; | ||
574 | + //} | ||
575 | + $this->sst[]=$retstr; | ||
576 | + } | ||
577 | + /*$continueRecords = array(); | ||
578 | + while ($this->getNextCode() == Type_CONTINUE) { | ||
579 | + $continueRecords[] = &$this->nextRecord(); | ||
580 | + } | ||
581 | + //echo " 1 Type_SST\n"; | ||
582 | + $this->shareStrings = new SSTRecord($r, $continueRecords); | ||
583 | + //print_r($this->shareStrings->strings); | ||
584 | + */ | ||
585 | + // echo 'SST read: '.($time_end-$time_start)."\n"; | ||
586 | + break; | ||
587 | + | ||
588 | + case SPREADSHEET_EXCEL_READER_TYPE_FILEPASS: | ||
589 | + return false; | ||
590 | + break; | ||
591 | + case SPREADSHEET_EXCEL_READER_TYPE_NAME: | ||
592 | + //echo "Type_NAME\n"; | ||
593 | + break; | ||
594 | + case SPREADSHEET_EXCEL_READER_TYPE_FORMAT: | ||
595 | + $indexCode = ord($this->data[$pos+4]) | ord($this->data[$pos+5]) << 8; | ||
596 | + | ||
597 | + if ($version == SPREADSHEET_EXCEL_READER_BIFF8) { | ||
598 | + $numchars = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8; | ||
599 | + if (ord($this->data[$pos+8]) == 0){ | ||
600 | + $formatString = substr($this->data, $pos+9, $numchars); | ||
601 | + } else { | ||
602 | + $formatString = substr($this->data, $pos+9, $numchars*2); | ||
603 | + } | ||
604 | + } else { | ||
605 | + $numchars = ord($this->data[$pos+6]); | ||
606 | + $formatString = substr($this->data, $pos+7, $numchars*2); | ||
607 | + } | ||
608 | + | ||
609 | + $this->formatRecords[$indexCode] = $formatString; | ||
610 | + // echo "Type.FORMAT\n"; | ||
611 | + break; | ||
612 | + case SPREADSHEET_EXCEL_READER_TYPE_XF: | ||
613 | + //global $dateFormats, $numberFormats; | ||
614 | + $indexCode = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8; | ||
615 | + //echo "\nType.XF ".count($this->formatRecords['xfrecords'])." $indexCode "; | ||
616 | + if (array_key_exists($indexCode, $this->dateFormats)) { | ||
617 | + //echo "isdate ".$dateFormats[$indexCode]; | ||
618 | + $this->formatRecords['xfrecords'][] = array( | ||
619 | + 'type' => 'date', | ||
620 | + 'format' => $this->dateFormats[$indexCode] | ||
621 | + ); | ||
622 | + }elseif (array_key_exists($indexCode, $this->numberFormats)) { | ||
623 | + //echo "isnumber ".$this->numberFormats[$indexCode]; | ||
624 | + $this->formatRecords['xfrecords'][] = array( | ||
625 | + 'type' => 'number', | ||
626 | + 'format' => $this->numberFormats[$indexCode] | ||
627 | + ); | ||
628 | + }else{ | ||
629 | + $isdate = FALSE; | ||
630 | + if ($indexCode > 0){ | ||
631 | + if (isset($this->formatRecords[$indexCode])) | ||
632 | + $formatstr = $this->formatRecords[$indexCode]; | ||
633 | + //echo '.other.'; | ||
634 | + //echo "\ndate-time=$formatstr=\n"; | ||
635 | + if ($formatstr) | ||
636 | + if (preg_match("/[^hmsday\/\-:\s]/i", $formatstr) == 0) { // found day and time format | ||
637 | + $isdate = TRUE; | ||
638 | + $formatstr = str_replace('mm', 'i', $formatstr); | ||
639 | + $formatstr = str_replace('h', 'H', $formatstr); | ||
640 | + //echo "\ndate-time $formatstr \n"; | ||
641 | + } | ||
642 | + } | ||
643 | + | ||
644 | + if ($isdate){ | ||
645 | + $this->formatRecords['xfrecords'][] = array( | ||
646 | + 'type' => 'date', | ||
647 | + 'format' => $formatstr, | ||
648 | + ); | ||
649 | + }else{ | ||
650 | + $this->formatRecords['xfrecords'][] = array( | ||
651 | + 'type' => 'other', | ||
652 | + 'format' => '', | ||
653 | + 'code' => $indexCode | ||
654 | + ); | ||
655 | + } | ||
656 | + } | ||
657 | + //echo "\n"; | ||
658 | + break; | ||
659 | + case SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR: | ||
660 | + //echo "Type.NINETEENFOUR\n"; | ||
661 | + $this->nineteenFour = (ord($this->data[$pos+4]) == 1); | ||
662 | + break; | ||
663 | + case SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET: | ||
664 | + //echo "Type.BOUNDSHEET\n"; | ||
665 | + $rec_offset = $this->_GetInt4d($this->data, $pos+4); | ||
666 | + $rec_typeFlag = ord($this->data[$pos+8]); | ||
667 | + $rec_visibilityFlag = ord($this->data[$pos+9]); | ||
668 | + $rec_length = ord($this->data[$pos+10]); | ||
669 | + | ||
670 | + if ($version == SPREADSHEET_EXCEL_READER_BIFF8){ | ||
671 | + $chartype = ord($this->data[$pos+11]); | ||
672 | + if ($chartype == 0){ | ||
673 | + $rec_name = substr($this->data, $pos+12, $rec_length); | ||
674 | + } else { | ||
675 | + $rec_name = $this->_encodeUTF16(substr($this->data, $pos+12, $rec_length*2)); | ||
676 | + } | ||
677 | + }elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7){ | ||
678 | + $rec_name = substr($this->data, $pos+11, $rec_length); | ||
679 | + } | ||
680 | + $this->boundsheets[] = array('name'=>$rec_name, | ||
681 | + 'offset'=>$rec_offset); | ||
682 | + | ||
683 | + break; | ||
684 | + | ||
685 | + } | ||
686 | + | ||
687 | + //echo "Code = ".base_convert($r['code'],10,16)."\n"; | ||
688 | + $pos += $length + 4; | ||
689 | + $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; | ||
690 | + $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; | ||
691 | + | ||
692 | + //$r = &$this->nextRecord(); | ||
693 | + //echo "1 Code = ".base_convert($r['code'],10,16)."\n"; | ||
694 | + } | ||
695 | + | ||
696 | + foreach ($this->boundsheets as $key=>$val){ | ||
697 | + $this->sn = $key; | ||
698 | + $this->_parsesheet($val['offset']); | ||
699 | + } | ||
700 | + return true; | ||
701 | + | ||
702 | + } | ||
703 | + | ||
704 | + /** | ||
705 | + * Parse a worksheet | ||
706 | + * | ||
707 | + * @access private | ||
708 | + * @param todo | ||
709 | + * @todo fix return codes | ||
710 | + */ | ||
711 | + function _parsesheet($spos) | ||
712 | + { | ||
713 | + $cont = true; | ||
714 | + // read BOF | ||
715 | + $code = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
716 | + $length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
717 | + | ||
718 | + $version = ord($this->data[$spos + 4]) | ord($this->data[$spos + 5])<<8; | ||
719 | + $substreamType = ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8; | ||
720 | + | ||
721 | + if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && ($version != SPREADSHEET_EXCEL_READER_BIFF7)) { | ||
722 | + return -1; | ||
723 | + } | ||
724 | + | ||
725 | + if ($substreamType != SPREADSHEET_EXCEL_READER_WORKSHEET){ | ||
726 | + return -2; | ||
727 | + } | ||
728 | + //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; | ||
729 | + $spos += $length + 4; | ||
730 | + //var_dump($this->formatRecords); | ||
731 | + //echo "code $code $length"; | ||
732 | + while($cont) { | ||
733 | + //echo "mem= ".memory_get_usage()."\n"; | ||
734 | +// $r = &$this->file->nextRecord(); | ||
735 | + $lowcode = ord($this->data[$spos]); | ||
736 | + if ($lowcode == SPREADSHEET_EXCEL_READER_TYPE_EOF) break; | ||
737 | + $code = $lowcode | ord($this->data[$spos+1])<<8; | ||
738 | + $length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
739 | + $spos += 4; | ||
740 | + $this->sheets[$this->sn]['maxrow'] = $this->_rowoffset - 1; | ||
741 | + $this->sheets[$this->sn]['maxcol'] = $this->_coloffset - 1; | ||
742 | + //echo "Code=".base_convert($code,10,16)." $code\n"; | ||
743 | + unset($this->rectype); | ||
744 | + $this->multiplier = 1; // need for format with % | ||
745 | + switch ($code) { | ||
746 | + case SPREADSHEET_EXCEL_READER_TYPE_DIMENSION: | ||
747 | + //echo 'Type_DIMENSION '; | ||
748 | + if (!isset($this->numRows)) { | ||
749 | + if (($length == 10) || ($version == SPREADSHEET_EXCEL_READER_BIFF7)){ | ||
750 | + $this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+2]) | ord($this->data[$spos+3]) << 8; | ||
751 | + $this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+6]) | ord($this->data[$spos+7]) << 8; | ||
752 | + } else { | ||
753 | + $this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8; | ||
754 | + $this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+10]) | ord($this->data[$spos+11]) << 8; | ||
755 | + } | ||
756 | + } | ||
757 | + //echo 'numRows '.$this->numRows.' '.$this->numCols."\n"; | ||
758 | + break; | ||
759 | + case SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS: | ||
760 | + $cellRanges = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
761 | + for ($i = 0; $i < $cellRanges; $i++) { | ||
762 | + $fr = ord($this->data[$spos + 8*$i + 2]) | ord($this->data[$spos + 8*$i + 3])<<8; | ||
763 | + $lr = ord($this->data[$spos + 8*$i + 4]) | ord($this->data[$spos + 8*$i + 5])<<8; | ||
764 | + $fc = ord($this->data[$spos + 8*$i + 6]) | ord($this->data[$spos + 8*$i + 7])<<8; | ||
765 | + $lc = ord($this->data[$spos + 8*$i + 8]) | ord($this->data[$spos + 8*$i + 9])<<8; | ||
766 | + //$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1); | ||
767 | + if ($lr - $fr > 0) { | ||
768 | + $this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['rowspan'] = $lr - $fr + 1; | ||
769 | + } | ||
770 | + if ($lc - $fc > 0) { | ||
771 | + $this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['colspan'] = $lc - $fc + 1; | ||
772 | + } | ||
773 | + } | ||
774 | + //echo "Merged Cells $cellRanges $lr $fr $lc $fc\n"; | ||
775 | + break; | ||
776 | + case SPREADSHEET_EXCEL_READER_TYPE_RK: | ||
777 | + case SPREADSHEET_EXCEL_READER_TYPE_RK2: | ||
778 | + //echo 'SPREADSHEET_EXCEL_READER_TYPE_RK'."\n"; | ||
779 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
780 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
781 | + $rknum = $this->_GetInt4d($this->data, $spos + 6); | ||
782 | + $numValue = $this->_GetIEEE754($rknum); | ||
783 | + //echo $numValue." "; | ||
784 | + if ($this->isDate($spos)) { | ||
785 | + list($string, $raw) = $this->createDate($numValue); | ||
786 | + }else{ | ||
787 | + $raw = $numValue; | ||
788 | + if (isset($this->_columnsFormat[$column + 1])){ | ||
789 | + $this->curformat = $this->_columnsFormat[$column + 1]; | ||
790 | + } | ||
791 | + $string = sprintf($this->curformat, $numValue * $this->multiplier); | ||
792 | + //$this->addcell(RKRecord($r)); | ||
793 | + } | ||
794 | + $this->addcell($row, $column, $string, $raw); | ||
795 | + //echo "Type_RK $row $column $string $raw {$this->curformat}\n"; | ||
796 | + break; | ||
797 | + case SPREADSHEET_EXCEL_READER_TYPE_LABELSST: | ||
798 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
799 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
800 | + $xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8; | ||
801 | + $index = $this->_GetInt4d($this->data, $spos + 6); | ||
802 | + //var_dump($this->sst); | ||
803 | + $this->addcell($row, $column, $this->sst[$index]); | ||
804 | + //echo "LabelSST $row $column $string\n"; | ||
805 | + break; | ||
806 | + case SPREADSHEET_EXCEL_READER_TYPE_MULRK: | ||
807 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
808 | + $colFirst = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
809 | + $colLast = ord($this->data[$spos + $length - 2]) | ord($this->data[$spos + $length - 1])<<8; | ||
810 | + $columns = $colLast - $colFirst + 1; | ||
811 | + $tmppos = $spos+4; | ||
812 | + for ($i = 0; $i < $columns; $i++) { | ||
813 | + $numValue = $this->_GetIEEE754($this->_GetInt4d($this->data, $tmppos + 2)); | ||
814 | + if ($this->isDate($tmppos-4)) { | ||
815 | + list($string, $raw) = $this->createDate($numValue); | ||
816 | + }else{ | ||
817 | + $raw = $numValue; | ||
818 | + if (isset($this->_columnsFormat[$colFirst + $i + 1])){ | ||
819 | + $this->curformat = $this->_columnsFormat[$colFirst + $i + 1]; | ||
820 | + } | ||
821 | + $string = sprintf($this->curformat, $numValue * $this->multiplier); | ||
822 | + } | ||
823 | + //$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8; | ||
824 | + $tmppos += 6; | ||
825 | + $this->addcell($row, $colFirst + $i, $string, $raw); | ||
826 | + //echo "MULRK $row ".($colFirst + $i)." $string\n"; | ||
827 | + } | ||
828 | + //MulRKRecord($r); | ||
829 | + // Get the individual cell records from the multiple record | ||
830 | + //$num = ; | ||
831 | + | ||
832 | + break; | ||
833 | + case SPREADSHEET_EXCEL_READER_TYPE_NUMBER: | ||
834 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
835 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
836 | + $tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent | ||
837 | + if ($this->isDate($spos)) { | ||
838 | + list($string, $raw) = $this->createDate($tmp['double']); | ||
839 | + // $this->addcell(DateRecord($r, 1)); | ||
840 | + }else{ | ||
841 | + //$raw = $tmp['']; | ||
842 | + if (isset($this->_columnsFormat[$column + 1])){ | ||
843 | + $this->curformat = $this->_columnsFormat[$column + 1]; | ||
844 | + } | ||
845 | + $raw = $this->createNumber($spos); | ||
846 | + $string = sprintf($this->curformat, $raw * $this->multiplier); | ||
847 | + | ||
848 | + // $this->addcell(NumberRecord($r)); | ||
849 | + } | ||
850 | + $this->addcell($row, $column, $string, $raw); | ||
851 | + //echo "Number $row $column $string\n"; | ||
852 | + break; | ||
853 | + case SPREADSHEET_EXCEL_READER_TYPE_FORMULA: | ||
854 | + case SPREADSHEET_EXCEL_READER_TYPE_FORMULA2: | ||
855 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
856 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
857 | + if ((ord($this->data[$spos+6])==0) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { | ||
858 | + //String formula. Result follows in a STRING record | ||
859 | + //echo "FORMULA $row $column Formula with a string<br>\n"; | ||
860 | + } elseif ((ord($this->data[$spos+6])==1) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { | ||
861 | + //Boolean formula. Result is in +2; 0=false,1=true | ||
862 | + } elseif ((ord($this->data[$spos+6])==2) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { | ||
863 | + //Error formula. Error code is in +2; | ||
864 | + } elseif ((ord($this->data[$spos+6])==3) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { | ||
865 | + //Formula result is a null string. | ||
866 | + } else { | ||
867 | + // result is a number, so first 14 bytes are just like a _NUMBER record | ||
868 | + $tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent | ||
869 | + if ($this->isDate($spos)) { | ||
870 | + list($string, $raw) = $this->createDate($tmp['double']); | ||
871 | + // $this->addcell(DateRecord($r, 1)); | ||
872 | + }else{ | ||
873 | + //$raw = $tmp['']; | ||
874 | + if (isset($this->_columnsFormat[$column + 1])){ | ||
875 | + $this->curformat = $this->_columnsFormat[$column + 1]; | ||
876 | + } | ||
877 | + $raw = $this->createNumber($spos); | ||
878 | + $string = sprintf($this->curformat, $raw * $this->multiplier); | ||
879 | + | ||
880 | + // $this->addcell(NumberRecord($r)); | ||
881 | + } | ||
882 | + $this->addcell($row, $column, $string, $raw); | ||
883 | + //echo "Number $row $column $string\n"; | ||
884 | + } | ||
885 | + break; | ||
886 | + case SPREADSHEET_EXCEL_READER_TYPE_BOOLERR: | ||
887 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
888 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
889 | + $string = ord($this->data[$spos+6]); | ||
890 | + $this->addcell($row, $column, $string); | ||
891 | + //echo 'Type_BOOLERR '."\n"; | ||
892 | + break; | ||
893 | + case SPREADSHEET_EXCEL_READER_TYPE_ROW: | ||
894 | + case SPREADSHEET_EXCEL_READER_TYPE_DBCELL: | ||
895 | + case SPREADSHEET_EXCEL_READER_TYPE_MULBLANK: | ||
896 | + break; | ||
897 | + case SPREADSHEET_EXCEL_READER_TYPE_LABEL: | ||
898 | + $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; | ||
899 | + $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; | ||
900 | + $this->addcell($row, $column, substr($this->data, $spos + 8, ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8)); | ||
901 | + | ||
902 | + // $this->addcell(LabelRecord($r)); | ||
903 | + break; | ||
904 | + | ||
905 | + case SPREADSHEET_EXCEL_READER_TYPE_EOF: | ||
906 | + $cont = false; | ||
907 | + break; | ||
908 | + default: | ||
909 | + //echo ' unknown :'.base_convert($r['code'],10,16)."\n"; | ||
910 | + break; | ||
911 | + | ||
912 | + } | ||
913 | + $spos += $length; | ||
914 | + } | ||
915 | + | ||
916 | + if (!isset($this->sheets[$this->sn]['numRows'])) | ||
917 | + $this->sheets[$this->sn]['numRows'] = $this->sheets[$this->sn]['maxrow']; | ||
918 | + if (!isset($this->sheets[$this->sn]['numCols'])) | ||
919 | + $this->sheets[$this->sn]['numCols'] = $this->sheets[$this->sn]['maxcol']; | ||
920 | + | ||
921 | + } | ||
922 | + | ||
923 | + /** | ||
924 | + * Check whether the current record read is a date | ||
925 | + * | ||
926 | + * @param todo | ||
927 | + * @return boolean True if date, false otherwise | ||
928 | + */ | ||
929 | + function isDate($spos) | ||
930 | + { | ||
931 | + //$xfindex = GetInt2d(, 4); | ||
932 | + $xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8; | ||
933 | + //echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']."\n"; | ||
934 | + //var_dump($this->formatRecords['xfrecords'][$xfindex]); | ||
935 | + if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'date') { | ||
936 | + $this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format']; | ||
937 | + $this->rectype = 'date'; | ||
938 | + return true; | ||
939 | + } else { | ||
940 | + if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'number') { | ||
941 | + $this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format']; | ||
942 | + $this->rectype = 'number'; | ||
943 | + if (($xfindex == 0x9) || ($xfindex == 0xa)){ | ||
944 | + $this->multiplier = 100; | ||
945 | + } | ||
946 | + }else{ | ||
947 | + $this->curformat = $this->_defaultFormat; | ||
948 | + $this->rectype = 'unknown'; | ||
949 | + } | ||
950 | + return false; | ||
951 | + } | ||
952 | + } | ||
953 | + | ||
954 | + //}}} | ||
955 | + //{{{ createDate() | ||
956 | + | ||
957 | + /** | ||
958 | + * Convert the raw Excel date into a human readable format | ||
959 | + * | ||
960 | + * Dates in Excel are stored as number of seconds from an epoch. On | ||
961 | + * Windows, the epoch is 30/12/1899 and on Mac it's 01/01/1904 | ||
962 | + * | ||
963 | + * @access private | ||
964 | + * @param integer The raw Excel value to convert | ||
965 | + * @return array First element is the converted date, the second element is number a unix timestamp | ||
966 | + */ | ||
967 | + function createDate($numValue) | ||
968 | + { | ||
969 | + if ($numValue > 1) { | ||
970 | + $utcDays = $numValue - ($this->nineteenFour ? SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904 : SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS); | ||
971 | + $utcValue = round(($utcDays+1) * SPREADSHEET_EXCEL_READER_MSINADAY); | ||
972 | + $string = date ($this->curformat, $utcValue); | ||
973 | + $raw = $utcValue; | ||
974 | + } else { | ||
975 | + $raw = $numValue; | ||
976 | + $hours = floor($numValue * 24); | ||
977 | + $mins = floor($numValue * 24 * 60) - $hours * 60; | ||
978 | + $secs = floor($numValue * SPREADSHEET_EXCEL_READER_MSINADAY) - $hours * 60 * 60 - $mins * 60; | ||
979 | + $string = date ($this->curformat, mktime($hours, $mins, $secs)); | ||
980 | + } | ||
981 | + | ||
982 | + return array($string, $raw); | ||
983 | + } | ||
984 | + | ||
985 | + function createNumber($spos) | ||
986 | + { | ||
987 | + $rknumhigh = $this->_GetInt4d($this->data, $spos + 10); | ||
988 | + $rknumlow = $this->_GetInt4d($this->data, $spos + 6); | ||
989 | + //for ($i=0; $i<8; $i++) { echo ord($this->data[$i+$spos+6]) . " "; } echo "<br>"; | ||
990 | + $sign = ($rknumhigh & 0x80000000) >> 31; | ||
991 | + $exp = ($rknumhigh & 0x7ff00000) >> 20; | ||
992 | + $mantissa = (0x100000 | ($rknumhigh & 0x000fffff)); | ||
993 | + $mantissalow1 = ($rknumlow & 0x80000000) >> 31; | ||
994 | + $mantissalow2 = ($rknumlow & 0x7fffffff); | ||
995 | + $value = $mantissa / pow( 2 , (20- ($exp - 1023))); | ||
996 | + if ($mantissalow1 != 0) $value += 1 / pow (2 , (21 - ($exp - 1023))); | ||
997 | + $value += $mantissalow2 / pow (2 , (52 - ($exp - 1023))); | ||
998 | + //echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n"; | ||
999 | + if ($sign) {$value = -1 * $value;} | ||
1000 | + return $value; | ||
1001 | + } | ||
1002 | + | ||
1003 | + function addcell($row, $col, $string, $raw = '') | ||
1004 | + { | ||
1005 | + //echo "ADD cel $row-$col $string\n"; | ||
1006 | + $this->sheets[$this->sn]['maxrow'] = max($this->sheets[$this->sn]['maxrow'], $row + $this->_rowoffset); | ||
1007 | + $this->sheets[$this->sn]['maxcol'] = max($this->sheets[$this->sn]['maxcol'], $col + $this->_coloffset); | ||
1008 | + $this->sheets[$this->sn]['cells'][$row + $this->_rowoffset][$col + $this->_coloffset] = $string; | ||
1009 | + if ($raw) | ||
1010 | + $this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['raw'] = $raw; | ||
1011 | + if (isset($this->rectype)) | ||
1012 | + $this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['type'] = $this->rectype; | ||
1013 | + | ||
1014 | + } | ||
1015 | + | ||
1016 | + | ||
1017 | + function _GetIEEE754($rknum) | ||
1018 | + { | ||
1019 | + if (($rknum & 0x02) != 0) { | ||
1020 | + $value = $rknum >> 2; | ||
1021 | + } else { | ||
1022 | +//mmp | ||
1023 | +// first comment out the previously existing 7 lines of code here | ||
1024 | +// $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc))); | ||
1025 | +// //$value = $tmp['']; | ||
1026 | +// if (array_key_exists(1, $tmp)) { | ||
1027 | +// $value = $tmp[1]; | ||
1028 | +// } else { | ||
1029 | +// $value = $tmp['']; | ||
1030 | +// } | ||
1031 | +// I got my info on IEEE754 encoding from | ||
1032 | +// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html | ||
1033 | +// The RK format calls for using only the most significant 30 bits of the | ||
1034 | +// 64 bit floating point value. The other 34 bits are assumed to be 0 | ||
1035 | +// So, we use the upper 30 bits of $rknum as follows... | ||
1036 | + $sign = ($rknum & 0x80000000) >> 31; | ||
1037 | + $exp = ($rknum & 0x7ff00000) >> 20; | ||
1038 | + $mantissa = (0x100000 | ($rknum & 0x000ffffc)); | ||
1039 | + $value = $mantissa / pow( 2 , (20- ($exp - 1023))); | ||
1040 | + if ($sign) {$value = -1 * $value;} | ||
1041 | +//end of changes by mmp | ||
1042 | + | ||
1043 | + } | ||
1044 | + | ||
1045 | + if (($rknum & 0x01) != 0) { | ||
1046 | + $value /= 100; | ||
1047 | + } | ||
1048 | + return $value; | ||
1049 | + } | ||
1050 | + | ||
1051 | + function _encodeUTF16($string) | ||
1052 | + { | ||
1053 | + $result = $string; | ||
1054 | + if ($this->_defaultEncoding){ | ||
1055 | + switch ($this->_encoderFunction){ | ||
1056 | + case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string); | ||
1057 | + break; | ||
1058 | + case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' ); | ||
1059 | + break; | ||
1060 | + } | ||
1061 | + } | ||
1062 | + return $result; | ||
1063 | + } | ||
1064 | + | ||
1065 | + function _GetInt4d($data, $pos) | ||
1066 | + { | ||
1067 | + $value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24); | ||
1068 | + if ($value>=4294967294) | ||
1069 | + { | ||
1070 | + $value=-2; | ||
1071 | + } | ||
1072 | + return $value; | ||
1073 | + } | ||
1074 | + | ||
1075 | +} | ||
1076 | + | ||
1077 | +/* | ||
1078 | + * Local variables: | ||
1079 | + * tab-width: 4 | ||
1080 | + * c-basic-offset: 4 | ||
1081 | + * c-hanging-comment-ender-p: nil | ||
1082 | + * End: | ||
1083 | + */ | ||
1084 | + | ||
1085 | +?> |
common/components/parsers/Parser.php
@@ -9,8 +9,6 @@ | @@ -9,8 +9,6 @@ | ||
9 | namespace common\components\parsers; | 9 | namespace common\components\parsers; |
10 | 10 | ||
11 | //@todo - заменить read на parse | 11 | //@todo - заменить read на parse |
12 | -//@todo - xml - убрать из названий функций xml и array - это и так понятно | ||
13 | - | ||
14 | 12 | ||
15 | use common\components\CustomVarDamp; | 13 | use common\components\CustomVarDamp; |
16 | 14 | ||
@@ -32,20 +30,8 @@ abstract class Parser | @@ -32,20 +30,8 @@ abstract class Parser | ||
32 | /** @var array - массив с заголовком, | 30 | /** @var array - массив с заголовком, |
33 | * */ | 31 | * */ |
34 | public $keys = NULL; | 32 | public $keys = NULL; |
35 | - /** @var bool | ||
36 | - имеет ли файл заголовок который будет установлен ключами возвращемого массива*/ | ||
37 | - public $has_header_row = false; | ||
38 | - /* | ||
39 | - *если есть ключи, то колонки с пустыми значениями будут пропускаться (из ряда такие значения будут удаляться), | ||
40 | - * например если в файле вторая колонка пустая то она будет удалена | ||
41 | - * если есть $has_header_row - то первая значимая строка становится ключами, но пустые колонки не удаляются из ряда | ||
42 | - * например если в файле вторая колонка пустая то ей будет назначен соответсвующий ключ (второй) из первой строки | ||
43 | - * все описаное выше реализуется в дочернем семействе классов TableParser в методе filterRow() | ||
44 | - * для xml происходит просто сопоставление переданных ключей с прочитанными | ||
45 | - */ | ||
46 | - | ||
47 | - | ||
48 | 33 | ||
34 | + public abstract function read(); | ||
49 | 35 | ||
50 | public function setup() | 36 | public function setup() |
51 | { | 37 | { |
@@ -54,7 +40,7 @@ abstract class Parser | @@ -54,7 +40,7 @@ abstract class Parser | ||
54 | 40 | ||
55 | protected function setupConverter() | 41 | protected function setupConverter() |
56 | { | 42 | { |
57 | - if ( $this->has_header_row || $this->keys !== NULL ) { | 43 | + if ( !empty( $this->keys ) ) { |
58 | // если у файла есть заголовок, то в результате имеем ассоциативный массив | 44 | // если у файла есть заголовок, то в результате имеем ассоциативный массив |
59 | $this->converter_conf['hasKey'] = 1; | 45 | $this->converter_conf['hasKey'] = 1; |
60 | } | 46 | } |
@@ -67,12 +53,8 @@ abstract class Parser | @@ -67,12 +53,8 @@ abstract class Parser | ||
67 | 53 | ||
68 | } | 54 | } |
69 | } | 55 | } |
70 | - | ||
71 | - | ||
72 | } | 56 | } |
73 | 57 | ||
74 | - public abstract function read(); | ||
75 | - | ||
76 | /** | 58 | /** |
77 | * @param $arr | 59 | * @param $arr |
78 | * @return mixed | 60 | * @return mixed |
@@ -80,27 +62,24 @@ abstract class Parser | @@ -80,27 +62,24 @@ abstract class Parser | ||
80 | */ | 62 | */ |
81 | protected function convert( $arr ) | 63 | protected function convert( $arr ) |
82 | { | 64 | { |
83 | - | ||
84 | if ($this->converter !== NULL) { | 65 | if ($this->converter !== NULL) { |
85 | 66 | ||
86 | $arr = $this->converter->convertByConfiguration( $arr, $this->converter_conf ); | 67 | $arr = $this->converter->convertByConfiguration( $arr, $this->converter_conf ); |
87 | 68 | ||
88 | } | 69 | } |
89 | - | ||
90 | - | ||
91 | return $arr; | 70 | return $arr; |
71 | + } | ||
92 | 72 | ||
73 | + public final static function supportedExtension() | ||
74 | + { | ||
75 | + return ['csv','xml','xlsx','txt','xls']; | ||
93 | } | 76 | } |
94 | 77 | ||
95 | protected function cleanUp( ) | 78 | protected function cleanUp( ) |
96 | { | 79 | { |
97 | - | ||
98 | unset( $this->file ); | 80 | unset( $this->file ); |
99 | unset( $this->converter ); | 81 | unset( $this->converter ); |
100 | unset( $this->converter_conf ); | 82 | unset( $this->converter_conf ); |
101 | - | ||
102 | - | ||
103 | } | 83 | } |
104 | 84 | ||
105 | - | ||
106 | } | 85 | } |
107 | \ No newline at end of file | 86 | \ No newline at end of file |
common/components/parsers/TableParser.php
@@ -13,14 +13,19 @@ use common\components\CustomVarDamp; | @@ -13,14 +13,19 @@ use common\components\CustomVarDamp; | ||
13 | 13 | ||
14 | abstract class TableParser extends Parser | 14 | abstract class TableParser extends Parser |
15 | { | 15 | { |
16 | - | ||
17 | - | ||
18 | /** | 16 | /** |
19 | * @var array - текущий отпарсенный ряд | 17 | * @var array - текущий отпарсенный ряд |
18 | + *если есть ключи, то колонки с пустыми значениями будут пропускаться (из ряда такие значения будут удаляться), | ||
19 | + * например если в файле вторая колонка пустая то она будет удалена | ||
20 | + * в остальных случаях парсятся все колонки (не проверяется - пустая ли колонка) и попадёт в итоговый массив | ||
20 | */ | 21 | */ |
21 | protected $row = []; | 22 | protected $row = []; |
22 | 23 | ||
23 | - /** @var int - первая строка с которой начинать парсить */ | 24 | + /** @var int - первая строка с которой начинать парсить |
25 | + * эта строка будет считаться первой значимой строкой | ||
26 | + * если установлен аттрибут $has_header_row, | ||
27 | + * тогда следующая строка будет считаться заголовком и будет пропущена | ||
28 | + */ | ||
24 | public $first_line = 0; | 29 | public $first_line = 0; |
25 | 30 | ||
26 | /** @var int - последняя строка до которой парсить | 31 | /** @var int - последняя строка до которой парсить |
@@ -32,9 +37,11 @@ abstract class TableParser extends Parser | @@ -32,9 +37,11 @@ abstract class TableParser extends Parser | ||
32 | 37 | ||
33 | 38 | ||
34 | /** @var bool | 39 | /** @var bool |
35 | - нужно ли искать автоматически первоую значисмую строку (не пустая строка) | ||
36 | - * иначе первая строка будет взята из аттрибута $first_line */ | ||
37 | - public $auto_detect_first_line = false; | 40 | + * имеет ли файл заголовок в первой значимой строке |
41 | + * true - первая значимая строка будет пропущена | ||
42 | + */ | ||
43 | + public $has_header_row = true; | ||
44 | + | ||
38 | 45 | ||
39 | /** @var int - количество значимых колонок, что бы определить первую значимую строку | 46 | /** @var int - количество значимых колонок, что бы определить первую значимую строку |
40 | * используется при автоопределении первой строки*/ | 47 | * используется при автоопределении первой строки*/ |
@@ -48,8 +55,6 @@ abstract class TableParser extends Parser | @@ -48,8 +55,6 @@ abstract class TableParser extends Parser | ||
48 | protected $current_row_number = 0; | 55 | protected $current_row_number = 0; |
49 | 56 | ||
50 | 57 | ||
51 | - protected abstract function isEmptyRow(); | ||
52 | - | ||
53 | protected abstract function isEmptyColumn($column_value); | 58 | protected abstract function isEmptyColumn($column_value); |
54 | 59 | ||
55 | protected abstract function readRow(); | 60 | protected abstract function readRow(); |
@@ -59,70 +64,71 @@ abstract class TableParser extends Parser | @@ -59,70 +64,71 @@ abstract class TableParser extends Parser | ||
59 | 64 | ||
60 | public function read() | 65 | public function read() |
61 | { | 66 | { |
62 | - if ($this->auto_detect_first_line) { | ||
63 | - $this->shiftToFirstValuableLine(); | ||
64 | - } | 67 | + // получим первую значимую строку |
68 | + $this->shiftToFirstValuableLine(); | ||
69 | + | ||
70 | + // первый проход, строка прочитана в shiftToFirstValuableLine | ||
71 | + $first_circle = true; | ||
65 | 72 | ||
66 | // будем считать количество пустых строк подряд - при достижении $empty_lines_quantity - считаем что это конец файла и выходим | 73 | // будем считать количество пустых строк подряд - при достижении $empty_lines_quantity - считаем что это конец файла и выходим |
67 | $empty_lines = 0; | 74 | $empty_lines = 0; |
68 | while ($empty_lines < $this->empty_lines_quantity) { | 75 | while ($empty_lines < $this->empty_lines_quantity) { |
69 | - // прочтем строку из файла | ||
70 | - $this->readRow(); | ||
71 | 76 | ||
72 | - if ($this->isEmptyRow()) { | ||
73 | - //счетчик пустых строк | ||
74 | - //CustomVarDamp::dump($this->current_row_number); | ||
75 | - $empty_lines++; | ||
76 | - continue; | 77 | + // прочтем строку из файла, если это не первый проход |
78 | + if (!$first_circle){ | ||
79 | + $this->readRow(); | ||
77 | } | 80 | } |
78 | 81 | ||
82 | + $first_circle = false; | ||
83 | + | ||
79 | // уберем пустые колонки из ряда | 84 | // уберем пустые колонки из ряда |
80 | if ($this->keys === NULL) { | 85 | if ($this->keys === NULL) { |
81 | $this->filterRow(); | 86 | $this->filterRow(); |
82 | } | 87 | } |
83 | 88 | ||
89 | + if ($this->isEmptyRow()) { | ||
90 | + //счетчик пустых строк | ||
91 | + $empty_lines++; | ||
92 | + $this->current_row_number++; | ||
93 | + continue; | ||
94 | + } | ||
84 | 95 | ||
96 | + // запустим конвертирование | ||
85 | $this->adjustRowToSettings(); | 97 | $this->adjustRowToSettings(); |
86 | 98 | ||
99 | + // установим отпарсенную строку в итоговый массив результата | ||
100 | + $this->setResult(); | ||
87 | // строка не пустая, имеем прочитанный массив значений | 101 | // строка не пустая, имеем прочитанный массив значений |
88 | $this->current_row_number++; | 102 | $this->current_row_number++; |
89 | 103 | ||
90 | - // для первой строки утановим ключи из заголовка | ||
91 | - if (!$this->setKeysFromHeader()) { | ||
92 | - $this->setResult(); | ||
93 | - } | ||
94 | - | ||
95 | - | ||
96 | // если у нас установлен лимит, при его достижении прекращаем парсинг | 104 | // если у нас установлен лимит, при его достижении прекращаем парсинг |
97 | if ($this->isLastLine()) | 105 | if ($this->isLastLine()) |
98 | break; | 106 | break; |
99 | 107 | ||
100 | // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД | 108 | // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД |
101 | $empty_lines = 0; | 109 | $empty_lines = 0; |
102 | - | ||
103 | } | 110 | } |
104 | - | ||
105 | } | 111 | } |
106 | 112 | ||
107 | /** | 113 | /** |
108 | * определяет первую значимую строку, | 114 | * определяет первую значимую строку, |
109 | * считывается файл пока в нем не встретится строка с непустыми колонками | 115 | * считывается файл пока в нем не встретится строка с непустыми колонками |
110 | - * в количестве указанном в атрибуте min_column_quantity | ||
111 | - * в результате выполнения $current_row_number будет находится на последней незначимой строке | 116 | + * или пока не дойдет до first_line |
117 | + * пропускает заголовок если он указан | ||
112 | */ | 118 | */ |
113 | protected function shiftToFirstValuableLine() | 119 | protected function shiftToFirstValuableLine() |
114 | { | 120 | { |
121 | + // читаем пока не встретим значимую строку, или пока не дойдем до first_line | ||
115 | do { | 122 | do { |
116 | - | ||
117 | $this->current_row_number++; | 123 | $this->current_row_number++; |
118 | $this->readRow(); | 124 | $this->readRow(); |
125 | + } while ( $this->isEmptyRow() && ( $this->first_line < $this->current_row_number ) ); | ||
119 | 126 | ||
120 | - } while ($this->isEmptyRow()); | ||
121 | - | ||
122 | - // @todo - сделать опционально | ||
123 | - // код для того что бы парсить первую строку, закомментировано как предполагается что первая значимая строка это заголовок | ||
124 | - // $this->current_row_number --; | ||
125 | -// $this->file->seek( $this->current_row_number ); | 127 | + // если указан заголовок, то его мы тоже пропускаем (читаем далее) |
128 | + if( $this->has_header_row ) { | ||
129 | + $this->current_row_number++; | ||
130 | + $this->readRow(); | ||
131 | + } | ||
126 | } | 132 | } |
127 | 133 | ||
128 | /** | 134 | /** |
@@ -130,7 +136,6 @@ abstract class TableParser extends Parser | @@ -130,7 +136,6 @@ abstract class TableParser extends Parser | ||
130 | */ | 136 | */ |
131 | protected function adjustRowToSettings() | 137 | protected function adjustRowToSettings() |
132 | { | 138 | { |
133 | - | ||
134 | // если есть заголовок, то перед конвертацией его нужно назначить | 139 | // если есть заголовок, то перед конвертацией его нужно назначить |
135 | if ($this->keys !== NULL) { | 140 | if ($this->keys !== NULL) { |
136 | // adjust row to keys | 141 | // adjust row to keys |
@@ -151,22 +156,43 @@ abstract class TableParser extends Parser | @@ -151,22 +156,43 @@ abstract class TableParser extends Parser | ||
151 | 156 | ||
152 | } | 157 | } |
153 | 158 | ||
154 | - protected function setKeysFromHeader() | ||
155 | - { | ||
156 | - if ($this->has_header_row) { | ||
157 | - // в файле есть заголовок, но он еще не назначен - назначим | ||
158 | - if ($this->keys === NULL) { | ||
159 | - $this->keys = array_values($this->row); | ||
160 | - return true; | 159 | + protected function isEmptyRow(){ |
160 | + | ||
161 | + $is_empty = false; | ||
162 | + | ||
163 | + if ( empty( $this->row ) ) { | ||
164 | + return true; | ||
165 | + } | ||
166 | + if ( count( $this->row ) < $this->min_column_quantity ) { | ||
167 | + return true; | ||
168 | + } | ||
169 | + | ||
170 | + $j = 0; | ||
171 | + for ($i = 1; $i <= count( $this->row ); $i++) { | ||
172 | + | ||
173 | + if ( !isset( $this->row[ $i - 1 ] ) ) { | ||
174 | + continue; | ||
175 | + } | ||
176 | + | ||
177 | + if ( $this->isEmptyColumn( $this->row[$i - 1] ) ) { | ||
178 | + $j++; | ||
179 | + } | ||
180 | + | ||
181 | + if ( $j >= $this->min_column_quantity ) { | ||
182 | + $is_empty = true; | ||
183 | + break; | ||
161 | } | 184 | } |
162 | } | 185 | } |
163 | - return false; | 186 | + |
187 | + return $is_empty; | ||
164 | } | 188 | } |
165 | 189 | ||
190 | + | ||
191 | + | ||
166 | protected function filterRow() | 192 | protected function filterRow() |
167 | { | 193 | { |
168 | - // если есть заголовок - все значения нужны, не фильтруем | ||
169 | - if ($this->has_header_row || !is_array($this->row)) { | 194 | + // нет строки - нет фильтрации |
195 | + if ( empty( $this->row ) ) { | ||
170 | return; | 196 | return; |
171 | } | 197 | } |
172 | $this->row = array_filter($this->row, function ($val) { | 198 | $this->row = array_filter($this->row, function ($val) { |
1 | +<?php | ||
2 | +/** | ||
3 | + | ||
4 | + */ | ||
5 | +namespace common\components\parsers; | ||
6 | + | ||
7 | +/** | ||
8 | + * Class XlsParser | ||
9 | + * @package yii\multiparser | ||
10 | + * @todo - перевести на анг. яз. | ||
11 | + */ | ||
12 | + | ||
13 | + | ||
14 | +class XlsParser extends TableParser | ||
15 | +{ | ||
16 | + // экземпляр класса Spreadsheet_Excel_Reader - для чтения листов Excel | ||
17 | + protected $reader; | ||
18 | + // строка кодировки | ||
19 | + protected $encoding = 'CP1251'; | ||
20 | + | ||
21 | + /** | ||
22 | + * @var int - номер листа с которого будет происходить чтение | ||
23 | + */ | ||
24 | + public $active_sheet = 0; | ||
25 | + | ||
26 | + /** | ||
27 | + * метод устанавливает настройки конвертера и ридера | ||
28 | + */ | ||
29 | + public function setup() | ||
30 | + { | ||
31 | + parent::setup(); | ||
32 | + $this->setupReader(); | ||
33 | + } | ||
34 | + | ||
35 | + | ||
36 | + /** | ||
37 | + * устанавливает ридер и его параметры | ||
38 | + */ | ||
39 | + protected function setupReader() | ||
40 | + { | ||
41 | + require_once 'ExcelReader/reader.php'; | ||
42 | + $this->reader = new \Spreadsheet_Excel_Reader(); | ||
43 | + $this->reader->setOutputEncoding( $this->encoding ); | ||
44 | + $this->reader->read( $this->file_path ); | ||
45 | + | ||
46 | + } | ||
47 | + | ||
48 | + public function read() | ||
49 | + { | ||
50 | + parent::read(); | ||
51 | + | ||
52 | + $this->cleanUp(); | ||
53 | + | ||
54 | + return $this->result; | ||
55 | + } | ||
56 | + | ||
57 | + | ||
58 | + protected function readRow( ) | ||
59 | + { | ||
60 | + $this->row = []; | ||
61 | + $current_sheet = $this->reader->sheets[ $this->active_sheet ]; | ||
62 | + | ||
63 | + for ( $j = 1; $j <= $current_sheet['numCols']; $j++ ) { | ||
64 | + if ( isset( $current_sheet['cells'][ $this->current_row_number ][$j]) ) | ||
65 | + $this->row[] = $current_sheet['cells'][ $this->current_row_number ][$j]; | ||
66 | + } | ||
67 | + } | ||
68 | + | ||
69 | + | ||
70 | + protected function isEmptyColumn( $val ){ | ||
71 | + return $val == ''; | ||
72 | + } | ||
73 | + | ||
74 | + protected function setResult( ){ | ||
75 | + $this->result[] = $this->row; | ||
76 | + } | ||
77 | +} | ||
0 | \ No newline at end of file | 78 | \ No newline at end of file |
common/components/parsers/XlsxParser.php
@@ -37,7 +37,7 @@ class XlsxParser extends TableParser | @@ -37,7 +37,7 @@ class XlsxParser extends TableParser | ||
37 | protected $current_sheet; | 37 | protected $current_sheet; |
38 | 38 | ||
39 | // глубина округления для флоата | 39 | // глубина округления для флоата |
40 | - // @todo - перенести вродительский класс и применить в дочерних классах | 40 | + // @todo - перенести в родительский класс и применить в дочерних классах |
41 | protected $float_precision = 6; | 41 | protected $float_precision = 6; |
42 | 42 | ||
43 | public function setup() | 43 | public function setup() |
@@ -175,62 +175,21 @@ class XlsxParser extends TableParser | @@ -175,62 +175,21 @@ class XlsxParser extends TableParser | ||
175 | $value = (string)round( $value, $this->float_precision ); | 175 | $value = (string)round( $value, $this->float_precision ); |
176 | } | 176 | } |
177 | 177 | ||
178 | - | ||
179 | } else { | 178 | } else { |
180 | $value = ''; | 179 | $value = ''; |
181 | } | 180 | } |
182 | - | ||
183 | // set | 181 | // set |
184 | $this->row[$i] = $value; | 182 | $this->row[$i] = $value; |
185 | - | ||
186 | } | 183 | } |
187 | -// // fill the row by empty values for keys that we are missed in previous step | ||
188 | - // only for 'has_header_row = true' mode | ||
189 | - if ( $this->has_header_row && $this->keys !== Null ) { | ||
190 | - $extra_column = count( $this->keys ) - count( $this->row ); | ||
191 | - if ( $extra_column ) { | ||
192 | - foreach ( $this->keys as $key => $key ) { | ||
193 | - | ||
194 | - if ( isset( $this->row[$key] ) ) { | ||
195 | - continue; | ||
196 | - } | ||
197 | - $this->row[$key] = ''; | ||
198 | - } | ||
199 | - } | ||
200 | 184 | ||
201 | - } | ||
202 | ksort( $this->row ); | 185 | ksort( $this->row ); |
203 | $this->current_node->next(); | 186 | $this->current_node->next(); |
204 | } | 187 | } |
205 | 188 | ||
206 | - protected function isEmptyRow() | ||
207 | - { | ||
208 | - | ||
209 | - $is_empty = false; | ||
210 | - | ||
211 | - if (!count($this->row) || !$this->current_node->valid()) { | ||
212 | - return true; | ||
213 | - } | ||
214 | - | ||
215 | - $j = 0; | ||
216 | - for ($i = 1; $i <= count($this->row); $i++) { | ||
217 | - | ||
218 | - if (isset($this->row[$i - 1]) && $this->isEmptyColumn($this->row[$i - 1])) { | ||
219 | - $j++; | ||
220 | - } | ||
221 | - | ||
222 | - if ($j >= $this->min_column_quantity) { | ||
223 | - $is_empty = true; | ||
224 | - break; | ||
225 | - } | ||
226 | - } | ||
227 | - | ||
228 | - return $is_empty; | ||
229 | - } | ||
230 | 189 | ||
231 | protected function isEmptyColumn($val) | 190 | protected function isEmptyColumn($val) |
232 | { | 191 | { |
233 | - return $val == ''; | 192 | + return $val == '' || $val === null; |
234 | } | 193 | } |
235 | 194 | ||
236 | protected function setResult() | 195 | protected function setResult() |
@@ -261,7 +220,6 @@ class XlsxParser extends TableParser | @@ -261,7 +220,6 @@ class XlsxParser extends TableParser | ||
261 | } | 220 | } |
262 | } | 221 | } |
263 | 222 | ||
264 | - | ||
265 | /** | 223 | /** |
266 | * @param $cell_address - string with address like A1, B1 ... | 224 | * @param $cell_address - string with address like A1, B1 ... |
267 | * @return int - integer index | 225 | * @return int - integer index |
@@ -281,17 +239,7 @@ class XlsxParser extends TableParser | @@ -281,17 +239,7 @@ class XlsxParser extends TableParser | ||
281 | return $index; | 239 | return $index; |
282 | 240 | ||
283 | } | 241 | } |
284 | -// @todo - переписать родительский метод в универсальной манере а не переопределять его | ||
285 | - protected function setKeysFromHeader(){ | ||
286 | - if ( $this->has_header_row ) { | ||
287 | 242 | ||
288 | - if ($this->keys === NULL) { | ||
289 | - $this->keys = $this->row; | ||
290 | - return true; | ||
291 | - } | ||
292 | - } | ||
293 | - return false; | ||
294 | - } | ||
295 | protected function cleanUp() | 243 | protected function cleanUp() |
296 | { | 244 | { |
297 | parent::cleanUp(); | 245 | parent::cleanUp(); |
common/components/parsers/XmlParser.php
@@ -15,15 +15,13 @@ class XmlParser extends Parser{ | @@ -15,15 +15,13 @@ class XmlParser extends Parser{ | ||
15 | 15 | ||
16 | public function read() | 16 | public function read() |
17 | { | 17 | { |
18 | - //$file = $this->file; | ||
19 | - $result = $this->xmlToArray( ); | 18 | + $result = $this->parseToArray( ); |
20 | 19 | ||
21 | if ( isset($this->node) ) { | 20 | if ( isset($this->node) ) { |
22 | 21 | ||
23 | $result = $result[ $this->node ]; | 22 | $result = $result[ $this->node ]; |
24 | 23 | ||
25 | } | 24 | } |
26 | - | ||
27 | $this->cleanUp(); | 25 | $this->cleanUp(); |
28 | return $result; | 26 | return $result; |
29 | } | 27 | } |
@@ -36,17 +34,15 @@ class XmlParser extends Parser{ | @@ -36,17 +34,15 @@ class XmlParser extends Parser{ | ||
36 | * @throws Exception | 34 | * @throws Exception |
37 | * @throws \Exception | 35 | * @throws \Exception |
38 | */ | 36 | */ |
39 | - protected function xmlToArray( ) { | ||
40 | - | 37 | + protected function parseToArray( ) { |
41 | try { | 38 | try { |
42 | $xml = new \SimpleXMLElement( $this->file_path, 0, true ); | 39 | $xml = new \SimpleXMLElement( $this->file_path, 0, true ); |
43 | //\common\components\CustomVarDamp::dumpAndDie($xml->children()->children()); | 40 | //\common\components\CustomVarDamp::dumpAndDie($xml->children()->children()); |
44 | - $result = $this->recursiveXMLToArray( $xml ); | 41 | + $result = $this->recursiveParseToArray( $xml ); |
45 | } catch(\Exception $ex) { | 42 | } catch(\Exception $ex) { |
46 | 43 | ||
47 | throw $ex; | 44 | throw $ex; |
48 | } | 45 | } |
49 | - | ||
50 | return $result; | 46 | return $result; |
51 | } | 47 | } |
52 | 48 | ||
@@ -58,7 +54,7 @@ class XmlParser extends Parser{ | @@ -58,7 +54,7 @@ class XmlParser extends Parser{ | ||
58 | * | 54 | * |
59 | * @return mixed | 55 | * @return mixed |
60 | */ | 56 | */ |
61 | - protected function recursiveXMLToArray($xml) { | 57 | + protected function recursiveParseToArray($xml) { |
62 | if( $xml instanceof \SimpleXMLElement ) { | 58 | if( $xml instanceof \SimpleXMLElement ) { |
63 | $attributes = $xml->attributes(); | 59 | $attributes = $xml->attributes(); |
64 | 60 | ||
@@ -77,7 +73,7 @@ class XmlParser extends Parser{ | @@ -77,7 +73,7 @@ class XmlParser extends Parser{ | ||
77 | return (string) $previous_xml; // for CDATA | 73 | return (string) $previous_xml; // for CDATA |
78 | 74 | ||
79 | foreach($xml as $key => $value) { | 75 | foreach($xml as $key => $value) { |
80 | - $row[$key] = $this->recursiveXMLToArray($value); | 76 | + $row[$key] = $this->recursiveParseToArray($value); |
81 | } | 77 | } |
82 | if ( is_string($value) ) { | 78 | if ( is_string($value) ) { |
83 | // дошли до конца рекурсии | 79 | // дошли до конца рекурсии |
@@ -90,7 +86,6 @@ class XmlParser extends Parser{ | @@ -90,7 +86,6 @@ class XmlParser extends Parser{ | ||
90 | 86 | ||
91 | } | 87 | } |
92 | 88 | ||
93 | - | ||
94 | if( isset( $attribute_array ) ) | 89 | if( isset( $attribute_array ) ) |
95 | $row['@'] = $attribute_array; // Attributes | 90 | $row['@'] = $attribute_array; // Attributes |
96 | 91 |
common/components/parsers/config.php
1 | <?php | 1 | <?php |
2 | - return [ | ||
3 | - 'csv' => | ||
4 | - ['web' => | ||
5 | - ['class' => 'common\components\parsers\CustomCsvParser', | ||
6 | - 'auto_detect_first_line' => true, | ||
7 | - 'converter_conf' => [ | ||
8 | - 'class' => 'common\components\parsers\CustomConverter', | ||
9 | - 'configuration' => ["encode" => 'DESCR'], | ||
10 | - ] | ||
11 | - ], | ||
12 | - 'console' => | ||
13 | - ['class' => 'common\components\parsers\CustomCsvParser', | ||
14 | - 'auto_detect_first_line' => true, | ||
15 | - 'converter_conf' => [ | ||
16 | - 'class' => ' common\components\parsers\CustomConverter', | ||
17 | - 'configuration' => ["encode" => 'DESCR', | ||
18 | - "string" => 'DESCR', | ||
19 | - "float" => 'PRICE', | ||
20 | - "brand" => 'BRAND', | ||
21 | - "integer" => ['BOX','ADD_BOX'], | ||
22 | - "multiply" => [], | ||
23 | - "article" => [], | ||
24 | - "details" => [] | 2 | +return [ |
3 | + 'csv' => | ||
4 | + ['web' => | ||
5 | + ['class' => 'common\components\parsers\CustomCsvParser', | ||
6 | + 'converter_conf' => [ | ||
7 | + 'class' => 'common\components\parsers\CustomConverter', | ||
8 | + 'configuration' => ["encode" => 'DESCR'], | ||
9 | + ] | ||
10 | + ], | ||
11 | + 'console' => | ||
12 | + ['class' => 'common\components\parsers\CustomCsvParser', | ||
13 | + 'converter_conf' => [ | ||
14 | + 'class' => ' common\components\parsers\CustomConverter', | ||
15 | + 'configuration' => ["encode" => 'DESCR', | ||
16 | + "string" => 'DESCR', | ||
17 | + "float" => 'PRICE', | ||
18 | + "brand" => 'BRAND', | ||
19 | + "integer" => ['BOX', 'ADD_BOX'], | ||
20 | + "multiply" => [], | ||
21 | + "article" => [], | ||
22 | + "details" => [] | ||
23 | + ] | ||
24 | + ],], | ||
25 | 25 | ||
26 | - ] | ||
27 | - ],], | 26 | + 'basic_column' => [ |
27 | + Null => 'Пусто', | ||
28 | + "BRAND" => 'Бренд', | ||
29 | + "ARTICLE" => 'Артикул', | ||
30 | + "PRICE" => 'Цена', | ||
31 | + "DESCR" => 'Наименование', | ||
32 | + "BOX" => 'Колво', | ||
33 | + "ADD_BOX" => 'В пути', | ||
34 | + "GROUP" => 'Группа RG' | ||
35 | + ], | ||
36 | + 'crosses' => ['class' => 'common\components\parsers\CustomCsvParser', | ||
37 | + 'min_column_quantity' => 4, | ||
38 | + 'converter_conf' => [ | ||
39 | + 'class' => ' common\components\parsers\CustomConverter', | ||
40 | + 'hasKey' => 1, | ||
41 | + 'configuration' => [ | ||
42 | + "brand" => ['BRAND', 'CROSS_BRAND'], | ||
43 | + ] | ||
44 | + ], | ||
45 | + 'basic_column' => [ | ||
46 | + Null => 'Пусто', | ||
47 | + "ARTICLE" => 'Артикул', | ||
48 | + "CROSS_ARTICLE" => 'Кросс артикул', | ||
49 | + "BRAND" => 'Бренд', | ||
50 | + "CROSS_BRAND" => 'Кросс бренд' | ||
51 | + ], | ||
52 | + ], | ||
53 | + ], | ||
54 | + 'xml' => | ||
55 | + ['console' => | ||
56 | + ['class' => 'common\components\parsers\XmlParser', | ||
57 | + 'node' => 'Товар', | ||
58 | + 'keys' => [ | ||
59 | + "BRAND" => 'Производитель', | ||
60 | + "ARTICLE" => 'Код', | ||
61 | + "PRICE" => 'Розница', | ||
62 | + "DESCR" => 'Наименование', | ||
63 | + "BOX" => 'Колво', | ||
64 | + "ADD_BOX" => 'Ожидаемое', | ||
65 | + "GROUP" => 'Группа' | ||
66 | + ], | ||
67 | + 'converter_conf' => [ | ||
68 | + 'class' => 'common\components\parsers\CustomConverter', | ||
69 | + 'configuration' => ["details" => [] | ||
70 | + ],], | ||
71 | + ], | ||
72 | + ], | ||
73 | + 'xlsx' => | ||
74 | + ['web' => | ||
75 | + ['class' => 'common\components\parsers\XlsxParser', | ||
76 | + 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/xlsx/', | ||
77 | + 'min_column_quantity' => 5, | ||
78 | + 'active_sheet' => 1, | ||
79 | + 'converter_conf' => [ | ||
80 | + 'class' => 'common\components\parsers\CustomConverter', | ||
81 | + 'configuration' => ["string" => []], | ||
82 | + ] | ||
83 | + ], | ||
84 | + 'rg' => | ||
85 | + ['class' => 'common\components\parsers\XlsxParser', | ||
86 | + 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/xlsx/', | ||
87 | + 'min_column_quantity' => 4, | ||
88 | + 'has_header_row' => false, // заголовок есть, но мы его выводим пользователю для наглядности (так у них на сайте было) и принудительно удаляем первую строку при записи | ||
89 | + 'active_sheet' => 1, | ||
90 | + 'converter_conf' => [ | ||
91 | + 'class' => 'common\components\parsers\CustomConverter', | ||
92 | + 'configuration' => ["string" => []], | ||
93 | + ] | ||
94 | + ], | ||
95 | + 'console' => | ||
96 | + ['class' => 'common\components\parsers\XlsxParser', | ||
97 | + 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/xlsx/', | ||
98 | + 'active_sheet' => 1, | ||
99 | + 'min_column_quantity' => 5, | ||
100 | + 'converter_conf' => [ | ||
101 | + 'class' => ' common\components\parsers\CustomConverter', | ||
102 | + 'configuration' => ["encode" => 'DESCR', | ||
103 | + "string" => 'DESCR', | ||
104 | + "float" => 'PRICE', | ||
105 | + "brand" => 'BRAND', | ||
106 | + "integer" => ['BOX', 'ADD_BOX'], | ||
107 | + "multiply" => [], | ||
108 | + "article" => [], | ||
109 | + "details" => [] | ||
110 | + ] | ||
111 | + ],], | ||
112 | + ], | ||
113 | + 'txt' => | ||
114 | + ['web' => | ||
115 | + ['class' => 'common\components\parsers\CustomCsvParser', | ||
116 | + 'delimiter' => "\t", | ||
117 | + 'converter_conf' => [ | ||
118 | + 'class' => 'common\components\parsers\CustomConverter', | ||
119 | + 'configuration' => ["encode" => 'DESCR'], | ||
120 | + ] | ||
121 | + ], | ||
122 | + 'console' => | ||
123 | + ['class' => 'common\components\parsers\CustomCsvParser', | ||
124 | + 'delimiter' => "\t", | ||
125 | + 'converter_conf' => [ | ||
126 | + 'class' => ' common\components\parsers\CustomConverter', | ||
127 | + 'configuration' => ["encode" => 'DESCR', | ||
128 | + "string" => 'DESCR', | ||
129 | + "float" => 'PRICE', | ||
130 | + "brand" => 'BRAND', | ||
131 | + "integer" => ['BOX', 'ADD_BOX'], | ||
132 | + "multiply" => [], | ||
133 | + "article" => [], | ||
134 | + "details" => [] | ||
135 | + ] | ||
136 | + ], | ||
137 | + ], | ||
138 | + 'basic_column' => [ | ||
139 | + Null => 'Пусто', | ||
140 | + "BRAND" => 'Бренд', | ||
141 | + "ARTICLE" => 'Артикул', | ||
142 | + "PRICE" => 'Цена', | ||
143 | + "DESCR" => 'Наименование', | ||
144 | + "BOX" => 'Колво', | ||
145 | + "ADD_BOX" => 'В пути', | ||
146 | + "GROUP" => 'Группа RG' | ||
147 | + ], | ||
148 | + ], | ||
149 | + 'xls' => | ||
150 | + ['web' => | ||
151 | + ['class' => 'common\components\parsers\XlsParser', | ||
152 | + 'converter_conf' => [ | ||
153 | + 'class' => 'common\components\parsers\CustomConverter', | ||
154 | + 'configuration' => ["encode" => 'DESCR'], | ||
155 | + ] | ||
156 | + ], | ||
157 | + 'console' => | ||
158 | + ['class' => 'common\components\parsers\XlsParser', | ||
159 | + 'converter_conf' => [ | ||
160 | + 'class' => ' common\components\parsers\CustomConverter', | ||
161 | + 'configuration' => ["encode" => 'DESCR', | ||
162 | + "string" => 'DESCR', | ||
163 | + "float" => 'PRICE', | ||
164 | + "brand" => 'BRAND', | ||
165 | + "integer" => ['BOX', 'ADD_BOX'], | ||
166 | + "multiply" => [], | ||
167 | + "article" => [], | ||
168 | + "details" => [] | ||
28 | 169 | ||
29 | - 'basic_column' => [ | ||
30 | - Null => 'Пусто', | ||
31 | - "BRAND" => 'Бренд', | ||
32 | - "ARTICLE"=> 'Артикул', | ||
33 | - "PRICE" => 'Цена', | ||
34 | - "DESCR" => 'Наименование', | ||
35 | - "BOX" => 'Колво', | ||
36 | - "ADD_BOX"=> 'В пути', | ||
37 | - "GROUP" => 'Группа RG' | ||
38 | - ], | 170 | + ] |
171 | + ],], | ||
39 | 172 | ||
40 | - 'crosses' => ['class' => 'common\components\parsers\CustomCsvParser', | ||
41 | - 'auto_detect_first_line' => true, | ||
42 | - 'min_column_quantity' => 4, | ||
43 | - 'converter_conf' => [ | ||
44 | - 'class' => ' common\components\parsers\CustomConverter', | ||
45 | - 'hasKey' => 1, | ||
46 | - 'configuration' => [ | ||
47 | - "brand" => ['BRAND', 'CROSS_BRAND'], | ||
48 | - ] | ||
49 | - ], | ||
50 | - 'basic_column' => [ | ||
51 | - Null => 'Пусто', | ||
52 | - "ARTICLE"=> 'Артикул', | ||
53 | - "CROSS_ARTICLE" => 'Кросс артикул', | ||
54 | - "BRAND" => 'Бренд', | ||
55 | - "CROSS_BRAND" => 'Кросс бренд' | ||
56 | - ], | ||
57 | - ], | ||
58 | - ], | ||
59 | - 'xml' => | ||
60 | - ['console' => | ||
61 | - ['class' => 'common\components\parsers\XmlParser', | ||
62 | - 'node' => 'Товар', | ||
63 | - 'has_header_row' => true, | ||
64 | - 'keys' => [ | ||
65 | - "BRAND" => 'Производитель', | ||
66 | - "ARTICLE"=> 'Код', | ||
67 | - "PRICE" => 'Розница', | ||
68 | - "DESCR" => 'Наименование', | ||
69 | - "BOX" => 'Колво', | ||
70 | - "ADD_BOX"=> 'Ожидаемое', | ||
71 | - "GROUP" => 'Группа' | ||
72 | - ], | ||
73 | - 'converter_conf' => [ | ||
74 | - 'class' => 'common\components\parsers\CustomConverter', | ||
75 | - 'configuration' => ["details" => [] | ||
76 | - ],], | ||
77 | - ], | ||
78 | - ], | ||
79 | - 'xlsx' => | ||
80 | - ['web' => | ||
81 | - ['class' => 'common\components\parsers\XlsxParser', | ||
82 | - 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/xlsx/', | ||
83 | - //'auto_detect_first_line' => true, | ||
84 | - //'has_header_row' => true, | ||
85 | - 'active_sheet' => 1, | ||
86 | - 'converter_conf' => [ | ||
87 | - 'class' => 'common\components\parsers\CustomConverter', | ||
88 | - 'configuration' => ["string" => []], | ||
89 | - ] | ||
90 | - ], | ||
91 | - ] | ||
92 | - ]; | 173 | + 'basic_column' => [ |
174 | + Null => 'Пусто', | ||
175 | + "BRAND" => 'Бренд', | ||
176 | + "ARTICLE" => 'Артикул', | ||
177 | + "PRICE" => 'Цена', | ||
178 | + "DESCR" => 'Наименование', | ||
179 | + "BOX" => 'Колво', | ||
180 | + "ADD_BOX" => 'В пути', | ||
181 | + "GROUP" => 'Группа RG' | ||
182 | + ], | ||
183 | + ], | ||
184 | +]; | ||
93 | 185 |
common/models/Brands.php
@@ -2,6 +2,7 @@ | @@ -2,6 +2,7 @@ | ||
2 | 2 | ||
3 | namespace common\models; | 3 | namespace common\models; |
4 | 4 | ||
5 | +use backend\components\base\BaseActiveRecord; | ||
5 | use Yii; | 6 | use Yii; |
6 | 7 | ||
7 | /** | 8 | /** |
@@ -17,8 +18,12 @@ use Yii; | @@ -17,8 +18,12 @@ use Yii; | ||
17 | * @property string $IMG | 18 | * @property string $IMG |
18 | * @property string $timestamp | 19 | * @property string $timestamp |
19 | */ | 20 | */ |
20 | -class Brands extends \yii\db\ActiveRecord | 21 | +class Brands extends BaseActiveRecord |
21 | { | 22 | { |
23 | + // для валидации выбранного пользователем файла | ||
24 | + public $file; | ||
25 | + // флаг, нужно ли удалять изображение | ||
26 | + public $delete_img; | ||
22 | /** | 27 | /** |
23 | * @inheritdoc | 28 | * @inheritdoc |
24 | */ | 29 | */ |
@@ -33,13 +38,17 @@ class Brands extends \yii\db\ActiveRecord | @@ -33,13 +38,17 @@ class Brands extends \yii\db\ActiveRecord | ||
33 | public function rules() | 38 | public function rules() |
34 | { | 39 | { |
35 | return [ | 40 | return [ |
36 | - [['BRAND', 'CONTENT'], 'required'], | 41 | + [['BRAND'], 'required'], |
37 | [['if_tecdoc', 'if_oem', 'if_checked'], 'integer'], | 42 | [['if_tecdoc', 'if_oem', 'if_checked'], 'integer'], |
38 | [['CONTENT'], 'string'], | 43 | [['CONTENT'], 'string'], |
39 | [['timestamp'], 'safe'], | 44 | [['timestamp'], 'safe'], |
45 | + [['delete_img'], 'safe'], | ||
40 | [['BRAND'], 'string', 'max' => 100], | 46 | [['BRAND'], 'string', 'max' => 100], |
41 | [['tecdoc_logo'], 'string', 'max' => 50], | 47 | [['tecdoc_logo'], 'string', 'max' => 50], |
42 | - [['IMG'], 'string', 'max' => 255] | 48 | + ['IMG', 'string', 'max' => 255], |
49 | + ['IMG', 'match', 'pattern' => '/[a-zA-Z0-9]+\.[a-zA-Z]+/', 'message' => 'Имя файла изображения должно иметь только латинские символы и цифры'], | ||
50 | + // [['file'], 'image' ] | ||
51 | + [['file'], 'file', 'extensions' => ['jpg','png','bmp'], 'checkExtensionByMimeType'=>false ] | ||
43 | ]; | 52 | ]; |
44 | } | 53 | } |
45 | 54 | ||
@@ -49,15 +58,16 @@ class Brands extends \yii\db\ActiveRecord | @@ -49,15 +58,16 @@ class Brands extends \yii\db\ActiveRecord | ||
49 | public function attributeLabels() | 58 | public function attributeLabels() |
50 | { | 59 | { |
51 | return [ | 60 | return [ |
52 | - 'ID' => 'ID', | ||
53 | - 'BRAND' => 'Brand', | ||
54 | - 'if_tecdoc' => 'If Tecdoc', | 61 | + 'ID' => 'НОМЕР', |
62 | + 'BRAND' => 'БРЕНД', | ||
63 | + 'if_tecdoc' => 'ТЕКДОК?', | ||
55 | 'tecdoc_logo' => 'Tecdoc Logo', | 64 | 'tecdoc_logo' => 'Tecdoc Logo', |
56 | - 'if_oem' => 'If Oem', | 65 | + 'if_oem' => 'Оригинал', |
57 | 'if_checked' => 'If Checked', | 66 | 'if_checked' => 'If Checked', |
58 | - 'CONTENT' => 'Content', | ||
59 | - 'IMG' => 'Img', | 67 | + 'CONTENT' => 'Описание', |
68 | + 'IMG' => 'Изображение', | ||
60 | 'timestamp' => 'Timestamp', | 69 | 'timestamp' => 'Timestamp', |
70 | + 'delete_img' => 'Удалить', | ||
61 | ]; | 71 | ]; |
62 | } | 72 | } |
63 | } | 73 | } |
common/models/BrandsReplace.php
@@ -43,10 +43,10 @@ class BrandsReplace extends \yii\db\ActiveRecord | @@ -43,10 +43,10 @@ class BrandsReplace extends \yii\db\ActiveRecord | ||
43 | { | 43 | { |
44 | return [ | 44 | return [ |
45 | 'id' => 'ID', | 45 | 'id' => 'ID', |
46 | - 'from_brand' => 'From Brand', | ||
47 | - 'to_brand' => 'To Brand', | ||
48 | - 'finish' => 'Finish', | ||
49 | - 'timestamp' => 'Timestamp', | 46 | + 'from_brand' => 'Не правильный бренд', |
47 | + 'to_brand' => 'Правильный бренд', | ||
48 | + 'finish' => 'Замена закончена', | ||
49 | + 'timestamp' => 'Время', | ||
50 | ]; | 50 | ]; |
51 | } | 51 | } |
52 | } | 52 | } |
common/models/BrandsReplaceSearch.php
@@ -19,7 +19,7 @@ class BrandsReplaceSearch extends BrandsReplace | @@ -19,7 +19,7 @@ class BrandsReplaceSearch extends BrandsReplace | ||
19 | { | 19 | { |
20 | return [ | 20 | return [ |
21 | [['id', 'finish'], 'integer'], | 21 | [['id', 'finish'], 'integer'], |
22 | - [['from_brand', 'to_brand', 'timestamp'], 'safe'], | 22 | + [['from_brand', 'to_brand'], 'safe'], |
23 | ]; | 23 | ]; |
24 | } | 24 | } |
25 | 25 | ||
@@ -58,7 +58,6 @@ class BrandsReplaceSearch extends BrandsReplace | @@ -58,7 +58,6 @@ class BrandsReplaceSearch extends BrandsReplace | ||
58 | $query->andFilterWhere([ | 58 | $query->andFilterWhere([ |
59 | 'id' => $this->id, | 59 | 'id' => $this->id, |
60 | 'finish' => $this->finish, | 60 | 'finish' => $this->finish, |
61 | - 'timestamp' => $this->timestamp, | ||
62 | ]); | 61 | ]); |
63 | 62 | ||
64 | $query->andFilterWhere(['like', 'from_brand', $this->from_brand]) | 63 | $query->andFilterWhere(['like', 'from_brand', $this->from_brand]) |
common/models/BrandsSearch.php
@@ -18,8 +18,8 @@ class BrandsSearch extends Brands | @@ -18,8 +18,8 @@ class BrandsSearch extends Brands | ||
18 | public function rules() | 18 | public function rules() |
19 | { | 19 | { |
20 | return [ | 20 | return [ |
21 | - [['ID', 'if_tecdoc', 'if_oem', 'if_checked'], 'integer'], | ||
22 | - [['BRAND', 'tecdoc_logo', 'CONTENT', 'IMG', 'timestamp'], 'safe'], | 21 | + [['ID'], 'integer'], |
22 | + [['BRAND'], 'safe'], | ||
23 | ]; | 23 | ]; |
24 | } | 24 | } |
25 | 25 | ||
@@ -57,16 +57,10 @@ class BrandsSearch extends Brands | @@ -57,16 +57,10 @@ class BrandsSearch extends Brands | ||
57 | 57 | ||
58 | $query->andFilterWhere([ | 58 | $query->andFilterWhere([ |
59 | 'ID' => $this->ID, | 59 | 'ID' => $this->ID, |
60 | - 'if_tecdoc' => $this->if_tecdoc, | ||
61 | - 'if_oem' => $this->if_oem, | ||
62 | - 'if_checked' => $this->if_checked, | ||
63 | - 'timestamp' => $this->timestamp, | 60 | + 'BRAND' => $this->BRAND, |
64 | ]); | 61 | ]); |
65 | 62 | ||
66 | - $query->andFilterWhere(['like', 'BRAND', $this->BRAND]) | ||
67 | - ->andFilterWhere(['like', 'tecdoc_logo', $this->tecdoc_logo]) | ||
68 | - ->andFilterWhere(['like', 'CONTENT', $this->CONTENT]) | ||
69 | - ->andFilterWhere(['like', 'IMG', $this->IMG]); | 63 | + $query->orderBy('ID'); |
70 | 64 | ||
71 | return $dataProvider; | 65 | return $dataProvider; |
72 | } | 66 | } |
common/models/Currency.php
@@ -56,7 +56,7 @@ class Currency extends \yii\db\ActiveRecord | @@ -56,7 +56,7 @@ class Currency extends \yii\db\ActiveRecord | ||
56 | 56 | ||
57 | public function beforeSave($insert) | 57 | public function beforeSave($insert) |
58 | { | 58 | { |
59 | - if (parent::beforeSave($insert)) { | 59 | + if ( parent::beforeSave($insert) ) { |
60 | $this->timestamp = date("Y-m-d H:i:s"); | 60 | $this->timestamp = date("Y-m-d H:i:s"); |
61 | return true; | 61 | return true; |
62 | } else { | 62 | } else { |
1 | +<?php | ||
2 | + | ||
3 | +namespace common\models; | ||
4 | + | ||
5 | +use backend\models\Importers; | ||
6 | +use common\components\CustomVarDamp; | ||
7 | +use Yii; | ||
8 | +use backend\components\base\BaseActiveRecord; | ||
9 | + | ||
10 | +/** | ||
11 | + * This is the model class for table "{{%details}}". | ||
12 | + * | ||
13 | + * @property string $ID | ||
14 | + * @property string $IMPORT_ID | ||
15 | + * @property string $BRAND | ||
16 | + * @property string $ARTICLE | ||
17 | + * @property string $FULL_ARTICLE | ||
18 | + * @property double $PRICE | ||
19 | + * @property string $DESCR | ||
20 | + * @property string $BOX | ||
21 | + * @property string $ADD_BOX | ||
22 | + * @property string $GROUP | ||
23 | + * @property string $timestamp | ||
24 | + * | ||
25 | + * | ||
26 | + */ | ||
27 | +class Details extends BaseActiveRecord | ||
28 | +{ | ||
29 | + /** | ||
30 | + *обязательные колонки | ||
31 | + */ | ||
32 | + const KEY_COLUMN = 'IMPORT_ID~~BRAND~~ARTICLE'; | ||
33 | + | ||
34 | + /** | ||
35 | + * int - размер пакета запроса | ||
36 | + */ | ||
37 | + const BATCH = 500; | ||
38 | + | ||
39 | + /** | ||
40 | + * @var bool - признак необходимости удалить префикс Артикула перед вставкой | ||
41 | + */ | ||
42 | + | ||
43 | + public $delete_price = false; | ||
44 | + | ||
45 | + /** | ||
46 | + * @inheritdoc | ||
47 | + */ | ||
48 | + public static function tableName() | ||
49 | + { | ||
50 | + return '{{%details}}'; | ||
51 | + } | ||
52 | + | ||
53 | + public function getImporter () | ||
54 | + { | ||
55 | + $importer = Importers::findOne(['id' => $this->IMPORT_ID]); | ||
56 | + if ($importer) { | ||
57 | + return $importer->name; | ||
58 | + } else { | ||
59 | + return null; | ||
60 | + } | ||
61 | + | ||
62 | + } | ||
63 | + | ||
64 | + /** | ||
65 | + * @inheritdoc | ||
66 | + */ | ||
67 | + public function rules() | ||
68 | + { | ||
69 | + return [ | ||
70 | + [['BRAND', 'ARTICLE', 'PRICE', 'DESCR', 'BOX'], 'required' , 'on' => ['default','form_upload_validation']], | ||
71 | + // [['PRICE'], 'number', 'on' => 'default'], | ||
72 | + [['PRICE'], \common\components\CommaNumberValidator::className(), 'on' => 'default'], | ||
73 | + [['BOX'], 'integer' , 'on' => 'default'], | ||
74 | + [['timestamp'], 'safe' , 'on' => 'default'], | ||
75 | + [['BRAND', 'ARTICLE'], 'string', 'max' => 100 , 'on' => 'default'], | ||
76 | + [['FULL_ARTICLE'], 'string', 'max' => 150 , 'on' => 'default'], | ||
77 | + [['DESCR', 'GROUP'], 'string', 'max' => 200 , 'on' => 'default'] | ||
78 | + ]; | ||
79 | + } | ||
80 | + | ||
81 | + /** | ||
82 | + * @inheritdoc | ||
83 | + */ | ||
84 | + public function attributeLabels() | ||
85 | + { | ||
86 | + return [ | ||
87 | + 'ID' => Yii::t('app', 'ID'), | ||
88 | + 'IMPORT_ID' => Yii::t('app', 'ПОСТАВЩИК'), | ||
89 | + 'Importer' => Yii::t('app', 'ПОСТАВЩИК'), | ||
90 | + 'BRAND' => Yii::t('app', 'БРЕНД'), | ||
91 | + 'ARTICLE' => Yii::t('app', 'АРТИКУЛ'), | ||
92 | + 'FULL_ARTICLE' => Yii::t('app', 'ПОЛНЫЙ АРТИКУЛ'), | ||
93 | + 'PRICE' => Yii::t('app', 'ЦЕНА'), | ||
94 | + 'DESCR' => Yii::t('app', 'ОПИСАНИЕ'), | ||
95 | + 'BOX' => Yii::t('app', 'НАЛИЧИЕ'), | ||
96 | + 'ADD_BOX' => Yii::t('app', 'В ПУТИ'), | ||
97 | + 'GROUP' => Yii::t('app', 'ГРУППА RG'), | ||
98 | + 'timestamp' => Yii::t('app', 'Timestamp'), | ||
99 | + ]; | ||
100 | + } | ||
101 | + | ||
102 | + /** | ||
103 | + *удаление (если $delete_price установлен)б а затем вставка данных с апдейтом прямымыми запросоми SQL | ||
104 | + * @param $data - массив вставляемых данных, вставка будет прозводится пакетами размером указанным в константе BATCH | ||
105 | + * @param $importer_id - (int) - идентификатор поставщика у которого будет сперва удалены прайсы а потом вставлены из массива $data | ||
106 | + * @throws \yii\db\Exception | ||
107 | + */ | ||
108 | + public function manualInsert($data, $importer_id) | ||
109 | + { | ||
110 | + if ($this->delete_price) { | ||
111 | + // запустим пакетное удаление всех прайсов поставщика | ||
112 | + $conditions = "IMPORT_ID = {$importer_id}"; | ||
113 | + $this->manualDelete( $conditions ); | ||
114 | + } | ||
115 | + $this->manualInsertWithUpdate($data); | ||
116 | + | ||
117 | + } | ||
118 | + | ||
119 | + /** | ||
120 | + * вставка данных с апдейтом прямым запросом SQL | ||
121 | + * @param $data - массив вставляемых данный, вставка будет прозводится пакетами размером указанным в константе BATCH | ||
122 | + * @throws \yii\db\Exception | ||
123 | + */ | ||
124 | + private function manualInsertWithUpdate($data) | ||
125 | + { | ||
126 | + $table_name = self::tableName(); | ||
127 | + $keys_arr = array_keys($data[0]); | ||
128 | + // найдем те поля которые не являются ключами. Их нужно будет при дубляже апдейтить | ||
129 | + $fields_arr_to_update = array_diff($keys_arr, explode('~~', $this::KEY_COLUMN )); | ||
130 | + | ||
131 | + $query_update = ' on duplicate key update '; | ||
132 | + foreach ($fields_arr_to_update as $field) { | ||
133 | + $query_update .= "[[{$field}]] = values([[{$field}]]),"; | ||
134 | + } | ||
135 | + // удалим последнюю запятую | ||
136 | + $query_update = substr($query_update, 0, strlen($query_update) - 1); | ||
137 | + | ||
138 | + // запросы будем выполнять пакетами | ||
139 | + // размер пакета установлен в константе | ||
140 | + // разобъем массив на пакеты и будем их проходить | ||
141 | + $data = array_chunk($data, $this::BATCH); | ||
142 | + foreach ($data as $current_batch_array) { | ||
143 | + | ||
144 | + //воспользуемся пакетной вставкой от фреймворка | ||
145 | + $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql; | ||
146 | + | ||
147 | + // добавим фрагмент с апдейтом при дубляже | ||
148 | + $query = "{$query_insert} {$query_update}"; | ||
149 | + // \common\components\CustomVarDamp::dumpAndDie($query); | ||
150 | + Yii::$app->db->createCommand($query)->execute(); | ||
151 | + | ||
152 | + } | ||
153 | + } | ||
154 | + | ||
155 | + public function manualDelete( $conditions, $params = [] ) | ||
156 | + { | ||
157 | + do { | ||
158 | + $query = Yii::$app->db->createCommand()->delete( self::tableName(), $conditions, $params )->sql . ' Limit ' . $this::BATCH; | ||
159 | +// try { | ||
160 | + $res = Yii::$app->db->createCommand($query)->execute(); | ||
161 | +// } catch (\Exception $e) { | ||
162 | +// throw new \ErrorException('Ошибка удаления товаров '.$e->getMessage()); | ||
163 | +// } | ||
164 | + } while ($res); | ||
165 | + | ||
166 | + return true; | ||
167 | + } | ||
168 | + | ||
169 | +} |
common/models/Margins.php
@@ -28,7 +28,7 @@ class Margins extends \yii\db\ActiveRecord | @@ -28,7 +28,7 @@ class Margins extends \yii\db\ActiveRecord | ||
28 | { | 28 | { |
29 | return [ | 29 | return [ |
30 | [['name', 'koef'], 'required'], | 30 | [['name', 'koef'], 'required'], |
31 | - [['koef'], 'number'], | 31 | + ['koef', \common\components\CommaNumberValidator::className()], |
32 | [['name'], 'string', 'max' => 100], | 32 | [['name'], 'string', 'max' => 100], |
33 | [['name'], 'unique'] | 33 | [['name'], 'unique'] |
34 | ]; | 34 | ]; |
common/models/MarginsSearch.php
@@ -19,8 +19,8 @@ class MarginsSearch extends Margins | @@ -19,8 +19,8 @@ class MarginsSearch extends Margins | ||
19 | { | 19 | { |
20 | return [ | 20 | return [ |
21 | [['id'], 'integer'], | 21 | [['id'], 'integer'], |
22 | - [['name'], 'safe'], | ||
23 | - [['koef'], 'number'], | 22 | +// [['name'], 'safe'], |
23 | +// [['koef'], 'number'], | ||
24 | ]; | 24 | ]; |
25 | } | 25 | } |
26 | 26 | ||
@@ -56,12 +56,12 @@ class MarginsSearch extends Margins | @@ -56,12 +56,12 @@ class MarginsSearch extends Margins | ||
56 | return $dataProvider; | 56 | return $dataProvider; |
57 | } | 57 | } |
58 | 58 | ||
59 | - $query->andFilterWhere([ | ||
60 | - 'id' => $this->id, | ||
61 | - 'koef' => $this->koef, | ||
62 | - ]); | ||
63 | - | ||
64 | - $query->andFilterWhere(['like', 'name', $this->name]); | 59 | +// $query->andFilterWhere([ |
60 | +// 'id' => $this->id, | ||
61 | +// 'koef' => $this->koef, | ||
62 | +// ]); | ||
63 | +// | ||
64 | +// $query->andFilterWhere(['like', 'name', $this->name]); | ||
65 | 65 | ||
66 | return $dataProvider; | 66 | return $dataProvider; |
67 | } | 67 | } |
composer.json
@@ -24,7 +24,7 @@ | @@ -24,7 +24,7 @@ | ||
24 | "kartik-v/yii2-datecontrol": "dev-master", | 24 | "kartik-v/yii2-datecontrol": "dev-master", |
25 | "codeception/codeception": "*", | 25 | "codeception/codeception": "*", |
26 | "2amigos/yii2-ckeditor-widget": "~1.0", | 26 | "2amigos/yii2-ckeditor-widget": "~1.0", |
27 | - "mihaildev/yii2-ckeditor": "*", | 27 | + "mihaildev/yii2-ckeditor": "^1.0", |
28 | "kartik-v/yii2-widget-fileinput": "@dev", | 28 | "kartik-v/yii2-widget-fileinput": "@dev", |
29 | "phpmailer/phpmailer": "^5.2", | 29 | "phpmailer/phpmailer": "^5.2", |
30 | "mihaildev/yii2-elfinder": "*" | 30 | "mihaildev/yii2-elfinder": "*" |
composer.lock
@@ -4,8 +4,8 @@ | @@ -4,8 +4,8 @@ | ||
4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", | 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", |
5 | "This file is @generated automatically" | 5 | "This file is @generated automatically" |
6 | ], | 6 | ], |
7 | - "hash": "f6d5550f22108e48d542a099d5e9a3ea", | ||
8 | - "content-hash": "bc7f313c8871095badc7533a53ff3d53", | 7 | + "hash": "9ddc6cc1d58d87c992e53caaffe27119", |
8 | + "content-hash": "cfa3f3c9f04cb6b28af05c11197eb35b", | ||
9 | "packages": [ | 9 | "packages": [ |
10 | { | 10 | { |
11 | "name": "2amigos/yii2-ckeditor-widget", | 11 | "name": "2amigos/yii2-ckeditor-widget", |
@@ -1891,28 +1891,28 @@ | @@ -1891,28 +1891,28 @@ | ||
1891 | }, | 1891 | }, |
1892 | { | 1892 | { |
1893 | "name": "sebastian/diff", | 1893 | "name": "sebastian/diff", |
1894 | - "version": "1.3.0", | 1894 | + "version": "1.4.1", |
1895 | "source": { | 1895 | "source": { |
1896 | "type": "git", | 1896 | "type": "git", |
1897 | "url": "https://github.com/sebastianbergmann/diff.git", | 1897 | "url": "https://github.com/sebastianbergmann/diff.git", |
1898 | - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3" | 1898 | + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e" |
1899 | }, | 1899 | }, |
1900 | "dist": { | 1900 | "dist": { |
1901 | "type": "zip", | 1901 | "type": "zip", |
1902 | - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3", | ||
1903 | - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3", | 1902 | + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e", |
1903 | + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e", | ||
1904 | "shasum": "" | 1904 | "shasum": "" |
1905 | }, | 1905 | }, |
1906 | "require": { | 1906 | "require": { |
1907 | "php": ">=5.3.3" | 1907 | "php": ">=5.3.3" |
1908 | }, | 1908 | }, |
1909 | "require-dev": { | 1909 | "require-dev": { |
1910 | - "phpunit/phpunit": "~4.2" | 1910 | + "phpunit/phpunit": "~4.8" |
1911 | }, | 1911 | }, |
1912 | "type": "library", | 1912 | "type": "library", |
1913 | "extra": { | 1913 | "extra": { |
1914 | "branch-alias": { | 1914 | "branch-alias": { |
1915 | - "dev-master": "1.3-dev" | 1915 | + "dev-master": "1.4-dev" |
1916 | } | 1916 | } |
1917 | }, | 1917 | }, |
1918 | "autoload": { | 1918 | "autoload": { |
@@ -1935,11 +1935,11 @@ | @@ -1935,11 +1935,11 @@ | ||
1935 | } | 1935 | } |
1936 | ], | 1936 | ], |
1937 | "description": "Diff implementation", | 1937 | "description": "Diff implementation", |
1938 | - "homepage": "http://www.github.com/sebastianbergmann/diff", | 1938 | + "homepage": "https://github.com/sebastianbergmann/diff", |
1939 | "keywords": [ | 1939 | "keywords": [ |
1940 | "diff" | 1940 | "diff" |
1941 | ], | 1941 | ], |
1942 | - "time": "2015-02-22 15:13:53" | 1942 | + "time": "2015-12-08 07:14:41" |
1943 | }, | 1943 | }, |
1944 | { | 1944 | { |
1945 | "name": "sebastian/environment", | 1945 | "name": "sebastian/environment", |
@@ -2110,16 +2110,16 @@ | @@ -2110,16 +2110,16 @@ | ||
2110 | }, | 2110 | }, |
2111 | { | 2111 | { |
2112 | "name": "sebastian/recursion-context", | 2112 | "name": "sebastian/recursion-context", |
2113 | - "version": "1.0.1", | 2113 | + "version": "1.0.2", |
2114 | "source": { | 2114 | "source": { |
2115 | "type": "git", | 2115 | "type": "git", |
2116 | "url": "https://github.com/sebastianbergmann/recursion-context.git", | 2116 | "url": "https://github.com/sebastianbergmann/recursion-context.git", |
2117 | - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba" | 2117 | + "reference": "913401df809e99e4f47b27cdd781f4a258d58791" |
2118 | }, | 2118 | }, |
2119 | "dist": { | 2119 | "dist": { |
2120 | "type": "zip", | 2120 | "type": "zip", |
2121 | - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/994d4a811bafe801fb06dccbee797863ba2792ba", | ||
2122 | - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba", | 2121 | + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791", |
2122 | + "reference": "913401df809e99e4f47b27cdd781f4a258d58791", | ||
2123 | "shasum": "" | 2123 | "shasum": "" |
2124 | }, | 2124 | }, |
2125 | "require": { | 2125 | "require": { |
@@ -2159,7 +2159,7 @@ | @@ -2159,7 +2159,7 @@ | ||
2159 | ], | 2159 | ], |
2160 | "description": "Provides functionality to recursively process PHP variables", | 2160 | "description": "Provides functionality to recursively process PHP variables", |
2161 | "homepage": "http://www.github.com/sebastianbergmann/recursion-context", | 2161 | "homepage": "http://www.github.com/sebastianbergmann/recursion-context", |
2162 | - "time": "2015-06-21 08:04:50" | 2162 | + "time": "2015-11-11 19:50:13" |
2163 | }, | 2163 | }, |
2164 | { | 2164 | { |
2165 | "name": "sebastian/version", | 2165 | "name": "sebastian/version", |
console/controllers/ParserController.php
@@ -6,6 +6,7 @@ use common\components\archives\ArchiveCreator; | @@ -6,6 +6,7 @@ use common\components\archives\ArchiveCreator; | ||
6 | use common\components\CustomVarDamp; | 6 | use common\components\CustomVarDamp; |
7 | use common\components\mail\ImapMailReader; | 7 | use common\components\mail\ImapMailReader; |
8 | use common\components\mail\MailAttachmentsSaver; | 8 | use common\components\mail\MailAttachmentsSaver; |
9 | +use common\components\parsers\Parser; | ||
9 | use yii\console\Controller; | 10 | use yii\console\Controller; |
10 | use yii\helpers\Console; | 11 | use yii\helpers\Console; |
11 | use common\components\PriceWriter; | 12 | use common\components\PriceWriter; |
@@ -27,8 +28,11 @@ class ParserController extends Controller | @@ -27,8 +28,11 @@ class ParserController extends Controller | ||
27 | ['mode' => 2, 'path' => \Yii::getAlias('@mail_upload')], | 28 | ['mode' => 2, 'path' => \Yii::getAlias('@mail_upload')], |
28 | ]; | 29 | ]; |
29 | 30 | ||
30 | - $this->parseCsvFiles($path_arr); | ||
31 | - $this->parseXmlFiles($path_arr); | 31 | + $arr_supported_extension = Parser::supportedExtension(); |
32 | + foreach ($arr_supported_extension as $ext) { | ||
33 | + | ||
34 | + $this->parseFilesByExtension( $ext , $path_arr ); | ||
35 | + } | ||
32 | 36 | ||
33 | } | 37 | } |
34 | 38 | ||
@@ -69,40 +73,20 @@ class ParserController extends Controller | @@ -69,40 +73,20 @@ class ParserController extends Controller | ||
69 | $new_destination = \Yii::getAlias('@mail_upload') . '/'; | 73 | $new_destination = \Yii::getAlias('@mail_upload') . '/'; |
70 | 74 | ||
71 | $this->registerAndReplaceFiles($files, $new_destination); | 75 | $this->registerAndReplaceFiles($files, $new_destination); |
72 | - | ||
73 | - | ||
74 | } | 76 | } |
75 | 77 | ||
76 | - protected function parseCsvFiles($path_arr) | 78 | + protected function parseFilesByExtension( $ext, $path_arr ) |
77 | { | 79 | { |
78 | - \Yii::info('Начало загрузки файлов прайсов csv', 'parser'); | 80 | + \Yii::info("Начало загрузки файлов прайсов {$ext}", 'parser'); |
79 | foreach ($path_arr as $path_config) { | 81 | foreach ($path_arr as $path_config) { |
80 | - foreach (glob($path_config['path'] . '/*.csv') as $file_path) { | ||
81 | - $file_name = basename($file_path, ".csv"); | ||
82 | - \Yii::info("Обработка файла - $file_path", 'parser'); | ||
83 | - $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id; | ||
84 | - $current_importer = Importers::findOne(['id' => $importer_id]); | ||
85 | - $keys = $current_importer->keys; | ||
86 | - $mult_array = $current_importer->multiply; | ||
87 | - | ||
88 | - // получим настройки ценообразования и передадим их отдельно в конвертер | ||
89 | - $sign = ''; | ||
90 | - $multiplier = ''; | ||
91 | - extract($mult_array); | ||
92 | - | ||
93 | - $config = [ | ||
94 | - 'record_id' => $file_name, | ||
95 | - 'importer_id' => $importer_id, | ||
96 | - 'mode' => $path_config['mode'], | ||
97 | - 'parser_config' => ['keys' => $keys, | ||
98 | - 'converter_conf' => | ||
99 | - ['sign' => $sign, | ||
100 | - 'multiplier' => $multiplier], | ||
101 | - 'mode' => 'console'] | ||
102 | - ]; | 82 | + foreach ( glob( $path_config['path'] . "/*.{$ext}" ) as $file_path ) { |
83 | + $file_name = basename( $file_path, ".{$ext}" ); | ||
84 | + \Yii::info( "Обработка файла - $file_path", 'parser' ); | ||
85 | + | ||
86 | + $config = $this->getParsingConfiguration( $file_name, $path_config['mode'], $ext ); | ||
103 | 87 | ||
104 | if ($this->parseFile($file_path, $config)) { | 88 | if ($this->parseFile($file_path, $config)) { |
105 | - $temp_file = \Yii::getAlias('@temp_upload') . '/' . $file_name . '.csv'; | 89 | + $temp_file = \Yii::getAlias('@temp_upload') . '/' . $file_name . ".{$ext}"; |
106 | if( file_exists( $temp_file ) ) | 90 | if( file_exists( $temp_file ) ) |
107 | unlink($temp_file); | 91 | unlink($temp_file); |
108 | 92 | ||
@@ -111,55 +95,13 @@ class ParserController extends Controller | @@ -111,55 +95,13 @@ class ParserController extends Controller | ||
111 | \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser'); | 95 | \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser'); |
112 | } | 96 | } |
113 | //при любом завершении скрипта файл с очереди автозагрузки нужно удалить | 97 | //при любом завершении скрипта файл с очереди автозагрузки нужно удалить |
114 | - $auto_file = $path_config['path'] . '/' . $file_name . '.csv'; | 98 | + $auto_file = $path_config['path'] . '/' . $file_name . ".{$ext}"; |
115 | if( file_exists( $auto_file ) ) | 99 | if( file_exists( $auto_file ) ) |
116 | unlink($auto_file); | 100 | unlink($auto_file); |
117 | } | 101 | } |
118 | } | 102 | } |
119 | } | 103 | } |
120 | 104 | ||
121 | - protected function parseXmlFiles($path_arr) | ||
122 | - { | ||
123 | - \Yii::info('Начало загрузки файлов прайсов xml', 'parser'); | ||
124 | - foreach ($path_arr as $path_config) { | ||
125 | - foreach (glob($path_config['path'] . '/*.xml') as $file_path) { | ||
126 | - $file_name = basename($file_path, ".xml"); | ||
127 | - \Yii::info("Обработка файла - $file_path", 'parser'); | ||
128 | - | ||
129 | - $files_model = new ImportersFiles(); | ||
130 | - // id поставщика всегда = 1 - Склад | ||
131 | - $files_model->importer_id = 1; | ||
132 | - try { | ||
133 | - $files_model->save(); | ||
134 | - } catch (ErrorException $e) { | ||
135 | - throw $e; | ||
136 | - } | ||
137 | - // получим id только что записанной записи | ||
138 | - $record_id = $files_model->find() | ||
139 | - ->where(['importer_id' => $files_model->importer_id]) | ||
140 | - ->orderBy(['id' => SORT_DESC]) | ||
141 | - ->one() | ||
142 | - ->id; | ||
143 | - | ||
144 | - $config = ['record_id' => $record_id, | ||
145 | - 'importer_id' => 1, | ||
146 | - 'mode' => $path_config['mode'], | ||
147 | - 'parser_config' => [ | ||
148 | - 'mode' => 'console'] | ||
149 | - ]; | ||
150 | - | ||
151 | - if ($this->parseFile($file_path, $config)) { | ||
152 | - \Yii::info("Загрузка файла - $file_path успешно завершена", 'parser'); | ||
153 | - } else { | ||
154 | - \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser'); | ||
155 | - } | ||
156 | - | ||
157 | - $auto_file = $path_config['path'] . '/' . $file_name . '.xml'; | ||
158 | - if( file_exists( $auto_file ) ) | ||
159 | - unlink($auto_file); | ||
160 | - } | ||
161 | - } | ||
162 | - } | ||
163 | 105 | ||
164 | protected function parseFile($file_path, $configuration) | 106 | protected function parseFile($file_path, $configuration) |
165 | { | 107 | { |
@@ -193,9 +135,9 @@ class ParserController extends Controller | @@ -193,9 +135,9 @@ class ParserController extends Controller | ||
193 | $writer->setData($data); | 135 | $writer->setData($data); |
194 | 136 | ||
195 | $writer->writePriceToDB(); | 137 | $writer->writePriceToDB(); |
196 | - $error = $writer->hasValidationError(); | 138 | + $has_error = $writer->hasValidationError(); |
197 | $log_msg = strip_tags( $writer->getValidatedMsg() ); | 139 | $log_msg = strip_tags( $writer->getValidatedMsg() ); |
198 | - if ( $error ) { | 140 | + if ( $has_error ) { |
199 | \Yii::error($log_msg, 'parser'); | 141 | \Yii::error($log_msg, 'parser'); |
200 | } else { | 142 | } else { |
201 | \Yii::info($log_msg, 'parser'); | 143 | \Yii::info($log_msg, 'parser'); |
@@ -205,16 +147,12 @@ class ParserController extends Controller | @@ -205,16 +147,12 @@ class ParserController extends Controller | ||
205 | } | 147 | } |
206 | } | 148 | } |
207 | } | 149 | } |
208 | - | ||
209 | - $log_model->error = (int) $error; | 150 | + $log_model->error = (int) $has_error; |
210 | $log_model->log_msg = $log_msg; | 151 | $log_model->log_msg = $log_msg; |
211 | // запишем данные в лог | 152 | // запишем данные в лог |
212 | $log_model->save(); | 153 | $log_model->save(); |
213 | 154 | ||
214 | - | ||
215 | - | ||
216 | return true; | 155 | return true; |
217 | - | ||
218 | } | 156 | } |
219 | 157 | ||
220 | private function getMailAttachments($mail_reader, $importer_id_prefix = '') | 158 | private function getMailAttachments($mail_reader, $importer_id_prefix = '') |
@@ -313,4 +251,57 @@ class ParserController extends Controller | @@ -313,4 +251,57 @@ class ParserController extends Controller | ||
313 | } | 251 | } |
314 | } | 252 | } |
315 | } | 253 | } |
254 | + | ||
255 | + protected function getParsingConfiguration( $file_name, $mode, $ext ){ | ||
256 | + | ||
257 | + if ($ext === 'xml') { | ||
258 | + $files_model = new ImportersFiles(); | ||
259 | + // id поставщика всегда = 1 - Склад | ||
260 | + $files_model->importer_id = 1; | ||
261 | + try { | ||
262 | + $files_model->save(); | ||
263 | + } catch (ErrorException $e) { | ||
264 | + throw $e; | ||
265 | + } | ||
266 | + // получим id только что записанной записи | ||
267 | + $record_id = $files_model->find() | ||
268 | + ->where(['importer_id' => $files_model->importer_id]) | ||
269 | + ->orderBy(['id' => SORT_DESC]) | ||
270 | + ->one() | ||
271 | + ->id; | ||
272 | + | ||
273 | + $config = ['record_id' => $record_id, | ||
274 | + 'importer_id' => 1, | ||
275 | + 'mode' => $mode, | ||
276 | + 'parser_config' => [ | ||
277 | + 'mode' => 'console'] | ||
278 | + ]; | ||
279 | + } else { | ||
280 | + $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id; | ||
281 | + $current_importer = Importers::findOne(['id' => $importer_id]); | ||
282 | + $keys = $current_importer->keys; | ||
283 | + // если меньше 5 ключей, то чего-то нехватает - обнуляем | ||
284 | + if ( count( $keys ) < 5 ) { | ||
285 | + $keys = NULL; | ||
286 | + } | ||
287 | + $mult_array = $current_importer->multiply; | ||
288 | + | ||
289 | + // получим настройки ценообразования и передадим их отдельно в конвертер | ||
290 | + $sign = ''; | ||
291 | + $multiplier = ''; | ||
292 | + extract($mult_array); | ||
293 | + | ||
294 | + $config = [ | ||
295 | + 'record_id' => $file_name, | ||
296 | + 'importer_id' => $importer_id, | ||
297 | + 'mode' => $mode, | ||
298 | + 'parser_config' => ['keys' => $keys, | ||
299 | + 'converter_conf' => | ||
300 | + ['sign' => $sign, | ||
301 | + 'multiplier' => $multiplier], | ||
302 | + 'mode' => 'console'] | ||
303 | + ]; | ||
304 | + } | ||
305 | + return $config; | ||
306 | +} | ||
316 | } | 307 | } |
317 | \ No newline at end of file | 308 | \ No newline at end of file |
1 | +/temp |