Example #1
0
 /**
  * Display graphs as embedded images.  Graphs are noon to noon unless parameters are provided. Results undefined if bounds are narrower than data.
  * @param int $startHourPM earliest hour to show in graphs
  * @param int $endHourPM end bound of graphs
  */
 public function displaygraphs($startHourPM = 0, $endHourAM = 0)
 {
     foreach ($this->data as $night) {
         $nightstart = strtotime($night['Start of Night']);
         $nightend = strtotime($night['End of Night']);
         //find noon of that day
         $noon = self::previous_noon($nightstart);
         //start at 9pm (adjust this if you have data earlier than this)
         //The right way to do this would be to actually check the data upfront and set the offset automatically
         $startoffset = 60 * 60 * $startHourPM;
         $starttime = $noon + $startoffset;
         //end data at noon
         $endoffset = 60 * 60 * (12 - $endHourAM);
         //find out how many intervals are needed to pad the data from noon
         $intervalseconds = 30;
         $pad_needed = round(($nightstart - $starttime) / $intervalseconds);
         $pad = str_repeat('0 ', $pad_needed);
         //put the padded data in an array for progressbar
         $sleepdata = explode(' ', $pad . $night['Detailed Sleep Graph']);
         //pad the array for the total number of hours
         $sleepdata = array_pad($sleepdata, (60 * 60 * 24 - $startoffset - $endoffset) / $intervalseconds, 0);
         //print((round($nightend-$nightstart)/30) . '-'. count($sleepdata).'<br>');
         $progressbar = new ProgressBar($sleepdata, 1000, 50, ProgressBar::MODE_INTEGER, 'zeo');
         print $night['Start of Night'] . ' ' . $progressbar->embedded_imagetag() . $night['End of Night'] . '<br>';
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->getOption('remove-before')) {
         $this->get('library.indexation')->deleteIndexes();
         foreach (\LibraryDocumentCollectionPeer::doSelect(new \Criteria()) as $documentCollection) {
             $this->get('library.documentCollection')->map($this->get('library.documentCollection')->export($documentCollection));
         }
     }
     $vocabularyService = $this->get('library.vocabulary');
     foreach ($this->get('library.documentCollection')->getList() as $documentCollection) {
         $documents = $documentCollection->getLibraryDocuments();
         if (count($documents)) {
             $output->writeln($documentCollection->getName() . ':');
             $progress = new ProgressBar($output, count($documents));
             $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%');
             foreach ($documents as $document) {
                 $elasticaDocument = $this->get('library.indexation')->getDocument($document->getId());
                 if (false !== $elasticaDocument && !$input->getOption('update-image')) {
                     $this->get('library.indexation')->refreshDocument($document, $vocabularyService, false);
                 } else {
                     $this->get('library.indexation')->refreshDocument($document, $vocabularyService, !$input->getOption('ignore-image'));
                 }
                 $progress->advance();
             }
             $progress->finish();
             $output->writeln("\n");
         }
     }
 }
 public static function run()
 {
     function getProductSelection()
     {
         echo "Select Product (empty/sku/sku:sku range): ";
         $handle = fopen("php://stdin", "r");
         $line = fgets($handle);
         if (!trim($line)) {
             echo "All Products selected!\n";
             $IDS = array();
             foreach (Mage::getModel('catalog/product')->getCollection() as $prod) {
                 array_push($IDS, $prod->getId());
             }
         } else {
             $input = explode(':', trim($line));
             if (count($input) > 1) {
                 $return = array();
                 for ($i = $input[0]; $i <= $input[1]; $i++) {
                     array_push($return, $i);
                 }
                 $IDS = $return;
             } else {
                 $IDS = $input;
             }
         }
         $products = array();
         foreach ($IDS as $productID) {
             array_push($products, Mage::getModel('catalog/product')->load($productID));
         }
         return $products;
     }
     $products = getProductSelection();
     $progressBar = new ProgressBar(count($products));
     foreach ($products as $product) {
         $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
         if (!$stockItem->getId()) {
             $stockItem->setData('product_id', $product->getId());
             $stockItem->setData('stock_id', 1);
         }
         $stockItem->setData('manage_stock', 1);
         $stockItem->setData('use_config_manage_stock', 1);
         $stockItem->setData('is_in_stock', 1);
         $stockItem->setData('use_config_notify_stock_qty', 1);
         $stockItem->setData('use_config_max_sale_qty', 1);
         $stockItem->setData('use_config_min_sale_qty', 1);
         $stockItem->setData('use_config_backorders', 1);
         $stockItem->setData('use_config_min_qty', 1);
         $stockItem->setData('use_config_enable_qty_inc', 1);
         try {
             $stockItem->save();
             $product->save();
             echo $progressBar->drawCurrentProgress();
         } catch (Exception $e) {
             echo "{$e}";
         }
     }
     echo "Edited " . count($products) . " products\n";
 }
Example #4
0
 public function actionIndex($ajax = null)
 {
     $load = SystemHelper::getLoad();
     $totalspace = disk_total_space(VIREX_STORAGE_PATH);
     $freespace = disk_free_space(VIREX_STORAGE_PATH);
     $slov = new ProgressBar(100, $load, 150);
     $slov->suff = '';
     $slov->doneBg = '#9BB947';
     $duov = new ProgressBar($totalspace, $totalspace - $freespace, 150);
     $duov->suff = '';
     $duov->doneBg = '#9BB947';
     $sysHealth = array(array('id' => 2, 'Property' => 'Operating System', 'Value' => PHP_OS, 'Overview' => ''), array('id' => 3, 'Property' => 'Web server', 'Value' => $_SERVER["SERVER_SOFTWARE"], 'Overview' => ''), array('id' => 4, 'Property' => 'PHP version', 'Value' => PHP_VERSION, 'Overview' => ''), array('id' => 5, 'Property' => 'MySQL version', 'Value' => Yii::app()->db->serverVersion, 'Overview' => ''), array('id' => 1, 'Property' => 'Storage space', 'Value' => FileHelper::formatSize($totalspace - $freespace) . ' / ' . FileHelper::formatSize($totalspace), 'Overview' => $duov->display()), array('id' => 6, 'Property' => 'System load / CPU usage', 'Value' => '', 'Overview' => $slov->display()));
     $this->render('index', array('systemHealth' => new CArrayDataProvider($sysHealth)));
 }
 /**
  * create the static themes in format: array(theme name => array(mapped integer => array(r,g,b)))
  * 
  */
 private static function intialize_themes()
 {
     $lightgray = array(150, 150, 150);
     $gray = array(204, 204, 204);
     $white = array(255, 255, 255);
     $black = array(0, 0, 0);
     $blue = array(0, 0, 255);
     $lightblue = array(30, 144, 255);
     $zeo_deep = array(0, 85, 42);
     //00552A
     $zeo_light = array(153, 152, 155);
     //99989B
     $zeo_rem = array(41, 166, 57);
     //29A639
     $zeo_wake = array(208, 88, 39);
     //D05827
     self::$themes = array();
     //default for movie site
     self::$themes['default_boolean'] = array(self::UNINITIALIZED => $lightgray, self::OFF => $lightgray, self::ON => $blue, self::PARTIAL => $lightblue);
     //match zeo sleep graphs
     self::$themes['zeo'] = array(self::UNINITIALIZED => $white, 0 => $white, 1 => $zeo_wake, 2 => $zeo_rem, 3 => $zeo_light, 4 => $zeo_deep, 4 => $zeo_lightdeep);
 }
        if ($message) {
            $this->message = $message;
        }
        $command = sprintf("%d %s\n", $percent, $message);
        fwrite($this->pipe, $command);
    }
    /**
     * Close progress bar window
     */
    public function finish()
    {
        pclose($this->pipe);
    }
}
/**
 * Sample Usage
 */
