Exemple #1
0
 /**
  * @param $id
  *
  * @return Engines_EngineInterface
  * @throws Exception
  */
 public static function getInstance($id)
 {
     if (is_null($id) || $id == '') {
         throw new Exception("Missing id engineRecord", -1);
     }
     $engineDAO = new EnginesModel_EngineDAO(Database::obtain());
     $engineStruct = EnginesModel_EngineStruct::getStruct();
     $engineStruct->id = $id;
     $eng = $engineDAO->setCacheTTL(60 * 5)->read($engineStruct);
     /**
      * @var $engineRecord EnginesModel_EngineStruct
      */
     $engineRecord = @$eng[0];
     if (empty($engineRecord)) {
         throw new Exception("Engine {$id} not found", -2);
     }
     $className = 'Engines_' . $engineRecord->class_load;
     return new $className($engineRecord);
 }
 /**
  * This method deletes an engine from a user's keyring
  */
 private function disable()
 {
     if (empty($this->id)) {
         $this->result['errors'][] = array('code' => -5, 'message' => "Engine id required");
         return;
     }
     $engineToBeDeleted = EnginesModel_EngineStruct::getStruct();
     $engineToBeDeleted->id = $this->id;
     $engineToBeDeleted->uid = $this->uid;
     $engineDAO = new EnginesModel_EngineDAO(Database::obtain());
     $result = $engineDAO->disable($engineToBeDeleted);
     if (!$result instanceof EnginesModel_EngineStruct) {
         $this->result['errors'][] = array('code' => -9, 'message' => "Deletion failed. Generic error");
         return;
     }
     $this->result['data']['id'] = $result->id;
 }
