function flash_cmd($socket, $buf) { $objXML = new xml2Array(); $command = $objXML->parse($buf); if ($command === false) { system_class::log_message('ERROR: is not valid xml'); return; } if ($command['where'] == 'policy-file-request') { system_class::log_message('policy request'); $fl = new flash_class(); $xml = $fl->security_police(); system_class::log_message("REQ= {$xml} "); if (socket_write($socket, "{$xml}") === FALSE) { system_class::log_message("ERROR writing to sinta: " . socket_strerror(socket_last_error())); } } elseif (strpos($command['value'], 'BUTTON') !== false) { //sintako beste pantaie idatzi beharrekoa echo "sinta_controller.php : Button pressed " . $this->changed_socket . "\n"; //$xml='<sinta sarr="'.$command['value'].'"/>'; //$this->client_reply($socket, $command['value']); } elseif (strpos($command['value'], 'PLC') !== false) { $this->noFlashSocket($socket); $cmd = split(':', $command["value"]); AccesoControladoresDispositivos::$ctrlAutomata->procesarComandoSala($cmd[1]); } else { //AMAIARI AGINDUA //system_class::log_message("Command:: ".print_r($command,1)); ConexionServidorCliente::procesarComandoPantalla($command["value"]); system_class::log_message("\nCommand:: -------------------------FIN-----------\n\n"); } }
function gateway_hsbc($seperator, $sessionid) { global $wpdb; $purchase_log_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1"; $purchase_log = $wpdb->get_row($purchase_log_sql, ARRAY_A); $total_price = $purchase_log['totalprice'] * 100; $card_no = $_POST['card_number']; $cvv = $_POST['card_code']; $expiry = $_POST['expiry']['month'] . "/" . substr($_POST['expiry']['year'], 2); $xml = "<EngineDocList>\n\t\t\t\t<DocVersion DataType='String'>1.0</DocVersion>\n\t\t\t\t<EngineDoc>\n\t\t\t\t\t<ContentType DataType='String'>OrderFormDoc</ContentType>\n\t\t\t\t\t<User>\n\t\t\t\t\t\t<Name DataType='String'>" . get_option('hsbc_username') . "</Name>\n\t\t\t\t\t\t<Password DataType='String'>" . get_option('hsbc_password') . "</Password>\n\t\t\t\t\t\t<ClientId DataType='S32'>" . get_option('hsbc_id') . "</ClientId>\n\t\t\t\t\t</User>\n\t\t\t\t\t<Instructions>\n\t\t\t\t\t\t<Pipeline DataType='String'>Payment</Pipeline>\n\t\t\t\t\t</Instructions>\n\t\t\t\t\t<OrderFormDoc>\n\t\t\t\t\t\t<Mode DataType='String'>Y</Mode>\n\t\t\t\t\t\t<Consumer>\n\t\t\t\t\t\t\t<PaymentMech>\n\t\t\t\t\t\t\t\t<Type DataType='String'>CreditCard</Type>\n\t\t\t\t\t\t\t\t<CreditCard>\n\t\t\t\t\t\t\t\t\t<Number DataType='String'>" . $card_no . "</Number>\n\t\t\t\t\t\t\t\t\t<Cvv2Val DataType='String'>" . $cvv . "</Cvv2Val>\n\t\t\t\t\t\t\t\t\t<Cvv2Indicator DataType='String'>1</Cvv2Indicator>\n\t\t\t\t\t\t\t\t\t<Expires DataType='ExpirationDate'>" . $expiry . "</Expires>\n\t\t\t\t\t\t\t\t</CreditCard>\n\t\t\t\t\t\t\t</PaymentMech>\n\t\t\t\t\t\t</Consumer>\n\t\t\t\t\t\t<Transaction>\n\t\t\t\t\t\t\t<Type DataType='String'>Auth</Type>\n\t\t\t\t\t\t\t<CurrentTotals>\n\t\t\t\t\t\t\t\t<Totals>\n\t\t\t\t\t\t\t\t\t<Total DataType='Money' Currency='" . get_option('hsbc_currency') . "'>" . $total_price . "</Total>\n\t\t\t\t\t\t\t\t</Totals>\n\t\t\t\t\t\t\t</CurrentTotals>\n\t\t\t\t\t\t</Transaction>\n\t\t\t\t\t</OrderFormDoc>\n\t\t\t\t</EngineDoc>\n\t\t\t</EngineDocList>"; $ch = curl_init(); $url = 'https://www.uat.apixml.netq.hsbc.com/'; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); $data = curl_exec($ch); curl_close($ch); $xml2Array = new xml2Array(); $parsed = $xml2Array->Parse($data); $response_code = $parsed[0]['children'][1]['children'][4]['children'][6]['children'][1]['children'][2]['tagData']; $response_code = 0; $transact_url = get_option('transact_url'); if ($response_code == 1) { //Approved $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '2' WHERE `sessionid` = " . $sessionid . " LIMIT 1"); } //Something bad happened. header("Location: " . $transact_url . $seperator . "sessionid=" . $sessionid); exit; }
function Xml2Json($xml_data) { $xml2Array = new xml2Array(); $xml = $xml2Array->parse($xml_data); $json = array(); for ($i = 0, $c = count($xml); $i < $c; $i++) { array_push($json, Xml2JsonSub($xml[$i])); } return '{' . implode(', ', $json) . '}'; }
function consultar() { $xml = $this->generarXML(); $retorno = ""; // Relacionado a la conexión //$host = "localhost"; //$script = "/netpeople/bic_argentina/generaRespuesta.php"; $host = "10.0.0.242"; $port = "10009"; $esXML = false; //Cuando se vuelve true, guardamos las lineas del xml $output = array(); // abro la conexión $socket = @fsockopen($host, $port, $errno, $errstr); if ($socket) { $parametros = "xml=" . $xml; fputs($socket, "POST /BillingGateway/DescargasServlet HTTP/1.0\n"); fputs($socket, "Host: {$host}\n"); fputs($socket, "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\n"); fputs($socket, "Content-length: " . strlen($parametros) . "\n\n"); //fputs($socket, $xml); fputs($socket, $parametros); while (!feof($socket)) { $linea = fgets($socket); // obtengo el resultado $fplog = fopen("/var/www/tmp/billing_tigo_co/billing_tco.log", "a"); fwrite($fplog, date("Y-m-d H:i:s") . " | {$linea} \n"); fclose($fplog); if (trim($linea) == "<VAS>") { $esXML = true; } if ($esXML) { //Si estamos dentro del XML, vamos guardando sus lineas $output[] = $linea; } if (trim($linea) === "</VAS>") { $esXML = false; } } fclose($socket); } else { $fplog = fopen("/var/www/tmp/billing_tigo_co/billing_tco.log", "a"); fwrite($fplog, date("Y-m-d H:i:s") . " | Error Socket \n \n"); fclose($fplog); } /* $output[] = "<VAS>\n"; $output[] = "<Operacion nombre=\"Respuesta_Descarga\">\n"; $output[] = "<Parametros>\n"; $output[] = " <CodTransaccion>1111</CodTransaccion>\n"; $output[] = " <MSISDN>0000000000</MSISDN>\n"; $output[] = " <CodProveedor>555</CodProveedor>\n"; $output[] = " <EntregaContenido>N</EntregaContenido>\n"; $output[] = " <CodResultado>102</CodResultado>\n"; $output[] = "</Parametros>\n"; $output[] = "</Operacion>\n"; $output[] = "</VAS>\n"; */ //unset($output[count($output)-1]); $output = implode("\n", $output); $xmlParser = new xml2Array(); $xmlArray = $xmlParser->parse($output); $entrega_contenido = $xmlArray[0]['children'][0]['children'][0]['children'][3]['tagData']; $cod_resultado = $xmlArray[0]['children'][0]['children'][0]['children'][4]['tagData']; if ($entrega_contenido == "Y") { echo "Se efectuó el cobro correctamente."; } else { echo "No se pudo efectar el cobro correctamente."; $mensaje = $this->retornarMensaje($cod_resultado); echo $this->limpiarTexto($mensaje); } }
public function getFileSize($file = '/', $version = -1) { if ($version == -1 || $version > $this->actVersion) { $version = $this->actVersion; } $url = $this->cleanURL($this->_url . "/!svn/bc/" . $version . "/" . $file . "/"); $this->initQuery($args, "PROPFIND", $url); $args['Body'] = PHPSVN_GET_FILE_SIZE; $args['Headers']['Content-Length'] = strlen(PHPSVN_GET_FILE_SIZE); if (!$this->Request($args, $headers, $body)) { return false; } $xml2Array = new xml2Array(); $arrOutput = $xml2Array->xmlParse($body); if ($arrOutput) { $files = array(); foreach ($arrOutput['children'] as $key => $value) { array_walk_recursive($value, array($this, 'get_file_size_resursively')); } return $this->file_size; } }
function scorm_parse_scorm($pkgdir, $scormid) { global $CFG; $launch = 0; $manifestfile = $pkgdir . '/imsmanifest.xml'; if (is_file($manifestfile)) { $xmltext = file_get_contents($manifestfile); $pattern = '/&(?!\\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objXML = new xml2Array(); $manifests = $objXML->parse($xmltext); //print_object($manifests); $scoes = new stdClass(); $scoes->version = ''; $scoes = scorm_get_manifest($manifests, $scoes); //print_object($scoes); if (count($scoes->elements) > 0) { $olditems = get_records('scorm_scoes', 'scorm', $scormid); foreach ($scoes->elements as $manifest => $organizations) { foreach ($organizations as $organization => $items) { foreach ($items as $identifier => $item) { // This new db mngt will support all SCORM future extensions $newitem = new stdClass(); $newitem->scorm = $scormid; $newitem->manifest = $manifest; $newitem->organization = $organization; $standarddatas = array('parent', 'identifier', 'launch', 'scormtype', 'title'); foreach ($standarddatas as $standarddata) { if (isset($item->{$standarddata})) { $newitem->{$standarddata} = addslashes_js($item->{$standarddata}); } } // Insert the new SCO, and retain the link between the old and new for later adjustment $id = insert_record('scorm_scoes', $newitem); if (!empty($olditems) && ($olditemid = scorm_array_search('identifier', $newitem->identifier, $olditems))) { $olditems[$olditemid]->newid = $id; } if ($optionaldatas = scorm_optionals_data($item, $standarddatas)) { $data = new stdClass(); $data->scoid = $id; foreach ($optionaldatas as $optionaldata) { if (isset($item->{$optionaldata})) { $data->name = $optionaldata; $data->value = addslashes_js($item->{$optionaldata}); $dataid = insert_record('scorm_scoes_data', $data); } } } if (isset($item->sequencingrules)) { foreach ($item->sequencingrules as $sequencingrule) { $rule = new stdClass(); $rule->scoid = $id; $rule->ruletype = $sequencingrule->type; $rule->conditioncombination = $sequencingrule->conditioncombination; $rule->action = $sequencingrule->action; $ruleid = insert_record('scorm_seq_ruleconds', $rule); if (isset($sequencingrule->ruleconditions)) { foreach ($sequencingrule->ruleconditions as $rulecondition) { $rulecond = new stdClass(); $rulecond->scoid = $id; $rulecond->ruleconditionsid = $ruleid; $rulecond->referencedobjective = $rulecondition->referencedobjective; $rulecond->measurethreshold = $rulecondition->measurethreshold; $rulecond->cond = $rulecondition->cond; $rulecondid = insert_record('scorm_seq_rulecond', $rulecond); } } } } if (isset($item->rolluprules)) { foreach ($item->rolluprules as $rolluprule) { $rollup = new stdClass(); $rollup->scoid = $id; $rollup->childactivityset = $rolluprule->childactivityset; $rollup->minimumcount = $rolluprule->minimumcount; $rollup->minimumpercent = $rolluprule->minimumpercent; $rollup->rollupruleaction = $rolluprule->rollupruleaction; $rollup->conditioncombination = $rolluprule->conditioncombination; $rollupruleid = insert_record('scorm_seq_rolluprule', $rollup); if (isset($rollup->conditions)) { foreach ($rollup->conditions as $condition) { $cond = new stdClass(); $cond->scoid = $rollup->scoid; $cond->rollupruleid = $rollupruleid; $cond->operator = $condition->operator; $cond->cond = $condition->cond; $conditionid = insert_record('scorm_seq_rolluprulecond', $cond); } } } } if (isset($item->objectives)) { foreach ($item->objectives as $objective) { $obj = new stdClass(); $obj->scoid = $id; $obj->primaryobj = $objective->primaryobj; $obj->satisfiedbumeasure = $objective->satisfiedbymeasure; $obj->objectiveid = $objective->objectiveid; $obj->minnormalizedmeasure = $objective->minnormalizedmeasure; $objectiveid = insert_record('scorm_seq_objective', $obj); if (isset($objective->mapinfos)) { //print_object($objective->mapinfos); foreach ($objective->mapinfos as $objmapinfo) { $mapinfo = new stdClass(); $mapinfo->scoid = $id; $mapinfo->objectiveid = $objectiveid; $mapinfo->targetobjectiveid = $objmapinfo->targetobjectiveid; $mapinfo->readsatisfiedstatus = $objmapinfo->readsatisfiedstatus; $mapinfo->writesatisfiedstatus = $objmapinfo->writesatisfiedstatus; $mapinfo->readnormalizedmeasure = $objmapinfo->readnormalizedmeasure; $mapinfo->writenormalizedmeasure = $objmapinfo->writenormalizedmeasure; $mapinfoid = insert_record('scorm_seq_mapinfo', $mapinfo); } } } } //print_object($item); if ($launch == 0 && (empty($scoes->defaultorg) || $scoes->defaultorg == $identifier)) { $launch = $id; } } } } if (!empty($olditems)) { foreach ($olditems as $olditem) { delete_records('scorm_scoes', 'id', $olditem->id); delete_records('scorm_scoes_data', 'scoid', $olditem->id); if (isset($olditem->newid)) { set_field('scorm_scoes_track', 'scoid', $olditem->newid, 'scoid', $olditem->id); } delete_records('scorm_scoes_track', 'scoid', $olditem->id); delete_records('scorm_seq_objective', 'scoid', $olditem->id); delete_records('scorm_seq_mapinfo', 'scoid', $olditem->id); delete_records('scorm_seq_ruleconds', 'scoid', $olditem->id); delete_records('scorm_seq_rulecond', 'scoid', $olditem->id); delete_records('scorm_seq_rolluprule', 'scoid', $olditem->id); delete_records('scorm_seq_rolluprulecond', 'scoid', $olditem->id); } } if (empty($scoes->version)) { $scoes->version = 'SCORM_1.2'; } set_field('scorm', 'version', $scoes->version, 'id', $scormid); $scorm->version = $scoes->version; } } return $launch; }
function getxmlfiles() { global $opt; // letztes Update ermitteln $lastUpdate = getSysConfig('ocxml11client_lastupdate', '2005-08-01 00:00:00'); // URL zusammenbauen $url = $opt['url']; $url = mb_ereg_replace('{modifiedsince}', date('YmdHis', strtotime($lastUpdate) - 60), $url); $url = mb_ereg_replace('{user}', $opt['sync']['user'], $url); $url = mb_ereg_replace('{cache}', $opt['sync']['cache'], $url); $url = mb_ereg_replace('{cachedesc}', $opt['sync']['cachedesc'], $url); $url = mb_ereg_replace('{cachelog}', $opt['sync']['cachelog'], $url); $url = mb_ereg_replace('{picture}', $opt['sync']['picture'], $url); $url = mb_ereg_replace('{picturefromcachelog}', $opt['sync']['picturefromcachelog'], $url); $url = mb_ereg_replace('{removedobject}', $opt['sync']['removedobject'], $url); $url = mb_ereg_replace('{session}', $opt['session'], $url); $url = mb_ereg_replace('{zip}', $opt['zip'], $url); if ($opt['bycountry'] == 1) { $url .= $opt['urlappend_country']; $url = mb_ereg_replace('{country}', $opt['country'], $url); } else { if ($opt['bycoords'] == 1) { $url .= $opt['urlappend_coords']; $url = mb_ereg_replace('{lon}', $opt['lon'], $url); $url = mb_ereg_replace('{lat}', $opt['lat'], $url); $url = mb_ereg_replace('{distance}', $opt['distance'], $url); } } if ($opt['zip'] == '0') { $fileext = '.xml'; } else { if ($opt['zip'] == 'zip') { $fileext = '.xml.zip'; } else { if ($opt['zip'] == 'gzip') { $fileext = '.xml.gz'; } else { if ($opt['zip'] == 'bzip2') { $fileext = '.xml.bz2'; } else { die('error: unkown zip method'); } } } } if ($opt['session'] == 1) { // records abfragen $sessionfile = $opt['tmpdir'] . 'session.xml'; if (file_exists($sessionfile)) { unlink($sessionfile); } copy($url, $sessionfile); $xmlParser = new xml2Array(); $session = $xmlParser->parse(read_file($sessionfile)); $xmlParser = null; unlink($sessionfile); $sessionid = $session['OCXMLSESSION']['SESSIONID']['DATA']; $recordscount = $session['OCXMLSESSION']['RECORDS']['USER']; $recordscount += $session['OCXMLSESSION']['RECORDS']['CACHE']; $recordscount += $session['OCXMLSESSION']['RECORDS']['CACHEDESC']; $recordscount += $session['OCXMLSESSION']['RECORDS']['CACHELOG']; $recordscount += $session['OCXMLSESSION']['RECORDS']['PICTURE']; $recordscount += $session['OCXMLSESSION']['RECORDS']['REMOVEOBJECT']; echo 'Abruf seit ' . $lastUpdate . "\n"; echo "------------------------\n"; echo 'Session-Id: ' . $sessionid . "\n"; echo 'User: '******'OCXMLSESSION']['RECORDS']['USER'] . "\n"; echo 'Cache: ' . $session['OCXMLSESSION']['RECORDS']['CACHE'] . "\n"; echo 'Cachdesc: ' . $session['OCXMLSESSION']['RECORDS']['CACHEDESC'] . "\n"; echo 'Cachelog: ' . $session['OCXMLSESSION']['RECORDS']['CACHELOG'] . "\n"; echo 'Picture: ' . $session['OCXMLSESSION']['RECORDS']['PICTURE'] . "\n"; echo 'Removedobject: ' . $session['OCXMLSESSION']['RECORDS']['REMOVEOBJECT'] . "\n"; echo "------------------------\n"; echo 'Summe: ' . $recordscount . "\n"; $filescount = ($recordscount + (500 - $recordscount % 500)) / 500; echo 'Anzahl der Pakete: ' . $filescount . "\n"; echo "\n"; if ($recordscount == 0) { echo "No new data, exiting\n"; exit; } for ($i = 1; $i <= $filescount; $i++) { echo "Download Paket: " . $i . ' von ' . $filescount . "\n"; $fileurl = $opt['url_getsession']; $fileurl = mb_ereg_replace('{sessionid}', $sessionid, $fileurl); $fileurl = mb_ereg_replace('{file}', $i, $fileurl); $fileurl = mb_ereg_replace('{zip}', $opt['zip'], $fileurl); $target = $opt['tmpdir'] . $sessionid . '-' . sprintf('%04d', $i) . $fileext; copy($fileurl, $target); } } else { echo 'Download ...' . "\n"; $target = $opt['tmpdir'] . date('YmdHis') . $fileext; copy($url, $target); } }
/** * Get changes logs of a file. * * Get repository change of a file between version * $vini and $vend. * * @param * @param integer $vini Initial Version * @param integer $vend End Version * @return Array Respository Logs */ public function getFileLogs($file, $vini = 0, $vend = -1) { $fileLogs = array(); $actVersion = $this->getVersion(); if ($vend == -1 || $vend > $actVersion) { $vend = $actVersion; } if ($vini < 0) { $vini = 0; } if ($vini > $vend) { $vini = $vend; } $url = $this->cleanURL($this->_url . "/!svn/bc/" . $actVersion . "/" . $file . "/"); $this->initQuery($args, "REPORT", $url); $args['Body'] = sprintf(PHPSVN_LOGS_REQUEST, $vini, $vend); $args['Headers']['Content-Length'] = strlen($args['Body']); $args['Headers']['Depth'] = 1; if (!$this->Request($args, $headers, $body)) { return false; } $xml2Array = new xml2Array(); $arrOutput = $xml2Array->xmlParse($body); array_shift($arrOutput['children']); foreach ($arrOutput['children'] as $value) { $array = array(); foreach ($value['children'] as $entry) { if ($entry['name'] == 'D:VERSION-NAME') { $array['version'] = $entry['tagData']; } if ($entry['name'] == 'D:CREATOR-DISPLAYNAME') { $array['author'] = $entry['tagData']; } if ($entry['name'] == 'S:DATE') { $array['date'] = $entry['tagData']; } if ($entry['name'] == 'D:COMMENT') { $array['comment'] = $entry['tagData']; } if ($entry['name'] == 'S:ADDED-PATH' || $entry['name'] == 'S:MODIFIED-PATH' || $entry['name'] == 'S:DELETED-PATH') { // For backward compatability $array['files'][] = $entry['tagData']; if ($entry['name'] == 'S:ADDED-PATH') { $array['add_files'][] = $entry['tagData']; } if ($entry['name'] == 'S:MODIFIED-PATH') { $array['mod_files'][] = $entry['tagData']; } if ($entry['name'] == 'S:DELETED-PATH') { $array['del_files'][] = $entry['tagData']; } } } array_push($fileLogs, $array); } return $fileLogs; }
function renderInterface($params, &$that) { mslib_fe::init($that); if ($that->post['job_id']) { $that->get['job_id'] = $that->post['job_id']; } if ($that->get['delete'] and is_numeric($that->get['job_id'])) { // delete job $query = $GLOBALS['TYPO3_DB']->DELETEquery('tx_multishop_import_jobs', 'id=' . $that->get['job_id'] . ' and type=\'' . addslashes($params['importKey']) . '\''); $res = $GLOBALS['TYPO3_DB']->sql_query($query); } if (is_numeric($that->get['job_id']) and is_numeric($that->get['status'])) { // update the status of a job $updateArray = array(); $updateArray['status'] = $that->get['status']; $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=\'' . $that->get['job_id'] . '\' and type=\'' . addslashes($params['importKey']) . '\'', $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); // update the status of a job eof } if (isset($that->get['download']) && $that->get['download'] == 'task' && is_numeric($that->get['job_id'])) { $sql = $GLOBALS['TYPO3_DB']->SELECTquery('*', 'tx_multishop_import_jobs ', 'id= \'' . $that->get['job_id'] . '\'', '', '', ''); $qry = $GLOBALS['TYPO3_DB']->sql_query($sql); if ($GLOBALS['TYPO3_DB']->sql_num_rows($qry)) { $data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $jobArray = $row; $serial_value = array(); foreach ($data as $key_idx => $key_val) { if ($key_idx != 'id' && $key_idx != 'page_uid') { $serial_value[$key_idx] = $key_val; } } $serial_data = ''; if (count($serial_value) > 0) { $serial_data = serialize($serial_value); } $filename = 'multishop_' . $params['importKey'] . '_import_task_' . date('YmdHis') . '_' . $that->get['job_id'] . '.txt'; $filepath = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/' . $filename; file_put_contents($filepath, $serial_data); header("Content-disposition: attachment; filename={$filename}"); //Tell the filename to the browser header('Content-type: application/octet-stream'); //Stream as a binary file! So it would force browser to download readfile($filepath); //Read and stream the file @unlink($filepath); exit; } } if (isset($that->get['upload']) && $that->get['upload'] == 'task' && $_FILES) { if (!$_FILES['task_file']['error']) { $filename = $_FILES['task_file']['name']; $target = $that->DOCUMENT_ROOT . '/uploads/tx_multishop' . $filename; if (move_uploaded_file($_FILES['task_file']['tmp_name'], $target)) { $task_content = file_get_contents($target); $unserial_task_data = unserialize($task_content); $insertArray = array(); $insertArray['page_uid'] = $that->showCatalogFromPage; foreach ($unserial_task_data as $col_name => $col_val) { if ($col_name == 'code') { $insertArray[$col_name] = md5(uniqid()); } else { if ($col_name == 'name' && isset($that->post['new_cron_name']) && !empty($that->post['new_cron_name'])) { $insertArray[$col_name] = $that->post['new_cron_name']; } else { if ($col_name == 'prefix_source_name' && isset($that->post['new_prefix_source_name']) && !empty($that->post['new_prefix_source_name'])) { $insertArray[$col_name] = $that->post['new_prefix_source_name']; } else { $insertArray[$col_name] = $col_val; } } } } $query = $GLOBALS['TYPO3_DB']->INSERTquery('tx_multishop_import_jobs', $insertArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); @unlink($target); } } header('Location: ' . $that->FULL_HTTP_URL . $params['postForm']['actionUrl'] . '#tasks'); } $GLOBALS['TSFE']->additionalHeaderData['tx_multishop_pi1_block_ui'] = mslib_fe::jQueryBlockUI(); if (is_numeric($that->post['job_id']) && $that->post['action'] == 'import-preview') { if ($that->post['job_id']) { $that->get['job_id'] = $that->post['job_id']; } $str = "SELECT * from tx_multishop_import_jobs where id='" . $that->post['job_id'] . "' and type='" . addslashes($params['importKey']) . "'"; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $jobArray = $row; $updateArray = array(); $cron_data = array(); $cron_data[0] = array(); $that->post['cron_period'] = ''; $cron_data[1] = $that->post; $updateArray['data'] = serialize($cron_data); $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $that->post['job_id'], $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); } if ($that->post['action'] == 'import-preview' or is_numeric($that->get['job_id']) and $_REQUEST['action'] == 'edit_job') { // preview if (is_numeric($that->get['job_id'])) { $that->ms['mode'] = 'edit'; // load the job $str = "SELECT * from tx_multishop_import_jobs where id='" . $that->get['job_id'] . "' and type='" . addslashes($params['importKey']) . "'"; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $jobArray = $row; $data = unserialize($row['data']); // copy the previous post data to the current post so it can run the job // again $that->post = $data[1]; $that->post['cid'] = $row['categories_id']; // enable file logging if ($that->get['relaxed_import']) { $that->post['relaxed_import'] = $that->get['relaxed_import']; } // update the last run time $updateArray = array(); $updateArray['last_run'] = time(); $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $row['id'], $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); // update the last run time eof } if ($that->post['database_name']) { $file_location = $that->post['database_name']; } elseif ($that->post['file_url']) { if (strstr($that->post['file_url'], "../")) { die; } $filename = time(); $file_location = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename; $file_content = mslib_fe::file_get_contents($that->post['file_url']); if (!$file_content or !file_put_contents($file_location, $file_content)) { die('cannot save the file or the file is empty'); } } elseif ($that->ms['mode'] == 'edit') { $filename = $that->post['filename']; $file_location = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename; } if ($_FILES['file']['tmp_name']) { $file = $_FILES['file']['tmp_name']; $filename = time() . '.import'; $file_location = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename; $that->post['filename'] = $filename; move_uploaded_file($file, $file_location); if (preg_match("/\\.gz\$/", $_FILES['file']['name'])) { // lets uncompress realtime $str = mslib_fe::file_get_contents($file_location, 1); file_put_contents($file_location, $str); } } if ($this->ms['mode'] == 'edit' and is_array($data) and count($data) and $filename) { if ($filename) { $data[1]['filename'] = $filename; $this->post['filename'] = $filename; } $string = serialize($data); $updateArray = array(); $updateArray['data'] = $string; $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $_REQUEST['job_id'], $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); } if ($file_location and $this->ms['mode'] == 'edit') { // if file not exists then show form to upload new file if (!file_exists($file_location)) { $content .= '<h2>Feed no longer available</h2>' . $file_location . ' is not existing.'; } } if (file_exists($file_location) or $that->post['database_name']) { if (!$that->post['database_name']) { $str = mslib_fe::file_get_contents($file_location); } if ($that->post['parser_template']) { $processed = 0; $rows = array(); } else { if ($str && mslib_befe::isSerializedString($str)) { $tmpData = unserialize($str); $counter = 0; foreach ($tmpData as $data) { $colCounter = 0; if ($counter == 0) { $row = array(); foreach ($data as $key => $val) { $row[] = $key; } $table_cols = $row; } $row = array(); foreach ($data as $key => $val) { $row[] = $val; } $rows[] = $row; $counter++; if ($counter == 5) { break; } } } elseif ($that->post['database_name']) { if ($that->ms['mode'] == 'edit') { $limit = 10; } else { $limit = '10'; } if (strstr(mslib_befe::strtolower($that->post['database_name']), 'select ')) { // its not a table name, its a full query $that->databaseMode = 'query'; $str = $that->post['database_name'] . ' LIMIT ' . $limit; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); if ($that->conf['debugEnabled'] == '1') { $logString = 'Load records for importer query: ' . $str; \TYPO3\CMS\Core\Utility\GeneralUtility::devLog($logString, 'multishop', -1); } $datarows = array(); while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry)) != false) { $datarows[] = $row; } } else { $datarows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', $that->post['database_name'], '', '', '', $limit); } $i = 0; $table_cols = array(); foreach ($datarows as $datarow) { $s = 0; foreach ($datarow as $colname => $datacol) { $table_cols[$s] = $colname; $rows[$i][$s] = $datacol; $s++; } $i++; if ($i == 5) { break; } } } elseif ($that->post['format'] == 'excel') { if (!$that->ms['mode'] == 'edit') { $filename = 'tmp-file-' . $GLOBALS['TSFE']->fe_user->user['uid'] . '-cat-' . $that->post['cid'] . '-' . time() . '.txt'; if (!($handle = fopen($that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename, 'w'))) { exit; } if (fwrite($handle, $str) === false) { exit; } fclose($handle); } // excel $paths = array(); $paths[] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpexcel_service') . 'Resources/Private/Contributed/PHPExcel/IOFactory.php'; $paths[] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpexcel_service') . 'Classes/PHPExcel/IOFactory.php'; foreach ($paths as $path) { if (file_exists($path)) { require_once $path; break; } } $phpexcel = PHPExcel_IOFactory::load($file_location); foreach ($phpexcel->getWorksheetIterator() as $worksheet) { $counter = 0; foreach ($worksheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); foreach ($cellIterator as $cell) { $clean_products_data = ltrim(rtrim($cell->getCalculatedValue(), " ,"), " ,"); $clean_products_data = trim($clean_products_data); if ($row->getRowIndex() > 1) { $rows[$counter - 1][] = $clean_products_data; } else { $table_cols[] = mslib_befe::strtolower($clean_products_data); } } $counter++; if ($counter == 5) { break; } } } // excel eol } elseif ($that->post['format'] == 'xml') { // try the generic way if (!$that->ms['mode'] == 'edit') { $filename = 'tmp-file-' . $GLOBALS['TSFE']->fe_user->user['uid'] . '-cat-' . $that->post['cid'] . '-' . time() . '.txt'; if (!($handle = fopen($that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename, 'w'))) { exit; } if (fwrite($handle, $str) === false) { exit; } fclose($handle); } // try the generic way $objXML = new xml2Array(); $arrOutput = $objXML->parse($str); $i = 0; $s = 0; $rows = array(); foreach ($arrOutput[0]['children'] as $item) { foreach ($item['children'] as $internalitem) { $rows[$i][$s] = $internalitem['tagData']; $s++; } // foreach ($item['attrs'] as $key => $value) // { // $rows[$i][$s] = $value; // $s++; // } $i++; $s = 0; if ($i == 5) { break; } } } else { if ($that->post['os'] == 'linux') { $splitter = "\n"; } else { $splitter = "\r\n"; } // csv if ($that->post['delimiter'] == "tab") { $delimiter = "\t"; } elseif ($that->post['delimiter'] == "dash") { $delimiter = "|"; } elseif ($that->post['delimiter'] == "dotcomma") { $delimiter = ";"; } elseif ($that->post['delimiter'] == "comma") { $delimiter = ","; } else { $delimiter = "\t"; } if ($that->post['backquotes']) { $backquotes = '"'; } else { $backquotes = '"'; } if ($that->post['format'] == 'txt') { $row = 1; $rows = array(); if (($handle = fopen($file_location, "r")) !== false) { $counter = 0; while (($data = fgetcsv($handle, '', $delimiter, $backquotes)) !== false) { //print_r($data); if ($that->post['escape_first_line']) { if ($counter == 0) { $table_cols = $data; } else { $rows[] = $data; } } else { $rows[] = $data; } $counter++; if ($counter == 5) { break; } } fclose($handle); } } // csv } // try the generic way eol } $tmpcontent = ''; $tmpcontent .= '<div class="panel-body"> <form id="product_import_form" class="form-horizontal" name="form1" method="post" action="' . $params['postForm']['actionUrl'] . '"> <input name="consolidate" type="hidden" value="' . $that->post['consolidate'] . '" /> <input name="os" type="hidden" value="' . $that->post['os'] . '" /> <input name="escape_first_line" type="hidden" value="' . $that->post['escape_first_line'] . '" /> <input name="parser_template" type="hidden" value="' . $that->post['parser_template'] . '" /> <input name="format" type="hidden" value="' . $that->post['format'] . '" /> <input name="action" type="hidden" value="import" /> <input name="delimiter" type="hidden" value="' . $that->post['delimiter'] . '" /> <input name="backquotes" type="hidden" value="' . $that->post['backquotes'] . '" /> <input name="filename" type="hidden" value="' . $filename . '" /> <input name="file_url" type="hidden" value="' . $that->post['file_url'] . '" /> '; if ($that->ms['mode'] == 'edit' or $that->post['preProcExistingTask']) { // if the existing import task is rerunned indicate it so we dont save the task double $tmpcontent .= '<input name="preProcExistingTask" type="hidden" value="1" />'; } if (!$rows) { $tmpcontent .= '<div class="alert alert-danger"><h3>No data available.</h3></div>'; } else { $tmpcontent .= '<table id="product_import_table" class="table table-striped table-bordered">'; $header = '<thead><tr><th>' . $that->pi_getLL('target_column') . '</th><th>' . $that->pi_getLL('source_column') . '</th>'; for ($x = 1; $x < 6; $x++) { $header .= '<th>' . $that->pi_getLL('row') . ' ' . $x . '</th>'; } $header .= '</tr></thead>'; $tmpcontent .= $header; $cols = count($rows[0]); $preview_listing = array(); for ($i = 0; $i < $cols; $i++) { if ($switch == 'odd') { $switch = 'even'; } else { $switch = 'odd'; } $tmpcontent .= ' <tr class="' . $switch . '"> <td class="cellAux"> <div class="form-inline"> <select name="select[' . $i . ']" id="select[' . $i . ']" class="select_columns_fields"> <option value="">' . $that->pi_getLL('skip') . '</option> '; foreach ($params['importColumns'] as $key => $value) { $tmpcontent .= '<option value="' . $key . '" ' . ($that->post['select'][$i] != '' && $that->post['select'][$i] == $key ? 'selected' : '') . '>' . htmlspecialchars($value) . '</option>'; } $tmpcontent .= ' </select> <input name="advanced_settings" class="btn btn-primary importer_advanced_settings" type="button" value="' . $that->pi_getLL('admin_advanced_settings') . '" /> </div> <div class="advanced_settings_container" style="display:none;"> <div class="form-group no-mb"> <div class="col-md-12"> <label class="control-label">aux</label> <input name="input[' . $i . ']" class="form-control" type="text" value="' . htmlspecialchars($this->post['input'][$i]) . '"> </div> </div> </fieldset> </td> <td class="column_name"><strong>' . htmlspecialchars($table_cols[$i]) . '</strong></td> '; // now 5 records $teller = 0; foreach ($rows as $row) { foreach ($row as $key => $col) { if (!mb_detect_encoding($col, 'UTF-8', true)) { $row[$key] = mslib_befe::convToUtf8($col); } } $teller++; $tmpitem = $row; $cols = count($tmpitem); if ($that->post['backquotes']) { $tmpitem[$i] = trim($tmpitem[$i], "\""); } if (strlen($tmpitem[$i]) > 100) { $tmpitem[$i] = substr($tmpitem[$i], 0, 100) . '...'; } $tmpcontent .= '<td class="cellBreak product_' . $teller . '">' . htmlspecialchars($tmpitem[$i]) . '</td>'; if ($teller == 5 or $teller == count($rows)) { break; } } if ($teller < 5) { for ($x = $teller; $x < 5; $x++) { $tmpcontent .= '<td class="cellBreak product_' . $x . '"> </td>'; } } // now 5 products eof $tmpcontent .= ' </tr>'; /* * prefix '.$i.': <input name="input['.$i.']" type="text" * value="'.htmlspecialchars($that->post['input'][$i]).'" /> */ } $importer_add_aux_input = ' <div class="form-field ms_dynamic_add_property"> <label>type</label> <select name="type"> <option value="append">append content with value</option> <option value="prepend">prepend content with value</option> <option value="find_and_replace">find and replace</option> <option value="custom_code">custom php code</option> </select> <label>aux</label> <input name="aux_input[]" type="text" value="' . htmlspecialchars($that->post['aux_input']) . '" /> <input name="delete" class="delete_property" type="button" value="delete" /><input name="disable" type="button" value="enable" /> </div> '; $importer_add_aux_input = str_replace("\r\n", '', $importer_add_aux_input); $importer_add_aux_input = str_replace("\n", '', $importer_add_aux_input); $tmpcontent .= $header . '</table>'; $tmpcontent .= ' <script type="text/javascript"> jQuery(document).ready(function($) { var add_property_html=\'' . addslashes($importer_add_aux_input) . '\'; $(document).on("click", ".delete_property", function() { $(this).parent().hide("fast"); }); $(".importer_add_property").click(function(event) { $(this).prev().append(add_property_html); }); $(".importer_advanced_settings").click(function(event) { $(this).parent().next().toggle(); }); $(\'.select_columns_fields\').select2({ dropdownCssClass: "bigdropWider", // apply css that makes the dropdown taller width:\'250px\' }); }); </script> '; } //$tmpcontent.=self::renderImportJobProperties($params,$that); $tmpcontent .= ' <div class="panel panel-default"> <div class="panel-heading"><h3>' . $that->pi_getLL('save_import_task') . '</h3></div> <div class="panel-body"> <div class="form-group"> <label for="cron_name" class="control-label col-md-2">' . $that->pi_getLL('name') . '</label> <div class="col-md-10"> <input name="cron_name" type="text" class="form-control" value="' . htmlspecialchars($that->post['cron_name']) . '" /> </div> </div> '; if ($that->get['action'] == 'edit_job') { $tmpcontent .= ' <div class="form-group"> <label for="duplicate" class="control-label col-md-2">' . $that->pi_getLL('duplicate') . '</label> <div class="col-md-10"> <div class="checkbox checkbox-success checkbox-inline"> <input name="duplicate" id="duplicate" type="checkbox" value="1" /><label for="duplicate"></label> <input name="skip_import" type="hidden" value="1" /> <input name="job_id" type="hidden" value="' . $that->get['job_id'] . '" /> <input name="file_url" type="hidden" value="' . $that->post['file_url'] . '" /> </div> </div> </div> '; } $tmpcontent .= ' <div class="form-group"> <label for="cron_period" class="control-label col-md-2">' . $that->pi_getLL('schedule') . '</label> <div class="col-md-10"> <select name="cron_period" id="cron_period" class="form-control"> <option value="" ' . (!$that->post['cron_period'] ? 'selected' : '') . '>' . $that->pi_getLL('manual') . '</option> <option value="' . 3600 * 24 . '" ' . ($that->post['cron_period'] == 3600 * 24 ? 'selected' : '') . '>' . $that->pi_getLL('daily') . '</option> <option value="' . 3600 * 24 * 7 . '" ' . ($that->post['cron_period'] == 3600 * 24 * 7 ? 'selected' : '') . '>' . $that->pi_getLL('weekly') . '</option> <option value="' . 3600 * 24 * 30 . '" ' . ($that->post['cron_period'] == 3600 * 24 * 30 ? 'selected' : '') . '>' . $that->pi_getLL('monthly') . '</option> </select> </div> </div> <div class="form-group"> <label for="prefix_source_name" class="control-label col-md-2">' . $that->pi_getLL('source_name') . '</label> <div class="col-md-10"> <input name="prefix_source_name" type="text" class="form-control" value="' . htmlspecialchars($that->post['prefix_source_name']) . '" /> </div> </div> <input name="database_name" type="hidden" value="' . $that->post['database_name'] . '" /> <input name="cron_data" type="hidden" value="' . htmlspecialchars(serialize($that->post)) . '" /> <div class="form-group"> <div class="col-md-10 col-md-offset-2"> <button type="submit" class="btn btn-success submit_block" id="cl_submit" name="AdSubmit" value=""><i class="fa fa-save"></i> ' . ($that->get['action'] == 'edit_job' ? $that->pi_getLL('save') : $that->pi_getLL('import')) . '</button> </div> </div> </div> </div> </form> '; $content = '' . mslib_fe::shadowBox($tmpcontent) . ''; // $content='<div // class="fullwidth_div">'.mslib_fe::shadowBox($tmpcontent).'</div>'; } // preview eof } elseif (is_numeric($that->get['job_id']) and $that->get['action'] == 'run_job' or $that->post['action'] == 'import' and ($that->post['filename'] and file_exists($that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $that->post['filename']) or $that->post['database_name'])) { if (!$that->post['preProcExistingTask'] and $that->post['cron_name'] and !$that->post['skip_import'] or $that->post['skip_import'] and $that->post['duplicate']) { // we have to save the import job $updateArray = array(); $updateArray['name'] = $that->post['cron_name']; $updateArray['status'] = 1; $updateArray['last_run'] = time(); $updateArray['code'] = md5(uniqid()); $updateArray['period'] = $that->post['cron_period']; $updateArray['prefix_source_name'] = $that->post['prefix_source_name']; $cron_data = array(); $cron_data[0] = unserialize($that->post['cron_period']); $that->post['cron_period'] = ''; $cron_data[1] = $that->post; $updateArray['data'] = serialize($cron_data); $updateArray['page_uid'] = $that->shop_pid; $updateArray['categories_id'] = $that->post['cid']; $updateArray['type'] = $params['importKey']; $query = $GLOBALS['TYPO3_DB']->INSERTquery('tx_multishop_import_jobs', $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); // we have to save the import job eof $that->ms['show_default_form'] = 1; } elseif ($that->post['skip_import']) { // we have to update the import job $updateArray = array(); $updateArray['name'] = $that->post['cron_name']; $updateArray['status'] = 1; $updateArray['last_run'] = time(); $updateArray['period'] = $that->post['cron_period']; $updateArray['prefix_source_name'] = $that->post['prefix_source_name']; $cron_data = array(); $cron_data[0] = unserialize($that->post['cron_period']); $that->post['cron_period'] = ''; $cron_data[1] = $that->post; $updateArray['data'] = serialize($cron_data); $updateArray['page_uid'] = $that->shop_pid; $updateArray['categories_id'] = $that->post['cid']; $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $that->post['job_id'] . ' and type=\'' . addslashes($params['importKey']) . '\'', $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); // we have to update the import job eof $that->ms['show_default_form'] = 1; } if (!$that->post['skip_import']) { if (!$that->get['job_id'] && $that->post['cron_data']) { $data = unserialize($that->post['cron_data']); if (is_numeric($data['job_id'])) { // NEW STUFF FOR 123 IMPORT APPROACH WITH PREDEFINED VALUES TEST $that->get['job_id'] = $data['job_id']; // load the job $str = "SELECT * from tx_multishop_import_jobs where id='" . $that->get['job_id'] . "'" . ' and type=\'' . addslashes($params['importKey']) . '\''; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $jobArray = $row; $cron_data = array(); $cron_data[0] = array(); $that->post['cron_period'] = ''; $cron_data[1] = $that->post; $updateArray['data'] = serialize($cron_data); $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $that->get['job_id'], $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); } } if (is_numeric($that->get['job_id'])) { // load the job $str = "SELECT * from tx_multishop_import_jobs where id='" . $that->get['job_id'] . "'" . ' and type=\'' . addslashes($params['importKey']) . '\''; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $jobArray = $row; $data = unserialize($row['data']); // copy the previous post data to the current post so it can run the // job again $that->post = $data[1]; if ($row['categories_id']) { $that->post['cid'] = $row['categories_id']; } // update the last run time $updateArray = array(); $updateArray['last_run'] = time(); $query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_multishop_import_jobs', 'id=' . $row['id'] . ' and type=\'' . addslashes($params['importKey']) . '\'', $updateArray); $res = $GLOBALS['TYPO3_DB']->sql_query($query); // update the last run time eof if ($log_file) { file_put_contents($log_file, $that->FULL_HTTP_URL . ' - cron job settings loaded.(' . date("Y-m-d G:i:s") . ")\n", FILE_APPEND); } } if ($that->post['file_url']) { if (strstr($that->post['file_url'], "../")) { die; } $filename = time(); $file = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $filename; file_put_contents($file, mslib_fe::file_get_contents($that->post['file_url'])); } if ($that->post['filename']) { $file = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $that->post['filename']; } if ($that->post['database_name'] or $file) { if ($file) { $str = mslib_fe::file_get_contents($file); } if ($that->post['parser_template']) { $processed = 0; $rows = array(); /* if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/scripts/admin_pages/admin_import.php']['TmpproductImportParserTemplateProc'])) { $params=array( 'parser_template'=>&$that->post['parser_template'], 'prefix_source_name'=>$that->post['prefix_source_name'], 'str'=>$str, 'rows'=>&$rows, 'file_location'=>&$file, 'table_cols'=>&$table_cols, 'processed'=>&$processed ); foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/scripts/admin_pages/admin_import.php']['TmpproductImportParserTemplateProc'] as $funcRef) { \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($funcRef, $params, $that); } } */ } else { if ($str && mslib_befe::isSerializedString($str)) { $tmpData = unserialize($str); $counter = 0; foreach ($tmpData as $data) { $colCounter = 0; if ($counter == 0) { $row = array(); foreach ($data as $key => $val) { $row[] = $key; } $table_cols = $row; } $row = array(); foreach ($data as $key => $val) { $row[] = $val; } $rows[] = $row; $counter++; } } elseif ($that->post['database_name']) { if (is_numeric($that->get['limit'])) { $limit = $that->get['limit']; } else { $limit = 2000; } if (strstr(mslib_befe::strtolower($that->post['database_name']), 'select ')) { $that->databaseMode = 'query'; // its not a table name, its a full query $that->databaseMode = 'query'; $str = $that->post['database_name'] . ' LIMIT ' . $limit; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); if ($that->conf['debugEnabled'] == '1') { $logString = 'Load records for importer query: ' . $str; \TYPO3\CMS\Core\Utility\GeneralUtility::devLog($logString, 'multishop', -1); } $datarows = array(); while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry)) != false) { $datarows[] = $row; } } else { // get primary key first $str = "show index FROM " . $that->post['database_name'] . ' where Key_name = \'PRIMARY\''; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry); $primaryKeyColumn = $row['Column_name']; $query = $GLOBALS['TYPO3_DB']->SELECTquery('*', $that->post['database_name'], '', '', '', $limit); $qry = $GLOBALS['TYPO3_DB']->sql_query($query); $datarows = array(); while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry)) != false) { $datarows[] = $row; if ($primaryKeyColumn and isset($row[$primaryKeyColumn])) { $str2 = "delete from " . $that->post['database_name'] . " where " . $primaryKeyColumn . "='" . $row[$primaryKeyColumn] . "'"; $qry2 = $GLOBALS['TYPO3_DB']->sql_query($str2); } } } $total_datarows = count($datarows); if ($that->msLogFile) { file_put_contents($that->msLogFile, $that->HTTP_HOST . ' - loaded (' . $total_datarows . ') records. (' . date("Y-m-d G:i:s") . ")\n", FILE_APPEND); } $i = 0; $rows = array(); foreach ($datarows as $datarow) { $s = 0; foreach ($datarow as $datacol) { $rows[$i][$s] = $datacol; $s++; } $i++; } } elseif ($that->post['format'] == 'excel') { // excel $paths = array(); $paths[] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpexcel_service') . 'Resources/Private/Contributed/PHPExcel/IOFactory.php'; $paths[] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpexcel_service') . 'Classes/PHPExcel/IOFactory.php'; foreach ($paths as $path) { if (file_exists($path)) { require_once $path; break; } } $phpexcel = PHPExcel_IOFactory::load($file); foreach ($phpexcel->getWorksheetIterator() as $worksheet) { $counter = 0; foreach ($worksheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); foreach ($cellIterator as $cell) { $clean_products_data = ltrim(rtrim($cell->getCalculatedValue(), " ,"), " ,"); $clean_products_data = trim($clean_products_data); if ($row->getRowIndex() > 1) { $rows[$counter - 1][] = $clean_products_data; } else { $table_cols[] = mslib_befe::strtolower($clean_products_data); } } $counter++; } } // excel eof } elseif ($that->post['format'] == 'xml') { $objXML = new xml2Array(); $arrOutput = $objXML->parse($str); $i = 0; $s = 0; $rows = array(); foreach ($arrOutput[0]['children'] as $item) { // image foreach ($item['children'] as $internalitem) { $rows[$i][$s] = $internalitem['tagData']; $s++; } foreach ($item['attrs'] as $key => $value) { $rows[$i][$s] = $value; $s++; } $i++; $s = 0; } } else { if ($that->post['os'] == 'linux') { $splitter = "\n"; } else { $splitter = "\r\n"; } $str = trim($str, $splitter); if ($that->post['escape_first_line']) { $pos = strpos($str, $splitter); $str = substr($str, $pos + strlen($splitter)); } // csv if ($that->post['delimiter'] == "tab") { $delimiter = "\t"; } elseif ($that->post['delimiter'] == "dash") { $delimiter = "|"; } elseif ($that->post['delimiter'] == "dotcomma") { $delimiter = ";"; } elseif ($that->post['delimiter'] == "comma") { $delimiter = ","; } else { $delimiter = "\t"; } if ($that->post['backquotes']) { $backquotes = '"'; } else { $backquotes = '"'; } if ($that->post['format'] == 'txt') { $row = 1; $rows = array(); if (($handle = fopen($file, "r")) !== false) { $counter = 0; while (($data = fgetcsv($handle, '', $delimiter, $backquotes)) !== false) { if ($that->post['escape_first_line']) { if ($counter == 0) { $table_cols = $data; } else { $rows[] = $data; } } else { $rows[] = $data; } $counter++; } fclose($handle); } } // csv } } $item_counter = 0; $inserteditems = array(); $global_start_time = microtime(true); $start_time = microtime(true); $total_datarows = count($rows); if ($that->msLogFile) { if ($total_datarows) { // sometimes the preload takes so long that the database connection is lost. $GLOBALS['TYPO3_DB']->connectDB(); file_put_contents($that->msLogFile, $that->HTTP_HOST . ' - ' . $params['importKey'] . ' importer loaded, now starting the import. (' . date("Y-m-d G:i:s") . ")\n", FILE_APPEND); } else { file_put_contents($that->msLogFile, $that->HTTP_HOST . ' - no records needed to be imported' . "\n", FILE_APPEND); } } // $global_start_time = microtime(); foreach ($rows as $row) { foreach ($row as $key => $col) { if (!mb_detect_encoding($col, 'UTF-8', true)) { if ($col == 'NULL' || $col == 'null') { $col = ''; } $row[$key] = mslib_befe::convToUtf8($col); } } $that->ms['target-cid'] = $that->post['cid']; $teller++; if ($that->post['escape_first_line'] and $teller > 1 or !$that->post['escape_first_line']) { $tmpitem = $row; $cols = count($tmpitem); $flipped_select = array_flip($that->post['select']); // if($tmpitem[$that->post['select'][0]] and $cols > 0) // { $item = array(); // if the source is a database table name add the unique id // so we can delete it after the import if ($that->post['database_name']) { $item['table_unique_id'] = $row[0]; } // aux $input = array(); // name for ($i = 0; $i < $cols; $i++) { $tmpitem[$i] = trim($tmpitem[$i]); $char = ''; $item[$that->post['select'][$i]] = $tmpitem[$i]; if ($item[$that->post['select'][$i]] == $char and $char) { $item[$that->post['select'][$i]] = ''; } $input[$that->post['select'][$i]] = $that->post['input'][$i]; } if ($jobArray['predefined_variables']) { $array = unserialize($jobArray['predefined_variables']); foreach ($array as $col => $val) { $item[$col] = $val; } } // custom hook that can be controlled by third-party plugin if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/pi1/classes/class.tx_mslib_admin_import.php']['msAdminImportItemIterateProc'])) { $params = array('importKey' => &$params['importKey'], 'row' => &$row, 'item' => &$item, 'prefix_source_name' => $that->post['prefix_source_name'], 'params' => &$params, 'content' => &$content); foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/multishop/pi1/classes/class.tx_mslib_admin_import.php']['msAdminImportItemIterateProc'] as $funcRef) { \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($funcRef, $params, $that); } } } if ($log_file) { $content = ''; } // end foreach } // if($file_location and file_exists($file_location)) // @unlink($file_location); } } // end import } else { $that->ms['show_default_form'] = 1; } if ($that->ms['show_default_form']) { $that->ms['upload_' . $params['importKey'] . 'feed_form'] .= self::renderImportJobProperties($params, $that); $content .= '<div class="panel-body"><form action="' . $params['postForm']['actionUrl'] . '" method="post" enctype="multipart/form-data" name="form1" id="form1" class="form-horizontal">'; $content .= $that->ms['upload_' . $params['importKey'] . 'feed_form']; $content .= '</form>'; // load the jobs templates $str = "SELECT * from tx_multishop_import_jobs where page_uid='" . $that->shop_pid . "' and type='" . addslashes($params['importKey']) . "' order by prefix_source_name asc, id desc"; $qry = $GLOBALS['TYPO3_DB']->sql_query($str); $jobs = array(); while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($qry)) != false) { $jobs[] = $row; } if (count($jobs) > 0) { $schedule_content .= ' <div class="panel panel-default" id="scheduled_import_jobs_form"><div class="panel-heading"><h3>' . $that->pi_getLL('import_tasks') . '</h3></div> <div class="panel-body"> <table class="table table-striped table-bordered no-mb" id="msAdminImportTableInterface"> <thead> <tr> <th>' . $that->pi_getLL('source_name') . '</th> <th class="cellName">' . $that->pi_getLL('name') . '</th> <th class="cellDate">' . $that->pi_getLL('last_run') . '</th> <th>' . $that->pi_getLL('action') . '</th> <th class="cellStatus">' . ucfirst($that->pi_getLL('status')) . '</th> <th class="cellAction">' . ucfirst($that->pi_getLL('delete')) . '</th> <th class="cellStatus">' . $that->pi_getLL('file_exists') . '</th> <th>' . $that->pi_getLL('upload_file') . '</th> <th>' . $that->pi_getLL('download_import_task') . '</th> </tr> </thead> '; $switch = ''; $schedule_content .= '<tbody>'; foreach ($jobs as $job) { if ($switch == 'odd') { $switch = 'even'; } else { $switch = 'odd'; } $schedule_content .= '<tr class="' . $switch . '">'; $schedule_content .= '<td>' . $job['prefix_source_name'] . '</td> <td class="cellName"><a href="' . $params['postForm']['actionUrl'] . '&job_id=' . $job['id'] . '&action=edit_job">' . $job['name'] . '</a></td> '; $lastRun = ''; if ($job['last_run'] > 0) { $lastRun = date("Y-m-d", $job['last_run']) . '<br />' . date("G:i:s", $job['last_run']); } $schedule_content .= '<td class="cellDate">' . $lastRun . '</td>'; if (!$job['period']) { $schedule_content .= '<td>manual<br /><a href="' . $params['postForm']['actionUrl'] . '&job_id=' . $job['id'] . '&action=run_job&limit=99999999" class="btn btn-success" onClick="return CONFIRM(\'' . addslashes($that->pi_getLL('are_you_sure_you_want_to_run_the_import_job')) . ': ' . htmlspecialchars(addslashes($job['name'])) . '?\')"><i>' . $that->pi_getLL('run_now') . '</i></a><br /><a href="" class="copy_to_clipboard" rel="' . htmlentities('/usr/bin/wget -O /dev/null --tries=1 --timeout=30 -q "' . $that->FULL_HTTP_URL . $params['postForm']['actionUrl'] . '&job_id=' . $job['id'] . '&code=' . $job['code'] . '&action=run_job&run_as_cron=1&limit=99999999" >/dev/null 2>&1') . '" ><i>' . $that->pi_getLL('run_by_crontab') . '</i></a></td>'; } else { $schedule_content .= '<td>' . date("Y-m-d G:i:s", $job['last_run'] + $job['period']) . '</td>'; } $schedule_content .= '<td class="cellStatus">'; if (!$job['status']) { $schedule_content .= '<span class="admin_status_red" alt="Disable"></span>'; $schedule_content .= '<a href="' . $params['postForm']['actionUrl'] . '&job_id=' . $job['id'] . '&status=1"><span class="admin_status_green disabled" alt="Enabled"></span></a>'; } else { $schedule_content .= '<a href="' . $params['postForm']['actionUrl'] . '&job_id=' . $job['id'] . '&status=0"><span class="admin_status_red disabled" alt="Disabled"></span></a>'; $schedule_content .= '<span class="admin_status_green" alt="Enable"></span>'; } $schedule_content .= '</td> <td class="cellAction"> <a href="' . $params['postForm']['actionUrl'] . '&delete=1&&job_id=' . $job['id'] . '&action=delete_job" onClick="return CONFIRM(\'Are you sure you want to delete the import job: ' . htmlspecialchars($job['name']) . '?\')" alt="Remove ' . htmlspecialchars($job['name']) . '" class="btn btn-danger btn-sm admin_menu_remove" title="Remove ' . htmlspecialchars($job['name']) . '"><i class="fa fa-trash-o"></i></a> </td> <td class="cellStatus"> '; $data = unserialize($job['data']); if ($data[1]['filename']) { $file_location = $that->DOCUMENT_ROOT . 'uploads/tx_multishop/tmp/' . $data[1]['filename']; if (file_exists($file_location)) { $schedule_content .= '<span class="admin_status_green" alt="Enable"></span>'; } else { $schedule_content .= '<span class="admin_status_red" alt="Disable"></span>'; } } $schedule_content .= ' </td> <td> <form action="' . $params['postForm']['actionUrl'] . '" method="post" enctype="multipart/form-data" name="form1" id="form1"> <div class="input-group"> <input type="file" name="file" class="form-control" style="width:300px" /> <input name="skip_import" type="hidden" value="1" /> <input name="preProcExistingTask" type="hidden" value="1" /> <input name="job_id" type="hidden" value="' . $job['id'] . '" /> <input name="action" type="hidden" value="edit_job" /> <span class="input-group-btn"> <input type="submit" name="Submit" class="submit btn btn-success" id="cl_submit" value="' . $that->pi_getLL('upload') . '" /> </span> </div> </form> </td> <td> <a href="' . $params['postForm']['actionUrl'] . '&download=task&job_id=' . $job['id'] . '" class="btn btn-success"><i class="fa fa-download"></i> ' . $that->pi_getLL('download_import_task') . '</a> </td> '; $schedule_content .= '</tr>'; } $schedule_content .= '</tbody>'; $schedule_content .= '</table> </div> </div> <script type="text/javascript"> jQuery(document).ready(function($) { $(".copy_to_clipboard").click(function(event) { event.preventDefault(); var string=$(this).attr("rel"); $.blockUI({ theme: true, title: \'' . addslashes($that->pi_getLL('copy_below_text_and_add_it_to_crontab')) . '\', message: \'<p>\'+string+\'</p>\', timeout: 8000 }); }); }); </script> '; $tmptab = ''; $content .= $schedule_content; //$tabs['tasks']=array($that->pi_getLL('import_tasks'),$schedule_content); } // load the jobs templates eof if ($this->ROOTADMIN_USER) { $content .= ' <div id="scheduled_import_jobs_form" class="panel panel-default"> <div class="panel-heading"><h3>' . $that->pi_getLL('upload_import_task') . '</h3></div> <div class="panel-body"> <form action="' . $params['postForm']['actionUrl'] . '&upload=task" method="post" enctype="multipart/form-data" name="upload_task" id="upload_task" class="form-horizontal blockSubmitForm"> <div class="form-group"> <label for="new_cron_name" class="control-label col-md-2">' . $that->pi_getLL('name') . '</label> <div class="col-md-10"> <input name="new_cron_name" type="text" class="form-control" value="" size="125"> </div> </div> <div class="form-group"> <label for="new_prefix_source_name" class="control-label col-md-2">' . $that->pi_getLL('source_name') . '</label> <div class="col-md-10"> <input name="new_prefix_source_name" type="text" class="form-control" value="" /> </div> </div> <div class="form-group"> <label for="upload_task_file" class="control-label col-md-2">' . $that->pi_getLL('file') . '</label> <div class="col-md-10"> <input type="file" name="task_file" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-10 col-md-offset-2"> <input type="submit" name="upload_task_file" class="submit btn btn-success" id="upload_task_file" value="upload"> </div> </div> </form> </div> </div>'; } } $content .= '<hr><div class="clearfix"><a class="btn btn-success msAdminBackToCatalog" href="' . mslib_fe::typolink() . '"><span class="fa-stack"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-arrow-left fa-stack-1x"></i></span> ' . $that->pi_getLL('admin_close_and_go_back_to_catalog') . '</a></div></div>'; $content = '<div class="panel panel-default">' . mslib_fe::shadowBox($content) . '</div>'; return $content; }
/** * Sets up SCORM 1.2/2004 packages using the manifest file. * Called whenever SCORM changes * @param object $scorm instance - fields are updated and changes saved into database * @param stored_file|string $manifest - path to manifest file or stored_file. * @return bool */ function scorm_parse_scorm(&$scorm, $manifest) { global $CFG, $DB; // load manifest into string if ($manifest instanceof stored_file) { $xmltext = $manifest->get_content(); } else { require_once "{$CFG->libdir}/filelib.php"; $xmltext = download_file_content($manifest); } $defaultorgid = 0; $firstinorg = 0; $pattern = '/&(?!\\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objXML = new xml2Array(); $manifests = $objXML->parse($xmltext); $scoes = new stdClass(); $scoes->version = ''; $scoes = scorm_get_manifest($manifests, $scoes); $newscoes = array(); $sortorder = 0; if (count($scoes->elements) > 0) { $olditems = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id)); foreach ($scoes->elements as $manifest => $organizations) { foreach ($organizations as $organization => $items) { foreach ($items as $identifier => $item) { $sortorder++; // This new db mngt will support all SCORM future extensions $newitem = new stdClass(); $newitem->scorm = $scorm->id; $newitem->manifest = $manifest; $newitem->organization = $organization; $newitem->sortorder = $sortorder; $standarddatas = array('parent', 'identifier', 'launch', 'scormtype', 'title'); foreach ($standarddatas as $standarddata) { if (isset($item->{$standarddata})) { $newitem->{$standarddata} = $item->{$standarddata}; } else { $newitem->{$standarddata} = ''; } } if (!empty($defaultorgid) && !empty($scoes->defaultorg) && empty($firstinorg) && $newitem->parent == $scoes->defaultorg) { $firstinorg = $sortorder; } if (!empty($olditems) && ($olditemid = scorm_array_search('identifier', $newitem->identifier, $olditems))) { $newitem->id = $olditemid; // Update the Sco sortorder but keep id so that user tracks are kept against the same ids. $DB->update_record('scorm_scoes', $newitem); $id = $olditemid; // Remove all old data so we don't duplicate it. $DB->delete_records('scorm_scoes_data', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_objective', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_mapinfo', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_ruleconds', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rulecond', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rolluprule', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rolluprulecond', array('scoid' => $olditemid)); // Now remove this SCO from the olditems object as we have dealt with it. unset($olditems[$olditemid]); } else { // Insert the new SCO, and retain the link between the old and new for later adjustment $id = $DB->insert_record('scorm_scoes', $newitem); } $newscoes[$id] = $newitem; // Save this sco in memory so we can use it later. if ($optionaldatas = scorm_optionals_data($item, $standarddatas)) { $data = new stdClass(); $data->scoid = $id; foreach ($optionaldatas as $optionaldata) { if (isset($item->{$optionaldata})) { $data->name = $optionaldata; $data->value = $item->{$optionaldata}; $dataid = $DB->insert_record('scorm_scoes_data', $data); } } } if (isset($item->sequencingrules)) { foreach ($item->sequencingrules as $sequencingrule) { $rule = new stdClass(); $rule->scoid = $id; $rule->ruletype = $sequencingrule->type; $rule->conditioncombination = $sequencingrule->conditioncombination; $rule->action = $sequencingrule->action; $ruleid = $DB->insert_record('scorm_seq_ruleconds', $rule); if (isset($sequencingrule->ruleconditions)) { foreach ($sequencingrule->ruleconditions as $rulecondition) { $rulecond = new stdClass(); $rulecond->scoid = $id; $rulecond->ruleconditionsid = $ruleid; $rulecond->referencedobjective = $rulecondition->referencedobjective; $rulecond->measurethreshold = $rulecondition->measurethreshold; $rulecond->operator = $rulecondition->operator; $rulecond->cond = $rulecondition->cond; $rulecondid = $DB->insert_record('scorm_seq_rulecond', $rulecond); } } } } if (isset($item->rolluprules)) { foreach ($item->rolluprules as $rolluprule) { $rollup = new stdClass(); $rollup->scoid = $id; $rollup->childactivityset = $rolluprule->childactivityset; $rollup->minimumcount = $rolluprule->minimumcount; $rollup->minimumpercent = $rolluprule->minimumpercent; $rollup->rollupruleaction = $rolluprule->rollupruleaction; $rollup->conditioncombination = $rolluprule->conditioncombination; $rollupruleid = $DB->insert_record('scorm_seq_rolluprule', $rollup); if (isset($rollup->conditions)) { foreach ($rollup->conditions as $condition) { $cond = new stdClass(); $cond->scoid = $rollup->scoid; $cond->rollupruleid = $rollupruleid; $cond->operator = $condition->operator; $cond->cond = $condition->cond; $conditionid = $DB->insert_record('scorm_seq_rolluprulecond', $cond); } } } } if (isset($item->objectives)) { foreach ($item->objectives as $objective) { $obj = new stdClass(); $obj->scoid = $id; $obj->primaryobj = $objective->primaryobj; $obj->satisfiedbumeasure = $objective->satisfiedbymeasure; $obj->objectiveid = $objective->objectiveid; $obj->minnormalizedmeasure = trim($objective->minnormalizedmeasure); $objectiveid = $DB->insert_record('scorm_seq_objective', $obj); if (isset($objective->mapinfos)) { foreach ($objective->mapinfos as $objmapinfo) { $mapinfo = new stdClass(); $mapinfo->scoid = $id; $mapinfo->objectiveid = $objectiveid; $mapinfo->targetobjectiveid = $objmapinfo->targetobjectiveid; $mapinfo->readsatisfiedstatus = $objmapinfo->readsatisfiedstatus; $mapinfo->writesatisfiedstatus = $objmapinfo->writesatisfiedstatus; $mapinfo->readnormalizedmeasure = $objmapinfo->readnormalizedmeasure; $mapinfo->writenormalizedmeasure = $objmapinfo->writenormalizedmeasure; $mapinfoid = $DB->insert_record('scorm_seq_mapinfo', $mapinfo); } } } } if (empty($defaultorgid) && (empty($scoes->defaultorg) || $scoes->defaultorg == $identifier)) { $defaultorgid = $id; } } } } if (!empty($olditems)) { foreach ($olditems as $olditem) { $DB->delete_records('scorm_scoes', array('id' => $olditem->id)); $DB->delete_records('scorm_scoes_data', array('scoid' => $olditem->id)); $DB->delete_records('scorm_scoes_track', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_objective', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_mapinfo', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_ruleconds', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rulecond', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprule', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprulecond', array('scoid' => $olditem->id)); } } if (empty($scoes->version)) { $scoes->version = 'SCORM_1.2'; } $DB->set_field('scorm', 'version', $scoes->version, array('id' => $scorm->id)); $scorm->version = $scoes->version; } $scorm->launch = 0; // Check launch sco is valid. if (!empty($defaultorgid) && isset($newscoes[$defaultorgid]) && !empty($newscoes[$defaultorgid]->launch)) { // Launch param is valid - do nothing. $scorm->launch = $defaultorgid; } else { if (!empty($defaultorgid) && isset($newscoes[$defaultorgid]) && empty($newscoes[$defaultorgid]->launch)) { // The launch is probably the default org so we need to find the first launchable item inside this org. $sqlselect = 'scorm = ? AND sortorder >= ? AND ' . $DB->sql_isnotempty('scorm_scoes', 'launch', false, true); // We use get_records here as we need to pass a limit in the query that works cross db. $scoes = $DB->get_records_select('scorm_scoes', $sqlselect, array($scorm->id, $firstinorg), 'sortorder', 'id', 0, 1); if (!empty($scoes)) { $sco = reset($scoes); // We only care about the first record - the above query only returns one. $scorm->launch = $sco->id; } } } if (empty($scorm->launch)) { // No valid Launch is specified - find the first launchable sco instead. $sqlselect = 'scorm = ? AND ' . $DB->sql_isnotempty('scorm_scoes', 'launch', false, true); // We use get_records here as we need to pass a limit in the query that works cross db. $scoes = $DB->get_records_select('scorm_scoes', $sqlselect, array($scorm->id), 'sortorder', 'id', 0, 1); if (!empty($scoes)) { $sco = reset($scoes); // We only care about the first record - the above query only returns one. $scorm->launch = $sco->id; } } return true; }
/** * * Parse the TCAPI resource. * * @param object $scorm * @param object $manifest */ function scorm_parse_tincan($scorm, $manifest) { global $CFG, $DB; // load manifest into string if ($manifest instanceof stored_file) { $xmltext = $manifest->get_content(); } else { require_once("$CFG->libdir/filelib.php"); $xmltext = download_file_content($manifest); } $launch = 0; $pattern = '/&(?!\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objXML = new xml2Array(); $manifests = $objXML->parse($xmltext); $scoes = new stdClass(); $scoes->version = 'TCAPI'; $scoes = scorm_get_tincan_manifest($manifests, $scoes); if (count($scoes->elements) > 0) { $olditems = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id)); foreach ($scoes->elements as $manifest => $organizations) { foreach ($organizations as $organization => $items) { foreach ($items as $identifier => $item) { $newitem = new stdClass(); $newitem->scorm = $scorm->id; $newitem->manifest = $manifest; $newitem->organization = $organization; $standarddatas = array('parent', 'identifier', 'launch', 'scormtype', 'title'); foreach ($standarddatas as $standarddata) { if (isset($item->$standarddata)) { $newitem->$standarddata = $item->$standarddata; } } // Insert the new SCO, and retain the link between the old and new for later adjustment $id = $DB->insert_record('scorm_scoes', $newitem); if (!empty($olditems) && ($olditemid = scorm_array_search('identifier', $newitem->identifier, $olditems))) { $olditems[$olditemid]->newid = $id; } if ($optionaldatas = scorm_tincan_optionals_data($item, $standarddatas)) { $data = new stdClass(); $data->scoid = $id; foreach ($optionaldatas as $optionaldata) { if (isset($item->$optionaldata)) { $data->name = $optionaldata; $data->value = $item->$optionaldata; $dataid = $DB->insert_record('scorm_scoes_data', $data); } } } if (($launch == 0) && ((empty($scoes->defaultorg)) || ($scoes->defaultorg == $identifier))) { $launch = $id; } } } } if (!empty($olditems)) { foreach ($olditems as $olditem) { $DB->delete_records('scorm_scoes', array('id'=>$olditem->id)); $DB->delete_records('scorm_scoes_data', array('scoid'=>$olditem->id)); if (isset($olditem->newid)) { $DB->set_field('scorm_scoes_track', 'scoid', $olditem->newid, array('scoid' => $olditem->id)); } $DB->delete_records('scorm_scoes_track', array('scoid'=>$olditem->id)); } } $DB->set_field('scorm', 'version', $scoes->version, array('id'=>$scorm->id)); $scorm->version = $scoes->version; } $scorm->launch = $launch; return true; }
/** * 发送验证码 */ public function postmessage() { import('ORG.Util.String'); $randval = String::randString(6, 1); $content = '尊敬的客户,您的验证码为' . $randval . '。【爱阅公益阅芽计划】'; $ml = M('regsms'); if (isset($_POST['del'])) { $flag = $ml->where(array('mobile' => $_POST['mobile']))->delete(); if (false !== $flag) { print_r(json_encode(array("status" => 0))); exit; } else { print_r(json_encode(array('status' => 1))); exit; } } else { $ml = M('regsms'); $data['mobile'] = $_POST['mobile']; $data['smsCode'] = $randval; $flag = $ml->add($data); } $retinfo = ''; $xmlstring = ''; $info = ''; $xmlstring = ''; $userid = '93122'; //$_POST['userid'] ? $_POST['userid'] : false; $password = '******'; //$_POST['password'] ? $_POST['password'] : false; $msg = $content; //$_POST['msg'] ? $_POST['msg'] : false; $destnumbers = $_POST['mobile'] ? $_POST['mobile'] : false; $sendtime = $_POST['sendtime'] ? $_POST['sendtime'] : false; if ($userid && $password && $destnumbers && $msg) { $qUrl = "http://183.61.109.140:9801/CASServer/SmsAPI/SendMessage.jsp"; $qUrl .= '?userid=' . $userid . '&password='******'&destnumbers=' . $destnumbers . '&msg=' . urlencode($msg) . '&sendtime=' . $sendtime; if (function_exists('file_get_contents')) { //(PHP 4 >= 4.3.0, PHP 5) $xmlstring = file_get_contents($qUrl); } else { if (function_exists('fopen')) { //(PHP 3, PHP 4, PHP 5) $fopenXML = fopen($qUrl, 'r'); if ($fopenXML) { while (!feof($fopenXML)) { $xmlstring .= fgets($fopenXML, 4096); } fclose($fopenXML); } } } if ($xmlstring && trim($xmlstring)) { if (function_exists('simplexml_load_string')) { //PHP5.0以上版本(PHP 5) $xml = simplexml_load_string($xmlstring); $retinfo = $xml['return'] . ',' . $xml['info']; if ('' . $xml['return'] === '0') { $info = '总计号码个数:' . $xml['numbers'] . '<br />'; $info .= '总计短信条数:' . $xml['messages'] . '<br />'; } //将验证码存放在session session('checkCode', null); session('checkCode', $randval); } else { //PHP5.0以下版本 require_once 'xml2Array.class.php'; $objXML = new xml2Array(); $arrOutput = $objXML->parse($xmlstring); $retinfo = $arrOutput[0]['attrs']['RETURN'] . ',' . $arrOutput[0]['attrs']['INFO']; if ('' . $arrOutput[0]['attrs']['RETURN'] === "0") { $info = '总计号码个数:' . $arrOutput[0]['attrs']['NUMBERS'] . '<br />'; $info .= '总计短信条数:' . $arrOutput[0]['attrs']['MESSAGES'] . '<br />'; } } } } }
function read_track($track_file, $current_time = 0, $max_cache_age = 0) { global $config_track; /* sanity check */ if (empty($track_file)) { print "ERROR: Invalid track file\n"; return false; } /* set defaults if not passed */ if (empty($current_time)) { $current_time = time(); } if (empty($max_cache_age)) { $max_cache_age = 428; } /* set cache pruning */ $old_time = mktime(0, 0, 0, date("m", $current_time), date("j", $current_time) - $max_cache_age, date("Y", $current_time)); /* read track file */ if (!($config_FH = @fopen($track_file, "r"))) { $config_track = array(); return true; } $data = fread($config_FH, filesize($track_file)); if (empty($data)) { print "ERROR: Track file seems to be empty.\n"; return false; } fclose($config_FH); $objXML = new xml2Array(); if (!($track = $objXML->parse($data))) { exit; } /* Process XML Data */ if (isset($track[0]["name"])) { if ($track[0]["name"] != "track") { print "ERROR: Invalid track file format.\n"; return false; } } else { print "Invalid track file format\n"; return false; } if (isset($track[0]["children"])) { foreach ($track[0]["children"] as $child_track) { if (!isset($child_track["attrs"]["name"])) { print "ERROR: Invalid track item found in track file\n"; return false; } if ($child_track["name"] != "customer") { print "ERROR: Invalid track file format.\n"; return false; } if (isset($child_track["tagData"])) { /* Old format */ debug("Track file old record format found, will be upgraded"); $config_track[$child_track["attrs"]["name"]]["last_run"] = $child_track["tagData"]; } else { /* New format that includes cache */ if (isset($child_track["children"])) { foreach ($child_track["children"] as $child_track_new) { if ($child_track_new["name"] == "last_run") { $config_track[$child_track["attrs"]["name"]]["last_run"] = $child_track_new["tagData"]; } if ($child_track_new["name"] == "notification") { $config_track[$child_track["attrs"]["name"]]["notification"][$child_track_new["attrs"]["graph_id"]] = $child_track_new["tagData"]; } if ($child_track_new["name"] == "cache") { if (isset($child_track_new["children"])) { foreach ($child_track_new["children"] as $child_cache_item) { if ($child_cache_item["name"] == "item") { $cache_date = ""; $graph_id = ""; $graph_item_id = ""; /* Discard non-numeric values */ if (is_numeric($child_cache_item["tagData"])) { foreach ($child_cache_item["attrs"] as $key => $value) { if ($key == "date") { $cache_date = $value; } if ($key == "start") { $cache_start = $value; } if ($key == "graph_id") { $graph_id = $value; } if ($key == "graph_item_id") { $graph_item_id = $value; } } /* Do not read into memory values which are older than a certain time - cache pruning */ if ($cache_date > $old_time) { $config_track[$child_track["attrs"]["name"]][$graph_id][$graph_item_id][$cache_start][$cache_date] = $child_cache_item["tagData"]; } } } } } } } } else { print "ERROR: Invalid track file format.\n"; return false; } } } } else { $config_track = array(); } $track = array(); return true; }
/** * Handles uploaded zip packages when a module is added or updated. Unpacks the zip contents and extracts the launch url and activity id from the tincan.xml file. * Note: This takes the *first* activity from the tincan.xml file to be the activity intended to be launched. It will not go hunting for launch URLs any activities listed below. * Based closely on code from the SCORM and (to a lesser extent) Resource modules. * @package mod_tincanlaunch * @category tincan * @param object $tincanlaunch An object from the form in mod_form.php * @return array empty if no issue is found. Array of error message otherwise */ function tincanlaunch_process_new_package($tincanlaunch) { global $DB, $CFG; $cmid = $tincanlaunch->coursemodule; $context = context_module::instance($cmid); // Reload TinCan instance. $record = $DB->get_record('tincanlaunch', array('id' => $tincanlaunch->id)); $fs = get_file_storage(); $fs->delete_area_files($context->id, 'mod_tincanlaunch', 'package'); file_save_draft_area_files($tincanlaunch->packagefile, $context->id, 'mod_tincanlaunch', 'package', 0, array('subdirs' => 0, 'maxfiles' => 1)); // Get filename of zip that was uploaded. $files = $fs->get_area_files($context->id, 'mod_tincanlaunch', 'package', 0, '', false); if (count($files) < 1) { return false; } $zipFile = reset($files); $zipFilename = $zipFile->get_filename(); $packagefile = false; $packagefile = $fs->get_file($context->id, 'mod_tincanlaunch', 'package', 0, '/', $zipFilename); $fs->delete_area_files($context->id, 'mod_tincanlaunch', 'content'); $packer = get_file_packer('application/zip'); $packagefile->extract_to_storage($packer, $context->id, 'mod_tincanlaunch', 'content', 0, '/'); //If the tincan.xml file isn't there, don't do try to use it. This is unlikely as it should have been checked when the file was validated. if ($manifestFile = $fs->get_file($context->id, 'mod_tincanlaunch', 'content', 0, '/', 'tincan.xml')) { $xmltext = $manifestFile->get_content(); $defaultorgid = 0; $firstinorg = 0; $pattern = '/&(?!\\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objxml = new xml2Array(); $manifest = $objxml->parse($xmltext); //Update activity id from the first activity in tincan.xml, if it is found. Skip without error if not. (The Moodle admin will need to enter the id manually.) if (isset($manifest[0]["children"][0]["children"][0]["attrs"]["ID"])) { $record->tincanactivityid = $manifest[0]["children"][0]["children"][0]["attrs"]["ID"]; } //Update launch from the first activity in tincan.xml, if it is found. Skip if not. (The Moodle admin will need to enter the url manually.) foreach ($manifest[0]["children"][0]["children"][0]["children"] as $property) { if ($property["name"] === "LAUNCH") { $record->tincanlaunchurl = $CFG->wwwroot . "/pluginfile.php/" . $context->id . "/mod_tincanlaunch/" . $manifestFile->get_filearea() . "/" . $property["tagData"]; } } } // Save reference. return $DB->update_record('tincanlaunch', $record); }
/** * @internal */ function execSoapCall($request, $params = array(), $options = null) { $result = null; $soapHeader = $this->getSoapHeader(); if ($options["retry"] === false) { $retry = false; } else { $retry = true; } unset($options["retry"]); $n = 0; while (true) { try { $soapRes = null; $this->client->__soapCall($request, $params, $options, $soapHeader); $soapRes = $this->client->__getLastResponse(); //$this->auth->setSoapHeader($soapRes['authToken']); $xml = new xml2Array(); $result = $xml->parse($soapRes); //echo htmlentities($result); //A tester : $this->objLastResponse = simplexml_load_string($this->_getBodyContent($this->objLastResponseRaw)); break; } catch (SoapFault $exception) { // if $retryAttempts>0 retry after a random time using exponential backoff // if 'retry' option is false (usually when checking account existence) retries just once $n++; if ($this->retryAttempts > 0 && $n <= $this->retryAttempts && ($retry || $n == 1)) { $minT = 1 + $n * 1000000 / 10; $maxT = pow(2, $n - 1) * 1000000; $waitT = rand($minT, $maxT); usleep($waitT); } else { // we must re-throw the exception here because this method is only called by the // Zm_Account, Zm_Domain, Zm_Server class methods with their own try ... catch throw $exception; break; } } } return $result; }
function dar_browse_build_xml($database){ $dar_collection_root=dar_collection_root(); $path=dirname(__FILE__). "/ressources/dar_collection/$dar_collection_root"; $cache_index="DAR_ARRAY_{$dar_collection_root}_{$database}"; if(is_array($_SESSION[$cache_index][0])){ if(count($_SESSION[$cache_index][0])>0){ writelogs("return array from xml cache $cache_index",__FUNCTION__,__FILE__); return $_SESSION[$cache_index]; }else{ writelogs("bad cache $cache_index ".count($_SESSION[$cache_index][0]) ." rows",__FUNCTION__,__FILE__); } }else{ writelogs("bad cache $cache_index \"not an array\"",__FUNCTION__,__FILE__); } $sock=new sockets(); if(is_file("$path/{$database}.xml")){ writelogs("Reading form file cache \"$path/{$database}.xml\"",__FUNCTION__,__FILE__); $datas=file_get_contents("$path/{$database}.xml"); }else{ writelogs("$path/{$database}.xml didn't exists invoke artica to get cache...",__FUNCTION__,__FILE__); $sock->getfile('DarBrowser:'.$database); if(is_file("$path/{$database}.xml")){ $datas=file_get_contents("$path/{$database}.xml"); }else{ writelogs("unable to stat cache $path/{$database}.xml",__FUNCTION__,__FILE__); return array(); } } writelogs(strlen($datas)." bytes for $database.xml",__FUNCTION__,__FILE__); $datas=str_replace("\n\n","\n",$datas); if(preg_match('#(.+?)<Catalog(.+?)>#is',$datas,$re)){ $datas=str_replace($re[0],'',$datas); $datas=trim($datas); }else{ writelogs("unable to preg #(.+?)<Catalog(.+?)>#is fot these datas",__FUNCTION__,__FILE__); return array(); } $xml=new xml2Array(); $xml->parse("<Catalog format=\"1.0\">$datas"); $_SESSION[$cache_index]=$xml->arrOutput; writelogs("Writing cache index $cache_index ".count($_SESSION[$cache_index][0]) . " rows",__FUNCTION__,__FILE__); return $_SESSION[$cache_index]; }
function GetLogs($fromRev) { global $LNG; $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_URL, 'http://2moons.googlecode.com/svn/trunk/'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type' => 'text/xml', 'Depth' => 1)); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'REPORT'); curl_setopt($ch, CURLOPT_USERAGENT, "2Moons Update API"); curl_setopt($ch, CURLOPT_CRLF, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, sprintf('<?xml version="1.0" encoding="utf-8"?> <S:log-report xmlns:S="svn:"> <S:start-revision>%d</S:start-revision><S:end-revision>%d</S:end-revision><S:path></S:path><S:discover-changed-paths/></S:log-report>', $fromRev, -1)); $DATA = curl_exec($ch); curl_close($ch); if (function_exists('xml_parser_create')) { $xml2Array = new xml2Array(); $arrOutput = $xml2Array->xmlParse($DATA); if ((array) $arrOutput['children'] === $arrOutput['children']) { $fileLogs = array(); foreach ($arrOutput['children'] as $value) { if (empty($value['children'])) { continue; } $array = array(); $array['add'] = array(); $array['edit'] = array(); $array['del'] = array(); foreach ($value['children'] as $entry) { if ($entry['name'] == 'D:VERSION-NAME') { $array['version'] = $entry['tagData']; } if ($entry['name'] == 'D:CREATOR-DISPLAYNAME') { $array['author'] = $entry['tagData']; } if ($entry['name'] == 'S:DATE') { $array['date'] = _date($LNG['php_tdformat'], strtotime($entry['tagData']), $USER['timezone']); } if ($entry['name'] == 'D:COMMENT') { $array['comment'] = makebr($entry['tagData']); } if ($entry['name'] == 'S:ADDED-PATH' || $entry['name'] == 'S:MODIFIED-PATH' || $entry['name'] == 'S:DELETED-PATH') { if (strpos($entry['tagData'], 'trunk/') === false) { continue; } else { $entry['tagData'] = substr($entry['tagData'], 7); } if ($entry['name'] == 'S:ADDED-PATH') { $array['add'][] = $entry['tagData']; } if ($entry['name'] == 'S:MODIFIED-PATH') { $array['edit'][] = $entry['tagData']; } if ($entry['name'] == 'S:DELETED-PATH') { $array['del'][] = $entry['tagData']; } } } array_push($fileLogs, $array); } } else { $fileLogs = array(array('error' => $LNG['up_offline'])); } } else { $fileLogs = array(array('error' => $LNG['up_no_xml_ext'])); } return $fileLogs; }
/** * parse(): Parses an SCORM-File * * @author Matteo Savio <*****@*****.**> * @param msg The location of the imsmanifest.xml * @return The page-tree */ function parse($scormfile) { $tree = array(); // Check if file exists and extract path from filename if (ereg("^(.*)imsmanifest.xml\$", $scormfile, $regs) && is_file($scormfile)) { $this->dir = $regs[1]; $imsfile = $regs[0]; } else { $this->setError("File " . $scormfile . " is no SCORM-File."); return false; } // read content of file, parse the xml to an array and parse the SCORM-File if there is a root-element $xmlstring = file_get_contents($imsfile); // read content of file $objXML = new xml2Array(); $arrOutput = $objXML->parse($xmlstring); // parse the xml to an array if ($arrOutput === false) { $this->setError($objXML->error); return false; } else { if (count($arrOutput) == 1) { $manifest = $this->parse_manifest(array_shift($arrOutput)); // parse the manifest (if a manifest exists) } else { $this->setError("XML not well formed"); return false; } } // merge the organisation with the resources if (isset($manifest["organization"]) && isset($manifest["resources"])) { $tree = $this->combine($manifest["organization"], $manifest["resources"]); } // if there was an error at parsing, false is returned, else the tree if ($this->error) { return false; } return $tree; }
foreach ($cellIterator as $cell) { $clean_products_data = ltrim(rtrim($cell->getCalculatedValue(), " ,"), " ,"); $clean_products_data = trim($clean_products_data); if ($row->getRowIndex() > 1) { $rows[$counter - 1][] = $clean_products_data; } else { $table_cols[] = mslib_befe::strtolower($clean_products_data); } } $counter++; } } // excel eof } else { if ($this->post['format'] == 'xml') { $objXML = new xml2Array(); $arrOutput = $objXML->parse($str); $i = 0; $s = 0; $rows = array(); foreach ($arrOutput[0]['children'] as $item) { // image foreach ($item['children'] as $internalitem) { $rows[$i][$s] = $internalitem['tagData']; $s++; } foreach ($item['attrs'] as $key => $value) { $rows[$i][$s] = $value; $s++; } $i++;
//Need: http://github.com/api/v1/xml/bluescripts/bbug/commits/master $fp = fsockopen("github.com", 80, $errno, $errstr, 30); if (!$fp) { echo "{$errstr} ({$errno})<br />\n"; } else { $out = "GET /api/v1/xml/" . $user_proj . "/commit/" . $sum . " HTTP/1.1\r\n"; $out .= "Host: google.com \r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { $results .= fgets($fp, 128); } fclose($fp); } $post_results = parseHttpResponse($results); $objXML = new xml2Array(); $arrOutput = $objXML->parse($post_results); $g = $arrOutput[0]['children'][3]['children']; for ($i = 0; $i < count($g); $i++) { $file = $g[$i]['children'][1]['tagData']; $diff = $g[$i]['children'][0]['tagData']; $diff = str_replace('>', '>', str_replace('<', '<', $diff)); # do highlighting $diff = preg_replace('/\\+(.*)/', '<span id="add">$1</span>', $diff); $diff = preg_replace('/\\-(.*)/', '<span id="remove">$1</span>', $diff); echo "<div id='file'>{$file}</div>"; echo "<div id='diff'>" . nl2br($diff) . "</div><hr>"; } //$arrOuptut = array_map() //$diff = $arrOutput[] //echo "<pre>";