$bar = new ProgressBar("ProgressBar.php Test");
for ($percent = 0; $percent < 25; $percent++) {
    usleep(150000);
    // .15 sec
    $bar->update($percent, "Test Starting...");
}
for ($percent = 25; $percent < 100; $percent++) {
    usleep(20000);
    // .02 sec
    $bar->update($percent, "Test Finishing...");
}
usleep(500000);
// .5 sec
$bar->finish();
function generoi_excel_tiedostot(&$data_array, $params, $kieli)
{
    global $yhtiorow;
    echo '<br/>' . t('Tehdään excel tiedostot') . '<br/>';
    $bar2 = new ProgressBar();
    $bar2->initialize(count($data_array) - 1);
    $excel_tiedostot = array();
    $i = 0;
    foreach ($data_array as &$data) {
        $bar2->increase();
        $temp_data = array('osastoittain' => $data['tilaukset_ilman_try'], 'tuoteryhmittain' => $data['tilaukset_try']);
        $excel = new vuosisopimus_asiakkaat_excel();
        $excel->set_kieli($kieli);
        $excel->set_asiakas($data['asiakasrow']);
        $excel->set_yhtiorow($yhtiorow);
        $alkumiinusyks = $params['alkuvv'] - 1;
        $loppumiinusyks = $params['loppuvv'] - 1;
        $excel->set_rajaus_paivat(array('alkupaiva' => $params['alkupp'] . '.' . $params['alkukk'] . '.' . $params['alkuvv'], 'loppupaiva' => $params['loppupp'] . '.' . $params['loppukk'] . '.' . $params['loppuvv'], 'edalkupaiva' => $params['alkupp'] . '.' . $params['alkukk'] . '.' . $alkumiinusyks, 'edloppupaiva' => $params['loppupp'] . '.' . $params['loppukk'] . '.' . $loppumiinusyks));
        $excel->set_tilausrivit($temp_data);
        $excel->set_summat_osastoittain($data['summat_ilman_try']);
        $excel->set_summat_tuoteryhmittain($data['summat_try']);
        $excel_tiedostot[] = $excel->generoi();
        $data['tiedosto'] = $excel_tiedostot[$i];
        unset($excel);
        $i++;
    }
    return $excel_tiedostot;
}
		}

		function endElement($parser, $tagname) {
			if ($tagname == "file") $currentfile = false;
		}

		print "<div class='message'>Updating elements to assess for pool $pool</div>";
		flush();
 	    sql_query("delete from $db_assessments where id_pool=$pool and in_pool='Y' and assessment='U'"); // don't delete assessments
	    $qh = sql_query("select xid, in_pool from $db_assessments where id_pool=$pool"); // don't delete assessments
		while ($row = sql_fetch_array($qh)) {
			$already_to_assess[$row["xid"]] = $row["in_pool"];
		}
		sql_free($qh);
		$number_inserted = $number_updated = 0;
		$bar = new ProgressBar(0,filesize($filename));
		$fh = fopen($filename,"r");
		$xml_parser = xml_parser_create();
		xml_set_element_handler($xml_parser, "startElement", "endElement");
		xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, FALSE);
		$bytes_read = 0;
		while ($data = fread($fh, 4096)) {
			$bytes_read += strlen($data);
			$bar->update($bytes_read);
    		if (!xml_parse($xml_parser, $data, feof($fh))) {
		        make_footer(sprintf("XML error: %s at line %d",
            	        xml_error_string(xml_get_error_code($xml_parser)),
                    	xml_get_current_line_number($xml_parser)));
    		}
		}
		?><div class="message"><?php 
