/** * Class Constructor * * @throws LogicException * */ public function __construct() { if (empty($this->review_order_page)) { throw new LogicException("Property 'review_order_page' can not be EMPTY"); } if (empty($this->tokenName)) { throw new LogicException("Property 'tokenName' can not be EMPTY"); } //SESSION ENABLED $this->sessionStart(); parent::__construct(false); $filterArgs = array($this->tokenName => array('filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH), $this->dataKeyName => array('filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)); $__getInput = filter_input_array(INPUT_GET, $filterArgs); /* * * Do something with Token ( send it for authentication on confirm ) * * $__getInput['tk'] * */ $this->tokenAuth = $__getInput[$this->tokenName]; $this->data_key_content = $__getInput[$this->dataKeyName]; Log::doLog($_GET); Log::doLog($_SERVER['QUERY_STRING']); }
function _TimeStampMsg($msg, $log = true) { if ($log) { Log::doLog($msg); } echo "[" . date(DATE_RFC822) . "] " . $msg . "\n"; }
public function doAction() { switch ($this->__postInput['exec']) { case 'stayAnonymous': unset($_SESSION['_anonym_pid']); unset($_SESSION['incomingUrl']); unset($_SESSION['_newProject']); break; case 'ping': $db = Database::obtain(); $db->query("SELECT 1"); $this->result['data'] = array("OK", time()); break; case 'checkTMKey': //get MyMemory apiKey service $tmxHandler = new TMSService(); $tmxHandler->setTmKey($this->__postInput['tm_key']); //validate the key try { $keyExists = $tmxHandler->checkCorrectKey(); } catch (Exception $e) { /* PROVIDED KEY IS NOT VALID OR WRONG, $keyExists IS NOT SET */ Log::doLog($e->getMessage()); } if (!isset($keyExists) || $keyExists === false) { $this->result['errors'][] = array("code" => -9, "message" => "TM key is not valid."); Log::doLog(__METHOD__ . " -> TM key is not valid."); $this->result['success'] = false; } else { $this->result['errors'] = array(); $this->result['success'] = true; } break; } }
static function uncompletedChunksByProjectId($id_project) { // for each project you can have several jobs, one per targert language. // for each job you can have one or more chunks. // jobs are identified by id_job and target language. // chunks are identified by id_job and password. // // translations have a reference to job, not to the chunk. // in order to associate the segment_translation to the chunk we need to // refer to the start and stop segment stored on the job. // // I would be great if we could have a chunk identifier on the segment_translation. // segments don't have a reference to the job neither, since they are linked to the file. // $query_most_recent_completion_events_for_chunk = " " . " SELECT * FROM ( " . " SELECT * FROM chunk_completion_events WHERE id_project = :id_project " . " ORDER BY create_date DESC ) t " . " GROUP BY id_project, id_job, password "; // This query should return no records, meaning all submitted events have // create_date greater than the chunk's latest translation date. $query_for_event_submitted_at_least_once = "SELECT ch.id_job, ch.password " . " FROM segment_translations st INNER JOIN " . "( {$query_most_recent_completion_events_for_chunk} ) ch ON " . " st.id_segment BETWEEN ch.job_first_segment AND ch.job_last_segment " . " AND st.id_job = ch.id_job AND ch.id_project = :id_project " . " AND ch.create_date < st.translation_date"; // This query should return no records, meaning all jobs have at least one // submitted chunk completion event. $query_to_return_unsubmitted_chunks = "SELECT jobs.id as id_job, jobs.password " . " FROM jobs LEFT JOIN chunk_completion_events ch ON " . " jobs.id = ch.id_job AND " . " jobs.password = ch.password AND " . " jobs.job_first_segment = ch.job_first_segment AND " . " jobs.job_last_segment = ch.job_last_segment AND " . " jobs.id_project = ch.id_project " . " WHERE jobs.id_project = :id_project " . " AND ch.id IS NULL "; $union_query = "SELECT * FROM ( {$query_to_return_unsubmitted_chunks} " . " UNION ALL {$query_for_event_submitted_at_least_once} ) t1 " . " GROUP BY id_job, password "; $query_to_return_chunks = "SELECT * from jobs INNER JOIN ( {$union_query} ) filtered " . " ON jobs.id = filtered.id_job AND jobs.password = filtered.password "; $conn = Database::obtain()->getConnection(); Log::doLog($query_to_return_chunks); $stmt = $conn->prepare($query_to_return_chunks); $stmt->execute(array('id_project' => $id_project)); $stmt->setFetchMode(PDO::FETCH_CLASS, 'Chunks_ChunkStruct'); return $stmt->fetchAll(); }
public function status() { // TODO: move this in to a json presenter class $uncompleted = Projects_ProjectDao::uncompletedChunksByProjectId($this->request->id_project); $is_completed = count($uncompleted) == 0; $id_project = $this->request->id_project; $response = array(); $response = array('id' => $id_project); try { if ($is_completed) { $jobs = $this->validator->getProject()->getJobs(); $response['jobs'] = array(); foreach ($jobs as $job) { $response['jobs'][] = array('id' => $job->id, 'password' => $job->password, 'download_url' => INIT::$HTTPHOST . "/?action=downloadFile" . "&id_job=" . $job->id . "&password=" . $job->password); } $response['completed'] = true; } else { $response['completed'] = false; $response['chunks'] = array(); foreach ($uncompleted as $chunk) { $response['chunks'][] = array('id' => $chunk->id, 'password' => $chunk->password); } } $this->response->json(array('project_status' => $response)); } catch (Exception $e) { Log::doLog($e->getMessage()); // TODO handle 500 response code here } }
/** * Call the output in JSON format * */ public function finalize() { $toJson = json_encode($this->result); if (function_exists("json_last_error")) { switch (json_last_error()) { case JSON_ERROR_NONE: // Log::doLog(' - No errors'); break; case JSON_ERROR_DEPTH: Log::doLog(' - Maximum stack depth exceeded'); break; case JSON_ERROR_STATE_MISMATCH: Log::doLog(' - Underflow or the modes mismatch'); break; case JSON_ERROR_CTRL_CHAR: Log::doLog(' - Unexpected control character found'); break; case JSON_ERROR_SYNTAX: Log::doLog(' - Syntax error, malformed JSON'); break; case JSON_ERROR_UTF8: Log::doLog(' - Malformed UTF-8 characters, possibly incorrectly encoded'); break; default: Log::doLog(' - Unknown error'); break; } } echo $toJson; }
/** * When Called it perform the controller action to retrieve/manipulate data * * @return mixed */ function doAction() { if (count($this->errors) > 0) { return null; } //get job language and data //Fixed Bug: need a specific job, because we need The target Language //Removed from within the foreach cycle, the job is always the same... $jobData = $this->jobInfo = getJobData($this->jobID, $this->jobPass); $pCheck = new AjaxPasswordCheck(); //check for Password correctness if (empty($jobData) || !$pCheck->grantJobAccessByJobData($jobData, $this->jobPass)) { $msg = "Error : wrong password provided for download \n\n " . var_export($_POST, true) . "\n"; Log::doLog($msg); Utils::sendErrMailReport($msg); return null; } $projectData = getProject($jobData['id_project']); $source = $jobData['source']; $target = $jobData['target']; $tmsService = new TMSService(); /** * @var $tmx SplTempFileObject */ $this->tmx = $tmsService->exportJobAsTMX($this->jobID, $this->jobPass, $source, $target); $this->fileName = $projectData[0]['name'] . "-" . $this->jobID . ".tmx"; }
public function __construct() { parent::__construct(); $filterArgs = array( 'id' => array( 'filter' => FILTER_SANITIZE_NUMBER_INT ), 'id_job' => array( 'filter' => FILTER_SANITIZE_NUMBER_INT ), 'src_content' => array( 'filter' => FILTER_UNSAFE_RAW ), 'trg_content' => array( 'filter' => FILTER_UNSAFE_RAW ), 'password' => array( 'filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH ), 'token' => array( 'filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW ), 'logs' => array( 'filter' => FILTER_UNSAFE_RAW), 'glossaryList' => array( 'filter' => FILTER_CALLBACK, 'options' => array('self','filterString') ) ); $this->__postInput = (object)filter_input_array( INPUT_POST, $filterArgs ); if( !empty( $this->__postInput->logs ) && $this->__postInput->logs != '[]' ){ Log::$fileName = 'clientLog.log'; Log::doLog( json_decode( $this->__postInput->logs ) ); Log::$fileName = 'log.txt'; } }
/** * @param $msg */ protected function _logMsg($msg) { // \INIT::$DEBUG = false; if (\INIT::$DEBUG) { echo "[" . date(DATE_RFC822) . "] " . $msg . "\n"; } \Log::doLog($msg); }
/** * When Called it perform the controller action to retrieve/manipulate data * * @return mixed */ function doAction() { try { $this->_checkData("auto_propagation.log"); } catch (Exception $e) { if ($e->getCode() == -1) { Utils::sendErrMailReport($e->getMessage()); } Log::doLog($e->getMessage()); return $e->getCode(); } $cookie_key = '_auto-propagation-' . $this->id_job . "-" . $this->password; $boolString = (string) (int) $this->propagateAll; $cookieLife = new DateTime(); $cookieLife->modify('+15 days'); $db = Database::obtain(); if ($this->propagateAll) { $db->begin(); $old_translation = getCurrentTranslation($this->id_job, $this->id_segment); //check tag mismatch //get original source segment, first $segment = getSegment($this->id_segment); //compare segment-translation and get results $check = new QA($segment['segment'], $this->translation); $check->performConsistencyCheck(); if ($check->thereAreWarnings()) { $err_json = $check->getWarningsJSON(); $translation = $this->translation; } else { $err_json = ''; $translation = $check->getTrgNormalized(); } $TPropagation = array(); $TPropagation['id_job'] = $this->id_job; $TPropagation['translation'] = $translation; $TPropagation['status'] = Constants_TranslationStatus::STATUS_DRAFT; $TPropagation['autopropagated_from'] = $this->id_segment; $_Translation['serialized_errors_list'] = $err_json; $TPropagation['warning'] = $check->thereAreWarnings(); $TPropagation['translation_date'] = date("Y-m-d H:i:s"); $TPropagation['segment_hash'] = $old_translation['segment_hash']; try { propagateTranslation($TPropagation, $this->jobData, $this->id_segment, true); $db->commit(); } catch (Exception $e) { $db->rollback(); $msg = $e->getMessage() . "\n\n" . $e->getTraceAsString(); Log::doLog($msg); Utils::sendErrMailReport($msg); } } setcookie($cookie_key, $boolString, $cookieLife->getTimestamp(), "/", $_SERVER['HTTP_HOST']); Log::doLog("Auto-propagation for already translated segments on Job " . $this->id_job . " set to '" . var_export($this->propagateAll, true) . "'. Cookie Expire at " . $cookieLife->format('Y-m-d H:i:s')); $this->result['errors'][] = array("code" => 0, "message" => "OK"); }
public function doAction() { if (empty($this->segment)) { $this->result['errors'][] = array("code" => -1, "message" => "missing source segment"); } if (empty($this->translation)) { $this->result['errors'][] = array("code" => -2, "message" => "missing target translation"); } if (empty($this->source_lang)) { $this->result['errors'][] = array("code" => -3, "message" => "missing source lang"); } if (empty($this->target_lang)) { $this->result['errors'][] = array("code" => -4, "message" => "missing target lang"); } if (empty($this->time_to_edit)) { $this->result['errors'][] = array("code" => -5, "message" => "missing time to edit"); } if (empty($this->id_segment)) { $this->result['errors'][] = array("code" => -6, "message" => "missing segment id"); } //get Job Infos, we need only a row of jobs ( split ) $job_data = getJobData((int) $this->id_job, $this->password); $pCheck = new AjaxPasswordCheck(); //check for Password correctness if (empty($job_data) || !$pCheck->grantJobAccessByJobData($job_data, $this->password)) { $this->result['errors'][] = array("code" => -10, "message" => "wrong password"); $msg = "\n\n Error \n\n " . var_export(array_merge($this->result, $_POST), true); Log::doLog($msg); Utils::sendErrMailReport($msg); return; } //mt engine to contribute to if ($job_data['id_mt_engine'] <= 1) { return false; } $this->mt = Engine::getInstance($job_data['id_mt_engine']); //array of storicised suggestions for current segment $this->suggestion_json_array = json_decode(getArrayOfSuggestionsJSON($this->id_segment), true); //extra parameters $extra = json_encode(array('id_segment' => $this->id_segment, 'suggestion_json_array' => $this->suggestion_json_array, 'chosen_suggestion_index' => $this->chosen_suggestion_index, 'time_to_edit' => $this->time_to_edit)); //send stuff $config = $this->mt->getConfigStruct(); $config['segment'] = CatUtils::view2rawxliff($this->segment); $config['translation'] = CatUtils::view2rawxliff($this->translation); $config['source'] = $this->source_lang; $config['target'] = $this->target_lang; $config['email'] = INIT::$MYMEMORY_API_KEY; $config['segid'] = $this->id_segment; $config['extra'] = $extra; $config['id_user'] = array("TESTKEY"); $outcome = $this->mt->set($config); if ($outcome->error->code < 0) { $this->result['errors'] = $outcome->error->get_as_array(); } }
public function lastTranslationByJobOrChunk($chunk) { $conn = Database::obtain()->getConnection(); $query = "SELECT * FROM segment_translations " . " WHERE id_job = :id_job " . " AND segment_translations.id_segment BETWEEN :job_first_segment AND :job_last_segment " . " ORDER BY translation_date DESC " . " LIMIT 1 "; Log::doLog($query); $stmt = $conn->prepare($query); $array = array('id_job' => $chunk->id, 'job_first_segment' => $chunk->job_first_segment, 'job_last_segment' => $chunk->job_last_segment); $stmt->execute($array); $stmt->setFetchMode(PDO::FETCH_CLASS, 'Translations_SegmentTranslationStruct'); return $stmt->fetch(); }
/** * * @return bool */ public static function thereIsAMisconfiguration() { try { $redisHandler = new Predis\Client(INIT::$REDIS_SERVERS); return INIT::$VOLUME_ANALYSIS_ENABLED && !Analysis_Manager::fastAnalysisIsRunning($redisHandler) && !Analysis_Manager::tmAnalysisIsRunning($redisHandler); } catch (Exception $ex) { $msg = "****** No REDIS instances found. ******"; Log::doLog($msg); return false; } }
public function getThreadContributorUids($input) { $obj = $this->sanitize($input); $query = "SELECT DISTINCT(uid) FROM " . self::TABLE . " WHERE id_job = {$obj->id_job} " . " AND id_segment = {$obj->id_segment} " . " AND uid IS NOT NULL "; if ($input->uid) { $query .= " AND uid <> {$obj->uid} "; } Log::doLog($query); $this->con->query($query); $arr_result = $this->_fetch_array($query); return $arr_result; }
public function __construct($response) { $this->responseData = isset($response['responseData']) ? $response['responseData'] : ''; $this->responseStatus = isset($response['responseStatus']) ? $response['responseStatus'] : ''; if ($this->responseStatus == 200 || $this->responseStatus == 202) { if (!isset($this->responseData['tm'])) { //TMX IMPORT STATUS CARRIES A LIST and not a single element, skip the id assignment $this->id = $this->responseData['id']; } } else { Log::doLog($response); } }
function testSubmitsProject() { $this->params = array('project_name' => 'foo', 'target_lang' => 'it', 'source_lang' => 'en', 'private_tm_key' => 'f05960431f879c750f48'); // $this->files[] = test_file_path('amex-test.docx.xlf'); $this->files[] = test_file_path('xliff/amex-test.docx.xlf'); $response = $this->getResponse(); $response = json_decode($response['body']); Log::doLog($response); $this->assertEquals('Success', $response->message); $this->assertEquals('OK', $response->status); $this->assertNotNull($response->id_project); $this->assertNotNull($response->project_pass); }
public static function sigSwitch($signo) { Log::doLog("Signo : {$signo}"); static::_TimeStampMsg("Signo : {$signo}" . "\n"); switch ($signo) { case SIGTERM: case SIGINT: case SIGHUP: static::$RUNNING = false; break; default: break; } }
/** * When Called it perform the controller action to retrieve/manipulate data * * @return void */ function doAction() { //if some error occured, stop execution. if (count(@$this->result['errors'])) { return; } try { $tmService = new TMSService(); $tmService->setTmKey($this->key); //validate the key try { $keyExists = $tmService->checkCorrectKey(); } catch (Exception $e) { /* PROVIDED KEY IS NOT VALID OR WRONG, $keyExists IS NOT SET */ Log::doLog($e->getMessage()); } if (!isset($keyExists) || $keyExists === false) { Log::doLog(__METHOD__ . " -> TM key is not valid."); throw new Exception("TM key is not valid.", -4); } $tmKeyStruct = new TmKeyManagement_TmKeyStruct(); $tmKeyStruct->key = $this->key; $tmKeyStruct->name = $this->description; $tmKeyStruct->tm = true; $tmKeyStruct->glos = true; $mkDao = new TmKeyManagement_MemoryKeyDao(Database::obtain()); $memoryKeyToUpdate = new TmKeyManagement_MemoryKeyStruct(); $memoryKeyToUpdate->uid = $this->uid; $memoryKeyToUpdate->tm_key = $tmKeyStruct; switch ($this->exec) { case 'delete': $userMemoryKeys = $mkDao->disable($memoryKeyToUpdate); break; case 'update': $userMemoryKeys = $mkDao->update($memoryKeyToUpdate); break; case 'newKey': $userMemoryKeys = $mkDao->create($memoryKeyToUpdate); break; default: throw new Exception("Unexpected Exception", -4); } if (!$userMemoryKeys) { throw new Exception("This key wasn't found in your keyring.", -3); } } catch (Exception $e) { $this->result['data'] = 'KO'; $this->result['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage()); } }
public function getByUids($uids_array) { $sanitized_array = array(); foreach ($uids_array as $k => $v) { array_push($sanitized_array, (int) $v['uid']); } if (empty($sanitized_array)) { return array(); } $query = "SELECT * FROM " . self::TABLE . " WHERE uid IN ( " . implode(', ', $sanitized_array) . " ) "; Log::doLog($query); $arr_result = $this->con->fetch_array($query); return $this->_buildResult($arr_result); }
protected function validateRequest() { // TODO: move this query somewhere else $pdo = PDOConnection::connectINIT(); // TODO this is pre PDO in Database::obtain(), change it. $stmt = $pdo->connection->prepare('SELECT id FROM jobs WHERE id = :id_job AND password = :password'); Log::doLog($this->auth_param); $stmt->bindValue(':id_job', $this->request->id_job); $stmt->bindValue(':password', $this->auth_param); $stmt->execute(); $result = $stmt->fetch(); if ($result[0]['id'] != (int) $this->request->id_job) { $this->response->code(403); $this->response->json(array('error' => 'Authentication failed')); } }
/** * When Called it perform the controller action to retrieve/manipulate data * * @return mixed */ function doAction() { $_project_data = getProjectJobData($this->id_project); $pCheck = new AjaxPasswordCheck(); $access = $pCheck->grantProjectAccess($_project_data, $this->password); //check for Password correctness if (!$access) { $msg = "Error : wrong password provided for download \n\n " . var_export($_POST, true) . "\n"; Log::doLog($msg); Utils::sendErrMailReport($msg); return null; } $analysisStatus = new Analysis_XTRFStatus($_project_data); $outputContent = $analysisStatus->fetchData()->getResult(); $this->content = $this->composeZip($_project_data[0]['pname'], $outputContent); $this->_filename = $_project_data[0]['pname'] . ".zip"; }
public function doAction() { switch ($this->__postInput['exec']) { case 'stayAnonymous': unset($_SESSION['_anonym_pid']); unset($_SESSION['incomingUrl']); unset($_SESSION['_newProject']); break; case 'ping': $db = Database::obtain(); $db->query("SELECT 1"); $this->result['data'] = array("OK", time()); break; case 'checkTMKey': //get MyMemory apiKey service $tmxHandler = new TMSService(); $tmxHandler->setTmKey($this->__postInput['tm_key']); //validate the key try { $keyExists = $tmxHandler->checkCorrectKey(); } catch (Exception $e) { /* PROVIDED KEY IS NOT VALID OR WRONG, $keyExists IS NOT SET */ Log::doLog($e->getMessage()); } if (!isset($keyExists) || $keyExists === false) { $this->result['errors'][] = array("code" => -9, "message" => "TM key is not valid."); Log::doLog(__METHOD__ . " -> TM key is not valid."); $this->result['success'] = false; } else { $this->result['errors'] = array(); $this->result['success'] = true; } break; case 'clearNotCompletedUploads': try { Utils::deleteDir(INIT::$UPLOAD_REPOSITORY . '/' . $_COOKIE['upload_session'] . '/'); } catch (Exception $e) { Log::doLog("ajaxUtils::clearNotCompletedUploads : " . $e->getMessage()); } setcookie("upload_session", null, -1, '/'); unset($_COOKIE['upload_session']); break; } }
public function __construct() { parent::__construct(); $filterArgs = array('id' => array('filter' => FILTER_SANITIZE_NUMBER_INT), 'id_job' => array('filter' => FILTER_SANITIZE_NUMBER_INT), 'src_content' => array('filter' => FILTER_UNSAFE_RAW), 'trg_content' => array('filter' => FILTER_UNSAFE_RAW), 'password' => array('filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH), 'token' => array('filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW), 'logs' => array('filter' => FILTER_UNSAFE_RAW), 'glossaryList' => array('filter' => FILTER_CALLBACK, 'options' => array('self', 'filterString')), 'segment_status' => array('filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)); $this->__postInput = (object) filter_input_array(INPUT_POST, $filterArgs); /** * Update 2015/08/11, roberto@translated.net * getWarning needs the segment status too because of a bug: * sometimes the client calls getWarning and sends an empty trg_content * because the suggestion has not been loaded yet. * This happens only if segment is in status NEW */ if (empty($this->__postInput->segment_status)) { $this->__postInput->segment_status = 'draft'; } if (!empty($this->__postInput->logs) && $this->__postInput->logs != '[]') { Log::$fileName = 'clientLog.log'; Log::doLog(json_decode($this->__postInput->logs)); Log::$fileName = 'log.txt'; } }
public function doAction() { if (!empty($this->result['errors'])) { return; } //save the 2 arrays in the DB $translationStruct = TranslationsSplit_SplitStruct::getStruct(); $translationStruct->id_segment = $this->id_segment; $translationStruct->id_job = $this->id_job; list($this->segment, $translationStruct->source_chunk_lengths) = CatUtils::parseSegmentSplit(CatUtils::view2rawxliff($this->segment)); /* Fill the statuses with DEFAULT DRAFT VALUES */ $pieces = count($translationStruct->source_chunk_lengths) > 1 ? count($translationStruct->source_chunk_lengths) - 1 : 1; $translationStruct->target_chunk_lengths = array('len' => array(0), 'statuses' => array_fill(0, $pieces, Constants_TranslationStatus::STATUS_DRAFT)); $translationDao = new TranslationsSplit_SplitDAO(Database::obtain()); $result = $translationDao->update($translationStruct); if ($result instanceof TranslationsSplit_SplitStruct) { //return success $this->result['data'] = 'OK'; } else { Log::doLog("Failed while splitting/merging segment."); Log::doLog($translationStruct); } }
/** * @brief 解析当前的url并且分发到webroot下面支持channel/module/action */ public function parseURL() { $paths = array(); // 解析URL if (!empty($_SERVER['PATH_INFO'])) { $paths = explode('/', trim($_SERVER['PATH_INFO'], '/')); } else { $paths = array(Convention::DEFAULT_CHANNEL, Convention::DEFAULT_MODULE, Convention::DEFAULT_ACTION); } //判断执行channel,module,action $paths[0] = isset($paths[0]) ? $paths[0] : Convention::DEFAULT_CHANNEL; $paths[1] = isset($paths[1]) ? $paths[1] : Convention::DEFAULT_MODULE; $paths[2] = isset($paths[2]) ? $paths[2] : Convention::DEFAULT_ACTION; if (!isset($paths[0]) || !file_exists(WEBROOT . '/' . $paths[0] . '/' . $paths[1] . '.php')) { $paths = array(Convention::DEFAULT_ERROR_CHANNEL, Convention::DEFAULT_MODULE, Convention::DEFAULT_ACTION); } define('CHANNEL_NAME', $paths[0]); define('MODULE_NAME', $paths[1]); define('ACTION_NAME', $paths[2]); require WEBROOT . '/' . $paths[0] . '/' . $paths[1] . '.php'; //处理log Log::doLog(); }
public function deliver() { $mail = new PHPMailer(); $mail->IsSMTP(); $mail->Host = INIT::$SMTP_HOST; $mail->Port = INIT::$SMTP_PORT; $mail->Sender = INIT::$SMTP_SENDER; $mail->Hostname = INIT::$SMTP_HOSTNAME; $mail->From = INIT::$SMTP_SENDER; $mail->FromName = INIT::$MAILER_FROM_NAME; $mail->ReturnPath = INIT::$MAILER_RETURN_PATH; $mail->AddReplyTo($mail->ReturnPath, $mail->FromName); $mail->Subject = $this->buildSubject(); $mail->Body = $this->buildHTMLMessage(); $mail->AltBody = $this->buildTextMessage(); $mail->MsgHTML($mail->Body); $mail->XMailer = 'Translated Mailer'; $mail->CharSet = 'UTF-8'; $mail->IsHTML(); $mail->AddAddress($this->user->email, $this->user->first_name); $mail->Send(); Log::doLog('email sent'); }
function main($args) { $db = Database::obtain(); do { //TODO: create DAO for this $today = date("Y-m-d"); $queryJobs = "SELECT\n source,\n target,\n sum( total_time_to_edit ) as total_time_to_edit,\n sum(translated_words) + sum(approved_words) + sum(rejected_words) as total_words,\n sum( COALESCE (avg_post_editing_effort, 0) ) as total_post_editing_effort,\n count(*) as job_count\n FROM\n jobs j\n WHERE\n completed = 1\n AND source = '%s'\n GROUP BY target"; $queryInsert = "INSERT into language_stats\n (date, source, target, total_word_count, total_post_editing_effort, total_time_to_edit, job_count)\n VALUES %s\n ON DUPLICATE KEY UPDATE\n total_post_editing_effort = values( total_post_editing_effort ),\n total_time_to_edit = values( total_time_to_edit ),\n job_count = values( job_count )"; $updateTuplesTemplate = "( '%s', '%s', '%s', %f, %f, %f, %u )"; $langsObj = Langs_Languages::getInstance(); //getlanguage list $languages = $langsObj->getEnabledLanguages(); $languages = Utils::array_column($languages, 'code'); foreach ($languages as $source_language) { Log::doLog("Current source_language: {$source_language}"); echo "Current source_language: {$source_language}\n"; $languageStats = $db->fetch_array(sprintf($queryJobs, $source_language)); $languageTuples = array(); foreach ($languageStats as $languageCoupleStat) { Log::doLog("Current language couple: " . $source_language . "-" . $languageCoupleStat['target']); echo "Current language couple: " . $source_language . "-" . $languageCoupleStat['target'] . "\n"; $languageTuples[] = sprintf($updateTuplesTemplate, $today, $languageCoupleStat['source'], $languageCoupleStat['target'], round($languageCoupleStat['total_words'], 4), round($languageCoupleStat['total_post_editing_effort'], 4), round($languageCoupleStat['total_time_to_edit'], 4), $languageCoupleStat['job_count']); } if (count($languageTuples) > 0) { Log::doLog("Found some stats. Saving in DB.."); echo "Found some stats. Saving in DB..\n"; $db->query(sprintf($queryInsert, implode(", ", $languageTuples))); } usleep(100); } //for the moment, this daemon is single-loop-execution self::$RUNNING = false; if (self::$RUNNING) { sleep(self::$sleeptime); } } while (self::$RUNNING); }
/** * * @throws Exception */ protected function __construct() { if (!class_exists('Memcache', false)) { throw new Exception('Class Memcache not Found. php5-memcache may not be installed.'); } self::$_Connection = new Memcache(); foreach (self::$_MemCachePool as $_host => $weight) { list($host, $port) = explode(":", $_host); self::$_Connection->addServer($host, $port, true, $weight); } $results = @self::$_Connection->getExtendedStats(); foreach ($results as $__host => $_stats) { if (empty($_stats)) { list($host, $port) = explode(":", $__host); self::$_Connection->setServerParams($host, $port, 1, -1, false); Log::doLog("Server {$host}:{$port} down, not available."); unset(self::$_MemCachePool[$__host]); } } if (empty(self::$_MemCachePool)) { throw new Exception('No Memcached servers available. All down.'); } register_shutdown_function('MemcacheHandler::close'); }
protected function _insertPreTranslations($jid) { // Log::doLog( array_shift( array_chunk( $SegmentTranslations, 5, true ) ) ); foreach ($this->projectStructure['translations'] as $internal_id => $struct) { if (empty($struct)) { // Log::doLog( $internal_id . " : " . var_export( $struct, true ) ); continue; } //id_segment, id_job, segment_hash, status, translation, translation_date, tm_analysis_status, locked $this->projectStructure['query_translations']->append("( '{$struct[0]}', {$jid}, '{$struct[3]}', 'TRANSLATED', '{$struct[2]}', NOW(), 'DONE', 1, 'ICE' )"); } // Executing the Query if (!empty($this->projectStructure['query_translations'])) { $baseQuery = "INSERT INTO segment_translations (id_segment, id_job, segment_hash, status, translation, translation_date, tm_analysis_status, locked, match_type )\n values "; Log::doLog("Pre-Translations: Total Rows to insert: " . count($this->projectStructure['query_translations'])); //split the query in to chunks if there are too much segments $this->projectStructure['query_translations']->exchangeArray(array_chunk($this->projectStructure['query_translations']->getArrayCopy(), 200)); Log::doLog("Pre-Translations: Total Queries to execute: " . count($this->projectStructure['query_translations'])); // Log::doLog( print_r( $this->projectStructure['translations'],true ) ); foreach ($this->projectStructure['query_translations'] as $i => $chunk) { $this->dbHandler->query($baseQuery . join(",\n", $chunk)); Log::doLog("Pre-Translations: Executed Query " . ($i + 1)); if ($this->dbHandler->get_error_number()) { Log::doLog("Segment import - DB Error: " . mysql_error() . " - \n"); throw new Exception("Translations Segment import - DB Error: " . mysql_error() . " - {$chunk}", -2); } } } //clean translations and queries $this->projectStructure['query_translations']->exchangeArray(array()); $this->projectStructure['translations']->exchangeArray(array()); }
/** * Checks for MyMemory Api Key correctness * * Filter Validate returns true/false for correct/not correct key and NULL is returned for all non-boolean values. ( 404, html, etc. ) * * @param $apiKey * * @return bool|null * @throws Exception */ public function checkCorrectKey($apiKey) { $postFields = array('key' => trim($apiKey)); //query db // $this->doQuery( 'api_key_check_auth', $postFields ); $this->call('api_key_check_auth_url', $postFields); if (!$this->result->responseStatus == 200) { Log::doLog("Error: The check for MyMemory private key correctness failed: " . $this->result['error']['message'] . " ErrNum: " . $this->result['error']['code']); throw new Exception("Error: The private TM key you entered ( {$apiKey} ) seems to be invalid. Please, check that the key is correct.", -2); } $isValidKey = filter_var($this->result->responseData, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($isValidKey === null) { throw new Exception("Error: The private TM key you entered seems to be invalid: {$apiKey}", -3); } return $isValidKey; }