Function to extract the order and order items from the $ipnData
3641
public function extractOrder()
    {
        $this->order = new $this->clsIpnOrders;
        // First extract the actual order record itself
        foreach ($this->ipnData as $key=>$value) {
            // This is very simple: the order fields are any fields which do not end in a number
            // (because those fields belong to the order items)
            // period, amount, mcAmount ends with number and belongs to order. Think condition line should be commented
            if (preg_match("/.*?(\d+)$/", $key) == 0){
                //this code iterate over ipnData fields, check if order have related field and set it
                $parts = explode('_',$key);
                foreach($parts as $i => $part)
                    $parts[$i] = ucfirst ($part);
                $method = join('',$parts);
                $method = 'set'.$method;
                if(method_exists($this->order, $method))
                    $this->order->$method($value);
            }
        }

        // Let's store the payment status too
        $this->order->setOrderStatus($this->orderStatus);
        
        //Updating dates
        if(!$this->order->getCreatedAt())
            $this->order->setCreatedAt(new \DateTime());
        $this->order->setUpdatedAt(new \DateTime());

    
        // Now retrieve the line items which belong to this order
        $hasCart = ($this->order->getTxnType() == 'cart');
        $numItems = $hasCart ? (int)$this->order->getNumCartItems() : 1;

        $totalBeforeDiscount = 0;
        for ($i = 0; $i < $numItems; $i++) {
            
            // Suffixes are different depending on whether there are multiple items (a cart) or not
            $suffix = $hasCart ? ($i + 1) : '';
            $suffixUnderscore = $hasCart ? '_' . $suffix : $suffix;

            $this->orderItems[$i] = new $this->clsIpnOrderItems;
            if(isset($this->ipnData['item_name' . $suffix]))
                $this->orderItems[$i]->setItemName($this->ipnData['item_name' . $suffix]);
            if(isset($this->ipnData['item_number' . $suffix]))
                $this->orderItems[$i]->setItemNumber($this->ipnData['item_number' . $suffix]);
            if(isset($this->ipnData['quantity' . $suffix]))
                $this->orderItems[$i]->setQuantity($this->ipnData['quantity' . $suffix]);
            if(isset($this->ipnData['mc_gross' . $suffixUnderscore]))
                $this->orderItems[$i]->setMcGross($this->ipnData['mc_gross' . $suffixUnderscore]);
            if(isset($this->ipnData['mc_gross' . $suffixUnderscore]) && isset($this->ipnData['quantity' . $suffix]))
                $this->orderItems[$i]->setCostPerItem(floatval($this->ipnData['mc_gross' . $suffixUnderscore]) / intval($this->ipnData['quantity' . $suffix])); // Should be fine because quantity can never be 0
            
            // Update the total before the discount was applied
            $totalBeforeDiscount +=  $this->orderItems[$i]->getMcGross();
            
            if(isset($this->ipnData['mc_handling' . $suffix]))
                $this->orderItems[$i]->setMcHandling($this->ipnData['mc_handling' . $suffix]);
            if(isset($this->ipnData['mc_shipping' . $suffix]))
                $this->orderItems[$i]->setMcShipping($this->ipnData['mc_shipping' . $suffix]);
            if(isset($this->ipnData['tax' . $suffix]))
                $this->orderItems[$i]->setTax($this->ipnData['tax' . $suffix]); // Tax is not always set on an item
                        
            
            // Set the order item options if any
            // $count = 7 because PayPal allows you to set a maximum of 7 options per item
            // Reference: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables
            for ($ii = 1, $count = 7; $ii < $count; $ii++)
            {
                if(isset($this->ipnData['option_name'.$ii.$suffixUnderscore])) {
                    $method = 'setOptionName' . $ii;
                    $this->orderItems[$i]->$method($this->ipnData['option_name'.$ii.$suffixUnderscore]);
                }
                if(isset($this->ipnData['option_selection'.$ii.$suffixUnderscore])) {
                    $method = 'setOptionSelection' . $ii;
                    $this->orderItems[$i]->$method($this->ipnData['option_selection'.$ii.$suffixUnderscore]);
                }
            }
            
            //Updating dates
            if(!$this->orderItems[$i]->getCreatedAt())
                $this->orderItems[$i]->setCreatedAt(new \DateTime());
            $this->orderItems[$i]->setUpdatedAt(new \DateTime());
        }

        // And calculate the discount, as it's useful to add this into emails etc
        $this->order->setDiscount($totalBeforeDiscount - $this->order->getMcGross());
    }