Exemple #3
0
 public function doAction()
 {
     $files_found = array();
     $lang_handler = Langs_Languages::getInstance();
     $data = getSegmentsInfo($this->jid, $this->password);
     if (empty($data) or $data < 0) {
         $this->job_not_found = true;
         //stop execution
         return;
     }
     //retrieve job owner. It will be useful also if the job is archived or cancelled
     $this->job_owner = $data[0]['job_owner'] != "" ? $data[0]['job_owner'] : "*****@*****.**";
     if ($data[0]['status'] == Constants_JobStatus::STATUS_CANCELLED) {
         $this->job_cancelled = true;
         //stop execution
         return;
     }
     if ($data[0]['status'] == Constants_JobStatus::STATUS_ARCHIVED) {
         $this->job_archived = true;
         //stop execution
         return;
     }
     /*
      * I prefer to use a programmatic approach to the check for the archive date instead of a pure query
      * because the query to check "Utils::getArchivableJobs($this->jid)" should be
      * executed every time a job is loaded ( F5 or CTRL+R on browser ) and it cost some milliseconds ( ~0.1s )
      * and it is little heavy for the database.
      * We use the data we already have from last query and perform
      * the check on the last translation only if the job is older than 30 days
      *
      */
     $lastUpdate = new DateTime($data[0]['last_update']);
     $oneMonthAgo = new DateTime();
     $oneMonthAgo->modify('-' . INIT::JOB_ARCHIVABILITY_THRESHOLD . ' days');
     if ($lastUpdate < $oneMonthAgo && !$this->job_cancelled) {
         $lastTranslationInJob = new Datetime(getLastTranslationDate($this->jid));
         if ($lastTranslationInJob < $oneMonthAgo) {
             $res = "job";
             $new_status = Constants_JobStatus::STATUS_ARCHIVED;
             updateJobsStatus($res, $this->jid, $new_status, null, null, $this->password);
             $this->job_archived = true;
         }
     }
     foreach ($data as $i => $job) {
         $this->project_status = $job;
         // get one row values for the project are the same for every row
         if (empty($this->pname)) {
             $this->pname = $job['pname'];
             $this->downloadFileName = $job['pname'] . ".zip";
             // will be overwritten below in case of one file job
         }
         if (empty($this->last_opened_segment)) {
             $this->last_opened_segment = $job['last_opened_segment'];
         }
         if (empty($this->cid)) {
             $this->cid = $job['cid'];
         }
         if (empty($this->pid)) {
             $this->pid = $job['pid'];
         }
         if (empty($this->create_date)) {
             $this->create_date = $job['create_date'];
         }
         if (empty($this->source_code)) {
             $this->source_code = $job['source'];
         }
         if (empty($this->target_code)) {
             $this->target_code = $job['target'];
         }
         if (empty($this->source)) {
             $s = explode("-", $job['source']);
             $source = strtoupper($s[0]);
             $this->source = $source;
             $this->source_rtl = $lang_handler->isRTL(strtolower($this->source)) ? ' rtl-source' : '';
         }
         if (empty($this->target)) {
             $t = explode("-", $job['target']);
             $target = strtoupper($t[0]);
             $this->target = $target;
             $this->target_rtl = $lang_handler->isRTL(strtolower($this->target)) ? ' rtl-target' : '';
         }
         //check if language belongs to supported right-to-left languages
         if ($job['status'] == Constants_JobStatus::STATUS_ARCHIVED) {
             $this->job_archived = true;
             $this->job_owner = $data[0]['job_owner'];
         }
         $id_file = $job['id_file'];
         if (!isset($this->data["{$id_file}"])) {
             $files_found[] = $job['filename'];
         }
         $wStruct = new WordCount_Struct();
         $wStruct->setIdJob($this->jid);
         $wStruct->setJobPassword($this->password);
         $wStruct->setNewWords($job['new_words']);
         $wStruct->setDraftWords($job['draft_words']);
         $wStruct->setTranslatedWords($job['translated_words']);
         $wStruct->setApprovedWords($job['approved_words']);
         $wStruct->setRejectedWords($job['rejected_words']);
         unset($job['id_file']);
         unset($job['source']);
         unset($job['target']);
         unset($job['source_code']);
         unset($job['target_code']);
         unset($job['mime_type']);
         unset($job['filename']);
         unset($job['jid']);
         unset($job['pid']);
         unset($job['cid']);
         unset($job['tid']);
         unset($job['pname']);
         unset($job['create_date']);
         unset($job['owner']);
         unset($job['last_opened_segment']);
         unset($job['new_words']);
         unset($job['draft_words']);
         unset($job['translated_words']);
         unset($job['approved_words']);
         unset($job['rejected_words']);
         //For projects created with No tm analysis enabled
         if ($wStruct->getTotal() == 0 && ($job['status_analysis'] == Constants_ProjectStatus::STATUS_DONE || $job['status_analysis'] == Constants_ProjectStatus::STATUS_NOT_TO_ANALYZE)) {
             $wCounter = new WordCount_Counter();
             $wStruct = $wCounter->initializeJobWordCount($this->jid, $this->password);
             Log::doLog("BackWard compatibility set Counter.");
         }
         $this->job_stats = CatUtils::getFastStatsForJob($wStruct);
     }
     //Needed because a just created job has last_opened segment NULL
     if (empty($this->last_opened_segment)) {
         $this->last_opened_segment = getFirstSegmentId($this->jid, $this->password);
     }
     $this->first_job_segment = $this->project_status['job_first_segment'];
     $this->last_job_segment = $this->project_status['job_last_segment'];
     if (count($files_found) == 1) {
         $this->downloadFileName = $files_found[0];
     }
     /**
      * get first segment of every file
      */
     $fileInfo = getFirstSegmentOfFilesInJob($this->jid);
     $TotalPayable = array();
     foreach ($fileInfo as &$file) {
         $file['file_name'] = ZipArchiveExtended::getFileName($file['file_name']);
         $TotalPayable[$file['id_file']]['TOTAL_FORMATTED'] = $file['TOTAL_FORMATTED'];
     }
     $this->firstSegmentOfFiles = json_encode($fileInfo);
     $this->fileCounter = json_encode($TotalPayable);
     list($uid, $user_email) = $this->getLoginUserParams();
     if (self::isRevision()) {
         $this->userRole = TmKeyManagement_Filter::ROLE_REVISOR;
     } elseif ($user_email == $data[0]['job_owner']) {
         $this->userRole = TmKeyManagement_Filter::OWNER;
     } else {
         $this->userRole = TmKeyManagement_Filter::ROLE_TRANSLATOR;
     }
     /*
      * Take the keys of the user
      */
     try {
         $_keyList = new TmKeyManagement_MemoryKeyDao(Database::obtain());
         $dh = new TmKeyManagement_MemoryKeyStruct(array('uid' => $uid));
         $keyList = $_keyList->read($dh);
     } catch (Exception $e) {
         $keyList = array();
         Log::doLog($e->getMessage());
     }
     $reverse_lookup_user_personal_keys = array('pos' => array(), 'elements' => array());
     /**
      * Set these keys as editable for the client
      *
      * @var $keyList TmKeyManagement_MemoryKeyStruct[]
      */
     foreach ($keyList as $_j => $key) {
         /**
          * @var $_client_tm_key TmKeyManagement_TmKeyStruct
          */
         //create a reverse lookup
         $reverse_lookup_user_personal_keys['pos'][$_j] = $key->tm_key->key;
         $reverse_lookup_user_personal_keys['elements'][$_j] = $key;
         $this->_keyList['totals'][$_j] = new TmKeyManagement_ClientTmKeyStruct($key->tm_key);
     }
     /*
      * Now take the JOB keys
      */
     $job_keyList = json_decode($data[0]['tm_keys'], true);
     $this->tid = count($job_keyList) > 0;
     /**
      * Start this N^2 cycle from keys of the job,
      * these should be statistically lesser than the keys of the user
      *
      * @var $keyList array
      */
     foreach ($job_keyList as $jobKey) {
         $jobKey = new TmKeyManagement_ClientTmKeyStruct($jobKey);
         if ($this->isLoggedIn() && count($reverse_lookup_user_personal_keys['pos'])) {
             /*
              * If user has some personal keys, check for the job keys if they are present, and obfuscate
              * when they are not
              */
             $_index_position = array_search($jobKey->key, $reverse_lookup_user_personal_keys['pos']);
             if ($_index_position !== false) {
                 //i found a key in the job that is present in my database
                 //i'm owner?? and the key is an owner type key?
                 if (!$jobKey->owner && $this->userRole != TmKeyManagement_Filter::OWNER) {
                     $jobKey->r = $jobKey->{TmKeyManagement_Filter::$GRANTS_MAP[$this->userRole]['r']};
                     $jobKey->w = $jobKey->{TmKeyManagement_Filter::$GRANTS_MAP[$this->userRole]['w']};
                     $jobKey = $jobKey->hideKey($uid);
                 } else {
                     if ($jobKey->owner && $this->userRole != TmKeyManagement_Filter::OWNER) {
                         // I'm not the job owner, but i know the key because it is in my keyring
                         // so, i can upload and download TMX, but i don't want it to be removed from job
                         // in tm.html relaxed the control to "key.edit" to enable buttons
                         //                            $jobKey = $jobKey->hideKey( $uid ); // enable editing
                     } else {
                         if ($jobKey->owner && $this->userRole == TmKeyManagement_Filter::OWNER) {
                             //do Nothing
                         }
                     }
                 }
                 unset($this->_keyList['totals'][$_index_position]);
             } else {
                 /*
                  * This is not a key of that user, set right and obfuscate
                  */
                 $jobKey->r = true;
                 $jobKey->w = true;
                 $jobKey = $jobKey->hideKey(-1);
             }
             $this->_keyList['job_keys'][] = $jobKey;
         } else {
             /*
              * This user is anonymous or it has no keys in its keyring, obfuscate all
              */
             $jobKey->r = true;
             $jobKey->w = true;
             $this->_keyList['job_keys'][] = $jobKey->hideKey(-1);
         }
     }
     //clean unordered keys
     $this->_keyList['totals'] = array_values($this->_keyList['totals']);
     /**
      * Retrieve information about job errors
      * ( Note: these information are fed by the revision process )
      * @see setRevisionController
      */
     $jobQA = new Revise_JobQA($this->jid, $this->password, $wStruct->getTotal());
     $jobQA->retrieveJobErrorTotals();
     $jobVote = $jobQA->evalJobVote();
     $this->qa_data = json_encode($jobQA->getQaData());
     $this->qa_overall = $jobVote['minText'];
     $engine = new EnginesModel_EngineDAO(Database::obtain());
     //this gets all engines of the user
     if ($this->isLoggedIn()) {
         $engineQuery = new EnginesModel_EngineStruct();
         $engineQuery->type = 'MT';
         $engineQuery->uid = $uid;
         $engineQuery->active = 1;
         $mt_engines = $engine->read($engineQuery);
     } else {
         $mt_engines = array();
     }
     // this gets MyMemory
     $engineQuery = new EnginesModel_EngineStruct();
     $engineQuery->type = 'TM';
     $engineQuery->active = 1;
     $tms_engine = $engine->setCacheTTL(3600 * 24 * 30)->read($engineQuery);
     //this gets MT engine active for the job
     $engineQuery = new EnginesModel_EngineStruct();
     $engineQuery->id = $this->project_status['id_mt_engine'];
     $engineQuery->active = 1;
     $active_mt_engine = $engine->setCacheTTL(60 * 10)->read($engineQuery);
     /*
      * array_unique cast EnginesModel_EngineStruct to string
      *
      * EnginesModel_EngineStruct implements __toString method
      *
      */
     $this->translation_engines = array_unique(array_merge($active_mt_engine, $tms_engine, $mt_engines));
 }
 public function doAction()
 {
     //Get the guid from the guid if it exists, otherwise set the guid into the cookie
     if (!isset($_COOKIE['upload_session'])) {
         setcookie("upload_session", $this->guid, time() + 86400);
     } else {
         $this->guid = $_COOKIE['upload_session'];
     }
     if (isset($_COOKIE["sourceLang"]) and $_COOKIE["sourceLang"] == "_EMPTY_") {
         $this->noSourceLangHistory = true;
     } else {
         if (!isset($_COOKIE['sourceLang'])) {
             setcookie("sourceLang", "_EMPTY_", time() + 86400 * 365);
             $this->noSourceLangHistory = true;
         } else {
             if ($_COOKIE["sourceLang"] != "_EMPTY_") {
                 $this->noSourceLangHistory = false;
                 $this->sourceLangHistory = $_COOKIE["sourceLang"];
                 $this->sourceLangAr = explode('||', urldecode($this->sourceLangHistory));
                 $tmpSourceAr = array();
                 $tmpSourceArAs = array();
                 foreach ($this->sourceLangAr as $key => $lang) {
                     if ($lang != '') {
                         $tmpSourceAr[$lang] = $this->lang_handler->getLocalizedName($lang);
                         $ar = array();
                         $ar['name'] = $this->lang_handler->getLocalizedName($lang);
                         $ar['code'] = $lang;
                         $ar['selected'] = $key == '0' ? 1 : 0;
                         $ar['direction'] = $this->lang_handler->isRTL(strtolower($lang)) ? 'rtl' : 'ltr';
                         array_push($tmpSourceArAs, $ar);
                     }
                 }
                 $this->sourceLangAr = $tmpSourceAr;
                 asort($this->sourceLangAr);
                 $this->array_sort_by_column($tmpSourceArAs, 'name');
                 $this->sourceLangArray = $tmpSourceArAs;
             }
         }
     }
     if (isset($_COOKIE["targetLang"]) and $_COOKIE["targetLang"] == "_EMPTY_") {
         $this->noTargetLangHistory = true;
     } else {
         if (!isset($_COOKIE['targetLang'])) {
             setcookie("targetLang", "_EMPTY_", time() + 86400 * 365);
             $this->noTargetLangHistory = true;
         } else {
             if ($_COOKIE["targetLang"] != "_EMPTY_") {
                 $this->noTargetLangHistory = false;
                 $this->targetLangHistory = $_COOKIE["targetLang"];
                 $this->targetLangAr = explode('||', urldecode($this->targetLangHistory));
                 $tmpTargetAr = array();
                 $tmpTargetArAs = array();
                 foreach ($this->targetLangAr as $key => $lang) {
                     if ($lang != '') {
                         $prova = explode(',', urldecode($lang));
                         $cl = "";
                         foreach ($prova as $ll) {
                             $cl .= $this->lang_handler->getLocalizedName($ll) . ',';
                         }
                         $cl = substr_replace($cl, "", -1);
                         $tmpTargetAr[$lang] = $cl;
                         //					$tmpTargetAr[$lang] = $this->lang_handler->getLocalizedName($lang,'en');
                         $ar = array();
                         $ar['name'] = $cl;
                         $ar['direction'] = $this->lang_handler->isRTL(strtolower($lang)) ? 'rtl' : 'ltr';
                         $ar['code'] = $lang;
                         $ar['selected'] = $key == '0' ? 1 : 0;
                         array_push($tmpTargetArAs, $ar);
                     }
                 }
                 $this->targetLangAr = $tmpTargetAr;
                 asort($this->targetLangAr);
                 $this->array_sort_by_column($tmpTargetArAs, 'name');
                 $this->targetLangArray = $tmpTargetArAs;
             }
         }
     }
     $intDir = INIT::$UPLOAD_REPOSITORY . '/' . $this->guid . '/';
     if (!is_dir($intDir)) {
         mkdir($intDir, 0775, true);
     }
     // check if user is logged and generate authURL for logging in
     $this->doAuth();
     $this->generateAuthURL();
     list($uid, $cid) = $this->getLoginUserParams();
     $engine = new EnginesModel_EngineDAO(Database::obtain());
     $engineQuery = new EnginesModel_EngineStruct();
     $engineQuery->type = 'MT';
     if (@(bool) $_GET['amt'] == true) {
         $engineQuery->uid = 'all';
     } else {
         $engineQuery->uid = $uid == null ? -1 : $uid;
     }
     $engineQuery->active = 1;
     $this->mt_engines = $engine->read($engineQuery);
     if ($this->isLoggedIn()) {
         try {
             $_keyList = new TmKeyManagement_MemoryKeyDao(Database::obtain());
             $dh = new TmKeyManagement_MemoryKeyStruct(array('uid' => @$_SESSION['uid']));
             $keyList = $_keyList->read($dh);
             foreach ($keyList as $memKey) {
                 //all keys are available in this condition ( we are creating a project
                 $this->keyList[] = $memKey->tm_key;
             }
         } catch (Exception $e) {
             Log::doLog($e->getMessage());
         }
     }
 }