Example #9
0
 $worksheet->writeString($excelrivi, $excelsarake++, t("Tuoteryhmä"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Tuoteno"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Nimitys"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Varastosaldo"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Vapaa saldo"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Tulossa"));
 $worksheet->writeString($excelrivi, $excelsarake++, t("Toimitusaika"));
 $excelrivi++;
 $query = "SELECT tuote.tuoteno, tuote.nimitys, tuote.osasto, tuote.try\n            FROM tuote\n            {$toimittaja_join}\n            WHERE tuote.yhtio                       = '{$kukarow["yhtio"]}'\n            {$lisa}\n            AND (tuote.status != 'P' OR (  SELECT sum(tuotepaikat.saldo)\n                            FROM tuotepaikat\n                            WHERE tuotepaikat.yhtio = tuote.yhtio\n                            AND tuotepaikat.tuoteno = tuote.tuoteno\n                            AND tuotepaikat.saldo   > 0) > 0)\n            ORDER BY tuote.osasto, tuote.try, tuote.tuoteno";
 $eresult = pupe_query($query);
 $total_rows = mysql_num_rows($eresult);
 $current_row = 0;
 if ($total_rows > 0) {
     echo "<font class='message'>", t("Käsitellään"), " {$total_rows} ", t("tuotetta"), ".</font>";
     require 'inc/ProgressBar.class.php';
     $bar = new ProgressBar();
     $bar->initialize($total_rows);
     // print the empty bar
     while ($row = mysql_fetch_assoc($eresult)) {
         $bar->increase();
         // ostopuoli
         $query = "SELECT min(toimaika) toimaika,\n                sum(varattu) tulossa\n                FROM tilausrivi\n                WHERE yhtio = '{$kukarow["yhtio"]}'\n                AND tuoteno = '{$row["tuoteno"]}'\n                AND tyyppi  = 'O'\n                AND varattu > 0";
         $ostoresult = pupe_query($query);
         $ostorivi = mysql_fetch_assoc($ostoresult);
         // Ajetaan saldomyytävissä niin, että JT-rivejä ei huomioida suuntaaan eikä toiseen
         list($saldo, $hyllyssa, $myytavissa) = saldo_myytavissa($row["tuoteno"], 'JTSPEC');
         $query = "SELECT sum(jt {$lisavarattu}) jt\n                FROM tilausrivi use index (yhtio_tyyppi_tuoteno_laskutettuaika)\n                WHERE yhtio        = '{$kukarow["yhtio"]}'\n                and tyyppi         in ('L','G')\n                and tuoteno        = '{$row["tuoteno"]}'\n                and laskutettuaika = '0000-00-00'\n                and jt {$lisavarattu} > 0\n                and kpl            = 0\n                and var            = 'J'";
         $juresult = pupe_query($query);
         $jurow = mysql_fetch_assoc($juresult);
         if ($myytavissa - $jurow["jt"] + $ostorivi["tulossa"] < 0) {
             $osastores = t_avainsana("OSASTO", "", "and avainsana.selite ='{$row['osasto']}'");
Example #10
0
            }
        }
        unset($levels, $date_min, $date_max, $i, $row, $created, $level, $parent_id);
        print ProgressBar::finish();
        print "DONE\r\n\n";
    }
}
// Generate articles.
if ($numbers['articles']) {
    ProgressBar::start($numbers['articles']);
    ProgressBar::setMessage('Adding articles...');
    $date_min = new DateTime('-3 years');
    $date_max = new DateTime();
    for ($i = 0; $i < $numbers['articles']; $i++) {
        $row = Library\ObjectManager::getInstance()->getObject('com:articles.model.articles')->getItem();
        $row->title = $generator->words(pick_random(range(1, 5)));
        $row->introtext = $generator->sentences(pick_random(range(1, 3)));
        $row->fulltext = $generator->sentences(pick_random(range(0, 5)));
        $row->published = (int) (rand(0, 20) > 0);
        $row->categories_category_id = pick_random($categories['articles']);
        $created = new DateTime('@' . rand($date_min->format('U'), $date_max->format('U')));
        $row->created_on = $created->format('Y-m-d H:i:s');
        $row->created_by = pick_random($users);
        $row->save();
        print ProgressBar::next();
    }
    unset($date_min, $date_max, $i, $row, $created);
    print ProgressBar::finish();
    print "DONE\r\n\n";
}
exit(0);
Example #11
0
    $styletab .= '  </style>' . "\n\n";
    if ($minsdk == 'holo') {
        $stylev11 .= $styletab;
        $style11_available = true;
    } else {
        $stylev8 .= $styletab;
        $style8_available = true;
    }
}
// ============= progressbar ================ //
if (isset($progressbar) && $progressbar == true) {
    require_once HOLO_COLORS_COMPONENTS_PATH . '/progressbar/common-progressbar.php';
    $logger->debug("generate progressbar");
    $img_sizes = array('mdpi', 'hdpi', 'xhdpi', 'xxhdpi');
    for ($i = 1; $i <= 8; $i++) {
        $pb = new ProgressBar("widgets/progressbar/", $i);
        foreach ($img_sizes as $img_size) {
            $pb->generate_image($color, $img_size, $holo, $kitkat);
        }
    }
    foreach ($progressbar_classes as $clazz) {
        generateImageOnDisk($clazz, $color, $holo, $kitkat, "widgets/progressbar/");
    }
    copy_directory("widgets/progressbar/res/", $folder . "/res/", $holo, $lower_name);
    if ($holo == "dark") {
        $stylev11 .= '  <style name="ProgressBar' . $name . '" parent="android:Widget.Holo.ProgressBar.Horizontal">' . "\n";
    } else {
        $stylev11 .= '  <style name="ProgressBar' . $name . '" parent="android:Widget.Holo.Light.ProgressBar.Horizontal">' . "\n";
    }
    $stylev11 .= '      <item name="android:progressDrawable">@drawable/' . $lower_name . '_progress_horizontal_holo_' . $holo . '</item>' . "\n";
    $stylev11 .= '      <item name="android:indeterminateDrawable">@drawable/' . $lower_name . '_progress_indeterminate_horizontal_holo_' . $holo . '</item>' . "\n";
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
Example #13
0
         exit;
     } else {
         // Jos tullaan api.php:stä ja päädytään virheeseen, tällä estetään ettei mennä for-looppiin riville 650
         // EI voida sanoa EXIT tai DIE koska api.php pitää mennä loppuun.
         $taulunrivit[$taulu] = array();
         $api_status = FALSE;
     }
 }
 lue_data_echo("<br><font class='message'>" . t("Tiedosto ok, aloitetaan päivitys") . " {$table_mysql}-" . t("tauluun") . "...<br></font>");
 lue_data_echo($lue_data_output_text, true);
 $lue_data_output_text = "";
 $rivilaskuri = 1;
 $puun_alkio_index_plus = 0;
 // REST-api ei salli etenemispalkkia
 if ((!$cli or $lue_data_output_file != "") and !isset($api_kentat)) {
     $bar = new ProgressBar();
     $bar->initialize($rivimaara);
 }
 $lisatyt_indeksit = array();
 for ($eriviindex = 0; $eriviindex < $rivimaara + $puun_alkio_index_plus; $eriviindex++) {
     // Komentorivillä piirretään progressbar, ellei ole output loggaus päällä
     // REST-api skippaa
     if (!isset($api_kentat)) {
         if ($cli and $lue_data_output_file == "") {
             progress_bar($eriviindex, $max_rivit);
         } elseif (!$cli or $lue_data_output_file != "") {
             $bar->increase();
         }
     }
     $hylkaa = 0;
     $tila = "";
Example #14
0
 }
 if ($aTableInfo['shared'] && empty($_POST['target'])) {
     lovd_errorAdd('target', 'Please select a ' . $aTableInfo['unit'] . ' from the list!');
 }
 if (!lovd_error()) {
     $_T->printHeader();
     $_T->printTitle();
     $sMessage = 'Removing column from data table ' . ($tAlter < 4 ? '' : '(this make take some time)') . '...';
     // If ALTER time is large enough, mention something about it.
     // ... but only if we're running it...
     if (!($aTableInfo['shared'] && count($aTargets) < $nPossibleTargets) && $tAlter > $tAlterMax) {
         lovd_showInfoTable('Please note that the time estimated to remove this column from the ' . $aTableInfo['table_name'] . ' data table is <B>' . round($tAlter) . ' seconds</B>.<BR>During this time, no updates to the data table are possible. If other users are trying to update information in the database during this time, they will have to wait a long time, or get an error.', 'warning');
     }
     require ROOT_PATH . 'class/progress_bar.php';
     // This already puts the progress bar on the screen.
     $_BAR = new ProgressBar('', $sMessage);
     $_T->printFooter(false);
     // The false prevents the footer to actually close the <BODY> and <HTML> tags.
     // Now we're still in the <BODY> so the progress bar can add <SCRIPT> tags as much as it wants.
     flush();
     // Now, end with ALTER TABLE if necessary, since that will take the longest time and ends a transaction anyway.
     if (!$aTableInfo['shared']) {
         // Query text; remove column registration first.
         $sQ = 'DELETE FROM ' . TABLE_ACTIVE_COLS . ' WHERE colid = ?';
         $_DB->query($sQ, array($zData['id']));
         $_BAR->setProgress(20);
         $_BAR->setMessage('Removing column...');
         // The whole transaction stuff is useless here; alter table will commit and there's just one query before that.
         // Alter data table.
         $sQ = 'ALTER TABLE ' . $aTableInfo['table_sql'] . ' DROP COLUMN `' . $zData['id'] . '`';
         $_DB->query($sQ);
Example #15
0
	function moveRoom(cs_environment $environment, cs_list $afterList, cs_room_item $roomItem, $exec = false, $newPortalId) {
		$linkedProjectedRoomItems = new cs_list();

		if ($exec) {
			if ($roomItem) {
				global $environment;

				$oldPortalId = $roomItem->getContextID();

				$portalManager = $environment->getPortalManager();
				$oldPortal = $portalManager->getItem($oldPortalId);

				$userManager = $environment->getUserManager();

				$roomList = new cs_list();
				$roomList->add($roomItem);

				// search for associated project rooms in list after this entry
				if ($roomItem->isCommunityRoom()) {
					$projectRoomList = $roomItem->getProjectRoomList();

					$afterListItem = $afterList->getFirst();
					while ($afterListItem) {
						if ($projectRoomList->inList($afterListItem)) {
							$linkedProjectedRoomItems->add($afterListItem);
						}

						$afterListItem = $afterList->getNext();
					}

					$roomList->addList($linkedProjectedRoomItems);
				} else if ($roomItem->isGrouproomActive()) {
					$groupManager = $environment->getGroupManager();
					$groupManager->setContextLimit($roomItem->getItemID());
					$groupManager->select();
					$groupList = $groupManager->get();

					if ($groupList->isNotEmpty()) {
						$groupItem = $groupList->getFirst();

						while($groupItem) {
							if ($groupItem->isGroupRoomActivated()) {
								$groupRoomItem = $groupItem->getGroupRoomItem();

								if (isset($groupRoomItem) && !empty($groupRoomItem)) {
									$roomList->add($groupRoomItem);
								}
							}

							$groupItem = $groupList->getNext();
						}
					}
				}

				$roomNameArray = array();
				$userArray = array();
				$authSourceArray = array();

				$roomListItem = $roomList->getFirst();
				while ($roomListItem) {

					$roomNameArray[$roomListItem->getItemID()] = $roomListItem->getTitle();

					$userManager->resetLimits();
					$userManager->setContextLimit($roomListItem->getItemID());
					$userManager->select();
					$userList = $userManager->get();

					if ($userList->isNotEmpty()) {
						$userItem = $userList->getFirst();

						while($userItem) {
							$authSourceArray[$userItem->getAuthSource()] = $userItem->getAuthSource();
							$userIdTest = $userItem->getUserID();

							if (!empty($userIdTest)) {
								$userRoomArray[$userItem->getUserID() . "__CS__" . $userItem->getAuthSource()] = $roomListItem->getItemID();

								if (empty($userArray[$userItem->getUserID()])) {
									$portalUserItem = $userItem->getRelatedCommSyUserItem();

									if (isset($portalUserItem)) {
										$userArray[$userItem->getUserID() . "__CS__" . $userItem->getAuthSource()] = $portalUserItem;
									}
								}

								$userIdTest = $userItem->getUserID();
							}

							$userItem = $userList->getNext();
						}
					}

					$roomListItem = $roomList->getNext();
				}

				$authSourceTranslationArray = array();
				$authSourceFindArray = array();
				$authSourceItemArray = array();

				$newPortal = $portalManager->getItem($newPortalId);
				$authSourceListNew = $newPortal->getAuthSourceList();

				foreach ($authSourceArray as $authSourceId) {
					$authSourceManager = $environment->getAuthSourceManager();

					$authSourceItemOld = $authSourceManager->getItem($authSourceId);
					$authSourceItemArray[$authSourceItemOld->getItemID()] = $authSourceItemOld;

					if (!$authSourceListNew->isEmpty()) {
						$authSourceItemNew = $authSourceListNew->getFirst();

						while ($authSourceItemNew) {
							$authSourceItemArray[$authSourceItemNew->getItemID()] = $authSourceItemNew;

							if ($authSourceItemOld->isCommSyDefault() && $authSourceItemNew->isCommSyDefault()) {
								$authSourceTranslationArray[$authSourceItemOld->getItemID()] = $authSourceItemNew->getItemID();
							}

							$authSourceItemNew = $authSourceListNew->getNext();
						}
					}
				}

				$authSourceNotTranslationArray = array();
				foreach ($authSourceArray as $authSourceId) {
					if (!array_key_exists($authSourceId, $authSourceTranslationArray)) {
						$authSourceNotTranslationArray[] = $authSourceId;
					}
				}

				$authSourceManager = $environment->getAuthSourceManager();
				foreach ($authSourceNotTranslationArray as $authSourceId) {
					$authSourceItemOld = $authSourceManager->getItem($authSourceId);
					
					$authSourceItemNew = clone $authSourceItemOld;
					$authSourceItemNew->setItemID('');
					$authSourceItemNew->setContextID($newPortalId);
					$authSourceItemNew->save();

					$authSourceTranslationArray[$authSourceItemOld->getItemID()] = $authSourceItemNew->getItemID();
					$authSourceItemArray[$authSourceItemNew->getItemID()] = $authSourceItemNew;
				}

				$userArrayAll = $userArray;
				$userArrayNew = array();

				$failure = false;
				$userChangeArray = array();
				foreach ($userArrayAll as $key => $userItem) {
					// does the user exist on current portal?
					$authentication = $environment->getAuthenticationObject();

					$userId = $userItem->getUserID();
					$authSource = $userItem->getAuthSource();
					$first = true;
					$go = true;

					while ($go) {
						$userManager->resetLimits();
						$userManager->setContextLimit($newPortalId);
						$userManager->setAuthSourceLimit($authSourceTranslationArray[$authSource]);
						$userManager->setUserIDLimit($userId);
						$userManager->select();
						$userList = $userManager->get();

						// commsy auth source, user id already exists
						if ($userList->isNotEmpty() && $userList->getCount() == 1) {
							$userItem2 = $userList->getFirst();

							// email is equal
							if ($userItem2->getEmail() == $userItem->getEmail()) {
								unset($userArray[$userItem->getUserID() . "__CS__" . $userItem->getAuthSource()]);

								if ($userItem->getUserID() != $userId) {
									$userChangeArray[$userItem->getUserID() . "__CS__" . $authSourceTranslationArray[$authSource]] = $userId;
								} else {
									$userArrayNoChange[$userItem->getUserID() . "__CS__" . $authSourceTranslationArray[$authSource]] = $userItem;
								}

								$go = false;
							} else {
								// generate new user id
								if ($first) {
									$first = false;
									$userId .= '1';
								} else {
									$count = $userId{mb_strlen($userId) - 1};
									$count = (int) $count;
									$count++;

									$userId = mb_substr($userId, 0, mb_strlen($userId) - 1);
									$userId .= $count;
								}
							}
						} elseif ($userList->isNotEmpty() && $userList->getCount() > 1) {
							include_once('functions/error_functions.php');
							trigger_error('ERROR: multiple user id ' . $userId . ' for one portal',E_USER_WARNING);
							$go = false;
							$failure = true;
						} else {
							// find free user id
							if ($userItem->getUserID() != $userId) {
								$userChangeArray[$userItem->getUserID() . "__CS__" . $authSourceTranslationArray[$authSource]] = $userId;
							} else {
								$userArrayNoChange[$userItem->getUserID() . "__CS__" . $authSourceTranslationArray[$authSource]] = $userItem;
							}

							$go = false;
						}
					}
				}

				if ($failure) {
					die("ERROR");
				}

				// commsy auth source
				// copy auth (user_id and password) and user (normal information) items
				foreach ($userArray as $key => $userItem) {
					$keyArray = explode("__CS__", $key);

					$userIdKey = $keyArray[0];
					$authSourceKey = $keyArray[1]; // old auth source

					$authManager = $authentication->getAuthManager($userItem->getAuthSource());
					$authManager->setContextLimit($oldPortalId);
					$authItemOld = $authManager->getItem($userItem->getUserID());

					if (!empty($authItemOld)) {
						$authItemNew = clone $authItemOld;
						$authItemNew->setPortalID($newPortalId);
						$authItemNew->setAuthSourceID($authSourceTranslationArray[$authSourceKey]);

						if (!empty($userChangeArray[$userIdKey . "__CS__" . $authSourceTranslationArray[$authSourceKey]])) {
							$authItemNew->setUserID($userChangeArray[$userIdKey . "__CS__" . $authSourceTranslationArray[$authSourceKey]]);
						}

						$authManager = $authentication->getAuthManager($authSourceTranslationArray[$authSourceKey]);
						$authManager->setContextLimit($newPortalId);
						$userIdAuthNew = $authItemNew->getUserID();

						if (!empty($userIdAuthNew)) {
							$authManager->save($authItemNew);
						}
					}

					unset ($userIdAuthNew);

					$userItemNew = $userItem->cloneData();
					$userItemNew->setContextID($newPortalId);

					$tempUser = $userManager->getItem($userItem->getCreatorID());
					$userItemNew->setCreatorItem($tempUser);

					if (!empty($userChangeArray[$userIdKey . "__CS__" . $authSourceTranslationArray[$authSourceKey]])) {
						$userItemNew->setUserID($userChangeArray[$userIdKey . "__CS__" . $authSourceTranslationArray[$authSourceKey]]);
					}

					$userIdUserNew = $userItemNew->getUserID();

					$userItemNew->setAuthSource($authSourceTranslationArray[$authSourceKey]);

					if (!empty($userIdUserNew)) {
						$userItemNew->save();
						$userItemNew->setCreatorID2ItemID();
					}
				}

				// external auth sources
				foreach ($userArrayNew as $key => $userItem) {
					$keyArray = explode("__CS__", $key);

					$userIdKey = $keyArray[0];
					$authSourceKey = $keyArray[1];

					$userItemnew = $userItem->cloneData();
					$userItemNew->setContextID($newPortalId);

					$tempUser = $userManager->getItem($userItem->getCreatorID());
					$userItemNew->setCreatorItem($tempUser);

					$userIdUserNew = $userItemNew->getUserID();

					$userItemNew->setAuthSource($authSourceKey);

					if (!empty($userIdUserNew)) {
						$userItemNew->save();
						$userItemNew->setCreatorID2ItemID();
					}
				}

				// change user ids of user in rooms to move
				// and cahnge auth source of user in rooms to move
				$roomListItem = $roomList->getFirst();
				while ($roomListItem) {
					$userManager = $environment->getUserManager();
					$userManager->resetLimits();
					$userManager->setContextLimit($roomListItem->getItemID());
					$userManager->select();

					$userList = $userManager->get();
					if ($userList->isNotEmpty()) {
						$userItem = $userList->getFirst();

						while ($userItem) {
							$userIdTest = $userItem->getUserID();

							if (!empty($userIdTest) && !empty($userChangeArray[$userIdTest . "__CS__" . $authSourceTranslationArray[$userItem->getAuthSource()]])) {
								$userItem->setUserID($userChangeArray[$userIdTest . "__CS__" . $authSourceTranslationArray[$userItem->getAuthSource()]]);
							}

							$newAuthSourceForUser = $authSourceTranslationArray[$userItem->getAuthSource()];
							$userItem->setAuthSource($newAuthSourceForUser);

							$userItem->setChangeModificationOnSave(false);
							$userItem->setSaveWithoutLinkModifier();
							$userItem->save();

							$userItem = $userList->getNext();
						}
					}

					// delete old links from community room to project rooms
					// before saving on new potal
					if ($linkedProjectedRoomItems->isEmpty() && $roomListItem->isCommunityRoom()) {
						$roomListItem->setProjectListByID(array());
						$roomListItem->save();
					}

					// move files from old portal folder to new portal folder
					$oldContext = $roomListItem->getContextID();
					$newContext = $newPortalId;
					if ($oldContext != $newContext) {
						$discManager = $environment->getDiscManager();
						$discManager->moveFiles($roomListItem->getItemID(), $oldContext, $newContext);
					}

					$roomListItem->setContextID($newPortalId);

					// set link between project and community room
					if ($linkedProjectedRoomItems->isNotEmpty() && $roomListItem->isProjectRoom()) {
						$tempArray = array();
						$tempArray[] = $roomItem->getItemID();
						$roomListItem->setCommunityListByID($tempArray);
					}

					// save room with new context id
					$roomListItem->save();
					echo ProgressBar::next();

					$roomListItem = $roomList->getNext();
				}
			}
		} else {
			usleep(1000);
			echo ProgressBar::next();
		}

		return $linkedProjectedRoomItems;
	}
Example #16
0
 if (!isset($_SESSION['work'][$sPathBase])) {
     $_SESSION['work'][$sPathBase] = array();
 }
 while (count($_SESSION['work'][$sPathBase]) >= 5) {
     unset($_SESSION['work'][$sPathBase][min(array_keys($_SESSION['work'][$sPathBase]))]);
 }
 $zGene = $_DB->query('SELECT id, name, chromosome, refseq_UD FROM ' . TABLE_GENES . ' WHERE id = ?', array($sGene))->fetchAssoc();
 $_T->printHeader();
 $_T->printTitle();
 require ROOT_PATH . 'class/progress_bar.php';
 require ROOT_PATH . 'inc-lib-form.php';
 // Generate a unique workID, that is sortable.
 $nTime = gettimeofday();
 $_POST['workID'] = $nTime['sec'] . $nTime['usec'];
 $sFormNextPage = '<FORM action="' . $sPath . '" id="createTranscript" method="post">' . "\n" . '          <INPUT type="hidden" name="workID" value="' . $_POST['workID'] . '">' . "\n" . '          <INPUT type="submit" value="Continue &raquo;">' . "\n" . '        </FORM>';
 $_BAR = new ProgressBar('', 'Collecting transcript information...', $sFormNextPage);
 $_T->printFooter(false);
 // The false prevents the footer to actually close the <BODY> and <HTML> tags.
 // Now we're still in the <BODY> so the progress bar can add <SCRIPT> tags as much as it wants.
 flush();
 require ROOT_PATH . 'class/soap_client.php';
 $_Mutalyzer = new LOVD_SoapClient();
 $_BAR->setMessage('Collecting all available transcripts...');
 $_BAR->setProgress(0);
 $aTranscripts = $_DATA->getTranscriptPositions($zGene['refseq_UD'], $zGene['id'], $zGene['name'], $nProgress);
 $_SESSION['work'][$sPathBase][$_POST['workID']]['values'] = array('gene' => $zGene, 'transcripts' => $aTranscripts['id'], 'transcriptMutalyzer' => $aTranscripts['mutalyzer'], 'transcriptsProtein' => $aTranscripts['protein'], 'transcriptNames' => $aTranscripts['name'], 'transcriptPositions' => $aTranscripts['positions'], 'transcriptsAdded' => $aTranscripts['added']);
 $_BAR->setProgress(100);
 $_BAR->setMessage('Information collected, now building form...');
 $_BAR->setMessageVisibility('done', true);
 print '<SCRIPT type="text/javascript">' . "\n" . '  document.forms[\'createTranscript\'].submit();' . "\n" . '</SCRIPT>' . "\n\n";
 print '</BODY>' . "\n" . '</HTML>' . "\n";
Example #17
0
 if (!empty($_POST)) {
     lovd_errorClean();
     // Mandatory fields.
     if (empty($_POST['password'])) {
         lovd_errorAdd('password', 'Please fill in the \'Enter your password for authorization\' field.');
     }
     // User had to enter his/her password for authorization.
     if ($_POST['password'] && !lovd_verifyPassword($_POST['password'], $_AUTH['password'])) {
         lovd_errorAdd('password', 'Please enter your correct password for authorization.');
     }
     if (!lovd_error()) {
         // Throwing away full submissions in one go is unfortunately not an option due to the many-to-many connection between screening and variant.
         // Deleting an individual does not delete its variants. Therefore, we might as well approach this the LOVD2 way: delete the variants, then delete the empty screenings, then the empty individuals.
         // Of course we MUST make sure those are at least entries related to the removed variants in question, otherwise we'll be deleting too much data (LOVD2 never allowed orphaned data like we do now).
         require ROOT_PATH . 'class/progress_bar.php';
         $_BAR = new ProgressBar('', 'Gathering data...');
         $aDone = array();
         $nDone = 0;
         $_DB->beginTransaction();
         // Determine which transcripts need their data deleted...
         // We must have transcripts and variants, otherwise we cannot get to this point.
         $aTranscripts = $_DB->query('SELECT id FROM ' . TABLE_TRANSCRIPTS . ' WHERE geneid = ?', array($sID))->fetchAllColumn();
         // Then determine which VOGs need to be deleted, because they will point to nothing else...
         $aVOGs = $_DB->query('SELECT DISTINCT vog.id FROM ' . TABLE_VARIANTS . ' AS vog INNER JOIN ' . TABLE_VARIANTS_ON_TRANSCRIPTS . ' AS vot1 ON (vog.id = vot1.id AND vot1.transcriptid IN (?' . str_repeat(', ?', count($aTranscripts) - 1) . ')) LEFT OUTER JOIN ' . TABLE_VARIANTS_ON_TRANSCRIPTS . ' AS vot2 ON (vog.id = vot2.id AND vot2.transcriptid NOT IN (?' . str_repeat(', ?', count($aTranscripts) - 1) . ')) WHERE vot2.transcriptid IS NULL', array_merge($aTranscripts, $aTranscripts), true)->fetchAllColumn();
         $_BAR->setProgress(10);
         $_BAR->setMessage('Deleting variants...');
         // Delete the VOTs!
         $q = $_DB->query('DELETE FROM ' . TABLE_VARIANTS_ON_TRANSCRIPTS . ' WHERE transcriptid IN (?' . str_repeat(', ?', count($aTranscripts) - 1) . ')', $aTranscripts);
         $aDone['Variants_On_Transcripts'] = $q->rowCount();
         $nDone++;
         unset($aTranscripts);
Example #18
0
    /**
     * Import COAs skipping same value and updating changed
     * @param $clientID
     * @param $projectID
     * @param $importedCoas
     */
    public static function importUniqueCOAs($clientID, $projectID, $importedCoas)
    {
        $all_amount=count($importedCoas);
        $i=0;
        ProgressBar::toZero();
        $pb= ProgressBar::init();


        //1.2 select from database all acctNumbers
        $list_items = Coa::getAllCoasAcctNumbers(Yii::app()->user->clientID,Yii::app()->user->projectID);

        foreach ($importedCoas as $imported_item) {

            $result_coa_model = self::addSingleCOA($clientID, $projectID, $imported_item,$list_items);

            /**
             * * Next block used for progress bar animation only
             * As COAs importing about 75% percents of whole COA Importing -so we multiply on 75 (not on 100)
             */
                $i++;
                $percent=intval($i/$all_amount*100);
                session_start();
                $_SESSION['progress']=$percent;
                session_write_close();
            //end of block
        }

    }
<?php

/**
 * Copyright 2013 Android Holo Colors by Jérôme Van Der Linden
 * Copyright 2010 Android Asset Studio by Google Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require_once 'common-progressbar.php';
$color = $_GET['color'];
$size = $_GET['size'];
$holo = $_GET['holo'];
$number = $_GET['number'];
if (isset($color) && isset($size) && isset($holo) && isset($number)) {
    $et = new ProgressBar(HOLO_COLORS_COMPONENTS_PATH . '/progressbar/', $number);
    $et->generate_image($color, $size, $holo);
}
Example #20
0
     if (!lovd_verifyPassword($_POST['password'], $_AUTH['password'])) {
         lovd_errorAdd('password', 'Please enter your correct password for authorization.');
     }
 }
 if (!lovd_error()) {
     if (isset($_GET['confirm'])) {
         // Check password.
         if (!lovd_verifyPassword($_POST['password'], $_AUTH['password'])) {
             lovd_errorAdd('password', 'Please enter your correct password for authorization.');
         }
         if (!lovd_error()) {
             // OK, uninstall the lot.
             print '      <B>Uninstalling LOVD...</B><BR>' . "\n" . '      <BR>' . "\n\n";
             require ROOT_PATH . 'class/progress_bar.php';
             // This already puts the progress bar on the screen.
             $_BAR = new ProgressBar('', 'Initiating removal of LOVD...');
             $_T->printFooter(false);
             // The false prevents the footer to actually close the <BODY> and <HTML> tags.
             // Now we're still in the <BODY> so the progress bar can add <SCRIPT> tags as much as it wants.
             flush();
             // The reason to invert the tables is to handle all foreign key constraints nicely.
             $aTables = array_reverse($_TABLES);
             $nTables = count($aTables);
             $_BAR->setMessage('Removing data tables...');
             // Actually run the SQL...
             $nSQLDone = 0;
             $nSQLDonePercentage = 0;
             $nSQLDonePercentagePrev = 0;
             foreach ($aTables as $sTable) {
                 $sSQL = 'DROP TABLE IF EXISTS ' . $sTable;
                 $q = $_DB->query($sSQL, array(), false);
 /**
  * Return via Ajax current status of running tool job
  */
 public function GetJobStatus()
 {
     if (!$this->request->isLoggedIn() || !$this->request->user->canDoAction('can_use_plugin_tools')) {
         $this->response->setRedirect($this->request->config->get('error_display_url') . '/n/3500?r=' . urlencode($this->request->getFullUrlPath()));
         return;
     }
     $ps_job_id = $this->request->getParameter('job_id', pString);
     $o_progress = new ProgressBar('WebUI', null, $ps_job_id);
     $va_data = $o_progress->getDataForJobID();
     $va_data['elapsedTime'] = caFormatInterval(time() - $va_data['start']);
     $this->view->setVar('jobinfo', $va_data);
     $this->render('tools/tool_runjob_json.php');
 }
Example #22
0
 static function Shutdown()
 {
     $error = error_get_last();
     if ($error !== NULL and isset($error['type']) and $error['type'] == 1) {
         //Only trigger fatal errors on shutdown.
         self::$php_errors++;
         self::Text('PHP ERROR - FATAL(' . $error['type'] . '): ' . $error['message'] . ' File: ' . $error['file'] . ' Line: ' . $error['line'], $error['file'], $error['line'], __METHOD__, 1);
         if (defined('TIMETREX_API') and TIMETREX_API == TRUE) {
             //Only when a fatal error occurs.
             global $amf_message_id;
             if ($amf_message_id != '') {
                 $progress_bar = new ProgressBar();
                 $progress_bar->start($amf_message_id, 2, 1, TTi18n::getText('ERROR: Operation cannot be completed.'));
                 unset($progress_bar);
             }
         }
     }
     if (self::$php_errors > 0) {
         self::Text('Detected PHP errors (' . self::$php_errors . '), emailing log...');
         self::Text('---------------[ ' . Date('d-M-Y G:i:s O') . ' (PID: ' . getmypid() . ') ]---------------');
         self::emailLog();
         if ($error !== NULL) {
             //Fatal error, write to log once more as this won't be called automatically.
             self::writeToLog();
         }
     }
     return TRUE;
 }
Example #23
0
    /**
     * Import Vendors
     * @param $clientID
     * @param $importedVendors
     */
    public static function importVendors($clientID, $importedVendors)
    {

        $all_amount=count($importedVendors);

        $i=0;
        $pb= ProgressBar::init();

        foreach($importedVendors as $importedVendor) {
            $company = Companies::model()->with('client')->findByAttributes(array(
                'Company_Fed_ID' => $importedVendor['fedId'],
            ));

            if ($company) {
                $client = $company->client;
            } else {
                //if company does not exists, create new company
                $client = Companies::createEmptyCompany($importedVendor['fedId'],  $importedVendor['companyName'], $importedVendor);
            }

            $vendorClientId = $client->Client_ID;

            $vendor = Vendors::model()->findByAttributes(array(
                'Client_Client_ID' => $clientID,
                'Vendor_Client_ID' => $vendorClientId,
            ));
            $newVendor = false;

            if (!$vendor) {
                $vendor = new Vendors();
                $newVendor = true;
            } else {
                $vendor->Active_Relationship = self::ACTIVE_RELATIONSHIP;
                $vendor->save();
            }

            $vendor->Vendor_ID_Shortcut = $importedVendor['shortcut'];
            $vendor->Vendor_Client_ID = $vendorClientId;
            $vendor->Client_Client_ID = $clientID;
            $vendor->Vendor_Name_Checkprint = $importedVendor['checkprint'];
            $vendor->Vendor_1099 = $importedVendor['v1099'];
            $vendor->Vendor_Default_GL = $importedVendor['defG'];
            $vendor->Vendor_Default_GL_Note = $importedVendor['defGLNote'];
            $vendor->Vendor_Note_General = $importedVendor['noteGeneral'];

            if ($vendor->validate()) {
                $vendor->save();
            } else if ($newVendor) {
                $vendor = new Vendors();
                $vendor->Vendor_ID_Shortcut = '';
                $vendor->Vendor_Client_ID = $vendorClientId;
                $vendor->Client_Client_ID = $clientID;
                $vendor->Vendor_Name_Checkprint = '';
                $vendor->Vendor_1099 = '';
                $vendor->Vendor_Default_GL = '';
                $vendor->Vendor_Default_GL_Note = '';
                $vendor->Vendor_Note_General = '';
                $vendor->Active_Relationship = self::ACTIVE_RELATIONSHIP;
                $vendor->save();
            }

            $i++;
            $percent=intval($i/$all_amount*100);
            session_start();
            $_SESSION['progress']=$percent;
            session_write_close();
        }
    }
Example #24
0
     $sqlhaku = "";
 }
 if ($sqlhaku != '' and isset($suoritanappi)) {
     $result = pupe_query($sqlhaku);
     if (mysql_num_rows($result) > 0) {
         require 'inc/ProgressBar.class.php';
         include 'inc/pupeExcel.inc';
         $worksheet = new pupeExcel();
         $format_bold = array("bold" => TRUE);
         $excelrivi = 0;
         $sarakemaara = mysql_num_fields($result);
         for ($i = 0; $i < $sarakemaara; $i++) {
             $worksheet->write($excelrivi, $i, ucfirst(t(mysql_field_name($result, $i))), $format_bold);
         }
         $excelrivi++;
         $bar = new ProgressBar();
         $bar->initialize(mysql_num_rows($result));
         while ($row = mysql_fetch_row($result)) {
             $bar->increase();
             for ($i = 0; $i < $sarakemaara; $i++) {
                 if (mysql_field_type($result, $i) == 'real') {
                     $worksheet->writeNumber($excelrivi, $i, sprintf("%.02f", $row[$i]));
                 } else {
                     $worksheet->writeString($excelrivi, $i, $row[$i]);
                 }
             }
             $excelrivi++;
         }
         $excelnimi = $worksheet->close();
         echo "<br><br><table>";
         echo "<tr><th>" . t("Tallenna Excel") . ":</th><td class='back'>";
Example #25
0
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage Expected integer, but got string for argument 1
  */
 public function testSizeMustBeAnInteger()
 {
     $this->progressBar->render('abc', array());
 }
 /**
  * Show table for values
  * @param array $Values
  */
 protected function showTableForValues(&$Values)
 {
     echo '<table class="fullwidth nomargin">';
     foreach ($Values as $Value) {
         if ($Value['show']) {
             $Label = '<strong>' . $Value['title'] . '</strong>&nbsp;<small>' . $Value['small'] . '</small>';
             $Text = $Value['tooltip'] != '' ? Ajax::tooltip($Label, $Value['tooltip']) : $Label;
             $ProgressBar = new ProgressBar();
             $ProgressBar->setInline();
             $ProgressBar->setTooltip($Value['bar-tooltip']);
             foreach ($Value['bars'] as &$Bar) {
                 $ProgressBar->addBar($Bar);
             }
             if (isset($Value['bar-goal'])) {
                 $ProgressBar->setGoalLine($Value['bar-goal']);
             }
             $Progress = $ProgressBar->getCode();
             echo '<tr><td>' . $Text . '</td><td style="width:99%;vertical-align:middle;">' . $Progress . '</td><td class="r">' . $Value['value'] . '</td></tr>';
         }
     }
     echo '</table>';
 }
Example #27
0
 /**
  * Perform a schema comparison on provided databases
  */
 public function data($isReplace, $algorithm, $upFile, $showChanges, $targetdb, $sourcedb)
 {
     $this->isReady();
     // Grab list of tables for each database
     $tables = array($targetdb->getTables(), $sourcedb->getTables());
     // Grab tables that are in both
     $matchingTables = array_intersect(array_keys($tables[0]), array_keys($tables[1]));
     // target - source
     $matchingNewTables = array_diff(array_keys($tables[1]), array_keys($tables[0]));
     // source - target
     $bar = new ProgressBar('Comparing different table data and fill new tables..', true, 0, 400, 40, "#cccccc", "blue", "cdata");
     $bar->initialize(count($matchingTables) + count($matchingNewTables));
     // total number of tables
     // Try to do quick checksum comparison
     foreach ($matchingTables as $tableName) {
         if ($algorithm == "groupby") {
             if ($targetdb->server != $sourcedb->server) {
                 die('Actually Cannot execute group by algorithm on different hosts: ' . $targetdb->server . ' - ' . $this->sourcedb->server);
             }
             $this->groupByMethod($tables, $tableName, $isReplace, $upFile, $showChanges, $targetdb, $sourcedb);
         } else {
             //processing use only array
             $rows = array($tables[0][$tableName]->getRows(), $tables[1][$tableName]->getRows());
             // Look for new/missing rows
             $newRows = array_diff_key($rows[1], $rows[0]);
             // while approach, to limit the memory consume not copying the array as in foreach
             reset($newRows);
             while (list($key, $value) = each($newRows)) {
                 $this->rowsSetDiff($value, "new");
             }
             unset($newRows);
             $missingRows = array_diff_key($rows[0], $rows[1]);
             reset($missingRows);
             while (list($key, $value) = each($missingRows)) {
                 $this->rowsSetDiff($value, "missing");
             }
             unset($missingRows);
             // Find rows that exist in both
             $compareRows = array_intersect_key($rows[0], $rows[1]);
             reset($compareRows);
             while (list($key, $value) = each($compareRows)) {
                 $this->rowsSetDiff($value, "compare", $rows[1][$key], $isReplace);
             }
             unset($compareRows, $rows);
             $upFile->fillData($this);
         }
         // Prune rows that havent got diffs
         $tables[0][$tableName]->pruneRows();
         $tables[1][$tableName]->pruneRows();
         $bar->increase();
     }
     foreach ($matchingNewTables as $tableName) {
         // don't use getRows() to avoid memory overload
         $select = $tables[1][$tableName]->getTable()->select()->from($tableName);
         $pColumns = $tables[1][$tableName]->getPrimaryColumns();
         $keycnt = count($pColumns);
         $tables[1][$tableName]->blankRows();
         $stmt = $select->query();
         while ($row = $stmt->fetch()) {
             $cRow = $tables[1][$tableName]->createRow($row, $tables[1][$tableName]->getRowsArray());
             $this->rowsSetDiff($cRow, "new");
             $upFile->createQuery($cRow, $pColumns, $keycnt, $tableName);
             if ($showChanges) {
                 $tables[1][$tableName]->addRow($cRow);
             }
         }
         $upFile->writeData($keycnt, $tableName);
         unset($select, $stmt);
         $bar->increase();
     }
     unset($bar, $tables, $tableNames, $matchingTables);
 }
Example #28
0
             $worksheet->write($excelrivi, $excelsarake++, "{$_yh} suoramarkkinointi", $format_bold);
             $worksheet->write($excelrivi, $excelsarake++, "{$_yh} email", $format_bold);
             $worksheet->write($excelrivi, $excelsarake++, "{$_yh} fakta", $format_bold);
             $worksheet->write($excelrivi, $excelsarake++, "{$_yh} tilausyhteyshenkilo", $format_bold);
         }
     }
     $excelsarake = 0;
     $excelrivi++;
 }
 $edluku = "x";
 $valisummat = array();
 $totsummat = array();
 $tarra_aineisto = "";
 if ($rivimaara > $rivilimitti) {
     require_once 'inc/ProgressBar.class.php';
     $bar = new ProgressBar();
     $elements = $rivimaara;
     // total number of elements to process
     $bar->initialize($elements);
     // print the empty bar
 }
 // Indeksien nimet
 $row_keys = array_keys($rows[0]);
 foreach ($rows as $row) {
     if ($rivimaara > $rivilimitti) {
         $bar->increase();
     }
     $piilosumma = 0;
     $ken_lask = 0;
     $excelsarake = 0;
     foreach ($row as $ken_nimi => $kentta) {
Example #29
0
function hae_rivit($tyyppi, $kukarow, $vva, $kka, $ppa, $vvl, $kkl, $ppl, $apaikka, $lpaikka, $varastot, $keraysvyohykkeet, $lisa_kentat, $kerayksettomat_tuotepaikat, $lisa)
{
    global $yhtiorow;
    $ostoehdotukset = array('' => t("Ehdotetaan ostoehdotusohjelmissa tilattavaksi"), 'E' => "Ei ehdoteta ostoehdotusohjelmissa tilattavaksi");
    if (strtotime("{$vva}-{$kka}-{$ppa}") < strtotime('now - 12 months')) {
        $_date = "AND tilausrivi.kerattyaika >= '{$vva}-{$kka}-{$ppa} 00:00:00'\n          AND tilausrivi.kerattyaika <= '{$vvl}-{$kkl}-{$ppl} 23:59:59'";
    } else {
        $_date = "AND tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 12 month)";
    }
    $tuotepaikka_where = "";
    $a = array_filter($apaikka);
    $l = array_filter($lpaikka);
    if (!empty($a) or !empty($l)) {
        $ahyllyalue = $apaikka['ahyllyalue'];
        $ahyllynro = $apaikka['ahyllynro'];
        $ahyllyvali = $apaikka['ahyllyvali'];
        $ahyllytaso = $apaikka['ahyllytaso'];
        $lhyllyalue = $lpaikka['lhyllyalue'];
        $lhyllynro = $lpaikka['lhyllynro'];
        $lhyllyvali = $lpaikka['lhyllyvali'];
        $lhyllytaso = $lpaikka['lhyllytaso'];
        $tuotepaikka_where = "and concat(rpad(upper(tilausrivi.hyllyalue) ,5,'0'),lpad(upper(tilausrivi.hyllynro) ,5,'0'),lpad(upper(tilausrivi.hyllyvali) ,5,'0'),lpad(upper(tilausrivi.hyllytaso) ,5,'0')) >=\n          concat(rpad(upper('{$ahyllyalue}'), 5, '0'),lpad(upper('{$ahyllynro}'), 5, '0'),lpad(upper('{$ahyllyvali}'), 5, '0'),lpad(upper('{$ahyllytaso}'),5, '0'))\n          and concat(rpad(upper(tilausrivi.hyllyalue) ,5,'0'),lpad(upper(tilausrivi.hyllynro) ,5,'0'),lpad(upper(tilausrivi.hyllyvali) ,5,'0'),lpad(upper(tilausrivi.hyllytaso) ,5,'0')) <=\n          concat(rpad(upper('{$lhyllyalue}'), 5, '0'),lpad(upper('{$lhyllynro}'), 5, '0'),lpad(upper('{$lhyllyvali}'), 5, '0'),lpad(upper('{$lhyllytaso}'),5, '0'))";
    }
    $varasto_lisa1 = "";
    $varasto_lisa2 = "";
    if (!empty($varastot)) {
        $varasto_lisa1 = " AND tuotepaikat.varasto IN (" . implode(",", $varastot) . ") ";
        $varasto_lisa2 = " AND tilausrivi.varasto IN (" . implode(",", $varastot) . ") ";
    }
    $tuote_select = "";
    $keraysvyohyke_select = "";
    $keraysvyohyke_join = "";
    $varaston_hyllypaikat_join = "";
    $group = ",";
    if ($yhtiorow['kerayserat'] == "K") {
        $keraysvyohyke_select = "keraysvyohyke.nimitys as keraysvyohykkeen_nimitys,";
        $keraysvyohyke_join = " JOIN keraysvyohyke ON (keraysvyohyke.yhtio = vh.yhtio AND keraysvyohyke.tunnus = vh.keraysvyohyke)";
        $varaston_hyllypaikat_join = " JOIN varaston_hyllypaikat AS vh\n                    ON (\n                      vh.yhtio = tilausrivi.yhtio\n                      AND vh.hyllyalue = tilausrivi.hyllyalue\n                      AND vh.hyllynro = tilausrivi.hyllynro\n                      AND vh.hyllytaso = tilausrivi.hyllytaso\n                      AND vh.hyllyvali = tilausrivi.hyllyvali";
        if (!empty($keraysvyohykkeet)) {
            $varaston_hyllypaikat_join .= "  AND vh.keraysvyohyke IN (" . implode(",", $keraysvyohykkeet) . ")";
        }
        $varaston_hyllypaikat_join .= ")";
        $group .= "keraysvyohykkeen_nimitys,";
    }
    if ($tyyppi == "TUOTE") {
        $vresult = t_avainsana("S");
        $tuote_statukset = array();
        while ($status = mysql_fetch_assoc($vresult)) {
            $tuote_statukset[$status['selite']] = $status['selitetark'];
        }
        $checked_count = 0;
        if (!empty($lisa_kentat)) {
            foreach ($lisa_kentat as $lisa_kentta) {
                if (!empty($lisa_kentta['checked'])) {
                    $tuote_select .= $lisa_kentta['kolumni'] . ', ';
                    $group .= $lisa_kentta['kolumni'] . ', ';
                    $checked_count++;
                }
            }
            // Ruksattiin jotain lisävalintoita (tuotekohtaisia), voidaan näyttää saldo
            if ($checked_count > 0) {
                $tuote_select .= "tuotepaikat.saldo,";
                $group .= "tuotepaikat.saldo,";
            }
        }
        $tuote_select .= "tilausrivi.hyllyalue, tilausrivi.hyllynro, tilausrivi.hyllyvali, tilausrivi.hyllytaso, ";
        $tuote_select .= "CONCAT_WS(' ', tilausrivi.hyllyalue, tilausrivi.hyllynro, tilausrivi.hyllyvali, tilausrivi.hyllytaso) as hylly, ";
        $tuote_select .= "group_concat(distinct tuotepaikat.tunnus) paikkatun, ";
        $group .= "tilausrivi.hyllyalue, tilausrivi.hyllynro, tilausrivi.hyllyvali, tilausrivi.hyllytaso, hylly,";
        if (empty($kerayksettomat_tuotepaikat)) {
            $tuote_select .= "if (tuotepaikat.tunnus IS NULL , 1, 0) poistettu, ";
            $group .= "poistettu,";
        }
    }
    $group = rtrim($group, " ,");
    if (!empty($kerayksettomat_tuotepaikat)) {
        $kerayksettomat_tuotepaikat_varaston_hyllypaikat_join = str_replace('tilausrivi', 'tuotepaikat', $varaston_hyllypaikat_join);
        $kerayksettomat_tuotepaikat_group = str_replace('tilausrivi', 'tuotepaikat', $group);
        $kerayksettomat_tuotepaikka_where = str_replace('tilausrivi', 'tuotepaikat', $tuotepaikka_where);
        $kerayksettomat_tuote_select = str_replace('tilausrivi', 'tuotepaikat', $tuote_select);
        $query = "SELECT varastopaikat.nimitys as varaston_nimitys,\n              {$keraysvyohyke_select}\n              {$kerayksettomat_tuote_select}\n              sum(if (tilausrivi.kerattyaika >= '{$vva}-{$kka}-{$ppa} 00:00:00' AND tilausrivi.kerattyaika <= '{$vvl}-{$kkl}-{$ppl} 23:59:59', 1, 0)) kpl_valittu_aika,\n              sum(if (tilausrivi.kerattyaika >= '{$vva}-{$kka}-{$ppa} 00:00:00' AND tilausrivi.kerattyaika <= '{$vvl}-{$kkl}-{$ppl} 23:59:59', tilausrivi.kpl+tilausrivi.varattu, 0)) tuokpl_valittu_aika,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 6 month), 1, 0)) kpl_6,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 6 month), tilausrivi.kpl+tilausrivi.varattu, 0)) tuo_kpl_6,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 12 month), 1, 0)) kpl_12,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 12 month), tilausrivi.kpl+tilausrivi.varattu, 0)) tuo_kpl_12\n              FROM tuotepaikat\n              JOIN tuote USE INDEX (tuoteno_index) ON (tuotepaikat.yhtio = tuote.yhtio\n                AND tuotepaikat.tuoteno  = tuote.tuoteno\n                AND tuote.ei_saldoa      = '')\n              JOIN varastopaikat ON (varastopaikat.yhtio = tuotepaikat.yhtio\n                AND varastopaikat.tunnus = tuotepaikat.varasto)\n              {$kerayksettomat_tuotepaikat_varaston_hyllypaikat_join}\n              {$keraysvyohyke_join}\n              LEFT JOIN tilausrivi ON ( tilausrivi.tyyppi = 'L'\n                AND tilausrivi.yhtio     = tuotepaikat.yhtio\n                AND tilausrivi.hyllyalue = tuotepaikat.hyllyalue\n                AND tilausrivi.hyllynro  = tuotepaikat.hyllynro\n                AND tilausrivi.hyllyvali = tuotepaikat.hyllyvali\n                AND tilausrivi.hyllytaso = tuotepaikat.hyllytaso\n                AND tilausrivi.tuoteno   = tuotepaikat.tuoteno\n                {$_date})\n              WHERE tuotepaikat.yhtio    = '{$kukarow['yhtio']}'\n              {$kerayksettomat_tuotepaikka_where}\n              {$varasto_lisa1}\n              GROUP BY 1\n              {$kerayksettomat_tuotepaikat_group}\n              ORDER BY kpl_valittu_aika DESC\n              {$lisa}";
    } else {
        $query = "SELECT varastopaikat.nimitys as varaston_nimitys,\n              {$keraysvyohyke_select}\n              {$tuote_select}\n              sum(if (tilausrivi.kerattyaika >= '{$vva}-{$kka}-{$ppa} 00:00:00' AND tilausrivi.kerattyaika <= '{$vvl}-{$kkl}-{$ppl} 23:59:59', 1, 0)) kpl_valittu_aika,\n              sum(if (tilausrivi.kerattyaika >= '{$vva}-{$kka}-{$ppa} 00:00:00' AND tilausrivi.kerattyaika <= '{$vvl}-{$kkl}-{$ppl} 23:59:59', tilausrivi.kpl+tilausrivi.varattu, 0)) tuokpl_valittu_aika,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 6 month), 1, 0)) kpl_6,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 6 month), tilausrivi.kpl+tilausrivi.varattu, 0)) tuo_kpl_6,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 12 month), 1, 0)) kpl_12,\n              sum(if (tilausrivi.kerattyaika >= Date_sub(CURRENT_DATE, INTERVAL 12 month), tilausrivi.kpl+tilausrivi.varattu, 0)) tuo_kpl_12\n              FROM tilausrivi\n              JOIN tuote USE INDEX (tuoteno_index) ON (tilausrivi.yhtio = tuote.yhtio\n                AND tilausrivi.tuoteno   = tuote.tuoteno\n                AND tuote.ei_saldoa      = '')\n              JOIN varastopaikat ON (varastopaikat.yhtio = tilausrivi.yhtio\n                AND varastopaikat.tunnus = tilausrivi.varasto)\n              {$varaston_hyllypaikat_join}\n              {$keraysvyohyke_join}\n              LEFT JOIN tuotepaikat USE INDEX (yhtio_tuoteno_paikka) ON ( tilausrivi.yhtio = tuotepaikat.yhtio\n                AND tilausrivi.hyllyalue = tuotepaikat.hyllyalue\n                AND tilausrivi.hyllynro  = tuotepaikat.hyllynro\n                AND tilausrivi.hyllyvali = tuotepaikat.hyllyvali\n                AND tilausrivi.hyllytaso = tuotepaikat.hyllytaso\n                AND tilausrivi.tuoteno   = tuotepaikat.tuoteno )\n              WHERE tilausrivi.yhtio     = '{$kukarow['yhtio']}'\n              AND tilausrivi.tyyppi      = 'L'\n              {$tuotepaikka_where}\n              {$_date}\n              {$varasto_lisa2}\n              GROUP BY 1\n              {$group}\n              ORDER BY kpl_valittu_aika DESC\n              {$lisa}";
    }
    $result = pupe_query($query);
    //päiviä aikajaksossa
    $epa1 = (int) date('U', mktime(0, 0, 0, $kka, $ppa, $vva));
    $epa2 = (int) date('U', mktime(0, 0, 0, $kkl, $ppl, $vvl));
    //Diff in workdays (5 day week)
    $pva = abs($epa2 - $epa1) / 60 / 60 / 24 / 7 * 5;
    $poistettu = t('Poistettu');
    $rows = array();
    $saldolliset = array();
    if (mysql_num_rows($result) > 0) {
        $progress_bar = new ProgressBar(t("Haetaan tiedot"));
        $progress_bar->initialize(mysql_num_rows($result));
    }
    while ($row = mysql_fetch_assoc($result)) {
        if (isset($progress_bar)) {
            $progress_bar->increase();
        }
        if ($tyyppi == 'TUOTE') {
            if (!empty($lisa_kentat['nimitys']['checked'])) {
                $row['nimitys'] = t_tuotteen_avainsanat($row, 'nimitys');
            }
            if (isset($row['status']) and array_key_exists($row['status'], $tuote_statukset)) {
                $row['status'] = $tuote_statukset[$row['status']];
            }
            if (isset($row['ostoehdotus']) and array_key_exists($row['ostoehdotus'], $ostoehdotukset)) {
                $row['ostoehdotus'] = $ostoehdotukset[$row['ostoehdotus']];
            } elseif (isset($row['ostoehdotus']) and !array_key_exists($row['ostoehdotus'], $ostoehdotukset)) {
                $row['ostoehdotus'] = t("Tuntematon");
            }
        }
        $row['kpl_kerays'] = number_format($row["kpl_valittu_aika"] > 0 ? round($row["tuokpl_valittu_aika"] / $row["kpl_valittu_aika"]) : 0, 0);
        $row['kpl_valittu_aika_pvm'] = number_format($row["kpl_valittu_aika"] / $pva, 0);
        if (is_numeric($row['poistettu'])) {
            if ($row['poistettu'] == 1) {
                $row['poistettu'] = $poistettu;
            } elseif ($row['poistettu'] == 0) {
                $saldolliset[] = $row["paikkatun"];
                $row['poistettu'] = '';
            }
        }
        unset($row['tuokpl_valittu_aika']);
        unset($row['tuo_kpl_6']);
        unset($row['tuo_kpl_12']);
        unset($row['paikkatun']);
        $rows[] = $row;
    }
    echo "<br/>";
    return array($rows, $saldolliset);
}
Example #30
0
            $myfield2 = $flt[2] . $myfield;
            $allfields[] = $myfield2;
            break;
        default:
            //Default settings
            $allfields[] = $myfield;
            break;
    }
    //end switch -> check question types and create filter forms
}
//end foreach -> loop through all questions with "public_statistics" enabled
$summary = $allfields;
//---------- CREATE STATISTICS ----------
//some progress bar stuff
// Create progress bar which is shown while creating the results
$prb = new ProgressBar();
$prb->pedding = 2;
// Bar Pedding
$prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
// Bar Border Color
$prb->setFrame();
// set ProgressBar Frame
$prb->frame['left'] = 50;
// Frame position from left
$prb->frame['top'] = 80;
// Frame position from top
$prb->addLabel('text', 'txt1', $clang->gT("Please wait ..."));
// add Text as Label 'txt1' and value 'Please wait'
$prb->addLabel('percent', 'pct1');
// add Percent as Label 'pct1'
$prb->addButton('btn1', $clang->gT('Go back'), '?action=statistics&amp;sid=' . $surveyid);