892058
function extractInfo($debug = false, $BMPonly = false, $kerninfo = false, $useOTL = 0)
	{
		$this->panose = [];
		$this->sFamilyClass = 0;
		$this->sFamilySubClass = 0;
		///////////////////////////////////
		// name - Naming table
		///////////////////////////////////
		$name_offset = $this->seek_table("name");
		$format = $this->read_ushort();
		if ($format != 0 && $format != 1) {
			throw new \Mpdf\MpdfException("Unknown name table format " . $format);
		}
		$numRecords = $this->read_ushort();
		$string_data_offset = $name_offset + $this->read_ushort();
		$names = [1 => '', 2 => '', 3 => '', 4 => '', 6 => ''];
		$K = array_keys($names);
		$nameCount = count($names);
		for ($i = 0; $i < $numRecords; $i++) {
			$platformId = $this->read_ushort();
			$encodingId = $this->read_ushort();
			$languageId = $this->read_ushort();
			$nameId = $this->read_ushort();
			$length = $this->read_ushort();
			$offset = $this->read_ushort();
			if (!in_array($nameId, $K)) {
				continue;
			}
			$N = '';
			if ($platformId == 3 && $encodingId == 1 && $languageId == 0x409) { // Microsoft, Unicode, US English, PS Name
				$opos = $this->_pos;
				$this->seek($string_data_offset + $offset);
				if ($length % 2 != 0) {
					throw new \Mpdf\MpdfException("PostScript name is UTF-16BE string of odd length");
				}
				$length /= 2;
				$N = '';
				while ($length > 0) {
					$char = $this->read_ushort();
					$N .= (chr($char));
					$length -= 1;
				}
				$this->_pos = $opos;
				$this->seek($opos);
			} else {
				if ($platformId == 1 && $encodingId == 0 && $languageId == 0) { // Macintosh, Roman, English, PS Name
					$opos = $this->_pos;
					$N = $this->get_chunk($string_data_offset + $offset, $length);
					$this->_pos = $opos;
					$this->seek($opos);
				}
			}
			if ($N && $names[$nameId] == '') {
				$names[$nameId] = $N;
				$nameCount -= 1;
				if ($nameCount == 0) {
					break;
				}
			}
		}
		if ($names[6]) {
			$psName = $names[6];
		} else {
			if ($names[4]) {
				$psName = preg_replace('/ /', '-', $names[4]);
			} else {
				if ($names[1]) {
					$psName = preg_replace('/ /', '-', $names[1]);
				} else {
					$psName = '';
				}
			}
		}
		if (!$psName) {
			throw new \Mpdf\MpdfException("Could not find PostScript font name: " . $this->filename);
		}
		if ($debug) {
			for ($i = 0; $i < count($psName); $i++) {
				$c = $psName[$i];
				$oc = ord($c);
				if ($oc > 126 || strpos(' [](){}<>/%', $c) !== false) {
					throw new \Mpdf\MpdfException("psName=" . $psName . " contains invalid character " . $c . " ie U+" . ord(c));
				}
			}
		}
		$this->name = $psName;
		if ($names[1]) {
			$this->familyName = $names[1];
		} else {
			$this->familyName = $psName;
		}
		if ($names[2]) {
			$this->styleName = $names[2];
		} else {
			$this->styleName = 'Regular';
		}
		if ($names[4]) {
			$this->fullName = $names[4];
		} else {
			$this->fullName = $psName;
		}
		if ($names[3]) {
			$this->uniqueFontID = $names[3];
		} else {
			$this->uniqueFontID = $psName;
		}

		if ($names[6]) {
			$this->fullName = $names[6];
		}

		///////////////////////////////////
		// head - Font header table
		///////////////////////////////////
		$this->seek_table("head");
		if ($debug) {
			$ver_maj = $this->read_ushort();
			$ver_min = $this->read_ushort();
			if ($ver_maj != 1) {
				throw new \Mpdf\MpdfException('Unknown head table version ' . $ver_maj . '.' . $ver_min);
			}
			$this->fontRevision = $this->read_ushort() . $this->read_ushort();

			$this->skip(4);
			$magic = $this->read_ulong();
			if ($magic != 0x5F0F3CF5) {
				throw new \Mpdf\MpdfException('Invalid head table magic ' . $magic);
			}
			$this->skip(2);
		} else {
			$this->skip(18);
		}
		$this->unitsPerEm = $unitsPerEm = $this->read_ushort();
		$scale = 1000 / $unitsPerEm;
		$this->skip(16);
		$xMin = $this->read_short();
		$yMin = $this->read_short();
		$xMax = $this->read_short();
		$yMax = $this->read_short();
		$this->bbox = [($xMin * $scale), ($yMin * $scale), ($xMax * $scale), ($yMax * $scale)];
		$this->skip(3 * 2);
		$indexToLocFormat = $this->read_ushort();
		$glyphDataFormat = $this->read_ushort();
		if ($glyphDataFormat != 0) {
			throw new \Mpdf\MpdfException('Unknown glyph data format ' . $glyphDataFormat);
		}

		///////////////////////////////////
		// hhea metrics table
		///////////////////////////////////
		// ttf2t1 seems to use this value rather than the one in OS/2 - so put in for compatibility
		if (isset($this->tables["hhea"])) {
			$this->seek_table("hhea");
			$this->skip(4);
			$hheaAscender = $this->read_short();
			$hheaDescender = $this->read_short();
			$this->ascent = ($hheaAscender * $scale);
			$this->descent = ($hheaDescender * $scale);
		}

		///////////////////////////////////
		// OS/2 - OS/2 and Windows metrics table
		///////////////////////////////////
		if (isset($this->tables["OS/2"])) {
			$this->seek_table("OS/2");
			$version = $this->read_ushort();
			$this->skip(2);
			$usWeightClass = $this->read_ushort();
			$this->skip(2);
			$fsType = $this->read_ushort();
			if ($fsType == 0x0002 || ($fsType & 0x0300) != 0) {
				global $overrideTTFFontRestriction;
				if (!$overrideTTFFontRestriction) {
					throw new \Mpdf\MpdfException('ERROR - Font file ' . $this->filename . ' cannot be embedded due to copyright restrictions.');
				}
				$this->restrictedUse = true;
			}
			$this->skip(20);
			$sF = $this->read_short();
			$this->sFamilyClass = ($sF >> 8);
			$this->sFamilySubClass = ($sF & 0xFF);
			$this->_pos += 10;  //PANOSE = 10 byte length
			$panose = fread($this->fh, 10);
			$this->panose = [];
			for ($p = 0; $p < strlen($panose); $p++) {
				$this->panose[] = ord($panose[$p]);
			}
			$this->skip(26);
			$sTypoAscender = $this->read_short();
			$sTypoDescender = $this->read_short();
			if (!$this->ascent) {
				$this->ascent = ($sTypoAscender * $scale);
			}
			if (!$this->descent) {
				$this->descent = ($sTypoDescender * $scale);
			}
			if ($version > 1) {
				$this->skip(16);
				$sCapHeight = $this->read_short();
				$this->capHeight = ($sCapHeight * $scale);
			} else {
				$this->capHeight = $this->ascent;
			}
		} else {
			$usWeightClass = 500;
			if (!$this->ascent) {
				$this->ascent = ($yMax * $scale);
			}
			if (!$this->descent) {
				$this->descent = ($yMin * $scale);
			}
			$this->capHeight = $this->ascent;
		}
		$this->stemV = 50 + intval(pow(($usWeightClass / 65.0), 2));

		///////////////////////////////////
		// post - PostScript table
		///////////////////////////////////
		$this->seek_table("post");
		if ($debug) {
			$ver_maj = $this->read_ushort();
			$ver_min = $this->read_ushort();
			if ($ver_maj < 1 || $ver_maj > 4) {
				throw new \Mpdf\MpdfException('Unknown post table version ' . $ver_maj);
			}
		} else {
			$this->skip(4);
		}
		$this->italicAngle = $this->read_short() + $this->read_ushort() / 65536.0;
		$this->underlinePosition = $this->read_short() * $scale;
		$this->underlineThickness = $this->read_short() * $scale;
		$isFixedPitch = $this->read_ulong();

		$this->flags = 4;

		if ($this->italicAngle != 0) {
			$this->flags = $this->flags | 64;
		}
		if ($usWeightClass >= 600) {
			$this->flags = $this->flags | 262144;
		}
		if ($isFixedPitch) {
			$this->flags = $this->flags | 1;
		}

		///////////////////////////////////
		// hhea - Horizontal header table
		///////////////////////////////////
		$this->seek_table("hhea");
		if ($debug) {
			$ver_maj = $this->read_ushort();
			$ver_min = $this->read_ushort();
			if ($ver_maj != 1) {
				throw new \Mpdf\MpdfException('Unknown hhea table version ' . $ver_maj);
			}
			$this->skip(28);
		} else {
			$this->skip(32);
		}
		$metricDataFormat = $this->read_ushort();
		if ($metricDataFormat != 0) {
			throw new \Mpdf\MpdfException('Unknown horizontal metric data format ' . $metricDataFormat);
		}
		$numberOfHMetrics = $this->read_ushort();
		if ($numberOfHMetrics == 0) {
			throw new \Mpdf\MpdfException('Number of horizontal metrics is 0');
		}

		///////////////////////////////////
		// maxp - Maximum profile table
		///////////////////////////////////
		$this->seek_table("maxp");
		if ($debug) {
			$ver_maj = $this->read_ushort();
			$ver_min = $this->read_ushort();
			if ($ver_maj != 1) {
				throw new \Mpdf\MpdfException('Unknown maxp table version ' . $ver_maj);
			}
		} else {
			$this->skip(4);
		}
		$numGlyphs = $this->read_ushort();

		///////////////////////////////////
		// cmap - Character to glyph index mapping table
		///////////////////////////////////
		$cmap_offset = $this->seek_table("cmap");
		$this->skip(2);
		$cmapTableCount = $this->read_ushort();
		$unicode_cmap_offset = 0;
		for ($i = 0; $i < $cmapTableCount; $i++) {
			$platformID = $this->read_ushort();
			$encodingID = $this->read_ushort();
			$offset = $this->read_ulong();
			$save_pos = $this->_pos;
			if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode
				$format = $this->get_ushort($cmap_offset + $offset);
				if ($format == 4) {
					if (!$unicode_cmap_offset) {
						$unicode_cmap_offset = $cmap_offset + $offset;
					}
					if ($BMPonly) {
						break;
					}
				}
			} // Microsoft, Unicode Format 12 table HKCS
			else {
				if ((($platformID == 3 && $encodingID == 10) || $platformID == 0) && !$BMPonly) {
					$format = $this->get_ushort($cmap_offset + $offset);
					if ($format == 12) {
						$unicode_cmap_offset = $cmap_offset + $offset;
						break;
					}
				}
			}
			$this->seek($save_pos);
		}

		if (!$unicode_cmap_offset) {
			throw new \Mpdf\MpdfException('Font (' . $this->filename . ') does not have cmap for Unicode (platform 3, encoding 1, format 4, or platform 0, any encoding, format 4)');
		}

		$sipset = false;
		$smpset = false;

		// mPDF 5.7.1
		$this->GSUBScriptLang = [];
		$this->rtlPUAstr = '';
		$this->rtlPUAarr = [];
		$this->GSUBFeatures = [];
		$this->GSUBLookups = [];
		$this->GPOSScriptLang = [];
		$this->GPOSFeatures = [];
		$this->GPOSLookups = [];
		$this->glyphIDtoUni = '';

		// Format 12 CMAP does characters above Unicode BMP i.e. some HKCS characters U+20000 and above
		if ($format == 12 && !$BMPonly) {
			$this->maxUniChar = 0;
			$this->seek($unicode_cmap_offset + 4);
			$length = $this->read_ulong();
			$limit = $unicode_cmap_offset + $length;
			$this->skip(4);

			$nGroups = $this->read_ulong();

			$glyphToChar = [];
			$charToGlyph = [];
			for ($i = 0; $i < $nGroups; $i++) {
				$startCharCode = $this->read_ulong();
				$endCharCode = $this->read_ulong();
				$startGlyphCode = $this->read_ulong();
				if ($endCharCode > 0x20000 && $endCharCode < 0x2FFFF) {
					$sipset = true;
				} else {
					if ($endCharCode > 0x10000 && $endCharCode < 0x1FFFF) {
						$smpset = true;
					}
				}
				$offset = 0;
				for ($unichar = $startCharCode; $unichar <= $endCharCode; $unichar++) {
					$glyph = $startGlyphCode + $offset;
					$offset++;
					if ($unichar < 0x30000) {
						$charToGlyph[$unichar] = $glyph;
						$this->maxUniChar = max($unichar, $this->maxUniChar);
						$glyphToChar[$glyph][] = $unichar;
					}
				}
			}
		} else {
			$glyphToChar = [];
			$charToGlyph = [];
			$this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph);
		}
		$this->sipset = $sipset;
		$this->smpset = $smpset;

		///////////////////////////////////
		// mPDF 5.7.1
		// Map Unmapped glyphs - from $numGlyphs
		if ($this->useOTL) {
			$bctr = 0xE000;
			for ($gid = 1; $gid < $numGlyphs; $gid++) {
				if (!isset($glyphToChar[$gid])) {
					while (isset($charToGlyph[$bctr])) {
						$bctr++;
					} // Avoid overwriting a glyph already mapped in PUA
					if (($bctr > 0xF8FF) && ($bctr < 0x2CEB0)) {
						if (!$BMPonly) {
							$bctr = 0x2CEB0;  // Use unassigned area 0x2CEB0 to 0x2F7FF (space for 10,000 characters)
							$this->sipset = $sipset = true; // forces subsetting; also ensure charwidths are saved
							while (isset($charToGlyph[$bctr])) {
								$bctr++;
							}
						} else {
							throw new \Mpdf\MpdfException($names[1] . " : WARNING - The font does not have enough space to map all (unmapped) included glyphs into Private Use Area U+E000 - U+F8FF");
						}
					}
					$glyphToChar[$gid][] = $bctr;
					$charToGlyph[$bctr] = $gid;
					$this->maxUniChar = max($bctr, $this->maxUniChar);
					$bctr++;
				}
			}
		}
		$this->glyphToChar = $glyphToChar;
		$this->charToGlyph = $charToGlyph;
		///////////////////////////////////
		// mPDF 5.7.1	OpenType Layout tables
		$this->GSUBScriptLang = [];
		$this->rtlPUAstr = '';
		$this->rtlPUAarr = [];
		if ($useOTL) {
			$this->_getGDEFtables();
			list($this->GSUBScriptLang, $this->GSUBFeatures, $this->GSUBLookups, $this->rtlPUAstr, $this->rtlPUAarr) = $this->_getGSUBtables();
			list($this->GPOSScriptLang, $this->GPOSFeatures, $this->GPOSLookups) = $this->_getGPOStables();
			$this->glyphIDtoUni = str_pad('', 256 * 256 * 3, "\x00");
			foreach ($glyphToChar as $gid => $arr) {
				if (isset($glyphToChar[$gid][0])) {
					$char = $glyphToChar[$gid][0];
					if ($char != 0 && $char != 65535) {
						$this->glyphIDtoUni[$gid * 3] = chr($char >> 16);
						$this->glyphIDtoUni[$gid * 3 + 1] = chr(($char >> 8) & 0xFF);
						$this->glyphIDtoUni[$gid * 3 + 2] = chr($char & 0xFF);
					}
				}
			}
		}
		///////////////////////////////////
		///////////////////////////////////
		// hmtx - Horizontal metrics table
		///////////////////////////////////
		$this->getHMTX($numberOfHMetrics, $numGlyphs, $glyphToChar, $scale);

		///////////////////////////////////
		// kern - Kerning pair table
		///////////////////////////////////
		if ($kerninfo) {
			// Recognises old form of Kerning table - as required by Windows - Format 0 only
			$kern_offset = $this->seek_table("kern");
			$version = $this->read_ushort();
			$nTables = $this->read_ushort();
			// subtable header
			$sversion = $this->read_ushort();
			$slength = $this->read_ushort();
			$scoverage = $this->read_ushort();
			$format = $scoverage >> 8;
			if ($kern_offset && $version == 0 && $format == 0) {
				// Format 0
				$nPairs = $this->read_ushort();
				$this->skip(6);
				for ($i = 0; $i < $nPairs; $i++) {
					$left = $this->read_ushort();
					$right = $this->read_ushort();
					$val = $this->read_short();
					if (count($glyphToChar[$left]) == 1 && count($glyphToChar[$right]) == 1) {
						if ($left != 32 && $right != 32) {
							$this->kerninfo[$glyphToChar[$left][0]][$glyphToChar[$right][0]] = intval($val * $scale);
						}
					}
				}
			}
		}
	}
