File indexing completed on 2024-05-12 05:58:31

0001 <?php
0002 
0003 /**
0004  *  ocs-webserver
0005  *
0006  *  Copyright 2016 by pling GmbH.
0007  *
0008  *    This file is part of ocs-webserver.
0009  *
0010  *    This program is free software: you can redistribute it and/or modify
0011  *    it under the terms of the GNU Affero General Public License as
0012  *    published by the Free Software Foundation, either version 3 of the
0013  *    License, or (at your option) any later version.
0014  *
0015  *    This program is distributed in the hope that it will be useful,
0016  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
0017  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0018  *    GNU Affero General Public License for more details.
0019  *
0020  *    You should have received a copy of the GNU Affero General Public License
0021  *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
0022  **/
0023 class Backend_HiveCliController extends Local_Controller_Action_CliAbstract
0024 {
0025     var $_HIVE_BASE_URL;
0026     var $_OCS_CN_FILE_SYNC_URL;
0027     var $_OCS_FILE_SYNC_URL;
0028 
0029     //Daily updated hive categories
0030     //var $hive_import_categories = array(56,57,210,211,212,213,214,220,221,222,223,224,241,242,243,260,261,282,285,284,270,271,272,273,281,280,230,231,232,233,234,235,236,310,311,312,313,314,320,321,322,323,324,341,342,343,360,361,382,385,384,370,371,372,373,381,380,330,331,332,333,334,335,336,4210,4211,4212,4213,4214,4220,4221,4222,4223,4224,4241,4242,4243,4260,4261,4282,4285,4284,4270,4271,4272,4273,4281,4280,4230,4231,4232,4233,4234,4235,4236,4298,4299,4283,4290,4320,4324,10,11,12,13,17,18,22,7525,7825,8025,8125,8121,8321,34,24,26,28,30,31,32,470,180,7304,186,90,190,91,92,638,690,691,83,687,646,694,686,643,35,413,4250,4251,4252,4253,4254,250,251,252,253,254,350,351,352,353,354,120,166,62,38,55,63,40,43,86,87,683,630,631,632,9821,9822,9823,9827,9840,644,642,7526,8726,8326,7826,8126,8026,7726,131,9700,60,14,20,6110,6120,7030,7060,7050,41,287,39,76,93,70,36,79,66,45,74,77,23,27,81,102,103,21,9,16,6700,165,101,188,189,133,130,160,150,121,104,191,167,100,430,420,7400,7402,7403,7311,7314,7313,7000,685,37,2,3,4,5,7,29,71,72,73,80,170,171,172,173,174,175,176,177,178,179);
0031     //var $hive_import_categories = array(15,8,64,8300,7700,8000,8100,7800,8400,8700,7600,7900,7500);
0032     //var $hive_import_categories = arra(25);
0033     //var $hive_import_categories = array(648, 692, 649);
0034     //var $hive_import_categories = array(322,323,324,325,326);
0035     //var $hive_import_categories = array(637);
0036     var $hive_import_categories = array(635);
0037     protected $_allowed = array(
0038         'image/jpeg'          => '.jpg',
0039         'image/jpg'           => '.jpg',
0040         'image/png'           => '.png',
0041         'image/gif'           => '.gif',
0042         'application/x-empty' => '.png'
0043     );
0044 
0045     /**
0046      * Run php code as cronjob.
0047      * I.e.:
0048      * /usr/bin/php /var/www/ocs-www/httpdocs/cron.php -a /backend/hive-cli/run/action/sync/context/users/ >> /var/www/ocs-www/logs/hive_sync.log $
0049      *
0050      * @see Local_Controller_Action_CliInterface::runAction()
0051      */
0052     public function runAction()
0053     {
0054         $this->initVars();
0055 
0056         $action = (int)$this->getParam('action');
0057         $context = $this->getParam('context');
0058 
0059         /**
0060          * Disable Sync
0061          * 20160627 Ronald
0062          */
0063 
0064         if (isset($action) && $action == 'sync' && isset($context) && $context == 'all') {
0065             /**$this->syncUser();
0066              * $this->syncContent();
0067              * $this->syncVotes();
0068              * $this->syncComments();
0069              * $this->syncDownloads();*/
0070             //} else if(isset($action) && $action == 'sync' && isset($context) && $context == 'users') {
0071             //  $this->syncUser();
0072             //} else if(isset($action) && $action == 'sync' && isset($context) && $context == 'content') {
0073             //  $this->syncContent();
0074         } else {
0075             if (isset($action) && $action == 'sync' && isset($context) && $context == 'votes') {
0076                 $this->syncVotes();
0077             } else {
0078                 if (isset($action) && $action == 'sync' && isset($context) && $context == 'comments') {
0079                     $this->syncComments();
0080                     //} else if(isset($action) && $action == 'sync' && isset($context) && $context == 'downloads') {
0081                     //  $this->syncDownloads();
0082                 }
0083             }
0084         }
0085     }
0086 
0087     public function initVars()
0088     {
0089         echo '################## SERVER: ' . php_uname("n") . ' ####################';
0090 
0091         if (strtolower(php_uname("n")) == 'do-pling-com') {
0092             $this->_HIVE_BASE_URL = 'http://cp1.hive01.com';
0093             $this->_OCS_CN_FILE_SYNC_URL = 'https://cn.com';
0094             $this->_OCS_FILE_SYNC_URL = 'https://www.ppload.com';
0095         } else {
0096             $this->_HIVE_BASE_URL = 'http://cp1.hive01.com';
0097             $this->_OCS_CN_FILE_SYNC_URL = 'https://cn.ws';
0098             $this->_OCS_FILE_SYNC_URL = 'https://ws.ppload.com';
0099         }
0100     }
0101 
0102     private function syncVotes()
0103     {
0104         $db = Zend_Db_Table::getDefaultAdapter();
0105 
0106         $sql = "SELECT ";
0107         $sql .= "   c.action,v.id,v.type,";
0108         $sql .= " m.member_id as `member_id`,";
0109         $sql .= " p.project_id as `project_id`,";
0110         $sql .= " case when v.vote > 0 then 1 else 0 end as `user_like`,";
0111         $sql .= " case when v.vote = 0 then 1 else 0 end `user_dislike`,";
0112         $sql .= " 1 as source_id,";
0113         $sql .= " v.id as source_pk from H01.changes c";
0114         $sql .= " JOIN H01.votes v ON c.id = v.id";
0115         $sql .= " join member m on m.source_id = 1 and m.username = v.user and v.userdb = 0";
0116         $sql .= " join project p on p.source_id = 1 and p.source_type = 'project' and p.source_pk = v.content";
0117         $sql .= " WHERE c.table = 'votes'";
0118         $sql .= " ORDER BY action,v.timestamp";
0119 
0120         $result = '';
0121 
0122         $stmt = $db->query($sql);
0123         $votes = $stmt->fetchAll();
0124         echo '###################### Start VotesSync: ' . count($votes) . ' votes ';
0125 
0126         //Insert/Update users in table project_rating
0127         foreach ($votes as $vote) {
0128             if ($vote['type'] == 2) {
0129                 if ($vote['action'] <> 'D') {
0130                     $vote_id = $this->insertUpdateVote($vote);
0131                 } else {
0132                     if ($vote['action'] == 'D') {
0133                         $this->deleteVote($vote);
0134                     }
0135                 }
0136                 $sql = "DELETE FROM H01.changes WHERE `table` = 'votes' AND `action` = '" . $vote['action'] . "' AND `id` = "
0137                     . $vote['id'];
0138                 $stmt = $db->query($sql);
0139                 $stmt->execute();
0140             }
0141         }
0142     }
0143 
0144     private function insertUpdateVote($vote)
0145     {
0146         $votingTable = new Default_Model_DbTable_ProjectRating();
0147         $votearray = $vote;
0148         unset($votearray['action']);
0149         unset($votearray['id']);
0150         unset($votearray['type']);
0151 
0152         $votingTable->delete('member_id = ' . $votearray['member_id'] . ' AND project_id = ' . $votearray['project_id']);
0153 
0154         $newVote = $votingTable->save($votearray);
0155 
0156         $projectTable = new Default_Model_Project();
0157         $project = $projectTable->find($votearray['project_id'])->current();
0158 
0159         if ($project) {
0160             $project = $project->toArray();
0161             $ratingSum = $votingTable->fetchRating($project['project_id']);
0162             $project['count_likes'] = $ratingSum['count_likes'];
0163             $project['count_dislikes'] = $ratingSum['count_dislikes'];
0164 
0165             $projectTable->save($project);
0166         }
0167 
0168         if ($newVote) {
0169             return $newVote;
0170         } else {
0171             return false;
0172         }
0173     }
0174 
0175     private function syncComments()
0176     {
0177         $db = Zend_Db_Table::getDefaultAdapter();
0178 
0179         //Parent-Comments
0180         $sql = "SELECT * FROM (";
0181         $sql .= " SELECT ch.`action`,c.parent,NULL AS comment_id,0 AS comment_type,0 AS comment_parent_id,p.project_id AS comment_target_id,m.member_id AS comment_member_id,convert(cast(convert(c.text using latin1) as binary) using utf8) AS comment_text, FROM_UNIXTIME(c.date) AS comment_created_at,1 AS source_id,c.id AS source_pk";
0182         $sql .= " FROM H01.changes ch";
0183         $sql .= " JOIN H01.comments c ON c.id = ch.id";
0184         $sql .= " JOIN member m ON m.source_id = 1 AND m.username = CONVERT(c.user USING utf8) AND c.userdb = 0";
0185         $sql .= " JOIN project p ON p.source_id = 1 AND p.source_type = 'project' AND p.source_pk = c.content";
0186         $sql .= " LEFT JOIN comments c3 ON c3.source_id = 1 AND c3.source_pk = c.id";
0187         $sql .= " WHERE ch.table = 'comments'";
0188         $sql .= " ) A";
0189         $sql .= " where parent = 0";
0190         $sql .= " ORDER BY action,comment_created_at";
0191 
0192         $result = '';
0193 
0194         $stmt = $db->query($sql);
0195         $comments = $stmt->fetchAll();
0196         echo '###################### Start ComentSync: ' . count($comments) . ' comments ';
0197 
0198         //Insert/Update users in table comments
0199         foreach ($comments as $comment) {
0200             if ($comment['action'] <> 'D') {
0201                 $comment_id = $this->insertUpdateComment($comment);
0202             }
0203             $sql = "DELETE FROM H01.changes WHERE `table` = 'comments' AND `action` = '" . $comment['action'] . "' AND `id` = "
0204                 . $comment['source_pk'];
0205             $stmt = $db->query($sql);
0206             $stmt->execute();
0207         }
0208 
0209         //Child-Comments
0210         $sql = "SELECT * FROM (";
0211         $sql .= " SELECT ch.action, c.parent, c3.comment_id,0 AS type,c2.comment_id AS comment_parent_id,p.project_id AS comment_target_id,m.member_id AS comment_member_id,convert(cast(convert(c.text using latin1) as binary) using utf8) AS comment_text, FROM_UNIXTIME(c.date) AS comment_created_at,1 AS source_id,c.id AS source_pk";
0212         $sql .= " FROM H01.changes ch";
0213         $sql .= " JOIN H01.comments c ON c.id = ch.id";
0214         $sql .= " JOIN member m ON m.source_id = 1 AND m.username = CONVERT(c.user USING utf8) AND c.userdb = 0";
0215         $sql .= " JOIN project p ON p.source_id = 1 AND p.source_type = 'project' AND p.source_pk = c.content";
0216         $sql .= " JOIN comments c2 ON c2.source_id = 1 AND c2.source_pk = c.parent";
0217         $sql .= " LEFT JOIN comments c3 ON c3.source_id = 1 AND c3.source_pk = c.id";
0218         $sql .= " WHERE ch.table = 'comments'";
0219         $sql .= " ) A";
0220         $sql .= " WHERE parent > 0 ";
0221         $sql .= " ORDER BY action,comment_created_at";
0222 
0223         $result = '';
0224 
0225         $stmt = $db->query($sql);
0226         $comments = $stmt->fetchAll();
0227         $countChildComments = count($comments);
0228         echo 'Start ChildCommentsSync: ' . count($comments) . ' comments ';
0229 
0230         //Insert/Update users in table comments
0231         foreach ($comments as $comment) {
0232             if ($comment['action'] <> 'D') {
0233                 $comment_id = $this->insertUpdateComment($comment);
0234             }
0235             $sql = "DELETE FROM H01.changes WHERE `table` = 'comments' AND `action` = '" . $comment['action'] . "' AND `id` = "
0236                 . $comment['source_pk'];
0237             $stmt = $db->query($sql);
0238             $stmt->execute();
0239         }
0240 
0241         //Deleted-Comments
0242         $sql = "SELECT c.* FROM H01.changes c WHERE c.`table` = 'comments' AND c.`action` = 'D'";
0243         $stmt = $db->query($sql);
0244         $comments = $stmt->fetchAll();
0245         echo '###################### Start ComentSync Deleted Comments: ' . count($comments) . ' comments ';
0246         //Insert/Update users in table comments
0247         foreach ($comments as $comment) {
0248             $comment_id = $this->deleteComment($comment);
0249             $sql = "DELETE FROM H01.changes WHERE `table` = 'comments' AND `action` = '" . $comment['action'] . "' AND `id` = "
0250                 . $comment['id'];
0251             $stmt = $db->query($sql);
0252             $stmt->execute();
0253         }
0254 
0255         if ($countChildComments > 1) {
0256             $this->syncComments();
0257         }
0258     }
0259 
0260     private function insertUpdateComment($comment)
0261     {
0262         $commentTable = new Default_Model_ProjectComments();
0263         $commentarray = $comment;
0264         unset($commentarray['action']);
0265         unset($commentarray['parent']);
0266 
0267         $orgComment = $commentTable->getCommentFromSource(0, 1, $comment['source_pk']);
0268         if ($orgComment) {
0269             $commentarray['comment_id'] = $orgComment['comment_id'];
0270             $newComment = $commentTable->save($commentarray);
0271         } else {
0272             $newComment = $commentTable->save($commentarray);
0273         }
0274 
0275         if ($newComment) {
0276             return $newComment;
0277         } else {
0278             return false;
0279         }
0280     }
0281 
0282     private function deleteComment($comment)
0283     {
0284 
0285         $ocsCommentTable = new Default_Model_DbTable_Comments();
0286         $ocsComment = $ocsCommentTable->fetchRow('source_id = 1 and source_pk = ' . $comment['id']);
0287 
0288         if ($ocsComment) {
0289             $ocsComment = $ocsComment->toArray();
0290             $ocsComment['comment_active'] = 0;
0291             $result = $ocsCommentTable->save($ocsComment);
0292 
0293             return $result;
0294         }
0295 
0296         return false;
0297     }
0298 
0299     public function initAction()
0300     {
0301         $action = (int)$this->getParam('action');
0302         $context = $this->getParam('context');
0303 
0304         $config = Zend_Registry::get('config');
0305         $this->_HIVE_BASE_URL = $config->admin->email;
0306 
0307         $this->createCronJob($action, $context);
0308     }
0309 
0310     /**
0311      * @param string $action
0312      * @param string $context
0313      *
0314      * @throws Zend_Exception
0315      */
0316     protected function createCronJob($action, $context)
0317     {
0318         try {
0319             $manager = new Crontab_Manager_CrontabManager();
0320             //           $manager->user = 'www-data';
0321             $newJob = $manager->newJob('*/60 * * * * php /var/www/ocs-www/httpdocs/cron.php -a /backend/hive-cli/run/action/' . $action
0322                 . '/context/' . $context . '/ >> /var/www/ocs-www/logs/hive_sync_' . $context . '.log 2>&1', 'www-data');
0323             if (false == $manager->jobExists($newJob)) {
0324                 $manager->add($newJob);
0325                 $manager->save();
0326             }
0327         } catch (Exception $e) {
0328             Zend_Registry::get('logger')->err(__METHOD__ . ' - ' . print_r($e, true));
0329             exit();
0330         }
0331     }
0332 
0333     private function syncUser()
0334     {
0335         $db = Zend_Db_Table::getDefaultAdapter();
0336         $sql = "SELECT c.action,u.* FROM H01.changes c";
0337         $sql .= " JOIN H01.users u ON c.id = u.id";
0338         $sql .= " WHERE c.table = 'users'";
0339         $sql .= " ORDER BY action,createtime";
0340 
0341         $result = '';
0342 
0343         $stmt = $db->query($sql);
0344         $users = $stmt->fetchAll();
0345         echo '###################### Start UserSync: ' . count($users) . ' users ';
0346 
0347         //Refresh files on cn
0348         $result = file_get_contents($this->_OCS_CN_FILE_SYNC_URL . '/sync.php');
0349         echo $result;
0350 
0351         //Insert/Update users in table hive_users
0352         foreach ($users as $user) {
0353             if ($user['action'] <> 'D') {
0354                 $newMember = $this->insertUpdateUserIntoImportTable($user);
0355             } else {
0356                 if ($user['action'] == 'D') {
0357                     $newMember = $this->deleteUserFromImportTable($user);
0358                 }
0359             }
0360             if ($newMember) {
0361                 $sql = "DELETE FROM H01.changes WHERE `table` = 'users' AND `action` = '" . $user['action'] . "' AND `id` = "
0362                     . $user['id'];
0363                 $stmt = $db->query($sql);
0364                 $stmt->execute();
0365             }
0366         }
0367 
0368         //Import users into member
0369         $this->importOcsMembers();
0370     }
0371 
0372     private function insertUpdateUserIntoImportTable($user)
0373     {
0374         $userTable = new Default_Model_DbTable_HiveUser();
0375         $updatearray = $user;
0376         $updatearray['is_imported'] = 0;
0377         $updatearray['import_error'] = '';
0378         unset($updatearray['action']);
0379 
0380         $member = $userTable->fetchRow('id = ' . $user['id']);
0381         if ($member) {
0382             $result = $userTable->update($updatearray, 'id = ' . $user['id']);
0383         } else {
0384             //save new user
0385             $result = $userTable->insert($updatearray);
0386         }
0387 
0388         return $result;
0389     }
0390 
0391     private function deleteUserFromImportTable($user)
0392     {
0393         return false;
0394     }
0395 
0396     private function importOcsMembers()
0397     {
0398         $hiveUserTable = new Default_Model_DbTable_HiveUser();
0399         $memberTable = new Default_Model_Member();
0400 
0401         $count = $hiveUserTable->fetchCountUsers();
0402         $import_counter = 0;
0403 
0404         $users = $hiveUserTable->fetchAllUsers(0, 100);
0405 
0406         $info = '';
0407 
0408         foreach ($users as $user) {
0409             $info .= " ## User: id = " . $user['id'] . ", name = " . $user['login'] . "  ";
0410             $start = microtime(true);
0411             $import_counter++;
0412             $member = $memberTable->fetchRow('source_id = 1 AND source_pk = ' . $user['id']);
0413 
0414             if ($member) {
0415                 $this->updateMember($user);
0416             } else {
0417                 $this->insertMember($user);
0418             }
0419             $time_elapsed_secs = microtime(true) - $start;
0420             $info .= $time_elapsed_secs . " secs";
0421             $info .= " - Done... ";
0422 
0423             //Mark user as imported
0424             $hiveUserTable->update(array("is_imported" => 1), "id = " . $user['id']);
0425         }
0426         echo $info;
0427     }
0428 
0429     private function updateMember($user)
0430     {
0431         $memberTable = new Default_Model_Member();
0432         $updatearray = $this->makeMemberFromHiveUser($user);
0433         unset($updatearray['roleId']);
0434 
0435         $member = $memberTable->fetchMemberFromHiveUserName($user['login']);
0436         $member_id = null;
0437         if ($member) {
0438             $member_id = $member['member_id'];
0439             $updatearray['member_id'] = $member_id;
0440             $memberTable->update($updatearray, 'member_id = ' . $member_id);
0441         } else {
0442             $member_id = $this->insertMember($user);
0443         }
0444 
0445         return $member_id;
0446     }
0447 
0448     private function makeMemberFromHiveUser($user)
0449     {
0450         $member = array();
0451         $member['source_id'] = 1;
0452         $member['source_pk'] = $user['id'];
0453         $member['username'] = $user['login'];
0454         $member['mail'] = $user['email'];
0455         $member['password'] = $user['passwd'];
0456         $member['roleId'] = 300;
0457         $member['type'] = 0;
0458         $member['is_active'] = 1;
0459         $member['is_deleted'] = 0;
0460         $member['mail_checked'] = 1;
0461         $member['agb'] = 1;
0462         $member['newsletter'] = $user['newsletter'];
0463         $member['login_method'] = 'local';
0464         $member['firstname'] = $user['firstname'];
0465         $member['lastname'] = $user['name'];
0466         $member['street'] = $user['street'];
0467         $member['zip'] = $user['zip'];
0468         $member['city'] = $user['city'];
0469         $member['country'] = $user['country_text'];
0470         $member['phone'] = $user['phonenumber'];
0471         $member['last_online'] = $user['last_online'];
0472         $member['biography'] = $user['description'];
0473         $member['paypal_mail'] = $user['paypalaccount'];
0474         //user pic
0475         $pic = $this->getHiveUserPicture($user['login'], $user['userdb']);
0476         if (empty($pic)) {
0477             $pic = 'hive/user-pics/nopic.png';
0478         }
0479         $member['profile_image_url'] = $pic;
0480         $member['profile_img_src'] = 'local';
0481 
0482         $member['validated'] = 0;
0483         $member['created_at'] = $user['created_at'];
0484         $member['changed_at'] = null;
0485 
0486         for ($i = 1; $i <= 10; $i++) {
0487             if (isset($user['homepage' . $i])) {
0488                 $link = $user['homepage' . $i];
0489                 $link_type = $user['homepagetype' . $i];
0490                 /**
0491                  * 0 = null
0492                  * 10 = Blog
0493                  * 20 = delicious
0494                  * 30 = Digg
0495                  * 40 = Facebook
0496                  * 50 = Homepage
0497                  * 60 = LinkedIn
0498                  * 70 = MySpace
0499                  * 80 = other
0500                  * 90 = Reddit
0501                  * 100 = YouTube
0502                  * 110 = Twitter
0503                  * 120 = Wikipedia
0504                  * 130 = Xing
0505                  * 140 = identi.ca
0506                  * 150 = libre.fm
0507                  * 160 = StackOverflow **/
0508                 if ($i == 1) {
0509                     $member['link_website'] = $user['homepage1'];
0510                 }
0511                 if ($link_type == 50) {
0512                     $member['link_website'] = $link;
0513                 } else {
0514                     if ($link_type == 40) {
0515                         $member['link_facebook'] = $link;
0516                     } else {
0517                         if ($link_type == 110) {
0518                             $member['link_twitter'] = $link;
0519                         } else {
0520                             if (!strpos($link, 'google.com/') === false) {
0521                                 $member['link_google'] = $link;
0522                             } else {
0523                                 if (!strpos($link, 'github.com/') === false) {
0524                                     $member['link_github'] = $link;
0525                                 }
0526                             }
0527                         }
0528                     }
0529                 }
0530             }
0531         }
0532 
0533         return $member;
0534     }
0535 
0536     private function getHiveUserPicture($username, $userdb)
0537     {
0538         $imageModel = new Default_Model_DbTable_Image();
0539         $path = 'https://cn.com/img/hive/user-bigpics/' . $userdb . '/' . $username . '.';
0540         $fileFolder = 'user-bigpics';
0541         $fileUrl = null;
0542         $fileExtention = null;
0543         if ($this->check_img($path . 'png')) {
0544             $fileUrl = ($path . 'png');
0545             $fileExtention = 'png';
0546         } else {
0547             if ($this->check_img($path . 'gif')) {
0548                 $fileUrl = ($path . 'gif');
0549                 $fileExtention = 'gif';
0550             } else {
0551                 if ($this->check_img($path . 'jpg')) {
0552                     $fileUrl = ($path . 'jpg');
0553                     $fileExtention = 'jpg';
0554                 } else {
0555                     if ($this->check_img($path . 'jpeg')) {
0556                         $fileUrl = ($path . 'jpeg');
0557                         $fileExtention = 'jpeg';
0558                     }
0559                 }
0560             }
0561         }
0562 
0563         if ($fileUrl == null) {
0564             $path = 'https://cn.com/img/hive/user-pics/' . $userdb . '/' . $username . '.';
0565             $fileFolder = 'user-pics';
0566             if ($this->check_img($path . 'png')) {
0567                 $fileUrl = ($path . 'png');
0568                 $fileExtention = 'png';
0569             } else {
0570                 if ($this->check_img($path . 'gif')) {
0571                     $fileUrl = ($path . 'gif');
0572                     $fileExtention = 'gif';
0573                 } else {
0574                     if ($this->check_img($path . 'jpg')) {
0575                         $fileUrl = ($path . 'jpg');
0576                         $fileExtention = 'jpg';
0577                     } else {
0578                         if ($this->check_img($path . 'jpeg')) {
0579                             $fileUrl = ($path . 'jpeg');
0580                             $fileExtention = 'jpeg';
0581                         }
0582                     }
0583                 }
0584             }
0585         }
0586 
0587         $cnFileUrl = null;
0588         if ($fileUrl != null) {
0589             $cnFileUrl = 'hive/' . $fileFolder . '/' . $userdb . '/' . $username . '.' . $fileExtention;
0590         }
0591 
0592         //var_dump($info);
0593         return $cnFileUrl;
0594     }
0595 
0596     private function check_img($file)
0597     {
0598         $response = false;
0599         $x = getimagesize($file);
0600 
0601         switch ($x['mime']) {
0602             case "image/gif":
0603                 $response = true;
0604                 break;
0605             case "image/jpeg":
0606                 $response = true;
0607                 break;
0608             case "image/png":
0609                 $response = true;
0610                 break;
0611             default:
0612                 $response = false;
0613                 break;
0614         }
0615 
0616         return $response;
0617     }
0618 
0619     private function insertMember($user)
0620     {
0621         $memberTable = new Default_Model_Member();
0622         $projectTable = new Default_Model_Project();
0623         $updatearray = $this->makeMemberFromHiveUser($user);
0624         //save member
0625         $member_id = $memberTable->insert($updatearray);
0626         $member = $memberTable->fetchMemberData($member_id);
0627         //save .me project
0628         $project = $this->makeProjectFromOcsUser($member);
0629         $project_id = $projectTable->insert($project);
0630 
0631         $updatearray = array();
0632         $updatearray['main_project_id'] = $project_id;
0633         $memberTable->update($updatearray, 'member_id = ' . $member_id);
0634 
0635         return $member_id;
0636     }
0637 
0638     private function makeProjectFromOcsUser($user)
0639     {
0640         $project = array();
0641         $project['source_id'] = 1;
0642         $project['source_pk'] = $user['member_id'];
0643         $project['source_type'] = 'user';
0644         $project['member_id'] = $user['member_id'];
0645         $project['content_type'] = 'text';
0646         $project['project_category_id'] = 0;
0647         $project['is_active'] = 1;
0648         $project['is_deleted'] = 0;
0649         $project['status'] = 100;
0650         $project['type_id'] = 0;
0651         $project['description'] = $user['biography'];
0652         $project['created_at'] = $user['created_at'];
0653         $project['changed_at'] = new Zend_Db_Expr('Now()');
0654 
0655         return $project;
0656     }
0657 
0658     private function syncDownloads()
0659     {
0660         $db = Zend_Db_Table::getDefaultAdapter();
0661 
0662         $sql = "SELECT ";
0663         $sql .= "   v.id,p.project_id as `project_id`,";
0664         $sql .= " v.downloads as count_downloads_hive";
0665         $sql .= " FROM H01.changes c";
0666         $sql .= " JOIN H01.content v ON c.id = v.id";
0667         $sql .= " join project p on p.source_id = 1 and p.source_type = 'project' and p.source_pk = c.id";
0668         $sql .= " WHERE c.table = 'downloads'";
0669         $sql .= " ORDER BY action,c.timestamp";
0670 
0671         $result = '';
0672 
0673         $stmt = $db->query($sql);
0674         $downloads = $stmt->fetchAll();
0675         echo '###################### Start DownloadsSync: ' . count($downloads) . ' downloads ';
0676 
0677         //Insert/Update users in table project_rating
0678         foreach ($downloads as $download) {
0679             $vote_id = $this->updateDownload($download);
0680             $sql = "DELETE FROM H01.changes WHERE `table` = 'downloads' AND `action` = 'U' AND `id` = " . $download['id'];
0681             $stmt = $db->query($sql);
0682             $stmt->execute();
0683         }
0684     }
0685 
0686     private function updateDownload($download)
0687     {
0688         $projectTable = new Default_Model_Project();
0689         $project = $projectTable->find($download['project_id'])->current();
0690 
0691         if ($project) {
0692             $project = $project->toArray();
0693             $project['count_downloads_hive'] = $download['count_downloads_hive'];
0694             $project = $projectTable->save($project);
0695         }
0696 
0697         if ($project) {
0698             return $project;
0699         } else {
0700             return false;
0701         }
0702     }
0703 
0704     private function deleteMember($user)
0705     {
0706         $memberTable = new Default_Model_Member();
0707         $member = $memberTable->fetchMemberFromHiveUserName($user['login']);
0708         $member_id = null;
0709         if ($member) {
0710             $member_id = $member['member_id'];
0711             $memberTable->setDeleted($member_id);
0712         }
0713 
0714         return true;
0715     }
0716 
0717     private function syncContent()
0718     {
0719         $db = Zend_Db_Table::getDefaultAdapter();
0720         $sql = "SELECT c.action,u.* FROM H01.changes c";
0721         $sql .= " JOIN H01.content u ON c.id = u.id";
0722         $sql .= " WHERE c.table = 'content'";
0723         $sql .= " ORDER BY action,created";
0724 
0725         $stmt = $db->query($sql);
0726         $contents = $stmt->fetchAll();
0727 
0728         echo '###################### Start ContentSync: ' . count($contents) . ' contents ';
0729 
0730         //Refresh files on ppload.com and cn.com
0731         $result = file_get_contents($this->_OCS_CN_FILE_SYNC_URL . '/sync.php');
0732         echo $result;
0733         $result = file_get_contents($this->_OCS_FILE_SYNC_URL . '/sync.php');
0734         echo $result;
0735 
0736         foreach ($contents as $content) {
0737             //Insert/Update users in table hive_users
0738             if ($content['action'] <> 'D') {
0739                 $newProject = $this->insertUpdateContentIntoImportTable($content);
0740             } else {
0741                 if ($content['action'] == 'D') {
0742                     $newProject = $this->deleteContentFromImportTable($content);
0743                 }
0744             }
0745             if ($newProject) {
0746                 $sql = "DELETE FROM H01.changes WHERE `table` = 'content' AND `action` = '" . $content['action'] . "' AND `id` = "
0747                     . $content['id'];
0748                 $stmt = $db->query($sql);
0749                 $stmt->execute();
0750             }
0751         }
0752 
0753         //Import content into project
0754         foreach ($this->hive_import_categories as $cat_id) {
0755             echo 'Start import cat: ' . $cat_id;
0756             $this->importOcsProjects($cat_id);
0757         }
0758     }
0759 
0760     private function insertUpdateContentIntoImportTable($content)
0761     {
0762         $contentTable = new Default_Model_DbTable_HiveContent();
0763         $updatearray = $content;
0764         $updatearray['is_imported'] = 0;
0765         $updatearray['import_error'] = '';
0766         unset($updatearray['action']);
0767 
0768         $project = $contentTable->fetchRow('id = ' . $content['id']);
0769         if ($project) {
0770             $newProject = $contentTable->update($updatearray, 'id = ' . $content['id']);
0771         } else {
0772             $newProject = $contentTable->insert($updatearray);
0773         }
0774 
0775         return $newProject;
0776     }
0777 
0778     private function importOcsProjects($cat_id, $importGalleryPics = true, $importFiles = true)
0779     {
0780 
0781         $_import_counter = 0;
0782         $_import_file_counter = 0;
0783         $_is_import_done = false;
0784         $info = '';
0785 
0786         $hiveCatTable = new Default_Model_DbTable_HiveContentCategory();
0787         $ocs_cat_id = $hiveCatTable->fetchOcsCategoryForHiveCategory($cat_id);
0788 
0789         if (!isset($ocs_cat_id)) {
0790             echo " - No ocs-Category found!";
0791             exit;
0792         }
0793 
0794         $startIndex = null;
0795         $limit = 100;
0796         $startIndex = 0;
0797 
0798         $result = array();
0799         $contentTable = new Default_Model_DbTable_HiveContent();
0800         $memberTable = new Default_Model_Member();
0801         $projectTable = new Default_Model_Project();
0802         try {
0803             $projects = $contentTable->fetchAllProjectsForCategory($cat_id, $startIndex, $limit, true);
0804 
0805             foreach ($projects as $project) {
0806                 $_import_counter++;
0807 
0808                 $info .= " ## Poject: id = " . $project['id'] . ", name = " . $project['name'] . "  ";
0809                 $start = microtime(true);
0810 
0811                 //1. Download/Upload Project-Picture
0812                 $cnFilePath = $this->getProjectPicture($project['id']);
0813 
0814                 //2. Create ocs Project
0815                 $projectId = null;
0816                 try {
0817                     $projectId = $this->createUpdateOcsProjects($project, $ocs_cat_id, $cnFilePath);
0818                 } catch (Exception $e) {
0819                     //Error: log error and go on
0820                     $error = array();
0821                     $error['import_error'] = $e;
0822                     $error['is_imported'] = 1;
0823                     $contentTable->update($error, 'id = ' . $project['id']);
0824                 }
0825 
0826                 if ($projectId) {
0827 
0828 
0829                     //3. Upload files
0830                     if ($importFiles) {
0831                         $pploadError = null;
0832                         $info .= " - Files ";
0833                         $start = microtime(true);
0834                         try {
0835                             $_import_file_counter = $this->uploadFilesAndLinks($project, $projectId);
0836                         } catch (Exception $e) {
0837                             $pploadError .= $e;
0838                             $info .= $pploadError;
0839                         }
0840                         $info .= " - Files Uploaded: " . $_import_file_counter . " -  ";
0841                         $time_elapsed_secs = microtime(true) - $start;
0842                         $info .= $time_elapsed_secs . " secs";
0843                     } else {
0844                         $_import_file_counter = 1;
0845                     }
0846 
0847                     if (true) {
0848 
0849                         //4. Gallery Pics
0850                         if ($importGalleryPics) {
0851 
0852                             $info .= " - Gallery Pics ";
0853                             $previewPicsArray = array();
0854                             if (!empty($project['preview1'])) {
0855                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 1, $project['preview1']);
0856                                 //add preview pic to ocs-project
0857                                 if (!empty($cnFilePathPre)) {
0858                                     $previewPicsArray[] = $cnFilePathPre;
0859                                     $info .= " - PreviewPic1 ";
0860                                 }
0861                             }
0862                             if (!empty($project['preview2'])) {
0863                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 2, $project['preview2']);
0864                                 if (!empty($cnFilePathPre)) {
0865                                     $previewPicsArray[] = $cnFilePathPre;
0866                                     $info .= " - PreviewPic2 ";
0867                                 }
0868                             }
0869                             if (!empty($project['preview3'])) {
0870                                 $cnFilePathPre = $this->getPreviewPicture($project['id'], 3, $project['preview3']);
0871                                 if (!empty($cnFilePathPre)) {
0872                                     $previewPicsArray[] = $cnFilePathPre;
0873                                     $info .= " - PreviewPic3 ";
0874                                 }
0875                             }
0876                             if (!empty($previewPicsArray)) {
0877                                 $projectTable->updateGalleryPictures($projectId, $previewPicsArray);
0878                             }
0879                         }
0880 
0881                         //5. Mark project as imported
0882                         $contentTable->update(array("is_imported" => 1), "id = " . $project['id']);
0883                     } else {
0884                         $info .= " - NO Files Uploaded";
0885                         $contentTable->update(array(
0886                             "is_imported"  => 1,
0887                             "import_error" => "Error on fileupload to cc.ppload.com Exception: " . $pploadError
0888                         ), "id = " . $project['id']);
0889                     }
0890                 } else {
0891                     $info .= " - Project NOT created! ";
0892                 }
0893 
0894                 $time_elapsed_secs = microtime(true) - $start;
0895                 $info .= $time_elapsed_secs . " secs";
0896                 $info .= " - Done... ";
0897             }
0898         } catch (Exception $e) {
0899             throw $e;
0900         }
0901         echo $info;
0902     }
0903 
0904     private function getProjectPicture($hiveProjectId)
0905     {
0906         $imageModel = new Default_Model_DbTable_Image();
0907         $path = 'https://cn.com/img/hive/content-pre1/' . $hiveProjectId . '-1.';
0908         $fileUrl = null;
0909         $fileExtention = null;
0910         $info = '';
0911 
0912         if ($this->check_img($path . 'gif')) {
0913             $fileUrl = ($path . 'gif');
0914             $fileExtention = 'gif';
0915         }
0916         if ($this->check_img($path . 'png')) {
0917             $fileUrl = ($path . 'png');
0918             $fileExtention = 'png';
0919         }
0920         if ($this->check_img($path . 'jpg')) {
0921             $fileUrl = ($path . 'jpg');
0922             $fileExtention = 'jpg';
0923         }
0924         if ($this->check_img($path . 'jpeg')) {
0925             $fileUrl = ($path . 'jpeg');
0926             $fileExtention = 'jpeg';
0927         }
0928         if ($this->check_img($path . 'mockup')) {
0929             $fileUrl = ($path . 'mockup');
0930             $fileExtention = 'mockup';
0931         }
0932         if ($this->check_img($path . 'GIF')) {
0933             $fileUrl = ($path . 'GIF');
0934             $fileExtention = 'GIF';
0935         }
0936         if ($this->check_img($path . 'PNG')) {
0937             $fileUrl = ($path . 'PNG');
0938             $fileExtention = 'PNG';
0939         }
0940         if ($this->check_img($path . 'JPG')) {
0941             $fileUrl = ($path . 'JPG');
0942             $fileExtention = 'JPG';
0943         }
0944         if ($this->check_img($path . 'JPEG')) {
0945             $fileUrl = ($path . 'JPEG');
0946             $fileExtention = 'JPEG';
0947         }
0948         if ($this->check_img($path . 'MOCKUP')) {
0949             $fileUrl = ($path . 'MOCKUP');
0950             $fileExtention = 'MOCKUP';
0951         }
0952         $cnFileUrl = null;
0953         if ($fileUrl != null) {
0954             $config = Zend_Registry::get('config');
0955             $cnFileUrl = '/hive/content-pre1/' . $hiveProjectId . '-1.' . $fileExtention;
0956 
0957             /**
0958              * //Workaround for gifs: don't use cache on cdn
0959              * $pos = strrpos($cnFileUrl, ".gif");
0960              * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
0961              * //gefunden ...
0962              * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
0963              * }
0964              **/
0965             $info .= "ImageUpload successfull: " . $cnFileUrl;
0966         } else {
0967             $path = 'https://cn.com/img/hive/content-pre2/' . $hiveProjectId . '-2.';
0968             $fileUrl = null;
0969             $fileExtention = null;
0970             $info = '';
0971 
0972             if ($this->check_img($path . 'gif')) {
0973                 $fileUrl = ($path . 'gif');
0974                 $fileExtention = 'gif';
0975             }
0976             if ($this->check_img($path . 'png')) {
0977                 $fileUrl = ($path . 'png');
0978                 $fileExtention = 'png';
0979             }
0980             if ($this->check_img($path . 'jpg')) {
0981                 $fileUrl = ($path . 'jpg');
0982                 $fileExtention = 'jpg';
0983             }
0984             if ($this->check_img($path . 'jpeg')) {
0985                 $fileUrl = ($path . 'jpeg');
0986                 $fileExtention = 'jpeg';
0987             }
0988             if ($this->check_img($path . 'mockup')) {
0989                 $fileUrl = ($path . 'mockup');
0990                 $fileExtention = 'mockup';
0991             }
0992             if ($this->check_img($path . 'GIF')) {
0993                 $fileUrl = ($path . 'GIF');
0994                 $fileExtention = 'GIF';
0995             }
0996             if ($this->check_img($path . 'PNG')) {
0997                 $fileUrl = ($path . 'PNG');
0998                 $fileExtention = 'PNG';
0999             }
1000             if ($this->check_img($path . 'JPG')) {
1001                 $fileUrl = ($path . 'JPG');
1002                 $fileExtention = 'JPG';
1003             }
1004             if ($this->check_img($path . 'JPEG')) {
1005                 $fileUrl = ($path . 'JPEG');
1006                 $fileExtention = 'JPEG';
1007             }
1008             if ($this->check_img($path . 'MOCKUP')) {
1009                 $fileUrl = ($path . 'MOCKUP');
1010                 $fileExtention = 'MOCKUP';
1011             }
1012             $cnFileUrl = null;
1013             if ($fileUrl != null) {
1014                 $config = Zend_Registry::get('config');
1015                 $cnFileUrl = '/hive/content-pre2/' . $hiveProjectId . '-2.' . $fileExtention;
1016 
1017                 /**
1018                  * //Workaround for gifs: don't use cache on cdn
1019                  * $pos = strrpos($cnFileUrl, ".gif");
1020                  * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
1021                  * //gefunden ...
1022                  * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
1023                  * }
1024                  **/
1025                 $info .= "ImageUpload successfull: " . $cnFileUrl;
1026             } else {
1027                 $path = 'https://cn.com/img/hive/content-pre3/' . $hiveProjectId . '-3.';
1028                 $fileUrl = null;
1029                 $fileExtention = null;
1030                 $info = '';
1031 
1032                 if ($this->check_img($path . 'gif')) {
1033                     $fileUrl = ($path . 'gif');
1034                     $fileExtention = 'gif';
1035                 }
1036                 if ($this->check_img($path . 'png')) {
1037                     $fileUrl = ($path . 'png');
1038                     $fileExtention = 'png';
1039                 }
1040                 if ($this->check_img($path . 'jpg')) {
1041                     $fileUrl = ($path . 'jpg');
1042                     $fileExtention = 'jpg';
1043                 }
1044                 if ($this->check_img($path . 'jpeg')) {
1045                     $fileUrl = ($path . 'jpeg');
1046                     $fileExtention = 'jpeg';
1047                 }
1048                 if ($this->check_img($path . 'mockup')) {
1049                     $fileUrl = ($path . 'mockup');
1050                     $fileExtention = 'mockup';
1051                 }
1052                 if ($this->check_img($path . 'GIF')) {
1053                     $fileUrl = ($path . 'GIF');
1054                     $fileExtention = 'GIF';
1055                 }
1056                 if ($this->check_img($path . 'PNG')) {
1057                     $fileUrl = ($path . 'PNG');
1058                     $fileExtention = 'PNG';
1059                 }
1060                 if ($this->check_img($path . 'JPG')) {
1061                     $fileUrl = ($path . 'JPG');
1062                     $fileExtention = 'JPG';
1063                 }
1064                 if ($this->check_img($path . 'JPEG')) {
1065                     $fileUrl = ($path . 'JPEG');
1066                     $fileExtention = 'JPEG';
1067                 }
1068                 if ($this->check_img($path . 'MOCKUP')) {
1069                     $fileUrl = ($path . 'MOCKUP');
1070                     $fileExtention = 'MOCKUP';
1071                 }
1072                 $cnFileUrl = null;
1073                 if ($fileUrl != null) {
1074                     $config = Zend_Registry::get('config');
1075                     $cnFileUrl = '/hive/content-pre3/' . $hiveProjectId . '-3.' . $fileExtention;
1076 
1077                     /**
1078                      * //Workaround for gifs: don't use cache on cdn
1079                      * $pos = strrpos($cnFileUrl, ".gif");
1080                      * if ($pos>0) { // Beachten sie die drei Gleichheitszeichen
1081                      * //gefunden ...
1082                      * $cnFileUrl = str_replace('/cache/120x96-2', '', $cnFileUrl);
1083                      * }
1084                      **/
1085                     $info .= "ImageUpload successfull: " . $cnFileUrl;
1086                 } else {
1087                     $info .= "No preview pic";
1088                 }
1089             }
1090         }
1091 
1092         var_dump($info);
1093 
1094         return $cnFileUrl;
1095     }
1096 
1097     private function createUpdateOcsProjects($project, $ocs_cat_id, $cnFilePath)
1098     {
1099         $projectTable = new Default_Model_Project();
1100         $memberTable = new Default_Model_Member();
1101         $info = '';
1102         $projectId = null;
1103         $uuid = null;
1104         $count_likes = null;
1105         $count_dislikes = null;
1106         try {
1107             $projectsResult = $projectTable->fetchAll("source_type = 'project' AND source_id = 1 AND source_pk = " . $project['id']);
1108             if (count($projectsResult) > 0) {
1109                 $info .= "Project load successfull: " . $projectsResult[0]['project_id'];
1110                 $projectId = $projectsResult[0]['project_id'];
1111                 $uuid = $projectsResult[0]['uuid'];
1112 
1113                 //delete old hive votings
1114                 $votingTable = new Default_Model_DbTable_ProjectRating();
1115                 $votingTable->delete('member_id = 0 AND project_id = ' . $projectId);
1116                 //insert the old hive votings
1117                 $votearray = array();
1118                 $votearray['member_id'] = 0;
1119                 $votearray['project_id'] = $projectId;
1120                 $votearray['user_like'] = $project['scoregood'];
1121                 $votearray['user_dislike'] = $project['scorebad'];
1122                 $newVote = $votingTable->save($votearray);
1123 
1124                 $ratingSum = $votingTable->fetchRating($projectId);
1125                 $count_likes = $ratingSum['count_likes'];
1126                 $count_dislikes = $ratingSum['count_dislikes'];
1127             } else {
1128                 $votingTable = new Default_Model_DbTable_ProjectRating();
1129                 //New project
1130                 $ratingSum = $votingTable->fetchRating($projectId);
1131                 $count_likes = $ratingSum['count_likes'];
1132                 $count_dislikes = $ratingSum['count_dislikes'];
1133             }
1134         } catch (Exception $e) {
1135             $info .= (__FUNCTION__ . '::ERROR load Project: ' . $e);
1136         }
1137 
1138         $memberId = null;
1139         try {
1140             $member = $memberTable->fetchMemberFromHiveUserName($project['user']);
1141             if ($member) {
1142                 $info .= "Member load successfull: " . $member['member_id'];
1143                 $memberId = $member['member_id'];
1144             } else {
1145                 throw new Exception(__FUNCTION__ . '::ERROR load member: Member not found: Username = ' . $project['user']);
1146             }
1147         } catch (Exception $e) {
1148             throw new Exception(__FUNCTION__ . '::ERROR load member: ' . $e);
1149         }
1150 
1151         $projectObj = array();
1152         $projectObj['member_id'] = $memberId;
1153         $projectObj['content_type'] = 'text';
1154         $projectObj['project_category_id'] = $ocs_cat_id;
1155         $projectObj['hive_category_id'] = $project['type'];
1156 
1157         //Project not deleted?
1158         if ($project['deletedat'] == 0 && $project['status'] == 1) {
1159             $projectObj['is_deleted'] = 0;
1160             $projectObj['deleted_at'] = $project['deleted_at'];
1161             $projectObj['is_active'] = 1;
1162             $projectObj['status'] = 100;
1163         } else {
1164             $projectObj['is_deleted'] = 1;
1165             $projectObj['deleted_at'] = $project['deleted_at'];
1166             $projectObj['is_active'] = 0;
1167             $projectObj['status'] = 30;
1168         }
1169 
1170         $projectObj['pid'] = null;
1171         $projectObj['type_id'] = 1;
1172         $projectObj['title'] = $project['name'];
1173         //$projectObj['description'] = $project['description'];
1174         $projectObj['description'] = $project['description_utf8'];
1175         $projectObj['version'] = $project['version'];
1176         $projectObj['image_big'] = $cnFilePath;
1177         $projectObj['image_small'] = $cnFilePath;
1178         $projectObj['start_date'] = null;
1179         $projectObj['content_url'] = null;
1180         $projectObj['created_at'] = $project['created_at'];
1181         $projectObj['changed_at'] = $project['changed_at'];
1182         $projectObj['creator_id'] = $memberId;
1183         $projectObj['count_likes'] = $count_likes;
1184         $projectObj['count_dislikes'] = $count_dislikes;
1185         $projectObj['count_downloads_hive'] = $project['downloads'];
1186 
1187         //      $projectObj['facebook_code'] = null;
1188         //      $projectObj['twitter_code'] = null;
1189         //      $projectObj['google_code'] = null;
1190         //      $projectObj['link_1'] = null;
1191         //      $projectObj['embed_code'] = null;
1192         //      $projectObj['ppload_collection_id'] = null;
1193         //      $projectObj['validated'] = null;
1194         //      $projectObj['validated_at'] = null;
1195         //      $projectObj['featured'] = null;
1196         //      $projectObj['amount'] = null;
1197         //      $projectObj['amount_period'] = null;
1198         //      $projectObj['claimable'] = null;
1199         //      $projectObj['claimed_by_member'] = null;
1200         $projectObj['source_id'] = 1;
1201         $projectObj['source_pk'] = $project['id'];
1202         $projectObj['source_type'] = 'project';
1203 
1204         if (!isset($uuid)) {
1205             $uuid = Local_Tools_UUID::generateUUID();
1206             $projectObj['uuid'] = $uuid;
1207         }
1208 
1209         if ($projectId) {
1210             try {
1211                 //update project
1212                 $updateCount = $projectTable->update($projectObj, "project_id = " . $projectId);
1213                 $info .= "Update Project successfull: Updated rows: " . $updateCount;
1214 
1215                 //update changelog?
1216                 if (isset($project['changelog']) && $project['changelog'] != '') {
1217                     $projectUpdatesTable = new Default_Model_ProjectUpdates();
1218                     $projectUpdate =
1219                         $projectUpdatesTable->fetchRow('project_id = ' . $projectId . ' AND source_id = 1 AND source_pk = '
1220                             . $project['id']);
1221                     if ($projectUpdate) {
1222                         $projectUpdate = $projectUpdate->toArray();
1223                         if ($projectUpdate['text'] != $project['changelog']) {
1224                             $projectUpdate['text'] = $project['changelog'];
1225                             $projectUpdate['changed_at'] = $projectObj['changed_at'];
1226                             $projectUpdatesTable->save($projectUpdate);
1227                         }
1228                     } else {
1229                         $data = array();
1230                         $data['project_id'] = $projectId;
1231                         $data['member_id'] = $projectObj['member_id'];
1232                         $data['public'] = 1;
1233                         $data['text'] = $project['changelog'];
1234                         $data['created_at'] = $projectObj['created_at'];
1235                         $data['changed_at'] = $projectObj['changed_at'];
1236                         $data['source_id'] = 1;
1237                         $data['source_pk'] = $project['id'];
1238 
1239                         $projectUpdatesTable->save($data);
1240                     }
1241                 }
1242             } catch (Exception $e) {
1243                 throw new Exception(__FUNCTION__ . '::ERROR update project: ' . $e);
1244             }
1245         } else {
1246             try {
1247                 //Create new project
1248                 $newProjectObj = $projectTable->save($projectObj);
1249                 $info .= "Create Project successfull: " . $newProjectObj['project_id'];
1250                 $projectId = $newProjectObj['project_id'];
1251 
1252                 //Add changelog
1253                 if (isset($project['changelog']) && $project['changelog'] != '') {
1254                     $projectUpdatesTable = new Default_Model_ProjectUpdates();
1255                     $data = array();
1256                     $data['project_id'] = $projectId;
1257                     $data['member_id'] = $projectObj['member_id'];
1258                     $data['public'] = 1;
1259                     $data['text'] = $project['changelog'];
1260                     $data['created_at'] = $projectObj['created_at'];
1261                     $data['changed_at'] = $projectObj['changed_at'];
1262                     $data['source_id'] = 1;
1263                     $data['source_pk'] = $project['id'];
1264 
1265                     $projectUpdatesTable->save($data);
1266                 }
1267 
1268                 //insert the old hive votings
1269                 $votearray = array();
1270                 $votearray['member_id'] = 0;
1271                 $votearray['project_id'] = $projectId;
1272                 $votearray['user_like'] = $count_likes;
1273                 $votearray['user_dislike'] = $count_dislikes;
1274                 $newVote = $votingTable->save($votearray);
1275 
1276                 if (null == $newProjectObj || null == $newProjectObj['project_id']) {
1277                     throw new Exception(__FUNCTION__ . '::ERROR save project: ' . implode(",", $newProjectObj));
1278                 }
1279             } catch (Exception $e) {
1280                 throw new Exception(__FUNCTION__ . '::ERROR save project: ' . $e);
1281             }
1282         }
1283 
1284         return $projectId;
1285     }
1286 
1287     private function uploadFilesAndLinks($project, $projectId)
1288     {
1289         $_import_file_counter = 0;
1290         //First real files
1291         $file1 = null;
1292         $info = '';
1293 
1294         //Clean up old collection data
1295         $pploadApi = new Ppload_Api(array(
1296             'apiUri'   => PPLOAD_API_URI,
1297             'clientId' => PPLOAD_CLIENT_ID,
1298             'secret'   => PPLOAD_SECRET
1299         ));
1300 
1301         $projectTable = new Default_Model_DbTable_Project();
1302         $projectData = $projectTable->find($projectId)->current();
1303         $oldFiles = array();
1304 
1305         if ($projectData->ppload_collection_id) {
1306             $param = array();
1307             $param['collection_id'] = $projectData->ppload_collection_id;
1308             $oldFiles = $pploadApi->getFiles($param);
1309 
1310             $pploadApi->deleteCollection($projectData->ppload_collection_id);
1311             $projectData->ppload_collection_id = null;
1312             $projectTable->save($projectData->toArray());
1313         }
1314 
1315         if ($project['downloadtyp1'] == 0) {
1316             //a real file
1317             $file1 = $project['download1'];
1318             //$file1 = str_replace(' ', '%20', $file1);
1319             $pploadError = null;
1320             if (!empty($file1)) {
1321                 try {
1322                     $downloadCounter = 0;
1323                     if (isset($oldFiles->files)) {
1324                         foreach ($oldFiles->files as $oldFile) {
1325                             $filename = $this->getFilenameFromUrl($this->_HIVE_BASE_URL . '/CONTENT/content-files/' . $file1);
1326                             var_dump('check file: ' . $oldFile->name . ' AND ' . $filename);
1327                             if ($oldFile->name == $filename) {
1328                                 $downloadCounter = $oldFile->downloaded_count;
1329                             }
1330                         }
1331                     }
1332 
1333                     //$uploadFileResult = $this->uploadFileToPpload($projectId, 'http://cp1.hive01.com/CONTENT/content-files/'.$file1);
1334                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname1'], $project['licensetype'],
1335                         base64_encode($project['license']), $downloadCounter,
1336                         $this->_HIVE_BASE_URL . '/CONTENT/content-files/' . $file1);
1337                     $info .= "Upload file successfull: " . $uploadFileResult;
1338                     if ($uploadFileResult == true) {
1339                         $_import_file_counter++;
1340                     } else {
1341                         throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $uploadFileResult);
1342                     }
1343                 } catch (Exception $e) {
1344                     throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
1345                 }
1346             }
1347         } else {
1348             //a link
1349             try {
1350                 $link1 = $project['downloadlink1'];
1351                 if ($link1 != 'http://' && !empty($link1)) {
1352                     $link1 = urlencode($link1);
1353                     $linkName1 = $project['downloadname1'];
1354                     if (empty($linkName1)) {
1355                         $linkName1 = "link";
1356                     }
1357                     $downloadCounter = 0;
1358                     //$uploadFileResult = $this->uploadFileToPpload($projectId, 'http://hive01.cc/CONTENT/content-files/link',$link1,$linkName1);
1359                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname1'], $project['licensetype'],
1360                         base64_encode($project['license']), 0, $this->_HIVE_BASE_URL . '/CONTENT/content-files/link', $link1,
1361                         $linkName1);
1362                     $info .= "Upload file successfull: " . $uploadFileResult;
1363                     if ($uploadFileResult == true) {
1364                         $_import_file_counter++;
1365                     }
1366                 }
1367             } catch (Exception $e) {
1368                 throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
1369             }
1370         }
1371 
1372         //Then links...
1373         for ($i = 2; $i <= 12; $i++) {
1374             try {
1375                 $link1 = $project['downloadlink' . $i];
1376                 if ($link1 != 'http://' && !empty($link1)) {
1377                     $link1 = urlencode($link1);
1378                     $linkName1 = $project['downloadname' . $i];
1379                     if (empty($linkName1)) {
1380                         $linkName1 = "link";
1381                     }
1382                     $downloadCounter = 0;
1383                     //$uploadFileResult = $this->uploadFileToPpload($projectId, 'http://hive01.cc/CONTENT/content-files/link',$link1,$linkName1);
1384                     $uploadFileResult = $this->saveFileInPpload($projectId, $project['downloadname' . $i], $project['licensetype'],
1385                         base64_encode($project['license']), 0, $this->_HIVE_BASE_URL . '/CONTENT/content-files/link', $link1,
1386                         $linkName1);
1387                     $info .= "Upload file successfull: " . $link1;
1388                     if ($uploadFileResult == true) {
1389                         $_import_file_counter++;
1390                     }
1391                 }
1392             } catch (Exception $e) {
1393                 //throw new Exception(__FUNCTION__ . '::ERROR Upload file: ' . $e);
1394             }
1395         }
1396 
1397         if ($_import_file_counter == 0) {
1398             return $info;
1399         }
1400 
1401         return $_import_file_counter;
1402     }
1403 
1404     private function getFilenameFromUrl($url)
1405     {
1406         $x = pathinfo($url);
1407         $fileName = $x['basename'];
1408 
1409         return $fileName;
1410     }
1411 
1412     private function saveFileInPpload(
1413         $projectId,
1414         $fileDescription,
1415         $licensetype,
1416         $license,
1417         $downloads,
1418         $fileUrl,
1419         $link = null,
1420         $linkName = null
1421     ) {
1422         $pploadInfo = "Start upload file " . $fileUrl . " for project " . $projectId;
1423 
1424         $projectTable = new Default_Model_DbTable_Project();
1425         $projectData = $projectTable->find($projectId)->current();
1426 
1427         if ($projectData) {
1428             $pploadInfo .= "Project found! ProjectId: " . $projectData->project_id . ", MemberId: " . $projectData->member_id;
1429         } else {
1430             $pploadInfo .= "ERROR::Project not found: " . $projectId;
1431             throw new Exception($pploadInfo);
1432 
1433             return false;
1434         }
1435 
1436         $filename = null;
1437         if (!empty($link)) {
1438             //take emtpy dummy file
1439             $filename = $this->getFilenameFromUrl($fileUrl);
1440             $tmpFilepath = "/hive/H01/CONTENT/content-files/link";
1441             $tmpFilename = $linkName;
1442         } else {
1443             //get file name
1444             $filename = $this->getFilenameFromUrl($fileUrl);
1445             $tmpFilepath = "/hive/H01/CONTENT/content-files/" . $filename;
1446             $tmpFilename = $filename;
1447             if (!empty($filename)) {
1448                 $pploadInfo .= "FileName found: " . $filename;
1449             } else {
1450                 $pploadInfo .= "ERROR::FileName not found: " . $filename;
1451                 throw new Exception($pploadInfo);
1452 
1453                 return false;
1454             }
1455         }
1456 
1457         $pploadApi = new Ppload_Api(array(
1458             'apiUri'   => PPLOAD_API_URI,
1459             'clientId' => PPLOAD_CLIENT_ID,
1460             'secret'   => PPLOAD_SECRET
1461         ));
1462 
1463         $fileRequest = array(
1464             'local_file_path' => $tmpFilepath,
1465             'local_file_name' => $tmpFilename,
1466             'owner_id'        => $projectData->member_id
1467         );
1468         if ($projectData->ppload_collection_id) {
1469             // Append to existing collection
1470             $fileRequest['collection_id'] = $projectData->ppload_collection_id;
1471         }
1472         if (!empty($fileDescription)) {
1473             $fileRequest['description'] = mb_substr($fileDescription, 0, 140);
1474         }
1475         if (!empty($downloads)) {
1476             $fileRequest['downloaded_count'] = $downloads;
1477         }
1478         $tags = '';
1479         if (!empty($link)) {
1480             $tags .= "link##" . $link . ',';
1481         }
1482         if (!empty($licensetype)) {
1483             $tags .= "licensetype-" . $licensetype . ',';
1484         }
1485         if (!empty($license)) {
1486             $tags .= "license##" . $license . ',';
1487         }
1488         if (!empty($tags)) {
1489             $fileRequest['tags'] = $tags;
1490         }
1491 
1492         //upload to ppload
1493         $fileResponse = $pploadApi->postFile($fileRequest);
1494 
1495         if (!empty($fileResponse)) {
1496             $pploadInfo .= "File uploaded to ppload! ";
1497         } else {
1498             $pploadInfo .= "ERROR::File NOT uploaded to ppload! Response: " . $fileResponse;
1499             throw new Exception($pploadInfo);
1500 
1501             return $pploadInfo;
1502         }
1503 
1504         //delete tmpFile
1505         //unlink($tmpFilename);
1506 
1507         //unlink($tmpFilename);
1508 
1509         if (!empty($fileResponse->file->collection_id)) {
1510             $pploadInfo .= "CollectionId: " . $fileResponse->file->collection_id;
1511             if (!$projectData->ppload_collection_id) {
1512                 // Save collection ID
1513                 $projectData->ppload_collection_id = $fileResponse->file->collection_id;
1514                 //$projectData->changed_at = new Zend_Db_Expr('NOW()');
1515                 $projectData->save();
1516 
1517                 // Update profile information
1518                 $memberTable = new Default_Model_DbTable_Member();
1519                 $memberSettings = $memberTable->find($projectData->member_id)->current();
1520                 $mainproject = $projectTable->find($memberSettings->main_project_id)->current();
1521                 $profileName = '';
1522                 if ($memberSettings->firstname
1523                     || $memberSettings->lastname) {
1524                     $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname);
1525                 } else {
1526                     if ($memberSettings->username) {
1527                         $profileName = $memberSettings->username;
1528                     }
1529                 }
1530                 $profileRequest = array(
1531                     'owner_id'    => $projectData->member_id,
1532                     'name'        => $profileName,
1533                     'email'       => $memberSettings->mail,
1534                     'homepage'    => $memberSettings->link_website,
1535                     'description' => $mainproject->description
1536                 );
1537                 $profileResponse = $pploadApi->postProfile($profileRequest);
1538                 // Update collection information
1539                 $collectionCategory = $projectData->project_category_id;
1540                 if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) {
1541                     $collectionCategory .= '-published';
1542                 }
1543                 $collectionRequest = array(
1544                     'title'       => $projectData->title,
1545                     'description' => $projectData->description,
1546                     'category'    => $collectionCategory
1547                 );
1548                 $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest);
1549                 // Store product image as collection thumbnail
1550                 $this->_updatePploadMediaCollectionthumbnail($projectData);
1551             }
1552 
1553             //return $fileResponse->file;
1554             return true;
1555         } else {
1556             //return false;
1557             $pploadInfo .= "ERROR::No CollectionId in ppload-file! Response Status: " . json_encode($fileResponse);
1558             throw new Exception($pploadInfo);
1559 
1560             return $pploadInfo;
1561         }
1562 
1563         return $pploadInfo;
1564     }
1565 
1566     private function _updatePploadMediaCollectionthumbnail($projectData)
1567     {
1568         if (empty($projectData->ppload_collection_id)
1569             || empty($projectData->image_small)) {
1570             return false;
1571         }
1572 
1573         $pploadApi = new Ppload_Api(array(
1574             'apiUri'   => PPLOAD_API_URI,
1575             'clientId' => PPLOAD_CLIENT_ID,
1576             'secret'   => PPLOAD_SECRET
1577         ));
1578 
1579         $filename = sys_get_temp_dir() . '/' . $projectData->image_small;
1580         if (false === file_exists(dirname($filename))) {
1581             mkdir(dirname($filename), 0777, true);
1582         }
1583         /**
1584          * $viewHelperImage = new Default_View_Helper_Image();
1585          * $uri = $viewHelperImage->Image(
1586          * $projectData->image_small,
1587          * array(
1588          * 'width' => 600,
1589          * 'height' => 600
1590          * )
1591          * );**/
1592         $uri = $this->_OCS_CN_FILE_SYNC_URL . '/cache/600x600/img' . $projectData->image_small;
1593 
1594         file_put_contents($filename, file_get_contents($uri));
1595 
1596         $mediaCollectionthumbnailResponse =
1597             $pploadApi->postMediaCollectionthumbnail($projectData->ppload_collection_id, array('file' => $filename));
1598 
1599         unlink($filename);
1600 
1601         if (isset($mediaCollectionthumbnailResponse->status)
1602             && $mediaCollectionthumbnailResponse->status == 'success') {
1603             return true;
1604         }
1605 
1606         return false;
1607     }
1608 
1609     private function getPreviewPicture($hiveProjectId, $previewNum, $hivePreviewFileExtension)
1610     {
1611         $imageModel = new Default_Model_DbTable_Image();
1612 
1613         $config = Zend_Registry::get('config');
1614 
1615         $fileName = $hiveProjectId . '-' . $previewNum . '.' . $hivePreviewFileExtension;
1616         $cnFileUrl = '/hive/content-pre' . $previewNum . '/' . $fileName;
1617 
1618         return $cnFileUrl;
1619     }
1620 
1621     private function file_get_contents_curl($url)
1622     {
1623         $ch = curl_init();
1624 
1625         curl_setopt($ch, CURLOPT_AUTOREFERER, true);
1626         curl_setopt($ch, CURLOPT_HEADER, 0);
1627         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1628         curl_setopt($ch, CURLOPT_URL, $url);
1629         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1630 
1631         $data = curl_exec($ch);
1632         curl_close($ch);
1633 
1634         return $data;
1635     }
1636 
1637 }