Exemple #5
0
 /**
  * Check for time to live and refresh cache and token info
  *
  * @return mixed
  * @throws Exception
  */
 protected function _authenticate()
 {
     $parameters = array();
     $parameters['client_id'] = $this->client_id;
     $parameters['client_secret'] = $this->client_secret;
     /**
      * Hardcoded params, from documentation
      * @see https://msdn.microsoft.com/en-us/library/hh454950.aspx
      */
     $parameters['grant_type'] = "client_credentials";
     $parameters['scope'] = "http://api.microsofttranslator.com";
     $url = $this->oauth_url;
     $curl_opt = array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($parameters), CURLOPT_TIMEOUT => 120);
     $rawValue = $this->_call($url, $curl_opt);
     $objResponse = json_decode($rawValue, true);
     if (isset($objResponse['error'])) {
         //format as a normal Translate Response and send to decoder to output the data
         $rawValue = sprintf($this->rawXmlErrStruct, $objResponse['error'], 'getToken', $objResponse['error_description']);
         $this->result = $this->_decode($rawValue, $parameters);
         throw new Exception($objResponse['error_description']);
     } else {
         $this->token = $objResponse['access_token'];
         /**
          * Gain a minute to not fallback into a recursion
          *
          * @see Engines_MicrosoftHub::get
          */
         $this->token_endlife = time() + $objResponse['expires_in'] - 60;
     }
     $record = clone $this->engineRecord;
     $engineDAO = new EnginesModel_EngineDAO(Database::obtain());
     /**
      * Use a generic Engine and not Engine_MicrosoftHubStruct
      * because the Engine Factory Class built the query as generic engine
      *
      */
     $engineStruct = EnginesModel_MicrosoftHubStruct::getStruct();
     $engineStruct->id = $record->id;
     //variable assignment only used for debugging purpose
     $debugParam = $engineDAO->destroyCache($engineStruct);
     $engineDAO->update($record);
 }