971855
static function fetchAlphabet()
    {
        $contentINI = eZINI::instance( 'content.ini' );

        $alphabetRangeList = $contentINI->hasVariable( 'AlphabeticalFilterSettings', 'AlphabetList' )
                             ? $contentINI->variable( 'AlphabeticalFilterSettings', 'AlphabetList' )
                             : array();

        $alphabetFromArray = $contentINI->hasVariable( 'AlphabeticalFilterSettings', 'ContentFilterList' )
                             ? $contentINI->variable( 'AlphabeticalFilterSettings', 'ContentFilterList' )
                             : array( 'default' );

        // If alphabet list is empty
        if ( count( $alphabetFromArray ) == 0 )
            return false;

        $alphabetRangeList = array_merge( $alphabetRangeList, array( 'default' => '97-122' ) );
        $alphabet = array();
        foreach ( $alphabetFromArray as $alphabetFrom )
        {
            // If $alphabetFrom exists in range array $alphabetRangeList
            if ( isset( $alphabetRangeList[$alphabetFrom] ) )
            {
                $lettersArray = explode( ',', $alphabetRangeList[$alphabetFrom] );
                foreach ( $lettersArray as $letter )
                {
                    $rangeArray =  explode( '-', $letter );
                    if ( isset( $rangeArray[1] ) )
                    {
                        $alphabet = array_merge( $alphabet, range( trim( $rangeArray[0] ), trim( $rangeArray[1] ) ) );
                    }
                    else
                        $alphabet = array_merge( $alphabet, array( trim( $letter ) ) );
                }
            }
        }
        // Get alphabet by default (eng-GB)
        if ( count( $alphabet ) == 0 )
        {
            $rangeArray = explode( '-', $alphabetRangeList['default'] );
            $alphabet = range( $rangeArray[0], $rangeArray[1] );
        }
        $resAlphabet = array();
        $i18nINI = eZINI::instance( 'i18n.ini' );
        $charset = $i18nINI->variable( 'CharacterSettings', 'Charset' );

        $codec = eZTextCodec::instance( 'utf-8', $charset );

        $utf8_codec = eZUTF8Codec::instance();
        // Convert all letters of alphabet from unicode to utf-8 and from utf-8 to current locale
        foreach ( $alphabet as $item )
        {
            $utf8Letter = $utf8_codec->toUtf8( $item );
            $resAlphabet[] = $codec ? $codec->convertString( $utf8Letter ) : $utf8Letter;
        }

        return $resAlphabet;
    }
