File indexing completed on 2024-12-22 05:33:26

0001 <?php
0002 /**
0003  *  ocs-webserver
0004  *
0005  *  Copyright 2016 by pling GmbH.
0006  *
0007  *    This file is part of ocs-webserver.
0008  *
0009  *    This program is free software: you can redistribute it and/or modify
0010  *    it under the terms of the GNU Affero General Public License as
0011  *    published by the Free Software Foundation, either version 3 of the
0012  *    License, or (at your option) any later version.
0013  *
0014  *    This program is distributed in the hope that it will be useful,
0015  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
0016  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0017  *    GNU Affero General Public License for more details.
0018  *
0019  *    You should have received a copy of the GNU Affero General Public License
0020  *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
0021  **/
0022 
0023 $_import_counter = 0;
0024 $_import_file_counter = 0;
0025 $_is_import_done = false;
0026 
0027 class Backend_HiveController extends Local_Controller_Action_Backend
0028 {
0029 
0030     const RESULT_OK = "OK";
0031     const RESULT_ERROR = "ERROR";
0032     const DATA_ID_NAME = 'id';
0033     var $_HIVE_BASE_URL;
0034     var $_OCS_CN_FILE_SYNC_URL;
0035     var $_OCS_FILE_SYNC_URL;
0036     protected $_errorMsg = null;
0037 
0038     protected $import_info;
0039 
0040 
0041     /** @var Default_Model_DbTable_HiveContent */
0042     protected $_model;
0043 
0044     protected $_modelName = 'Default_Model_DbTable_HiveContent';
0045     protected $_pageTitle = 'Import Hive01 Files';
0046     protected $_allowed = array(
0047         'image/jpeg'          => '.jpg',
0048         'image/jpg'           => '.jpg',
0049         'image/png'           => '.png',
0050         'image/gif'           => '.gif',
0051         'application/x-empty' => '.png'
0052     );
0053 
0054     public function init()
0055     {
0056         $this->_model = new $this->_modelName();
0057 
0058         $this->view->pageTitle = $this->_pageTitle;
0059 
0060         parent::init();
0061     }
0062 
0063     public function initVars()
0064     {
0065         if (strtolower(php_uname("n")) == 'do-pling-com') {
0066             $this->_HIVE_BASE_URL = 'http://cp1.hive01.com';
0067             $this->_OCS_CN_FILE_SYNC_URL = 'https://cn.opendesktop.org';
0068             $this->_OCS_FILE_SYNC_URL = 'https://www.ppload.com';
0069         } else {
0070             $this->_HIVE_BASE_URL = 'http://cp1.hive01.com';
0071             $this->_OCS_CN_FILE_SYNC_URL = 'https://cn.pling.ws';
0072             $this->_OCS_FILE_SYNC_URL = 'https://ws.ppload.com';
0073         }
0074     }
0075 
0076     public function indexAction()
0077     {
0078         $params = $this->getAllParams();
0079 
0080         if (empty($params['step'])) {
0081             $this->view->step = 0;
0082         } else {
0083             $this->view->step = $params['step'];
0084         }
0085         if ($this->view->step == 0) {
0086             $this->step0();
0087         } else {
0088             if ($this->view->step == 1) {
0089                 $this->step1();
0090             } else {
0091                 if ($this->view->step == 2) {
0092                     $this->step2();
0093                 } else {
0094                     if ($this->view->step == 3) {
0095                         $this->step3();
0096                     } else {
0097                         if ($this->view->step == 4) {
0098                             $this->step4();
0099                         } else {
0100                             if ($this->view->step == 10) {
0101                                 $this->step10();
0102                             } else {
0103                                 if ($this->view->step == 20) {
0104                                     $this->step20();
0105                                 } else {
0106                                     if ($this->view->step == 30) {
0107                                         $this->step30();
0108                                     }
0109                                 }
0110                             }
0111                         }
0112                     }
0113                 }
0114             }
0115         }
0116     }
0117 
0118     private function step0()
0119     {
0120         $countProjects = null;
0121         $contentTable = new Default_Model_DbTable_HiveContent();
0122         try {
0123             $count = $contentTable->fetchCountProjects();
0124             $this->view->info = "Erfolgreich geladen aus DB";
0125             $countProjects = $count;
0126         } catch (Exception $e) {
0127             Zend_Registry::get('logger')->info(__METHOD__ . ' - ' . "Error in fetchCountProjects");
0128             Zend_Registry::get('logger')->err(__METHOD__ . ' - ' . print_r($e, true));
0129 
0130             $this->view->info = "Error while loading from the database:" . $e->getMessage();
0131             $countProjects = 0;
0132         }
0133 
0134         $this->view->coutAll = $countProjects;
0135     }
0136 
0137     private function step1()
0138     {
0139         $catArray = null;
0140         $contentTable = new Default_Model_DbTable_HiveContent();
0141         try {
0142             $catArray = $contentTable->fetchHiveCategories();
0143             $this->view->info = "Successfully loaded from the database";
0144         } catch (Exception $e) {
0145             $this->view->info = "Error while loading from the database:" . $e->getMessage();
0146             $catArray = null;
0147         }
0148 
0149         $this->view->categories = $catArray;
0150     }
0151 
0152     private function step2()
0153     {
0154         $params = $this->getAllParams();
0155         $cat_id = $params['cat_id'];
0156         $cat = null;
0157         $contentTable = new Default_Model_DbTable_HiveContent();
0158         try {
0159             $count = $contentTable->fetchCountProjectsForCategory($cat_id);
0160 
0161             $cat = $contentTable->fetchHiveCategory($cat_id);
0162             $this->view->info .= "Successfully loaded from the database";
0163         } catch (Exception $e) {
0164             $this->view->info .= "Error while loading from the database:" . $e->getMessage();
0165             $cat = null;
0166             $count = 0;
0167         }
0168 
0169         $this->view->cat_id = $cat['id'];
0170         $this->view->cat_desc = $cat['desc'];
0171         $this->view->count = $count;
0172 
0173         try {
0174             $catArray = $contentTable->fetchOcsCategories();
0175             $this->view->info = "Successfully loaded from the database";
0176         } catch (Exception $e) {
0177             $this->view->info = "Error while loading from the database:" . $e->getMessage();
0178             $catArray = null;
0179         }
0180 
0181         $this->view->categories = $catArray;
0182     }
0183 
0184     private function step3()
0185     {
0186         $params = $this->getAllParams();
0187         $cat_id = $params['cat_id'];
0188         $ocs_cat_id = $params['ocs_cat_id'];
0189         $cat = null;
0190         $contentTable = new Default_Model_DbTable_HiveContent();
0191         try {
0192             $count = $contentTable->fetchCountProjectsForCategory($cat_id);
0193             $cat = $contentTable->fetchHiveCategory($cat_id);
0194             $this->view->info .= "Successfully loaded from the database";
0195             $this->view->cat_id = $cat['id'];
0196             $this->view->cat_desc = $cat['desc'];
0197             $this->view->count = $count;
0198 
0199             $ocs_cat = $contentTable->fetchOcsCategory($ocs_cat_id);
0200             $this->view->info .= "Successfully loaded from the database";
0201             $this->view->ocs_cat_id = $ocs_cat['id'];
0202             $this->view->ocs_cat_desc = $ocs_cat['desc'];
0203         } catch (Exception $e) {
0204             $this->view->info = "Error while loading from the database:" . $e->getMessage();
0205             $cat = null;
0206             $count = 0;
0207         }
0208 
0209         try {
0210             $catArray = $contentTable->fetchOcsCategories();
0211             $this->view->info .= "Successfully loaded from the database";
0212         } catch (Exception $e) {
0213             $this->view->info .= "Error while loading from the database:" . $e->getMessage();
0214             $catArray = null;
0215         }
0216 
0217         $this->view->categories = $catArray;
0218     }
0219 
0220     private function step4()
0221     {
0222         $params = $this->getAllParams();
0223         $cat_id = $params['cat_id'];
0224         $ocs_cat_id = $params['ocs_cat_id'];
0225         $importGalleryPics = $params['import_previews'];
0226         $importFiles = $params['import_files'];
0227         $this->view->cat_id = $cat_id;
0228         $this->view->ocs_cat_id = $ocs_cat_id;
0229         $this->view->import_files = $importFiles;
0230         $this->view->import_previews = $importGalleryPics;
0231     }
0232 
0233     private function step10()
0234     {
0235     }
0236 
0237     private function step20()
0238     {
0239         $catArray = null;
0240         $params = $this->getAllParams();
0241         $cat_ids = $params['cat_ids'];
0242 
0243         $contentTable = new Default_Model_DbTable_HiveContentCategory();
0244         try {
0245             if (isset($cat_ids)) {
0246                 $catArray = $contentTable->fetchHiveCategories($cat_ids);
0247                 $this->view->info = "Successfully loaded from the database";
0248             } else {
0249                 $this->view->info = "No category selected!";
0250             }
0251         } catch (Exception $e) {
0252             $this->view->info = "Error while loading from the database:" . $e->getMessage();
0253             $catArray = null;
0254         }
0255 
0256         $this->view->categories = $catArray;
0257         $this->view->cat_ids = $cat_ids;
0258     }
0259 
0260     private function step30()
0261     {
0262         $catArray = null;
0263         $params = $this->getAllParams();
0264         $cat_ids = $params['cat_ids'];
0265         $this->view->cat_ids = $cat_ids;
0266 
0267         $importGalleryPics = $params['import_previews'];
0268         $importFiles = $params['import_files'];
0269         $this->view->import_files = $importFiles;
0270         $this->view->import_previews = $importGalleryPics;
0271     }
0272 
0273     public function countAction()
0274     {
0275         $this->_helper->layout->disableLayout();
0276         $cat_id = (int)$this->getParam('cat_id');
0277         $contentTable = new Default_Model_DbTable_HiveContent();
0278         $count = $contentTable->fetchCountProjectsForCategory($cat_id);
0279 
0280         $result = array();
0281         $result['Result'] = self::RESULT_OK;
0282         $result['TotalRecordCount'] = $count;
0283 
0284         $this->_helper->json($result);
0285     }
0286 
0287     public function startImportAllAjaxAction()
0288     {
0289         global $_import_counter;
0290         global $_import_file_counter;
0291         global $_is_import_done;
0292 
0293         $_import_counter = 0;
0294         $_import_file_counter = 0;
0295         $_is_import_done = false;
0296 
0297         $this->_helper->layout->disableLayout();
0298         $params = $this->getAllParams();
0299         $cat_id = $params['cat_id'];
0300         $hiveCatTable = new Default_Model_DbTable_HiveContentCategory();
0301 
0302         $ocs_cat_id = $hiveCatTable->fetchOcsCategoryForHiveCategory($cat_id);
0303 
0304         if (!isset($ocs_cat_id)) {
0305             $info .= " - No Ocs-Category found!";
0306             exit;
0307         }
0308 
0309         $info = null;
0310 
0311         $importGalleryPics = false;
0312         if (isset($params['import_previews']) && $params['import_previews'] != '') {
0313             $importGalleryPics = true;
0314         }
0315         $info .= " - With Gallery Pics? " . $importGalleryPics;
0316 
0317         $importFiles = false;
0318         if (isset($params['import_files']) && $params['import_files'] != '') {
0319             $importFiles = true;
0320         }
0321         $info .= " - With Files? " . $importFiles;
0322 
0323         $startIndex = null;
0324         $limit = intval($params['limit']);
0325         if (empty($startIndex)) {
0326             $startIndex = 0;
0327         }
0328         if (empty($limit)) {
0329             $limit = 5;
0330         }
0331 
0332         $result = array();
0333         $contentTable = new Default_Model_DbTable_HiveContent();
0334         $memberTable = new Default_Model_Member();
0335         $projectTable = new Default_Model_Project();
0336         $hiveMemeberTable = new Default_Model_DbTable_HiveUser();
0337         try {
0338             $projects = $contentTable->fetchAllProjectsForCategory($cat_id, $startIndex, $limit);
0339 
0340             foreach ($projects as $project) {
0341                 $_import_counter++;
0342 
0343                 $info .= " ## Poject: id = " . $project['id'] . ", name = " . $project['name'] . "  ";
0344                 $start = microtime(true);
0345 
0346                 //1. Download/Upload Project-Picture
0347                 //$info .= " - Project-Picture ";
0348                 //$start = microtime(true);
0349                 //$cnFilePath = $this->uploadProjectPicture($project['id']);
0350                 $cnFilePath = $this->getProjectPicture($project['id']);
0351                 //$time_elapsed_secs = microtime(true) - $start;
0352                 //$info .= $time_elapsed_secs." secs";
0353 
0354                 //2. Create Ocs Project
0355                 //$info .= " - Project ";
0356                 //$start = microtime(true);
0357                 try {
0358                     $hiveUser = $hiveMemeberTable->fetchRow("login = '" . $project['user']."'");
0359                     if(!empty($hiveUser)) {
0360                         $projectId = $this->createUpdateOcsProjects($hiveUser, $project, $ocs_cat_id, $cnFilePath);
0361                     }
0362                 } catch (Exception $e) {
0363                     //Error: log error and go on
0364                     $error = array();
0365                     $error['import_error'] = $e;
0366                     $error['is_imported'] = 1;
0367                     $contentTable->update($error, 'id = ' . $project['id']);
0368                 }
0369                 //$time_elapsed_secs = microtime(true) - $start;
0370                 //$info .= $time_elapsed_secs." secs";
0371 
0372                 if ($projectId) {
0373 
0374                     //3. Upload files
0375                     if ($importFiles) {
0376                         $pploadError = null;
0377                         $info .= " - Files ";
0378                         $start = microtime(true);
0379                         try {
0380                             $_import_file_counter = $this->uploadFilesAndLinks($project, $projectId);
0381                         } catch (Exception $e) {
0382                             $pploadError .= $e;
0383                             $info .= $pploadError;
0384                         }
0385                         $info .= " - Files Uploaded: " . $_import_file_counter . " -  ";
0386                         $time_elapsed_secs = microtime(true) - $start;
0387                         $info .= $time_elapsed_secs . " secs";
0388                     } else {
0389                         $_import_file_counter = 1;
0390                     }
0391 
0392                     if (true) {
0393 
0394                         //4. Gallery Pics
0395                         if ($importGalleryPics) {
0396 
0397                             $info .= " - Gallery Pics ";
0398                             //$start = microtime(true);
0399                             $previewPicsArray = array();
0400                             if (!empty($project['preview1'])) {
0401                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 1, $project['preview1']);
0402                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 1, $project['preview1']);
0403                                 //add preview pic to ocs-project
0404                                 if (!empty($cnFilePathPre)) {
0405                                     $previewPicsArray[] = $cnFilePathPre;
0406                                     $info .= " - PreviewPic1 ";
0407                                 }
0408                             }
0409                             if (!empty($project['preview2'])) {
0410                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 2, $project['preview2']);
0411                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 2, $project['preview2']);
0412                                 if (!empty($cnFilePathPre)) {
0413                                     $previewPicsArray[] = $cnFilePathPre;
0414                                     $info .= " - PreviewPic2 ";
0415                                 }
0416                             }
0417                             if (!empty($project['preview3'])) {
0418                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 3, $project['preview3']);
0419                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 3, $project['preview3']);
0420                                 if (!empty($cnFilePathPre)) {
0421                                     $previewPicsArray[] = $cnFilePathPre;
0422                                     $info .= " - PreviewPic3 ";
0423                                 }
0424                             }
0425                             if (!empty($previewPicsArray)) {
0426                                 $projectTable->updateGalleryPictures($projectId, $previewPicsArray);
0427                             }
0428                         }
0429                         //$time_elapsed_secs = microtime(true) - $start;
0430                         //$info .= $time_elapsed_secs." secs";
0431 
0432                         //5. Mark project as imported
0433                         //$info .= " - Mark project as imported ";
0434                         //$start = microtime(true);
0435                         $contentTable->update(array("is_imported" => 1), "id = " . $project['id']);
0436                         //$time_elapsed_secs = microtime(true) - $start;
0437                         //$info .= $time_elapsed_secs." secs";
0438 
0439                     } else {
0440                         $info .= " - NO Files Uploaded";
0441                         $contentTable->update(array(
0442                             "is_imported"  => 1,
0443                             "import_error" => "Error on fileupload to cc.ppload.com Exception: " . $pploadError
0444                         ), "id = " . $project['id']);
0445                     }
0446                 } else {
0447                     $info .= " - Project NOT created! ";
0448                 }
0449 
0450                 $time_elapsed_secs = microtime(true) - $start;
0451                 $info .= $time_elapsed_secs . " secs";
0452                 $info .= " - Done... ";
0453             }
0454             $result['Message'] = $info;
0455             $_is_import_done = true;
0456         } catch (Exception $e) {
0457             $this->view->info = $e->getMessage();
0458             $_is_import_done = true;
0459 
0460             $result['Result'] = self::RESULT_ERROR;
0461             $result['Message'] = "Error while loading from database:" . $e->getMessage();
0462         }
0463 
0464         $count = $contentTable->fetchCountProjectsForCategory($cat_id);
0465 
0466         $result['Result'] = self::RESULT_OK;
0467         $result['IsImportDone'] = $_is_import_done;
0468         $result['TotalCounter'] = $count;
0469         $result['ImportCounter'] = $_import_counter;
0470         $result['ImportFileCounter'] = $_import_file_counter;
0471         $result['limit'] = $limit;
0472         $result['offset'] = $startIndex + $limit;
0473 
0474         $this->_helper->json($result);
0475     }
0476 
0477     private function getProjectPicture($hiveProjectId)
0478     {
0479         $imageModel = new Default_Model_DbTable_Image();
0480         $path = 'https://cn.opendesktop.org/img/hive/content-pre1/' . $hiveProjectId . '-1.';
0481         $fileUrl = null;
0482         $fileExtention = null;
0483         $info = '';
0484 
0485         if ($this->check_img($path . 'gif')) {
0486             $fileUrl = ($path . 'gif');
0487             $fileExtention = 'gif';
0488         }
0489         if ($this->check_img($path . 'png')) {
0490             $fileUrl = ($path . 'png');
0491             $fileExtention = 'png';
0492         }
0493         if ($this->check_img($path . 'jpg')) {
0494             $fileUrl = ($path . 'jpg');
0495             $fileExtention = 'jpg';
0496         }
0497         if ($this->check_img($path . 'jpeg')) {
0498             $fileUrl = ($path . 'jpeg');
0499             $fileExtention = 'jpeg';
0500         }
0501         if ($this->check_img($path . 'mockup')) {
0502             $fileUrl = ($path . 'mockup');
0503             $fileExtention = 'mockup';
0504         }
0505         if ($this->check_img($path . 'GIF')) {
0506             $fileUrl = ($path . 'GIF');
0507             $fileExtention = 'GIF';
0508         }
0509         if ($this->check_img($path . 'PNG')) {
0510             $fileUrl = ($path . 'PNG');
0511             $fileExtention = 'PNG';
0512         }
0513         if ($this->check_img($path . 'JPG')) {
0514             $fileUrl = ($path . 'JPG');
0515             $fileExtention = 'JPG';
0516         }
0517         if ($this->check_img($path . 'JPEG')) {
0518             $fileUrl = ($path . 'JPEG');
0519             $fileExtention = 'JPEG';
0520         }
0521         if ($this->check_img($path . 'MOCKUP')) {
0522             $fileUrl = ($path . 'MOCKUP');
0523             $fileExtention = 'MOCKUP';
0524         }
0525         $cnFileUrl = null;
0526         if ($fileUrl != null) {
0527             $config = Zend_Registry::get('config');
0528             $cnFileUrl = '/hive/content-pre1/' . $hiveProjectId . '-1.' . $fileExtention;
0529 
0530             /**
0531              * //Workaround for gifs: don't use cache on cdn
0532              * $pos = strrpos($cnFileUrl, ".gif");
0533              * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
0534              * //gefunden ...
0535              * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
0536              * }
0537              **/
0538             $info .= "ImageUpload successful: " . $cnFileUrl;
0539         } else {
0540             $path = 'https://cn.opendesktop.org/img/hive/content-pre2/' . $hiveProjectId . '-2.';
0541             $fileUrl = null;
0542             $fileExtention = null;
0543             $info = '';
0544 
0545             if ($this->check_img($path . 'gif')) {
0546                 $fileUrl = ($path . 'gif');
0547                 $fileExtention = 'gif';
0548             }
0549             if ($this->check_img($path . 'png')) {
0550                 $fileUrl = ($path . 'png');
0551                 $fileExtention = 'png';
0552             }
0553             if ($this->check_img($path . 'jpg')) {
0554                 $fileUrl = ($path . 'jpg');
0555                 $fileExtention = 'jpg';
0556             }
0557             if ($this->check_img($path . 'jpeg')) {
0558                 $fileUrl = ($path . 'jpeg');
0559                 $fileExtention = 'jpeg';
0560             }
0561             if ($this->check_img($path . 'mockup')) {
0562                 $fileUrl = ($path . 'mockup');
0563                 $fileExtention = 'mockup';
0564             }
0565             if ($this->check_img($path . 'GIF')) {
0566                 $fileUrl = ($path . 'GIF');
0567                 $fileExtention = 'GIF';
0568             }
0569             if ($this->check_img($path . 'PNG')) {
0570                 $fileUrl = ($path . 'PNG');
0571                 $fileExtention = 'PNG';
0572             }
0573             if ($this->check_img($path . 'JPG')) {
0574                 $fileUrl = ($path . 'JPG');
0575                 $fileExtention = 'JPG';
0576             }
0577             if ($this->check_img($path . 'JPEG')) {
0578                 $fileUrl = ($path . 'JPEG');
0579                 $fileExtention = 'JPEG';
0580             }
0581             if ($this->check_img($path . 'MOCKUP')) {
0582                 $fileUrl = ($path . 'MOCKUP');
0583                 $fileExtention = 'MOCKUP';
0584             }
0585             $cnFileUrl = null;
0586             if ($fileUrl != null) {
0587                 $config = Zend_Registry::get('config');
0588                 $cnFileUrl = '/hive/content-pre2/' . $hiveProjectId . '-2.' . $fileExtention;
0589 
0590                 /**
0591                  * //Workaround for gifs: don't use cache on cdn
0592                  * $pos = strrpos($cnFileUrl, ".gif");
0593                  * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
0594                  * //gefunden ...
0595                  * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
0596                  * }
0597                  **/
0598                 $info .= "ImageUpload successful: " . $cnFileUrl;
0599             } else {
0600                 $path = 'https://cn.opendesktop.org/img/hive/content-pre3/' . $hiveProjectId . '-3.';
0601                 $fileUrl = null;
0602                 $fileExtention = null;
0603                 $info = '';
0604 
0605                 if ($this->check_img($path . 'gif')) {
0606                     $fileUrl = ($path . 'gif');
0607                     $fileExtention = 'gif';
0608                 }
0609                 if ($this->check_img($path . 'png')) {
0610                     $fileUrl = ($path . 'png');
0611                     $fileExtention = 'png';
0612                 }
0613                 if ($this->check_img($path . 'jpg')) {
0614                     $fileUrl = ($path . 'jpg');
0615                     $fileExtention = 'jpg';
0616                 }
0617                 if ($this->check_img($path . 'jpeg')) {
0618                     $fileUrl = ($path . 'jpeg');
0619                     $fileExtention = 'jpeg';
0620                 }
0621                 if ($this->check_img($path . 'mockup')) {
0622                     $fileUrl = ($path . 'mockup');
0623                     $fileExtention = 'mockup';
0624                 }
0625                 if ($this->check_img($path . 'GIF')) {
0626                     $fileUrl = ($path . 'GIF');
0627                     $fileExtention = 'GIF';
0628                 }
0629                 if ($this->check_img($path . 'PNG')) {
0630                     $fileUrl = ($path . 'PNG');
0631                     $fileExtention = 'PNG';
0632                 }
0633                 if ($this->check_img($path . 'JPG')) {
0634                     $fileUrl = ($path . 'JPG');
0635                     $fileExtention = 'JPG';
0636                 }
0637                 if ($this->check_img($path . 'JPEG')) {
0638                     $fileUrl = ($path . 'JPEG');
0639                     $fileExtention = 'JPEG';
0640                 }
0641                 if ($this->check_img($path . 'MOCKUP')) {
0642                     $fileUrl = ($path . 'MOCKUP');
0643                     $fileExtention = 'MOCKUP';
0644                 }
0645                 $cnFileUrl = null;
0646                 if ($fileUrl != null) {
0647                     $config = Zend_Registry::get('config');
0648                     $cnFileUrl = '/hive/content-pre3/' . $hiveProjectId . '-3.' . $fileExtention;
0649 
0650                     /**
0651                      * //Workaround for gifs: don't use cache on cdn
0652                      * $pos = strrpos($cnFileUrl, ".gif");
0653                      * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
0654                      * //gefunden ...
0655                      * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
0656                      * }
0657                      **/
0658                     $info .= "ImageUpload successful: " . $cnFileUrl;
0659                 } else {
0660                     $info .= "No preview pic";
0661                 }
0662             }
0663         }
0664 
0665         //var_dump($info);
0666         return $cnFileUrl;
0667     }
0668 
0669     private function check_img($file)
0670     {
0671         $response = false;
0672         $x = getimagesize($file);
0673 
0674         switch ($x['mime']) {
0675             case "image/gif":
0676                 $response = true;
0677                 break;
0678             case "image/jpeg":
0679                 $response = true;
0680                 break;
0681             case "image/png":
0682                 $response = true;
0683                 break;
0684             default:
0685                 $response = false;
0686                 break;
0687         }
0688 
0689         return $response;
0690     }
0691 
0692     private function createUpdateOcsProjects($hiveUser, $project, $ocs_cat_id, $cnFilePath)
0693     {
0694         $projectTable = new Default_Model_Project();
0695         $memberTable = new Default_Model_Member();
0696         $info = '';
0697         $projectId = null;
0698         $uuid = null;
0699         $count_likes = null;
0700         $count_dislikes = null;
0701         try {
0702             $projectsResult = $projectTable->fetchAll("source_type = 'project' AND source_id = 1 AND source_pk = " . $project['id']);
0703 
0704             if (count($projectsResult) > 0) {
0705                 $info .= "Project load successfull: " . $projectsResult[0]['project_id'];
0706                 $projectId = $projectsResult[0]['project_id'];
0707                 $uuid = $projectsResult[0]['uuid'];
0708             }
0709         } catch (Exception $e) {
0710             $info .= (__FUNCTION__ . '::ERROR load Project: ' . $e);
0711         }
0712 
0713         $memberId = null;
0714         try {
0715             $member = $memberTable->fetchMemberFromHiveUserId($hiveUser['id']);
0716             if ($member) {
0717                 $info .= "Member load successfull: " . $member['member_id'];
0718                 $memberId = $member['member_id'];
0719             } else {
0720                 throw new Exception(__FUNCTION__ . '::ERROR load member: Member not found: Username = ' . $project['user']);
0721             }
0722         } catch (Exception $e) {
0723             throw new Exception(__FUNCTION__ . '::ERROR load member: ' . $e);
0724         }
0725 
0726         $projectObj = array();
0727         $projectObj['member_id'] = $memberId;
0728         $projectObj['content_type'] = 'text';
0729         $projectObj['project_category_id'] = $ocs_cat_id;
0730         $projectObj['hive_category_id'] = $project['type'];
0731 
0732         //Project not deleted?
0733         if ($project['deletedat'] == 0 && $project['status'] == 1) {
0734             $projectObj['is_deleted'] = 0;
0735             $projectObj['deleted_at'] = $project['deleted_at'];
0736             $projectObj['is_active'] = 1;
0737             $projectObj['status'] = 100;
0738         } else {
0739             $projectObj['is_deleted'] = 1;
0740             $projectObj['deleted_at'] = $project['deleted_at'];
0741             $projectObj['is_active'] = 0;
0742             $projectObj['status'] = 30;
0743         }
0744 
0745         $projectObj['pid'] = null;
0746         $projectObj['type_id'] = 1;
0747         $projectObj['title'] = $project['name_utf8'];
0748         $projectObj['description'] = $project['description_utf8'];
0749         $projectObj['version'] = $project['version'];
0750         $projectObj['image_big'] = $cnFilePath;
0751         $projectObj['image_small'] = $cnFilePath;
0752         $projectObj['start_date'] = null;
0753         $projectObj['content_url'] = null;
0754         $projectObj['created_at'] = $project['created_at'];
0755         $projectObj['changed_at'] = $project['changed_at'];
0756         $projectObj['creator_id'] = $memberId;
0757 
0758         $projectObj['count_downloads_hive'] = $project['downloads'];
0759 
0760         //      $projectObj['facebook_code'] = null;
0761         //      $projectObj['twitter_code'] = null;
0762         //      $projectObj['google_code'] = null;
0763         //      $projectObj['link_1'] = null;
0764         //      $projectObj['embed_code'] = null;
0765         //      $projectObj['ppload_collection_id'] = null;
0766         //      $projectObj['validated'] = null;
0767         //      $projectObj['validated_at'] = null;
0768         //      $projectObj['featured'] = null;
0769         //      $projectObj['amount'] = null;
0770         //      $projectObj['amount_period'] = null;
0771         //      $projectObj['claimable'] = null;
0772         //      $projectObj['claimed_by_member'] = null;
0773         $projectObj['source_id'] = 1;
0774         $projectObj['source_pk'] = $project['id'];
0775         $projectObj['source_type'] = 'project';
0776 
0777         if (!isset($uuid)) {
0778             $uuid = Local_Tools_UUID::generateUUID();
0779             $projectObj['uuid'] = $uuid;
0780         }
0781 
0782         if ($projectId) {
0783             try {
0784                 $votingTable = new Default_Model_DbTable_ProjectRating();
0785 
0786                 $votingTable->delete('member_id = 0 AND project_id = ' . $projectId);
0787                 //insert the old hive votings
0788                 $votearray = array();
0789                 $votearray['member_id'] = 0;
0790                 $votearray['project_id'] = $projectId;
0791                 $votearray['user_like'] = $project['scoregood'];
0792                 $votearray['user_dislike'] = $project['scorebad'];
0793                 $newVote = $votingTable->save($votearray);
0794 
0795                 $ratingSum = $votingTable->fetchRating($projectId);
0796                 $count_likes = $ratingSum['count_likes'];
0797                 $count_dislikes = $ratingSum['count_dislikes'];
0798                 $projectObj['count_likes'] = $count_likes;
0799                 $projectObj['count_dislikes'] = $count_dislikes;
0800 
0801                 //update project
0802                 $updateCount = $projectTable->update($projectObj, "project_id = " . $projectId);
0803                 $info .= "Update Project successful: Updated rows: " . $updateCount;
0804 
0805                 //update changelog?
0806                 if (isset($project['changelog']) && $project['changelog'] != '') {
0807                     $projectUpdatesTable = new Default_Model_ProjectUpdates();
0808                     $projectUpdate =
0809                         $projectUpdatesTable->fetchRow('project_id = ' . $projectId . ' AND source_id = 1 AND source_pk = '
0810                             . $project['id']);
0811                     if ($projectUpdate) {
0812                         $projectUpdate = $projectUpdate->toArray();
0813                         if ($projectUpdate['text'] != $project['changelog']) {
0814                             $projectUpdate['text'] = $project['changelog_utf8'];
0815                             $projectUpdate['changed_at'] = $projectObj['changed_at'];
0816                             $projectUpdatesTable->save($projectUpdate);
0817                         }
0818                     } else {
0819                         $data = array();
0820                         $data['project_id'] = $projectId;
0821                         $data['member_id'] = $projectObj['member_id'];
0822                         $data['public'] = 1;
0823                         $data['text'] = $project['changelog_utf8'];
0824                         $data['created_at'] = $projectObj['created_at'];
0825                         $data['changed_at'] = $projectObj['changed_at'];
0826                         $data['source_id'] = 1;
0827                         $data['source_pk'] = $project['id'];
0828 
0829                         $projectUpdatesTable->save($data);
0830                     }
0831                 }
0832             } catch (Exception $e) {
0833                 throw new Exception(__FUNCTION__ . '::ERROR update project: ' . $e);
0834             }
0835         } else {
0836             try {
0837                 //Create new project
0838                 $newProjectObj = $projectTable->save($projectObj);
0839                 $info .= "Create Project successful: " . $newProjectObj['project_id'];
0840                 $projectId = $newProjectObj['project_id'];
0841 
0842                 $votingTable = new Default_Model_DbTable_ProjectRating();
0843 
0844                 $votingTable->delete('member_id = 0 AND project_id = ' . $projectId);
0845                 //insert the old hive votings
0846                 $votearray = array();
0847                 $votearray['member_id'] = 0;
0848                 $votearray['project_id'] = $projectId;
0849                 $votearray['user_like'] = $project['scoregood'];
0850                 $votearray['user_dislike'] = $project['scorebad'];
0851                 $newVote = $votingTable->save($votearray);
0852 
0853                 $ratingSum = $votingTable->fetchRating($projectId);
0854                 $count_likes = $ratingSum['count_likes'];
0855                 $count_dislikes = $ratingSum['count_dislikes'];
0856                 $projectObj['count_likes'] = $count_likes;
0857                 $projectObj['count_dislikes'] = $count_dislikes;
0858 
0859                 //update project
0860                 $updateCount = $projectTable->update($projectObj, "project_id = " . $projectId);
0861 
0862                 //Add changelog
0863                 if (isset($project['changelog']) && $project['changelog'] != '') {
0864                     $projectUpdatesTable = new Default_Model_ProjectUpdates();
0865                     $data = array();
0866                     $data['project_id'] = $projectId;
0867                     $data['member_id'] = $projectObj['member_id'];
0868                     $data['public'] = 1;
0869                     $data['text'] = $project['changelog'];
0870                     $data['created_at'] = $projectObj['created_at'];
0871                     $data['changed_at'] = $projectObj['changed_at'];
0872                     $data['source_id'] = 1;
0873                     $data['source_pk'] = $project['id'];
0874 
0875                     $projectUpdatesTable->save($data);
0876                 }
0877 
0878                 if (null == $newProjectObj || null == $newProjectObj['project_id']) {
0879                     throw new Exception(__FUNCTION__ . '::ERROR save project: ' . implode(",", $newProjectObj));
0880                 }
0881             } catch (Exception $e) {
0882                 throw new Exception(__FUNCTION__ . '::ERROR save project: ' . $e);
0883             }
0884         }
0885 
0886         return $projectId;
0887     }
0888 
0889     private function uploadFilesAndLinks($project, $projectId)
0890     {
0891         $_import_file_counter = 0;
0892         //First real files
0893         $file1 = null;
0894         $info = '';
0895 
0896         //Clean up old collection data
0897         $pploadApi = new Ppload_Api(array(
0898             'apiUri'   => PPLOAD_API_URI,
0899             'clientId' => PPLOAD_CLIENT_ID,
0900             'secret'   => PPLOAD_SECRET
0901         ));
0902 
0903         $projectTable = new Default_Model_DbTable_Project();
0904         $projectData = $projectTable->find($projectId)->current();
0905         $oldFiles = array();
0906 
0907         if ($projectData->ppload_collection_id) {
0908             $param = array();
0909             $param['collection_id'] = $projectData->ppload_collection_id;
0910             $oldFiles = $pploadApi->getFiles($param);
0911 
0912             $pploadApi->deleteCollection($projectData->ppload_collection_id);
0913             $projectData->ppload_collection_id = null;
0914             $projectTable->save($projectData->toArray());
0915         }
0916 
0917         if ($project['downloadtyp1'] == 0) {
0918             //a real file
0919             $file1 = $project['download1'];
0920             //$file1 = str_replace(' ', '%20', $file1);
0921             $pploadError = null;
0922             if (!empty($file1)) {
0923                 try {
0924                     $downloadCounter = 0;
0925                     if (isset($oldFiles->files)) {
0926                         foreach ($oldFiles->files as $oldFile) {
0927                             $filename = $this->getFilenameFromUrl($this->_HIVE_BASE_URL . '/CONTENT/content-files/' . $file1);
0928                             //var_dump('check file: '. $oldFile->name . ' AND ' . $filename);
0929                             if ($oldFile->name == $filename) {
0930                                 $downloadCounter = $oldFile->downloaded_count;
0931                             }
0932                         }
0933                     }
0934 
0935                     //$uploadFileResult = $this->uploadFileToPpload($projectId, 'http://cp1.hive01.com/CONTENT/content-files/'.$file1);
0936                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname1'], $project['licensetype'],
0937                         base64_encode($project['license']), $downloadCounter,
0938                         $this->_HIVE_BASE_URL . '/CONTENT/content-files/' . $file1);
0939                     $info .= "Upload file successful: " . $uploadFileResult;
0940                     if ($uploadFileResult == true) {
0941                         $_import_file_counter++;
0942                     } else {
0943                         throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $uploadFileResult);
0944                     }
0945                 } catch (Exception $e) {
0946                     throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
0947                 }
0948             }
0949         } else {
0950             //a link
0951             try {
0952                 $link1 = $project['downloadlink1'];
0953                 if ($link1 != 'http://' && !empty($link1)) {
0954                     $link1 = urlencode($link1);
0955                     $linkName1 = $project['downloadname1'];
0956                     if (empty($linkName1)) {
0957                         $linkName1 = "link";
0958                     }
0959                     $downloadCounter = 0;
0960                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname1'], $project['licensetype'],
0961                         base64_encode($project['license']), 0, $this->_HIVE_BASE_URL . '/CONTENT/content-files/link', $link1,
0962                         $linkName1);
0963                     $info .= "Upload file successful: " . $uploadFileResult;
0964                     if ($uploadFileResult == true) {
0965                         $_import_file_counter++;
0966                     }
0967                 }
0968             } catch (Exception $e) {
0969                 throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
0970             }
0971         }
0972 
0973         //Then links...
0974         for ($i = 2; $i <= 12; $i++) {
0975             try {
0976                 $link1 = $project['downloadlink' . $i];
0977                 if ($link1 != 'http://' && !empty($link1)) {
0978                     $link1 = urlencode($link1);
0979                     $linkName1 = $project['downloadname' . $i];
0980                     if (empty($linkName1)) {
0981                         $linkName1 = "link";
0982                     }
0983                     $downloadCounter = 0;
0984                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname' . $i], $project['licensetype'],
0985                         base64_encode($project['license']), 0, $this->_HIVE_BASE_URL . '/CONTENT/content-files/link', $link1,
0986                         $linkName1);
0987                     $info .= "Upload file successful: " . $link1;
0988                     if ($uploadFileResult == true) {
0989                         $_import_file_counter++;
0990                     }
0991                 }
0992             } catch (Exception $e) {
0993                 //throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
0994             }
0995         }
0996 
0997         if ($_import_file_counter == 0) {
0998             return $info;
0999         }
1000 
1001         return $_import_file_counter;
1002     }
1003 
1004     private function getFilenameFromUrl($url)
1005     {
1006         $x = pathinfo($url);
1007         $fileName = $x['basename'];
1008 
1009         return $fileName;
1010     }
1011 
1012     private function saveFileInPpload(
1013         $projectId,
1014         $fileDescription,
1015         $licensetype,
1016         $license,
1017         $downloads,
1018         $fileUrl,
1019         $link = null,
1020         $linkName = null
1021     ) {
1022         $pploadInfo = "Start upload file " . $fileUrl . " for project " . $projectId;
1023 
1024         $projectTable = new Default_Model_DbTable_Project();
1025         $projectData = $projectTable->find($projectId)->current();
1026 
1027         if ($projectData) {
1028             $pploadInfo .= "Project found! ProjectId: " . $projectData->project_id . ", MemberId: " . $projectData->member_id;
1029         } else {
1030             $pploadInfo .= "ERROR::Project not found: " . $projectId;
1031             throw new Exception($pploadInfo);
1032 
1033             return false;
1034         }
1035 
1036         $filename = null;
1037         if (!empty($link)) {
1038             //take emtpy dummy file
1039             $filename = $this->getFilenameFromUrl($fileUrl);
1040             $tmpFilepath = "/hive/H01/CONTENT/content-files/link";
1041             $tmpFilename = $linkName;
1042         } else {
1043             //upload to ocs-www
1044             $filename = $this->getFilenameFromUrl($fileUrl);
1045             $tmpFilepath = "/hive/H01/CONTENT/content-files/" . $filename;
1046             $tmpFilename = $filename;
1047             if (!empty($filename)) {
1048                 $pploadInfo .= "FileName found: " . $filename;
1049             } else {
1050                 $pploadInfo .= "ERROR::FileName not found: " . $filename;
1051                 throw new Exception($pploadInfo);
1052 
1053                 return false;
1054             }
1055         }
1056 
1057         $pploadApi = new Ppload_Api(array(
1058             'apiUri'   => PPLOAD_API_URI,
1059             'clientId' => PPLOAD_CLIENT_ID,
1060             'secret'   => PPLOAD_SECRET
1061         ));
1062 
1063         $fileRequest = array(
1064             'local_file_path' => $tmpFilepath,
1065             'local_file_name' => $tmpFilename,
1066             'owner_id'        => $projectData->member_id
1067         );
1068         if ($projectData->ppload_collection_id) {
1069             // Append to existing collection
1070             $fileRequest['collection_id'] = $projectData->ppload_collection_id;
1071         }
1072         if (!empty($fileDescription)) {
1073             $fileRequest['description'] = mb_substr($fileDescription, 0, 140);
1074         }
1075         if (!empty($downloads)) {
1076             $fileRequest['downloaded_count'] = $downloads;
1077         }
1078         $tags = '';
1079         if (!empty($link)) {
1080             $tags .= "link##" . $link . ',';
1081         }
1082         if (!empty($licensetype)) {
1083             $tags .= "licensetype-" . $licensetype . ',';
1084         }
1085         if (!empty($license)) {
1086             $tags .= "license##" . $license . ',';
1087         }
1088         if (!empty($tags)) {
1089             $fileRequest['tags'] = $tags;
1090         }
1091 
1092         //upload to ppload
1093         $fileResponse = $pploadApi->postFile($fileRequest);
1094 
1095         if (!empty($fileResponse)) {
1096             $pploadInfo .= "File uploaded to ppload! ";
1097         } else {
1098             $pploadInfo .= "ERROR::File NOT uploaded to ppload! Response: " . $fileResponse;
1099             throw new Exception($pploadInfo);
1100 
1101             return $pploadInfo;
1102         }
1103 
1104         //delete tmpFile
1105         //unlink($tmpFilename);
1106 
1107         //unlink($tmpFilename);
1108 
1109         if (!empty($fileResponse->file->collection_id)) {
1110             $pploadInfo .= "CollectionId: " . $fileResponse->file->collection_id;
1111             if (!$projectData->ppload_collection_id) {
1112                 // Save collection ID
1113                 $projectData->ppload_collection_id = $fileResponse->file->collection_id;
1114                 //$projectData->changed_at = new Zend_Db_Expr('NOW()');
1115                 $projectData->save();
1116 
1117                 // Update profile information
1118                 $memberTable = new Default_Model_DbTable_Member();
1119                 $memberSettings = $memberTable->find($projectData->member_id)->current();
1120                 $mainproject = $projectTable->find($memberSettings->main_project_id)->current();
1121                 $profileName = '';
1122                 if ($memberSettings->firstname
1123                     || $memberSettings->lastname) {
1124                     $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname);
1125                 } else {
1126                     if ($memberSettings->username) {
1127                         $profileName = $memberSettings->username;
1128                     }
1129                 }
1130                 $profileRequest = array(
1131                     'owner_id'    => $projectData->member_id,
1132                     'name'        => $profileName,
1133                     'email'       => $memberSettings->mail,
1134                     'homepage'    => $memberSettings->link_website,
1135                     'description' => $mainproject->description
1136                 );
1137                 $profileResponse = $pploadApi->postProfile($profileRequest);
1138                 // Update collection information
1139                 $collectionCategory = $projectData->project_category_id;
1140                 if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) {
1141                     $collectionCategory .= '-published';
1142                 }
1143                 $collectionRequest = array(
1144                     'title'       => $projectData->title,
1145                     'description' => $projectData->description,
1146                     'category'    => $collectionCategory
1147                 );
1148                 $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest);
1149                 // Store product image as collection thumbnail
1150                 $this->_updatePploadMediaCollectionthumbnail($projectData);
1151             }
1152 
1153             //return $fileResponse->file;
1154             return true;
1155         } else {
1156             //return false;
1157             $pploadInfo .= "ERROR::No CollectionId in ppload-file! Response Status: " . json_encode($fileResponse);
1158             throw new Exception($pploadInfo);
1159 
1160             return $pploadInfo;
1161         }
1162 
1163         return $pploadInfo;
1164     }
1165 
1166     private function _updatePploadMediaCollectionthumbnail($projectData)
1167     {
1168         if (empty($projectData->ppload_collection_id)
1169             || empty($projectData->image_small)) {
1170             return false;
1171         }
1172 
1173         $pploadApi = new Ppload_Api(array(
1174             'apiUri'   => "https://dl.opendesktop.org/api/",
1175             'clientId' => "1387085484",
1176             'secret'   => "34gtd3w024deece710e1225d7bfe5e7337b1f45d"
1177         ));
1178 
1179         $filename = sys_get_temp_dir() . '/' . $projectData->image_small;
1180         if (false === file_exists(dirname($filename))) {
1181             mkdir(dirname($filename), 0777, true);
1182         }
1183         /**
1184          * $viewHelperImage = new Default_View_Helper_Image();
1185          * $uri = $viewHelperImage->Image(
1186          * $projectData->image_small,
1187          * array(
1188          * 'width' => 600,
1189          * 'height' => 600
1190          * )
1191          * );**/
1192         $uri = $this->_OCS_CN_FILE_SYNC_URL . '/cache/600x600/img' . $projectData->image_small;
1193 
1194         file_put_contents($filename, file_get_contents($uri));
1195 
1196         $mediaCollectionthumbnailResponse =
1197             $pploadApi->postMediaCollectionthumbnail($projectData->ppload_collection_id, array('file' => $filename));
1198 
1199         unlink($filename);
1200 
1201         if (isset($mediaCollectionthumbnailResponse->status)
1202             && $mediaCollectionthumbnailResponse->status == 'success') {
1203             return true;
1204         }
1205 
1206         return false;
1207     }
1208 
1209     private function getPreviewPicture($hiveProjectId, $previewNum, $hivePreviewFileExtension)
1210     {
1211         $imageModel = new Default_Model_DbTable_Image();
1212 
1213         $config = Zend_Registry::get('config');
1214 
1215         $fileName = $hiveProjectId . '-' . $previewNum . '.' . $hivePreviewFileExtension;
1216         $cnFileUrl = '/hive/content-pre' . $previewNum . '/' . $fileName;
1217 
1218         /**
1219          * if ($this->check_img($cnFileUrl)) {
1220          * if($hivePreviewFileExtension == 'gif') {
1221          * $cnFileUrl = $config->images->media->server.'/img/hive/content-pre'.$previewNum.'/'.$fileName;
1222          * }
1223          * }
1224          **/
1225         return $cnFileUrl;
1226     }
1227 
1228     public function startImportAjaxAction()
1229     {
1230         global $_import_counter;
1231         global $_import_file_counter;
1232         global $_is_import_done;
1233 
1234         $_import_counter = 0;
1235         $_import_file_counter = 0;
1236         $_is_import_done = false;
1237 
1238         $this->_helper->layout->disableLayout();
1239         $params = $this->getAllParams();
1240         $cat_id = $params['cat_id'];
1241         $ocs_cat_id = $params['ocs_cat_id'];
1242 
1243         $info = null;
1244 
1245         $importGalleryPics = false;
1246         if (isset($params['import_previews'])) {
1247             $importGalleryPics = true;
1248         }
1249         $info .= " - With Gallery Pics? " . $importGalleryPics;
1250 
1251         $importFiles = false;
1252         if (isset($params['import_files'])) {
1253             $importFiles = true;
1254         }
1255         $info .= " - With Files? " . $importFiles;
1256 
1257         $startIndex = null;
1258         $limit = intval($params['limit']);
1259         if (empty($startIndex)) {
1260             $startIndex = 0;
1261         }
1262         if (empty($limit)) {
1263             $limit = 5;
1264         }
1265 
1266         $result = array();
1267         $contentTable = new Default_Model_DbTable_HiveContent();
1268         $memberTable = new Default_Model_Member();
1269         $projectTable = new Default_Model_Project();
1270         $hiveMemeberTable = new Default_Model_DbTable_HiveUser();
1271         
1272         try {
1273             $projects = $contentTable->fetchAllProjectsForCategory($cat_id, $startIndex, $limit);
1274 
1275             foreach ($projects as $project) {
1276                 $_import_counter++;
1277 
1278                 $info .= " ## Poject: id = " . $project['id'] . ", name = " . $project['name'] . "  ";
1279                 $start = microtime(true);
1280 
1281                 //1. Download/Upload Project-Picture
1282                 //$info .= " - Project-Picture ";
1283                 //$start = microtime(true);
1284                 //$cnFilePath = $this->uploadProjectPicture($project['id']);
1285                 $cnFilePath = $this->getProjectPicture($project['id']);
1286                 //$time_elapsed_secs = microtime(true) - $start;
1287                 //$info .= $time_elapsed_secs." secs";
1288 
1289                 //2. Create ocs Project
1290                 //$info .= " - Project ";
1291                 //$start = microtime(true);
1292                 try {
1293                     $hiveUser = $hiveMemeberTable->fetchRow('user = ' . $project['user']);
1294                     if(!empty($hiveUser)) {
1295                         $projectId = $this->createUpdateOcsProjects($hiveUser, $project, $ocs_cat_id, $cnFilePath);
1296                     }
1297                 } catch (Exception $e) {
1298                     //Error: log error and go on
1299                     $error = array();
1300                     $error['import_error'] = $e;
1301                     $error['is_imported'] = 1;
1302                     $contentTable->update($error, 'id = ' . $project['id']);
1303                 }
1304                 //$time_elapsed_secs = microtime(true) - $start;
1305                 //$info .= $time_elapsed_secs." secs";
1306 
1307                 if ($projectId) {
1308 
1309                     //3. Upload files
1310                     if ($importFiles) {
1311                         $pploadError = null;
1312                         $info .= " - Files ";
1313                         $start = microtime(true);
1314                         try {
1315                             $_import_file_counter = $this->uploadFilesAndLinks($project, $projectId);
1316                         } catch (Exception $e) {
1317                             $pploadError .= $e;
1318                         }
1319                         $info .= " - Files Uploaded: " . $_import_file_counter . " -  ";
1320                         $time_elapsed_secs = microtime(true) - $start;
1321                         $info .= $time_elapsed_secs . " secs";
1322                     } else {
1323                         $_import_file_counter = 1;
1324                     }
1325                     if ($_import_file_counter > 0) {
1326 
1327                         //4. Gallery Pics
1328                         if ($importGalleryPics) {
1329 
1330                             $info .= " - Gallery Pics ";
1331                             //$start = microtime(true);
1332                             $previewPicsArray = array();
1333                             if (!empty($project['preview1'])) {
1334                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 1, $project['preview1']);
1335                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 1, $project['preview1']);
1336                                 //add preview pic to ocs-project
1337                                 if (!empty($cnFilePathPre)) {
1338                                     $previewPicsArray[] = $cnFilePathPre;
1339                                     $info .= " - PreviewPic1 ";
1340                                 }
1341                             }
1342                             if (!empty($project['preview2'])) {
1343                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 2, $project['preview2']);
1344                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 2, $project['preview2']);
1345                                 if (!empty($cnFilePathPre)) {
1346                                     $previewPicsArray[] = $cnFilePathPre;
1347                                     $info .= " - PreviewPic2 ";
1348                                 }
1349                             }
1350                             if (!empty($project['preview3'])) {
1351                                 //$cnFilePathPre = $this->uploadPreviewPicture($project['id'], 3, $project['preview3']);
1352                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 3, $project['preview3']);
1353                                 if (!empty($cnFilePathPre)) {
1354                                     $previewPicsArray[] = $cnFilePathPre;
1355                                     $info .= " - PreviewPic3 ";
1356                                 }
1357                             }
1358                             if (!empty($previewPicsArray)) {
1359                                 $projectTable->updateGalleryPictures($projectId, $previewPicsArray);
1360                             }
1361                         }
1362                         //$time_elapsed_secs = microtime(true) - $start;
1363                         //$info .= $time_elapsed_secs." secs";
1364 
1365                         //5. Mark project as imported
1366                         //$info .= " - Mark project as imported ";
1367                         //$start = microtime(true);
1368                         $contentTable->update(array("is_imported" => 1), "id = " . $project['id']);
1369                         //$time_elapsed_secs = microtime(true) - $start;
1370                         //$info .= $time_elapsed_secs." secs";
1371 
1372                     } else {
1373                         $info .= " - NO Files Uploaded";
1374                         $contentTable->update(array(
1375                             "is_imported"  => 1,
1376                             "import_error" => "Error on fileupload to cc.ppload.com Exception: " . $pploadError
1377                         ), "id = " . $project['id']);
1378                     }
1379                 } else {
1380                     $info .= " - Project NOT created! ";
1381                 }
1382 
1383                 $time_elapsed_secs = microtime(true) - $start;
1384                 $info .= $time_elapsed_secs . " secs";
1385                 $info .= " - Done... ";
1386             }
1387             $result['Message'] = $info;
1388             $_is_import_done = true;
1389         } catch (Exception $e) {
1390             $this->view->info = $e->getMessage();
1391             $_is_import_done = true;
1392 
1393             $result['Result'] = self::RESULT_ERROR;
1394             $result['Message'] = "Fehler bei laden aus DB:" . $e->getMessage();
1395         }
1396 
1397         $count = $contentTable->fetchCountProjectsForCategory($cat_id);
1398 
1399         $result['Result'] = self::RESULT_OK;
1400         $result['IsImportDone'] = $_is_import_done;
1401         $result['TotalCounter'] = $count;
1402         $result['ImportCounter'] = $_import_counter;
1403         $result['ImportFileCounter'] = $_import_file_counter;
1404         $result['limit'] = $limit;
1405         $result['offset'] = $startIndex + $limit;
1406 
1407         $this->_helper->json($result);
1408     }
1409 
1410     public function importStatusAjaxAction()
1411     {
1412         $this->_helper->layout->disableLayout();
1413         $cat_id = (int)$this->getParam('cat_id');
1414         $contentTable = new Default_Model_DbTable_HiveContent();
1415         $countAll = $contentTable->fetchCountAllProjectsForCategory($cat_id);
1416         $countImported = $contentTable->fetchCountProjectsForCategory($cat_id);
1417 
1418         $result = array();
1419         $result['Result'] = self::RESULT_OK;
1420         $result['IsImportDone'] = ($countAll == $countImported);
1421         $result['ImportCounter'] = $countImported;
1422         $result['ProjectCounter'] = $countAll;
1423 
1424         $this->_helper->json($result);
1425     }
1426 
1427     private function saveImageOnMediaServer($filePathName, $fileExtention, $content_type)
1428     {
1429         if (empty($filePathName)) {
1430             throw new Exception(__FUNCTION__ . "ERROR::No image path");
1431         }
1432         $srcPathOnMediaServer = $this->sendImageToMediaServer($filePathName, $content_type);
1433         if (!$srcPathOnMediaServer) {
1434             throw new Exception("Error in upload to CDN-Server. \n Server message:\n" . $this->_errorMsg);
1435         }
1436 
1437         return $srcPathOnMediaServer;
1438     }
1439 
1440     protected function sendImageToMediaServer($fullFilePath, $mimeType)
1441     {
1442         $config = Zend_Registry::get('config');
1443         $url = $config->images->media->upload;
1444 
1445         $client = new Zend_Http_Client($url);
1446         $client->setFileUpload($fullFilePath, basename($fullFilePath), null, $mimeType);
1447         $response = $client->request('POST');
1448 
1449         if ($response->getStatus() > 200) {
1450             $this->_errorMsg = $response->getBody();
1451 
1452             return null;
1453         }
1454 
1455         return $response->getBody();
1456     }
1457 
1458     private function uploadFileToPpload($projectId, $fileUrl, $link = null, $linkName = null)
1459     {
1460         $pploadInfo = "Start upload file " . $fileUrl . " for project " . $projectId;
1461 
1462         $projectTable = new Default_Model_DbTable_Project();
1463         $projectData = $projectTable->find($projectId)->current();
1464 
1465         if ($projectData) {
1466             $pploadInfo .= "Project found! ProjectId: " . $projectData->project_id . ", MemberId: " . $projectData->member_id;
1467         } else {
1468             $pploadInfo .= "ERROR::Project not found: " . $projectId;
1469             throw new Exception($pploadInfo);
1470 
1471             return false;
1472         }
1473 
1474         //upload to ocs-www
1475         $file = $this->file_get_contents_curl($fileUrl);
1476         if ($file) {
1477             $pploadInfo .= "File found!";
1478         } else {
1479             $pploadInfo .= "ERROR::File not found: " . $fileUrl;
1480             throw new Exception($pploadInfo);
1481 
1482             return false;
1483         }
1484         $filename = null;
1485         if (!empty($link)) {
1486             //take emtpy dummy file
1487             $filename = $linkName;
1488         } else {
1489             //upload to ocs-www
1490             $filename = $this->getFilenameFromUrl($fileUrl);
1491             if (!empty($filename)) {
1492                 $pploadInfo .= "FileName found: " . $filename;
1493             } else {
1494                 $pploadInfo .= "ERROR::FileName not found: " . $filename;
1495                 throw new Exception($pploadInfo);
1496 
1497                 return false;
1498             }
1499         }
1500         file_put_contents(IMAGES_UPLOAD_PATH . 'tmp/' . $filename, $file);
1501 
1502         $tmpFilename = IMAGES_UPLOAD_PATH . 'tmp/' . $filename;
1503 
1504         $mime = mime_content_type($tmpFilename);
1505         if (empty($mime) || $mime == 'text/html') {
1506             $pploadInfo .= "ERROR::File NOT found!";
1507             throw new Exception($pploadInfo);
1508 
1509             return false;
1510         }
1511 
1512         if (file_exists($tmpFilename)) {
1513             $pploadInfo .= "File uploaded to ocs-www!";
1514         } else {
1515             $pploadInfo .= "ERROR::File NOT uploaded to ocs-www!";
1516             throw new Exception($pploadInfo);
1517 
1518             return false;
1519         }
1520 
1521         $pploadApi = new Ppload_Api(array(
1522             'apiUri'   => PPLOAD_API_URI,
1523             'clientId' => PPLOAD_CLIENT_ID,
1524             'secret'   => PPLOAD_SECRET
1525         ));
1526 
1527         $fileRequest = array(
1528             'file'     => $tmpFilename,
1529             'owner_id' => $projectData->member_id
1530         );
1531         if ($projectData->ppload_collection_id) {
1532             // Append to existing collection
1533             $fileRequest['collection_id'] = $projectData->ppload_collection_id;
1534         }
1535         //if (isset($fileDescription)) {
1536         //  $fileRequest['description'] = mb_substr($fileDescription, 0, 140);
1537         //}
1538         if (!empty($link)) {
1539             $fileRequest['tags'] = "link##" . $link;
1540         }
1541 
1542         //upload to ppload
1543         $fileResponse = $pploadApi->postFile($fileRequest);
1544 
1545         if (!empty($fileResponse)) {
1546             $pploadInfo .= "File uploaded to ppload! ";
1547         } else {
1548             $pploadInfo .= "ERROR::File NOT uploaded to ppload! Response: " . $fileResponse;
1549             throw new Exception($pploadInfo);
1550 
1551             return $pploadInfo;
1552         }
1553 
1554         //delete tmpFile
1555         unlink($tmpFilename);
1556 
1557         //unlink($tmpFilename);
1558 
1559         if (!empty($fileResponse->file->collection_id)) {
1560             $pploadInfo .= "CollectionId: " . $fileResponse->file->collection_id;
1561             if (!$projectData->ppload_collection_id) {
1562                 // Save collection ID
1563                 $projectData->ppload_collection_id = $fileResponse->file->collection_id;
1564                 //$projectData->changed_at = new Zend_Db_Expr('NOW()');
1565                 $projectData->save();
1566 
1567                 // Update profile information
1568                 $memberTable = new Default_Model_DbTable_Member();
1569                 $memberSettings = $memberTable->find($projectData->member_id)->current();
1570                 $mainproject = $projectTable->find($memberSettings->main_project_id)->current();
1571                 $profileName = '';
1572                 if ($memberSettings->firstname
1573                     || $memberSettings->lastname) {
1574                     $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname);
1575                 } else {
1576                     if ($memberSettings->username) {
1577                         $profileName = $memberSettings->username;
1578                     }
1579                 }
1580                 $profileRequest = array(
1581                     'owner_id'    => $projectData->member_id,
1582                     'name'        => $profileName,
1583                     'email'       => $memberSettings->mail,
1584                     'homepage'    => $memberSettings->link_website,
1585                     'description' => $mainproject->description
1586                 );
1587                 $profileResponse = $pploadApi->postProfile($profileRequest);
1588                 // Update collection information
1589                 $collectionCategory = $projectData->project_category_id;
1590                 if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) {
1591                     $collectionCategory .= '-published';
1592                 }
1593                 $collectionRequest = array(
1594                     'title'       => $projectData->title,
1595                     'description' => $projectData->description,
1596                     'category'    => $collectionCategory
1597                 );
1598                 $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest);
1599                 // Store product image as collection thumbnail
1600                 $this->_updatePploadMediaCollectionthumbnail($projectData);
1601             }
1602 
1603             //return $fileResponse->file;
1604             return true;
1605         } else {
1606             //return false;
1607             $pploadInfo .= "ERROR::No CollectionId in ppload-file! Response Status: " . json_encode($fileResponse);
1608             throw new Exception($pploadInfo);
1609 
1610             return $pploadInfo;
1611         }
1612 
1613         return $pploadInfo;
1614     }
1615 
1616     private function file_get_contents_curl($url)
1617     {
1618         $ch = curl_init();
1619 
1620         curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1621         curl_setopt($ch, CURLOPT_HEADER, 0);
1622         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1623         curl_setopt($ch, CURLOPT_URL, $url);
1624         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1625 
1626         $data = curl_exec($ch);
1627         curl_close($ch);
1628 
1629         return $data;
1630     }
1631 }