939238
def sort_input(input, property, order)
      input.map { |item| [item_property(item, property), item] }
        .sort! do |a_info, b_info|
          a_property = a_info.first
          b_property = b_info.first

          if !a_property.nil? && b_property.nil?
            - order
          elsif a_property.nil? && !b_property.nil?
            + order
          else
            a_property <=> b_property || a_property.to_s <=> b_property.to_s
          end
        end
        .map!(&:last)
    end
377580
function buildOrderArray (order) {
    var direction = ''
    // check if last element is asc/desc
    if (order[order.length - 1].match(/^asc|desc$/i)) {
        var direction = order.pop().toUpperCase()
    }
    // join columns together and add direction
    this.order.push(
        _.map(order, columnName => {
            // split column on . to see if it has prefix
            var parts = columnName.split('.')
            // column does not have prefix
            if (parts.length === 1) {
                return this.alias+'.'+this.quoteName(this.model.columnName(columnName, true))
            }
            // column has prefix
            else if (parts.length === 2) {
                var prefix = parts[0]
                columnName = parts[1]
                // prefix must be for joined model
                assert.ok(this.joinRelations[prefix])
                // get join for table prefix
                var join = this.joinRelations[prefix]
                // get relation for model
                var relation = this.model.relation(prefix)
                // return order sql
                return join.relationAlias+'.'+this.quoteName(relation.model.columnName(columnName, true))
            }
            // error
            else {
                throw new Error('invalid column in order '+columnName)
            }
        }).join(', ')+' '+direction
    )
}
802576
def _ordered_idx_from_perm(self, perm_str):
        """"""
        for i, ordered_str in enumerate(ORDERED_PERM_LIST):
            if perm_str == ordered_str:
                return i
1235450
function extractOp(position) {
  const firstPositionPiece = position.slice(0, position.indexOf('['));
  return (firstPositionPiece.substring(0, 1) === '$') ? firstPositionPiece : null;
}
821156
function( json, field, params, callback ){
    field = field || 'id';
    var objectIds = [],
      props;

    if (params.orderByFields && params.orderByFields !== ''){
      var fld = params.orderByFields.split(' ');
      var order = params.orderByFields;
      if (fld[fld.length-1] == 'DESC'){
        order = '-' + params.orderByFields;
      }
      json.features = this.orderBy(json.features, params.orderByFields, order);
    }

    json.features.forEach( function(f){
      props = f.attributes || f.properties;
      objectIds.push( props[ field ] );
    });

    callback( null, {
      objectIdField: field,
      objectIds: objectIds
    });
  }
977702
function sortData(unorderedData) {
            let {data, dataZeroed} = unorderedData;

            if (orderingFunction) {
                data.sort(orderingFunction);
                dataZeroed.sort(orderingFunction)
            }

            return { data, dataZeroed };
        }
1169901
function getdata($page = 1, $length = 10, $ano = false, $mes = false, $dia = false)
    {
        
        $dt = [];
        $where = '';
        
        if ($ano !== false) {
            $where .= ' AND YEAR(data) = :ano ';
            $dt[':ano'] = $ano;
        }
        
        if ($mes !== false) {
            $where .= ' AND MONTH(data) = :mes ';
            $dt[':mes'] = $mes;
        }

        if ($dia !== false) {
            $where .= ' AND DAY(data) = :dia ';
            $dt[':dia'] = $dia;
        }

        //Calculando a página
        $data = $this->calculate($page, $length,
                                'SELECT id								 
								 FROM access								 
								 WHERE (uri LIKE "/a/%" 
								 OR uri = "/")
								 '.$where.'								 
								 GROUP BY uri, MONTH(data), DAY(data)', $dt);

        return $this->execute($data,
                                'SELECT data, COUNT(id)qt, uri AS Link 
								 FROM access
     							 WHERE (uri LIKE "/a/%" 
								 OR uri = "/")
								 '.$where.'
								 GROUP BY uri, MONTH(data), DAY(data)
								 ORDER BY DAY(data), uri
								 LIMIT '.$data['init'].', '.$data['length'], $dt);
    }
149210
function orderby (args, order) {
    if (this.typecheck) t.typecheck('orderby', [args, order]);
    
    var o = (order&&'string'===typeof order) ? order : '';
    var result = [];

    if ('string'===typeof args) {
        result = o ? [args+' '+o] : [args];
    }
    else if (args instanceof Array) {
        for (var i=0; i < args.length; i++) {
            if ('string'===typeof args[i]) {
                o ? result.push(args[i]+' '+o) : result.push(args[i]);
            }
            else if ('object'===typeof args[i]) {
                var key = Object.keys(args[i])[0];
                result.push(key+' '+args[i][key]);
            }
        }
    }
    else if (args instanceof Object) {
        var key = Object.keys(args)[0];
        result = [key+' '+args[key]];
    }

    return 'order by '+result.join();
}
1187307
function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
				n = children.length,
				options = this.options;

			for (; i < n; i++) {
				el = children[i];
				if (_closest(el, options.draggable, this.el)) {
					order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
				}
			}

			return order;
		}
740762
def get_orders(self, **params):
        """"""
        response = self._get('v2', 'orders', params=params)
        return self._make_api_object(response, Order)
654293
def get_ordering(self, *args, **kwargs):
        """"""
        result = super(SequenceCursorPagination, self).get_ordering(*args, **kwargs)

        # Because paginate_queryset sets self.ordering after reading it...we
        # need to only modify it sometimes. (This allows re-use of the
        # paginator, which probably only happens in tests.)
        if result[0] != '#':
            result = ('#', ) + result

        return result
22610
function templateNodeTransformation( $functionName, &$node,
                                         $tpl, $parameters, $privateData )
    {
        /*
        {foreach <array> as [$keyVar =>] $itemVar
                 [sequence <array> as $sequenceVar]
                 [offset <offset>]
                 [max <max>]
                 [reverse]
        }
        */

        $tpl->ForeachCounter++;
        $newNodes            = array();
        $nodePlacement       = eZTemplateNodeTool::extractFunctionNodePlacement( $node );
        $uniqid              =  md5( $nodePlacement[2] ) . "_" . $tpl->ForeachCounter;

        $loop = new eZTemplateCompiledLoop( eZTemplateForeachFunction::FUNCTION_NAME,
                                            $newNodes, $parameters, $nodePlacement, $uniqid,
                                            $node, $tpl, $privateData );



        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach begins" );

        $loop->initVars();

        $array           = "fe_array_$uniqid";
        $arrayKeys       = "fe_array_keys_$uniqid";
        $nItems          = "fe_n_items_$uniqid";
        $nItemsProcessed = "fe_n_items_processed_$uniqid";
        $i               = "fe_i_$uniqid";
        $key             = "fe_key_$uniqid";
        $val             = "fe_val_$uniqid";
        $offset          = "fe_offset_$uniqid";
        $max             = "fe_max_$uniqid";
        $reverse         = "fe_reverse_$uniqid";
        $firstVal        = "fe_first_val_$uniqid";
        $lastVal         = "fe_last_val_$uniqid";

        $variableStack   = "fe_variable_stack_$uniqid";
        $namesArray = array( $array, $arrayKeys, $nItems, $nItemsProcessed, $i, $key, $val, $offset, $max, $reverse, $firstVal, $lastVal );

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( !isset( \$$variableStack ) ) \$$variableStack = array();" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$" . $variableStack ."[] = compact( '" . implode( "', '", $namesArray ) . "' );" );

        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['array'], $nodePlacement, array( 'text-result' => false ), $array );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$arrayKeys = is_array( \$$array ) ? array_keys( \$$array ) : array();" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItems = count( \$$arrayKeys );" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItemsProcessed = 0;" );


        // process offset, max and reverse parameters
        if ( isset( $parameters['offset'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['offset'], $nodePlacement, array( 'text-result' => false ), $offset );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$offset = 0;" );

        if ( isset( $parameters['max'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['max'], $nodePlacement, array( 'text-result' => false ), $max );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$max = \$$nItems - \$$offset;" );

        if ( isset( $parameters['reverse'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['reverse'], $nodePlacement, array( 'text-result' => false ), $reverse );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$reverse = false;" );


        // fix definitely incorrect offset
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$offset < 0 || \$$offset >= \$$nItems )\n{\n".
                                                               "    \$$offset = ( \$$offset < 0 ) ? 0 : \$$nItems;\n".
                                                               "    if ( \$$nItems || \$$offset < 0 )\n {\n".
                                                               "        eZDebug::writeWarning(\"Invalid 'offset' parameter specified: '\$$offset'. Array count: \$$nItems\");   \n}\n}" );
        // fix definitely incorrect max
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$max < 0 || \$$offset + \$$max > \$$nItems )\n{\n".
                                                               "    if ( \$$max < 0 )\n eZDebug::writeWarning(\"Invalid 'max' parameter specified: \$$max\");\n".
                                                               "    \$$max = \$$nItems - \$$offset;\n}" );

        // initialize first and last indexes to iterate between them
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$reverse )\n" .
                                                               "{\n" .
                                                               "    \$$firstVal = \$$nItems - 1 - \$$offset;\n" .
                                                               "    \$$lastVal  = 0;\n" .
                                                               "}\n" .
                                                               "else\n" .
                                                               "{\n" .
                                                               "    \$$firstVal = \$$offset;\n" .
                                                               "    \$$lastVal  = \$$nItems - 1;\n" .
                                                               "}" );

        // generate loop header
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "for ( \$$i = \$$firstVal; " .
                                                               "\$$nItemsProcessed < \$$max && ( \$$reverse ? \$$i >= \$$lastVal : \$$i <= \$$lastVal ); " .
                                                               "\$$reverse ? \$$i-- : \$$i++ )\n" .
                                                               "{" );
        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$key = \$${arrayKeys}[\$$i];" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$val = \$${array}[\$$key];" );

        // export $itemVar
        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, "$val", $nodePlacement, array(),
                                                              $parameters['item_var'][0][1],
                                                              false, true, true );

        // export $keyVar (if specified)
        if ( isset( $parameters['key_var'] ) )
        {
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, "$key", $nodePlacement, array(),
                                                                  $parameters['key_var'][0][1],
                                                                  false, true, true );
        }

        $loop->processBody();

        // generate loop footer
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItemsProcessed++;" );
        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "} // foreach" );

        $loop->cleanup();

        // unset the loop variables
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( count( \$$variableStack ) ) extract( array_pop( \$$variableStack ) );\n" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "else\n{\n" );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $array );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $arrayKeys );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $nItems );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $nItemsProcessed );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $i );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $key );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $val );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $offset );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $max );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $reverse );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $firstVal );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $lastVal );

        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $variableStack );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}\n" );

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach ends" );

        return $newNodes;
    }
716061
public function prepare_items() {

		// Define Columns
		$columns = $this->get_columns();
		$hidden = [];
		$sortable = $this->get_sortable_columns();
		$this->_column_headers = [ $columns, $hidden, $sortable ];

		// Data
		$data = $this->getLatestExports();

		// Pagination
		$per_page = $this->get_items_per_page( 'pb_export_per_page', 50 );
		$current_page = $this->get_pagenum();
		$total_items = count( $data );
		$orderby = ( ! empty( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : 'exported';
		$order = ( ! empty( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : 'desc';

		// Data slice
		$sort = ( $orderby === 'exported' ) ? [ $orderby => $order ] : [
			$orderby => $order,
			'exported' => 'desc',
		];
		$data = wp_list_sort( $data, $sort );
		$data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page );
		$this->items = $data;

		$this->set_pagination_args(
			[
				'total_items' => $total_items,
				'per_page' => $per_page,
				'total_pages' => ceil( $total_items / $per_page ),
			]
		);
	}
1226286
def order_by(self, order_attribute):
        '''  '''
        to_return = []
        for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
            to_return.append(f)
        return to_return